# KernDX Framework — AI Code Generation Context

> **This is the KernDX AI rules file — load it into your AI assistant before writing KernDX code.**
>
> **Where it lives:** `docs/AI Agent Instructions.md` — in the KernDX repo, the release/source download,
> and the docs site. Nothing to generate or install; it is just this file.
>
> **How to use it:** an assistant that has merely *seen* this file once won't reliably apply it — put its
> full contents where the assistant *always* reads them. Copy it into the agent rules file your tool
> auto-loads at your project root (e.g. `AGENTS.md`, which Claude Code, Codex, Cursor and others read),
> or paste it into your tool's system prompt / project-knowledge. Tip: if you track KernDX in git,
> symlink or reference `docs/AI Agent Instructions.md` from that rules file so a `git pull` keeps it
> current automatically.
>
> Namespace: `kern`. API version: 68.0.
>
> **Audience: subscribers writing code that uses KernDX in their own org.** If you're instead working
> inside this repository (modifying the kern source itself or extending the framework),
> [`AGENTS.md`](https://github.com/JVB-Consulting/kerndx/blob/main/AGENTS.md) at the repo root is the entry point.

## STOP — Before Generating Code

**Collect these from the user before writing any code:**

1. **Namespace** — e.g., `kern`. Required for all framework class references.
2. **Class prefix convention** — e.g., `PRJ_`, `ACME_`, or none.
3. **Org alias** — only if deployment commands are needed.

If provided upfront, proceed immediately.

**Schema rule — If custom object fields are unknown, ask the user. Do not guess field API names.**

---

## CRITICAL — Namespace Prefix Rule

**Every framework class reference MUST be prefixed with the namespace.** Without it, code will NOT compile.
This is the single most common AI generation error. Verify EVERY line of generated code.

**Decision rule — apply this to every class reference:**

1. Does `docs/reference/apex/<ClassName>.md` exist in this repo? → It is a KernDX framework class. **Add the `kern.` prefix.**
2. Is the class defined inside YOUR subscriber repository? → **No prefix.**

This rule replaces any hardcoded list of framework classes (the kern namespace has 95+ global types and inner classes; any hardcoded list has gaps). The auto-generated reference
under `docs/reference/apex/` is the authoritative inventory — if a class is documented there, it ships in the kern package.

**Inner-class and interface members of framework classes also require the prefix** (e.g. `kern.IF_Trigger.BeforeInsert`, `kern.UTIL_AsyncChain.ChainStep`,
`kern.TST_Mock.MockBuilder`). The rule applies to the outermost class name; nested types inherit the same namespace.

**Your own subscriber classes do NOT get the namespace prefix.** Adding the prefix to your own classes causes `Invalid type` errors.

```apex
// WRONG — missing prefix on framework classes → "Invalid type: TRG_Base"
public class TRG_SetDefaults extends TRG_Base implements IF_Trigger.BeforeInsert { }
QRY_Builder.selectFrom(Account.SObjectType).toList();

// WRONG — adding prefix to YOUR OWN subscriber class → "Invalid type: kern.API_CreateOrder"
kern.API_Dispatcher.processInboundService(kern.API_CreateOrder.class.getName());

// RIGHT — prefix ONLY on framework classes; subscriber classes are bare
public with sharing class TRG_SetDefaults extends kern.TRG_Base implements kern.IF_Trigger.BeforeInsert { }
kern.QRY_Builder.selectFrom(Account.SObjectType).toList();
kern.API_Dispatcher.processInboundService(API_CreateOrder.class.getName());
```

**Self-check after generating:** For every class name in the generated code, run the decision rule. Framework classes (those documented under `docs/reference/apex/`) without the
`kern.` prefix → add it. Subscriber classes with the prefix → remove it. Both errors cause deployment failure.

**Always follow every rule in this document. Do not use alternative patterns (fflib, AT4DX, etc.).**

---

## Coding Standards

### Formatting

**Apex:** Tabs (size 3), Allman bracing, 180-char line limit (each leading tab counts as four columns, as the IDE does). Annotation attributes in camelCase
with a lower-case first letter (`@IsTest(seeAllData=false isParallel=true)`, `@AuraEnabled(cacheable=true)`); the annotation name keeps its capital (`@IsTest`).

```apex
public with sharing class MyClass
{
	public void myMethod()
	{
		if(condition)
		{
			// code
		}
	}
}
```

**Line wrap (>180 chars):** paren on new line, args indented:

```apex
List<Account> accounts = (List<Account>)kern.QRY_Builder.selectFrom
(
	Account.SObjectType
)
	.fields(new List<SObjectField>{ Account.Name, Account.Description })
	.toList();
```

**Never break the line between a `kern.`-qualified class and its first method call.** The Apex parser
then reads `kern` as a variable and the class fails to compile with `Variable does not exist: kern`.
Keep the class and its first call on one line; wrap on later calls in the chain:

```apex
// WRONG — line break after the namespaced class → "Variable does not exist: kern"
IpResponse response = (IpResponse) kern.UTIL_HttpClient
	.get('Echo', '/')
	.deserialize(IpResponse.class);

// RIGHT — the first call stays on the class's line; wrap afterwards
IpResponse response = (IpResponse) kern.UTIL_HttpClient.get('Echo', '/')
	.deserialize(IpResponse.class);
```

**JavaScript (LWC):** Tabs, single quotes, semicolons, Allman bracing, camelCase, JSDoc required on LWC component classes (`@description`, `@author`, `@date`) and methods with
parameters (`@param {type} name`).

### Source files come in pairs — every `.cls` needs its `.cls-meta.xml`

Salesforce deploys an Apex class only when its `*-meta.xml` descriptor sits beside it. A `.cls`
written without one is **silently skipped** — the deploy reports `No local changes to deploy` and the
class never lands. Whenever you create a class file (`.cls`), also create its paired `.cls-meta.xml` descriptor:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>68.0</apiVersion>
    <status>Active</status>
</ApexClass>
```

This pairing applies to **every** metadata type, each with its own descriptor — Apex triggers use
`*.trigger-meta.xml`, LWC use `*.js-meta.xml`, and so on. The exact shape differs by type, so when in
doubt copy the `*-meta.xml` descriptor of an existing file of the same kind in the project.

### Naming Conventions

| Prefix    | Use                         | Example              |
|-----------|-----------------------------|----------------------|
| `SEL_*`   | Object selectors            | `SEL_Cases`          |
| `QRY_*`   | Query infrastructure        | `QRY_Builder`        |
| `DML_*`   | DML operations              | `DML_Builder`        |
| `TRG_*`   | Trigger handlers/dispatcher | `TRG_SetDefaults`    |
| `IF_*`    | Interfaces                  | `IF_Trigger`         |
| `API_*`   | Web services                | `API_SendEmail`      |
| `REST_*`  | REST endpoints              | `REST_Echo`          |
| `DTO_*`   | Data Transfer Objects       | `DTO_JsonBase`       |
| `CTRL_*`  | LWC controllers             | `CTRL_ScheduledJob`  |
| `FLOW_*`  | Flow invocables             | `FLOW_CreateAccount` |
| `SVC_*`   | Service facades             | `SVC_Onboarding`     |
| `SCHED_*` | Schedulables                | `SCHED_PurgeRecords` |
| `BATCH_*` | Batch jobs                  | `BATCH_Process`      |
| `UTIL_*`  | Utilities                   | `UTIL_String`        |
| `LOG_*`   | Logging                     | `LOG_Builder`        |
| `MAP_*`   | In-memory indexing          | `MAP_SObject`        |
| `TST_*`   | Test utilities              | `TST_Builder`        |
| `*_TEST`  | Test classes                | `SEL_Cases_TEST`     |

### ApexDoc (Required)

**Class-level** (blank line between each tag):

```apex
/**
 * @description Handler for Foobar defaults.
 *
 * @see TRG_SetFoobarDefaults_TEST
 *
 * @author <your-author-tag>
 *
 * @group Trigger Actions
 *
 * @date January 2026
 */
```

Tags in order: `@description`, `@see`, `@author`, `@group`, `@date`, `@since`, `@example`

**Method-level (REQUIRED on EVERY method — including constructors and overrides like `getFields()`, `configure()`, `onSuccess()`):**
`@description`, `@param` (each), `@return` (if non-void), `@throws`, `@since` (if global)

**Do NOT skip ApexDoc on overridden methods.** Every method needs at minimum `@description`. Constructors also need `@description`.

**`@since`:** Required on ALL `global` members (classes, methods, properties). Format: `@since 1.0`. Not required on `public`/`private`. Subscribers need `@since` only on their
`global` classes: `REST_*`, plus any class the framework creates by name that is made `global`, `SCHED_*` included (see the Access rule below).

**`@example`:** Must use ` ```apex ` code fences.

**All properties and constants** require `@description`. **Bidirectional `@see`** between main class and test class.

### Critical Rules

| Rule                                         | Correct                                                                                                                                                                                                                | Wrong                                                                                                                                                                                                                                                                                                         |
|----------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| No inline SOQL                               | `new SEL_Cases().findOpen()` or `new SEL_Cases().query` (every read goes through a selector)                                                                                                                           | `[SELECT ...]`                                                                                                                                                                                                                                                                                                |
| No System.debug                              | `kern.LOG_Builder.build().info('msg').emitAt('Class.method')`                                                                                                                                                          | `System.debug(...)`                                                                                                                                                                                                                                                                                           |
| No LightningElement                          | `extends ComponentBuilder('notification')`                                                                                                                                                                             | `extends LightningElement`                                                                                                                                                                                                                                                                                    |
| No fflib layering pattern in subscriber code | `kern.QRY_Builder`, `kern.DML_Builder`, `extends kern.SEL_Base`, `extends kern.TRG_Base`                                                                                                                               | `fflib_SObjectSelector`, `fflib_SObjectDomain`, `fflib_Application`, `fflib_SObjectUnitOfWork`, `newQueryFactory()`. The framework's own `UTIL_SObjectDescribe` + `DML_Transaction` utilities are BSD-licensed from the same lineage (see `NOTICES.md`); subscriber code goes through `kern.*` not `fflib_*`. |
| No abbreviations                             | `account`, `message`                                                                                                                                                                                                   | `acc`, `msg`                                                                                                                                                                                                                                                                                                  |
| No Given/When/Then                           | Self-documenting code                                                                                                                                                                                                  | `// Given`, `// When`                                                                                                                                                                                                                                                                                         |
| No test cleanup                              | SF resets static state between tests                                                                                                                                                                                   | Cleanup code in tests                                                                                                                                                                                                                                                                                         |
| No hardcoded field names                     | `SObjectField` tokens or constants; `kern.UTIL_SObjectDescribe.getCachedFieldName(field)` when the name is needed as text; a field a page or a user picks goes through a `Map<String, SObjectField>` of allowed fields | String literal field names; a field name taken from a page or a user and passed to the query builder as text                                                                                                                                                                                                  |
| No section separators                        | Clean code                                                                                                                                                                                                             | `//====` banners                                                                                                                                                                                                                                                                                              |
| No inline DML in tests                       | `kern.TST_Builder.of(SObjectType).build()`                                                                                                                                                                             | `insert new Account()`                                                                                                                                                                                                                                                                                        |
| Use Assert.*                                 | `Assert.isTrue(result, 'msg')`                                                                                                                                                                                         | `System.assert(...)`                                                                                                                                                                                                                                                                                          |
| Declare sharing                              | Always `with sharing`; `inherited sharing` only for `SCHED_*`                                                                                                                                                          | Missing sharing                                                                                                                                                                                                                                                                                               |
| No unnecessary global                        | `public`; `global` for `REST_*` and classes created by name (`SCHED_*` included)                                                                                                                                       | `global` on selectors/services/flows; a `public` trigger action, chain step or schedulable with no Type Resolver                                                                                                                                                                                              |

### Sharing & Access by Class Type (mandatory)

**Subscriber code uses `with sharing` everywhere.** The `inherited sharing` you may see in framework source is a managed package internal pattern — it does NOT apply to subscriber
orgs.

| Class Type               | Sharing                                                       | Access                                                         |
|--------------------------|---------------------------------------------------------------|----------------------------------------------------------------|
| `TRG_*` handlers         | `with sharing`                                                | `global`, or `public` with a Type Resolver (created by name)   |
| `SEL_*` selectors        | `with sharing` (subscriber) / `inherited sharing` (framework) | `public`                                                       |
| `API_*` Inbound/Outbound | `with sharing`                                                | `global`, or `public` with a Type Resolver (created by name)   |
| `REST_*` routing         | `with sharing`                                                | `global` — SF requires for `@RestResource`                     |
| `SVC_*` services         | `with sharing`                                                | `public`                                                       |
| `FLOW_*` invocables      | `with sharing`                                                | `public`                                                       |
| `SCHED_*` schedulables   | `inherited sharing`                                           | `global`, or `public` with a Type Resolver (created by name)   |
| `UTIL_*` utilities       | `with sharing`                                                | `public`                                                       |
| `*_TEST` test classes    | (none)                                                        | `private`                                                      |

**Sharing rule:** Always `with sharing`. Never `without sharing` unless explicitly justified.

**Access rule:** `public` by default. Exceptions:

- `REST_*` classes: `global`, required for `@RestResource`.
- Every class the framework creates from its name: trigger actions and post-trigger actions, async chain steps, scheduled jobs (`SCHED_*`
  classes), inbound and outbound API
  handlers, DTOs extending `kern.DTO_JsonBase` (read back from JSON by name), feature-flag strategy classes, formula evaluation contexts,
  table data sources, search controllers and OmniCallable classes. Make the class `global`, or keep it `public` and set up a Type Resolver: a `global` class extending
  `kern.UTIL_TypeResolver.BaseClassResolver`, registered in a `kern__ClassTypeResolver__mdt` record (the Kern home page health check provides the
  code). With neither, the framework fails with `Unable to resolve type for class "<name>"`. See
  [Type Resolution](/utilities-guide#type-resolution-util-typeresolver).
- DTOs have a third option: override `getObjectType()` to return the DTO's own class, as the `DTOs - Guide.md` shows. An inner DTO such as
  `DTO_Request` inside an `API_*` class needs one of the three on its own: a `public` inner class stays hidden even when its outer class
  is `global`.

Selectors, services, Flow invocables and utilities are called directly from your own code, so they stay `public`.

### PMD

Cyclomatic complexity ≤15/method, ≤50/class. Parameters ≤5. Nested ifs ≤4. Suppress: `@SuppressWarnings('PMD.RuleName')`.

ApexGuru: opt in only when the scan's target org is a production or Full Copy Sandbox with ApexGuru enabled (`apex-guru` in `scanner.rule_selector`,
`engines.apexguru.target_org` set to that org); leave it off everywhere else, where its static mode sees only literal SOQL and DML.

---

## Selector Framework (SEL_Base)

Extend `kern.SEL_Base`. Define default fields. Custom methods use `query` property (NOT `QRY_Builder.selectFrom()`).

```apex
/**
 * @description Selector for the Case SObject.
 *
 * @see SEL_Cases_TEST
 */
public with sharing class SEL_Cases extends kern.SEL_Base  // MUST be "with sharing" in subscriber code
{
	/** @description Constructs the Case selector. */
	public SEL_Cases() { super(Case.SObjectType); }

	/** @description Returns the default fields for Case queries. */
	public override List<SObjectField> getFields()
	{
		return new List<SObjectField>{ Case.Id, Case.Subject, Case.Status };
	}

	/** @description Returns related field paths for Case queries. */
	public override List<String> getFieldPaths()
	{
		return new List<String>{ 'Account.Name', 'Owner.Name' };
	}

	/** @description Finds open cases ordered by creation date. */
	public List<Case> findOpen()
	{
		return query.condition(Case.IsClosed).equals(false)
			.orderBy(Case.CreatedDate).descending().toList();
	}
}
```

**Inherited methods:** `findById(Id)` / `findById(Set<Id>)` | `findByIdOrThrow(Id/Set<Id>)` | `findByField(field, value/Set)` | `findFirstByField(field, value)` |
`findByFields(Map)` / `findFirstByFields(Map)` | `query` (property → `QRY_Builder.Builder`) | `toList()` / `getFirst()` / `getRandomItem()` | `count()` / `exists()` |
`toQueryLocator()`

---

## Query Builder (QRY_Builder)

Every read goes through a SEL_* selector; QRY_Builder is the engine under its `query` property, so the builder methods below are called on `query`. Plain SOQL only when the framework cannot express the query (raise it with the KernDX team) or the code is outside the framework's reach. Prefer `List<SObjectField>` for compile-time safety.

```apex
List<Account> accounts = new SEL_Accounts().query
	.fields(new List<SObjectField>{ Account.Name, Account.Industry })
	.condition(Account.Industry).equals('Tech')
	.orderBy(Account.Name).ascending()
	.withLimit(100)
	.toList();
```

**Fields:** `.fields(List<SObjectField/String>)` | `.addFields()` | `.addField()` | `.relatedField(String)` | `.relatedFields(List<String>)` | `.selectAllFields()` |
`.fieldSet()` | `.subselect(Builder, String)`

**Conditions:** `.condition(field)` | `.andCondition(field)` | `.orCondition(field)` | `.addCondition(QRY_Condition.Evaluable)`

**Operators:** `.equals()` | `.notEquals()` | `.greaterThan()` | `.greaterThanOrEquals()` | `.lessThan()` | `.lessThanOrEquals()` | `.isNull()` | `.isNotNull()` |
`.isIn(Set/List/Builder)` | `.notInSet(Set/List/List<SObject>)` | `.notIn(Builder)` | `.contains()` | `.startsWith()` | `.endsWith()` | `.includes()` | `.excludes()`

**Ordering:** `.orderBy(field)` → `.ascending()` / `.descending()` / `.nullsFirst()` / `.nullsLast()` | `.orderBy(field, sortDescending)` |
`.orderBy(field, sortDescending, nullsLast)`

**Aggregates:** `.groupBy(field)` | `.sum()` / `.avg()` / `.min()` / `.max()` / `.count(String)` / `.countDistinct()` | Aliased multi-aggregate overloads:
`.sum(field, alias)` / `.avg(field, alias)` / `.min(field, alias)` / `.max(field, alias)` / `.count(field, alias)` / `.countDistinct(field, alias)` (several aggregates in one
query; read back via `AggregateRow.get(alias)`; alias must be a bare identifier) | `.orderByCount(field, sortDescending)` (ORDER BY COUNT for top-N groups with `.withLimit()`) |
`.havingSumOf()` / `.havingCount()` etc. | Terminal: `.toAggregateList()` → `List<QRY_Builder.AggregateRow>` (NOT `AggregateResult`)

**Aggregate mocks (tests):** `kern.QRY_Builder.setAggregateMock(SObjectType, List<Map<String, Object>>)` (or `kern.TST_Mock.registerAggregateRows`, see Testing) makes
`.toAggregateList()` / `.getFirstAggregate()` return the given rows; map keys are the aliases the code reads, so give every aggregate an explicit alias; only `LIMIT` applies;
`null` clears the type. Record mocks never answer an aggregate read (it throws `kern.UTIL_Exceptions.IllegalStateException`), and a record read on a
mocked aggregate query throws too.

**TYPEOF (polymorphic parents):** `.addField('TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN Amount ELSE Name END')`. Read the parent with
`SObject parent = event.What; switch on parent { when Account account { ... } when null { ... } when else { ... } }`, never a cast (an `ELSE` parent is a `Name` record). TYPEOF selects fields,
never filters rows, and cannot be combined with aggregate functions.

**Limit/Cache/Scope:** `.withLimit()` | `.withOffset()` | `.withCache(seconds)` | `.usingScope(QRY_Builder.Scope)` | `.forUpdate()` | `.allRows()`

**Security:** `.withUserMode()` / `.withSystemMode()` | `.stripInaccessible()` | `.withSharing()` / `.bypassSharing()` | `.withoutSecurity()`

> **Default access mode:** USER_MODE (CRUD, FLS, sharing enforced). Controlled by the `UserModeQueries_Enabled` feature flag (ships `IsEnabledByDefault__c = true`). Call
`.withSystemMode()` per-query to bypass, or subclass `kern.SEL_Base` and override `systemModeRequired()` to return `true` to pin a selector's queries to SYSTEM_MODE regardless of
> the flag. Under USER_MODE: `.withSharing()` changes nothing on its own (USER_MODE always enforces sharing; after `.bypassSharing()` it cancels the bypass); `.stripInaccessible()` does not stop the platform refusing a
> selected field the user cannot read (it strips only under `.withSystemMode()` or in a `.bypassSharing()` read); `.bypassSharing()` alone ignores sharing and
> keeps the object and field checks: hidden fields are removed from the rows, a hidden lookup or parent object on a selected path (or behind a child query) refuses the read, an unreadable object or a `condition(...)`/`orderBy(...)` on a hidden field is
> refused, and `toQueryLocator()`, `toCursor()` and aggregate reads are refused with `kern.UTIL_Exceptions.IllegalStateException` (add `.withSystemMode()`);
> refusing an object the user cannot read throws a `QueryException`, and the other refusals throw `IllegalStateException`.
> Only `.withSystemMode()`, `.bypassSharing()` and `.withoutSecurity()` write a bypass audit entry.

**Field names:** pass fields as `SObjectField` tokens (`Account.Name`, checked when the code compiles) or constants, never as text built from input. Values are always bound
(sent beside the query text) or escaped (quote marks made harmless). A method that takes a field name as text for a condition, a sort or a grouping accepts only a field API name,
a path through a lookup (`Account.Owner.Name`), a date or distance expression of the kind `kern.QRY_Function` writes, or, where SOQL allows it, an aggregate such as `SUM(Amount)`
or `toLabel()` around a field name; a sort item may end with `ASC` / `DESC` and `NULLS FIRST` / `NULLS LAST`, and `orderBy` / `groupBy` take a comma-joined list of those. Other
text throws `IllegalArgumentException` before a query runs. The `String` form of `.orderBy(field, sortDescending)` takes a field name, or a list of sort items whose last
item has no direction and no nulls order: write `.orderBy('Name', true)`, never `.orderBy('Name DESC', true)`, because the method adds the direction itself.
The check does not test field access, so a field a page or a user picks is mapped through a list of allowed fields, above all in system mode, and the same holds
for the select list (`.fields()`, `.addField()`): `.orderBy(ALLOWED_SORT_FIELDS.get(request.sortColumn) ?? Account.Name, request.sortDescending)` with
`Map<String, SObjectField> ALLOWED_SORT_FIELDS`. A semi-join subquery passed to `.isIn(Builder)` / `.notIn(Builder)` selects exactly one field, by API name or parent path.

**Terminal:** `.toList()` | `.getFirst()` | `.toQueryLocator()` | `.toCursor()` | `.toAggregateList()` | `.getFirstAggregate()` | `.getPage(page, size)` → `QueryPage` |
`.getRandomItem()` / `.getRandomItems(n)` | `.count()` | `.exists()` | `.asMap()` | `.asMapById(field)` | `.asMapByString(field)` | `.asGroupedMapById(field)` |
`.asGroupedMapByString(field)` | `.asIdSet()` | `.asIdList()` | `.asValueSet(field)` | `.asStringSet(field)` | `.toSoql()`

### Semi-join Subqueries

**IMPORTANT:** Do NOT call terminal methods on subqueries:

```apex
// CORRECT
kern.QRY_Builder.Builder subquery = kern.QRY_Builder.selectFrom(Contact.SObjectType)
	.fields(new List<String>{ 'AccountId' })
	.condition(Contact.Email).isNotNull();

List<Account> accounts = new SEL_Accounts().query
	.condition(Account.Id).isIn(subquery)
	.toList();
```

### Compound Conditions

```apex
kern.QRY_Condition.OrCondition statusGroup = new kern.QRY_Condition.OrCondition();
statusGroup.add(new kern.QRY_Condition.FieldCondition(Account.Status__c, kern.QRY_Condition.Operator.EQUALS, 'Active'));
statusGroup.add(new kern.QRY_Condition.FieldCondition(Account.Status__c, kern.QRY_Condition.Operator.EQUALS, 'Pending'));

List<Account> accounts = new SEL_Accounts().query
	.condition(Account.Industry).equals('Tech')
	.addCondition(statusGroup)
	.toList();
```

**LIKE-contains leaf** (field-only constructor + `contains()`, wildcards handled for you): `new kern.QRY_Condition.FieldCondition(Account.Name).contains('Acme')` → `Name LIKE '%Acme%'`

**LIKE-contains leaf for text a person typed** (`containsLiteral()` escapes `%`, `_` and `\` so the term matches exactly as typed): `new kern.QRY_Condition.FieldCondition(Account.Name).containsLiteral(searchBoxValue)`. Use it for every search box, filter or report parameter; `contains()` keeps the wildcards and is for patterns you wrote yourself.

### Date Literals

```apex
.condition(Account.CreatedDate).equals(new kern.QRY_Condition.DateLiteral().lastNDays(30))
.condition(Case.CreatedDate).equals(new kern.QRY_Condition.DateLiteral().today())
```

Methods: `.today()` / `.yesterday()` / `.tomorrow()` | `.lastNDays(n)` / `.nextNDays(n)` | `.thisUnit(UnitOfTime)` | `.last(UnitOfTime)` / `.next(UnitOfTime)` |
`.last(n, UnitOfTime)` / `.next(n, UnitOfTime)`

---

## DML Builder

```apex
kern.DML_Builder.TransactionResult result = kern.DML_Builder.newTransaction()
	.doInsert(account)
	.doInsert(contact, Contact.AccountId, account)
	.doInsert(opportunity, Opportunity.AccountId, account)
	.execute();
```

**Operations:** `.doInsert(SObject/List)` | `.doInsert(child, relField, parent)` | `.doUpdate()` | `.doDelete()` | `.doUpsert()` | `.doUpsert(records, externalId)` |
`.doUndelete()`

**Config:** `.allowPartial()` | `.expectRefusal(StatusCode)` | `.withRetryOnLock([retries])` | `.withUserMode()` / `.withSystemMode()` | `.bypassSharing()` | `.suppressLogging()` | `.suppressExceptions()`

**Result:** `isSuccess()` | `getInsertedIds()` | `getErrors()` | `getSuccessCount()` | `getFailureCount()` | `getFailureMessage()` (the reason when
`suppressExceptions()` caught a failure or an error stopped an `allowPartial()` save; `getErrors()` does not show that reason)

**Async:** `.async()` → `kern.DML_Builder.DML_AsyncBuilder` — a **type switch, not a config method**. The async builder exposes only `.withBatchSize(Integer)` and
`.execute()`, and its `execute()` returns **`void`**, not a `TransactionResult`. Chain `.async()` last; none of the Config methods above exist on it. Five
dials carry across the switch: `.allowPartial()`, the access mode (`.withUserMode()` / `.withSystemMode()`), `.bypassSharing()`, `.expectRefusal()`, and `.withRetryOnLock()`.
`.suppressLogging()` / `.suppressExceptions()` do not — the async leg always logs and rethrows a `DmlException`.

> **Record sharing on the async leg: enforced unless you opt out.** The async job cannot inherit your class's sharing declaration (the work runs inside the
framework's own job processor), so the framework pins the sharing context explicitly: the write runs **with record sharing enforced** by default, and
`.bypassSharing()` is the deliberate opt-out that carries across the switch. Under the default USER_MODE the bypass ignores sharing in the job too and keeps
the running user's object and field checks: fields the user cannot create or edit are left out of the save. The one remaining sync/async difference (in SYSTEM_MODE):
a synchronous chain called without a bypass inherits the sharing context of
the class that calls `.execute()`, while the async leg always enforces unless bypassed.

```apex
kern.DML_Builder.newTransaction().doInsert(accounts).async().withBatchSize(50).execute();   // returns void
```

> **Default access mode:** USER_MODE (CRUD, FLS, sharing enforced). Controlled by the `UserModeDml_Enabled` feature flag (ships `IsEnabledByDefault__c = true`). Call
`.withSystemMode()` on the transaction to bypass (e.g. writes to framework-owned audit objects). `.bypassSharing()` alone ignores record sharing and keeps
> the object and field checks: a field the user cannot create or edit is left out of the save with one WARN log naming it, and a save without the object
> permission is refused as USER_MODE refuses it. Only `.withSystemMode()` and `.bypassSharing()` write a bypass audit entry; `.withUserMode()` writes none.

Register the parent with its own `.doInsert()`, before or after the child: the transaction orders the inserts from the relationships you registered and fills in the
child's lookup Id.

---

## Trigger Framework

### Trigger File

```apex
trigger TRG_Account on Account (before insert, before update, after insert, after update)
{
	new kern.TRG_Dispatcher().run();
}
```

Only declare events needed by configured `TriggerAction__mdt` handlers.

### Trigger Action Class

```apex
public with sharing class TRG_SetAccountDefaults extends kern.TRG_Base implements kern.IF_Trigger.BeforeInsert
{
	/** @description Default description text. */
	private static final String DEFAULT_DESCRIPTION = 'New Account';

	/**
	 * @description Sets default Description on Account records when blank.
	 *
	 * @param newRecords The list of new Account records.
	 */
	public void beforeInsert(List<SObject> newRecords)
	{
		for(SObject record : newRecords)
		{
			Account account = (Account)record;

			if(String.isBlank(account.Description))
			{
				account.Description = DEFAULT_DESCRIPTION;
			}
		}
	}
}
```

**Rules:** Extract magic strings to named constants with `@description`. ApexDoc on every method including overrides.

### IF_Trigger Interfaces

**These are interface contracts — code will NOT compile if signatures differ. Copy exactly.**

| Interface                       | Method Signature                                                        |
|---------------------------------|-------------------------------------------------------------------------|
| `kern.IF_Trigger.BeforeInsert`  | `void beforeInsert(List<SObject> newRecords)`                           |
| `kern.IF_Trigger.AfterInsert`   | `void afterInsert(List<SObject> newRecords)`                            |
| `kern.IF_Trigger.BeforeUpdate`  | `void beforeUpdate(List<SObject> newRecords, List<SObject> oldRecords)` |
| `kern.IF_Trigger.AfterUpdate`   | `void afterUpdate(List<SObject> newRecords, List<SObject> oldRecords)`  |
| `kern.IF_Trigger.BeforeDelete`  | `void beforeDelete(List<SObject> oldRecords)`                           |
| `kern.IF_Trigger.AfterDelete`   | `void afterDelete(List<SObject> oldRecords)`                            |
| `kern.IF_Trigger.AfterUndelete` | `void afterUndelete(List<SObject> newRecords)`                          |

**Do NOT use `triggerNew` or omit the parameter.** Iterate the method parameter (e.g., `for(SObject record : newRecords)`).

**Update/delete handlers — pair old and new from the `oldRecords` parameter, NOT `triggerOldMap`.** The framework hands you the prior-state records as the `oldRecords` argument (the dispatcher calls `beforeUpdate(Trigger.new, Trigger.old)`). Pair them by Id with a map built from that parameter:

```apex
public with sharing class TRG_StampIndustryChange extends kern.TRG_Base implements kern.IF_Trigger.BeforeUpdate
{
	/** @description Stamp applied to Description when Industry changes. */
	private static final String INDUSTRY_CHANGED_STAMP = 'Industry updated';

	/**
	 * @description Stamps Description when an Account's Industry changes.
	 *
	 * @param newRecords The Accounts with their proposed values.
	 * @param oldRecords The same Accounts with their values prior to the update.
	 */
	public void beforeUpdate(List<SObject> newRecords, List<SObject> oldRecords)
	{
		Map<Id, SObject> oldById = new Map<Id, SObject>(oldRecords);

		for(SObject record : newRecords)
		{
			Account newAccount = (Account)record;
			Account oldAccount = (Account)oldById.get(newAccount.Id);

			if(oldAccount != null && newAccount.Industry != oldAccount.Industry)
			{
				newAccount.Description = INDUSTRY_CHANGED_STAMP;
			}
		}
	}
}
```

(Pairing by positional index — `newRecords[i]` vs `oldRecords[i]` — also works; the two lists are aligned.) The `triggerNew` / `triggerOld` / `triggerOldMap` accessors on `kern.TRG_Base` are convenience getters that read live `Trigger.*` context and are **null outside a running trigger** — an action that reads them cannot be unit-tested by direct handler invocation (the test pattern below), so pair from the method parameters instead.

### Custom Metadata Configuration (REQUIRED)

**A trigger handler will NOT execute without these records.** Always generate them alongside the handler class.

Two records needed per handler: a `TriggerSetting` (one per SObject) and a `TriggerAction` (one per handler + event).

**File naming:** `kern__TriggerSetting.{ObjectName}.md-meta.xml` and `kern__TriggerAction.{ActionName}_{Event}.md-meta.xml`

**TriggerSetting** — one per SObject (skip if one of yours already exists). File: `kern__TriggerSetting.{ObjectName}.md-meta.xml`

**Handlers on a KernDX object** (`kern__ApiCall__c`, `kern__ApiIssue__c`, `kern__ScheduledJob__c`, `kern__AsyncChainExecution__c`): the package's
triggers on these objects run all seven events, so generate only the metadata records, never a trigger of your own (a second trigger that calls the
dispatcher runs every action twice). Always create your own `TriggerSetting` for the object (`kern__SObjectType__c` = `kern__ApiIssue__c`, say),
even though the package ships one: the package's settings are protected and a subscriber row cannot reference them. Both settings' actions run, in
no defined order between the two (`Order__c` sorts within one setting only; the package's own rows on these objects use before events only). `kern__ApplyMasking__c`:
kern already masks ApiCall, ApiIssue and AsyncChainExecution, whatever this is; on ScheduledJob leave it `false` unless you add masking targets for it.
Leave `kern__FailureAction__c` blank (`LogAndContinue`): `BlockDml` or a governor-limit error
rolls back the package's own save, including the very record that started the action (on `kern__ApiIssue__c`, the issue itself).
`kern__ApiCall__c` and `kern__ApiIssue__c` have built-in formula contexts; the other two need a `global` context class. Full guide:
[How do I add actions to KernDX's own objects?](/triggers-guide#how-do-i-add-actions-to-kerndx-s-own-objects).

| Field                      | Value                             |
|----------------------------|-----------------------------------|
| `kern__SObjectType__c`     | Object API name (e.g., `Account`) |
| `kern__BypassExecution__c` | `false`                           |

Optional on TriggerSetting (omit unless needed):

| Field                               | Default | Purpose                                                                                                                                                           |
|-------------------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `kern__ObjectApiNameOverride__c`    | —       | Registers an entity `SObjectType__c` cannot reference — Change Data Capture events (`AccountChangeEvent`). Wins at dispatch; at least one of the two must be set. |
| `kern__ApplyMasking__c`             | `true`  | Runs the masking pass before insert/update on this object. Masking runs when ANY setting for the object has it on; uncheck it on every one to opt out. |
| `kern__BypassFeatureFlag__c`        | —       | Skip ALL actions on this object while the named `FeatureFlag__mdt` is on.                                                                                         |
| `kern__RequiredFeatureFlag__c`      | —       | Run actions on this object ONLY while the named `FeatureFlag__mdt` is on.                                                                                         |
| `kern__EnablePerformanceLogging__c` | `true`  | Deprecated: has no effect. Do not set it; use `kern__PerformanceThresholdMs__c`.                                                                                  |
| `kern__PerformanceThresholdMs__c`   | —       | Log a run of the actions under this setting that takes this long or longer (ms), even when `LogSetting__c.EnableTriggerPerformanceLogging__c` is off. Blank follows `LogSetting__c`; an action threshold wins. Never set it low on your own trigger setting or action for a log object (`kern__LogEntryEvent__e`): each entry can fire the trigger again. |

**TriggerAction** — one per handler + event. File: `kern__TriggerAction.{ActionName}_{Event}.md-meta.xml`

| Field                     | Value                                                                                                                     |
|---------------------------|---------------------------------------------------------------------------------------------------------------------------|
| `kern__ApexClassName__c`  | Handler class name (no namespace prefix)                                                                                  |
| `kern__Event__c`          | `Before Insert` / `Before Update` / `After Insert` / `After Update` / `Before Delete` / `After Delete` / `After Undelete` |
| `kern__Order__c`          | Execution sequence (lower first; use 100, 200, etc.)                                                                      |
| `kern__TriggerSetting__c` | DeveloperName of the TriggerSetting record                                                                                |
| `kern__Description__c`    | Human-readable description (a validation rule requires it)                                                                |

Optional on TriggerAction (omit unless needed):

| Field                                    | Default          | Purpose                                                                                                                                                                                                                                                     |
|------------------------------------------|:----------------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `kern__FlowName__c`                      | —                | Runs an active auto-launched flow instead of an Apex class. Set exactly one of `ApexClassName__c` / `FlowName__c` — a validation rule blocks both or neither. The flow needs an in/out `record` variable (plus input-only `recordPrior` for update events). |
| `kern__BypassExecution__c`               | `false`          | Kill switch for this one action.                                                                                                                                                                                                                            |
| `kern__BypassFeatureFlag__c`             | —                | Skip this action while the named `FeatureFlag__mdt` is on.                                                                                                                                                                                                  |
| `kern__RequiredFeatureFlag__c`           | —                | Run this action ONLY while the named `FeatureFlag__mdt` is on.                                                                                                                                                                                              |
| `kern__AllowRecursion__c`                | `true`           | Re-entrancy guard, NOT a once-per-transaction guard. Uncheck to skip the action while an earlier run of it is still in progress (its own DML re-firing the same trigger). It still runs for separate, later operations in the same transaction.             |
| `kern__AllowNonSelfInitiated__c`         | `true`           | Uncheck to skip the action when another trigger, not the original DML, caused this execution.                                                                                                                                                               |
| `kern__EntryCriteriaFormula__c`          | —                | Formula gate — the action runs only for records where it evaluates true.                                                                                                                                                                                    |
| `kern__EntryCriteriaContextClassName__c` | —                | Class implementing `kern.UTIL_FormulaFilter.INT_SObjectFormulaEvaluationContext`. Required for CUSTOM objects only — Account, Campaign, Case, Contact, Event, Lead, Opportunity, Task, User, `kern__ApiCall__c` and `kern__ApiIssue__c` resolve automatically. |
| `kern__FailureAction__c`                 | `LogAndContinue` | `LogAndContinue` or `BlockDml` when the action throws.                                                                                                                                                                                                      |
| `kern__PerformanceThresholdMs__c`        | —                | Threshold for this action (ms); wins over the trigger setting's. Logs even when `LogSetting__c.EnableTriggerPerformanceLogging__c` is off.                                                                                                                  |
| `kern__ForcePerformanceLogging__c`       | `false`          | Log every run of this action, even when `LogSetting__c.EnableTriggerPerformanceLogging__c` is off.                                                                                                                                                          |
| `kern__SuppressPerformanceLogging__c`    | `false`          | Never log this action's timing, even when Force is also ticked.                                                                                                                                                                                             |

**Copy-paste XML reference** (TriggerAction — required fields only; add optional fields from the table above as needed):

```xml
<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <label>Set Account Defaults - Before Insert</label>
    <protected>false</protected>
    <values><field>kern__ApexClassName__c</field><value xsi:type="xsd:string">TRG_SetAccountDefaults</value></values>
    <values><field>kern__Event__c</field><value xsi:type="xsd:string">Before Insert</value></values>
    <values><field>kern__Order__c</field><value xsi:type="xsd:double">100.0</value></values>
    <values><field>kern__TriggerSetting__c</field><value xsi:type="xsd:string">Account</value></values>
    <values><field>kern__Description__c</field><value xsi:type="xsd:string">Sets default Description when blank on Account insert</value></values>
</CustomMetadata>
```

TriggerSetting and ApiSetting use the same XML structure — only the field names differ (see tables above and below).

### Flow as a Trigger Action

Subscribers can register an auto-launched Flow as a trigger action by setting `kern__FlowName__c` on a
`TriggerAction__mdt` row and leaving `kern__ApexClassName__c` blank. The framework dispatches via its built-in
flow runner and the flow inherits ordering, bypass, recursion control, performance monitoring, audit logging, and
feature-flag gating. No subscriber Apex is required — registration is metadata-only.

Configure via a `TriggerAction__mdt` record with these flow-specific fields:

| Field                    | Required                          | Default          | Allowed values                                                                                                                                                               |
|--------------------------|-----------------------------------|------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `kern__FlowName__c`      | Yes (XOR with `ApexClassName__c`) | —                | Bare flow API name (no namespace prefix — the framework resolves cross-namespace)                                                                                            |
| `kern__ApexClassName__c` | Leave blank for flow rows         | —                | The `MutuallyExclusiveTarget` validation rule rejects rows with both `FlowName__c` and `ApexClassName__c` populated, and rows with neither populated.                        |
| `kern__FailureAction__c` | No                                | `LogAndContinue` | `LogAndContinue` (logs error, DML proceeds — for orchestration), `BlockDml` (calls `record.addError`, blocks save — for validation). Applies to Apex and flow actions alike. |

The registered flow declares variable `record` (input + output, type matching the trigger object) and — for update contexts — variable `recordPrior` (input only). Variable type
must match `TriggerSetting__mdt.SObjectType__c` exactly. `LogSetting__c.EnableFlowActionLogging__c` (`Off` / `ErrorsOnly` (default) / `AlwaysOn`) controls audit volume.

**Mock harness for tests:** `kern.TST_InvokeFlowMock.forFlow(name).succeed().withOutputRecord(record).register()` short-circuits `Flow.Interview` at test time. Helpers:
`.fail(message).register()`, `.assertInvoked(name, count)`, `.assertNotInvoked(name)`, `.getLastInputRecord(name)`, `.getLastInputPriorRecord(name)`, `.clear()`. Mocks test
framework orchestration, not flow logic — pair with one deployed-flow integration test per flow.

### Post-Trigger Actions

Runs after every `TriggerAction__mdt` on every touched object in a dispatch has completed. Transaction-scoped, not per-record — it receives no records. The class implements
`kern.IF_Trigger.PostAction` and does **not** extend `kern.TRG_Base`; registration is metadata-only via `PostTriggerAction__mdt` (no `Event__c` field — post-actions are
not bound to an event).

| Type                                      | Member                                                                                                |
|-------------------------------------------|-------------------------------------------------------------------------------------------------------|
| `kern.IF_Trigger.PostAction`              | `void execute(kern.IF_Trigger.PostActionContext context)`                                             |
| `kern.IF_Trigger.PostActionEntryCriteria` | `Boolean shouldRun(kern.IF_Trigger.PostActionContext context)` — optional gate; `false` skips the row |
| `kern.IF_Trigger.PostActionContext`       | `Set<SObjectType> touchedSObjectTypes` — read-only, never null, may be empty. The entire context.     |

**Synchronous DML is contractually banned.** The framework compares `Limits.getDmlStatements()` across `execute()` and throws a `PostActionDmlException`
(framework-internal — you cannot catch it by name), always rethrown regardless of `FailureAction__c`. Compute, or enqueue async (`System.enqueueJob` /
`@future` / `System.schedule`) instead.

**It fires once per timing per DML operation, not once per transaction.** Each trigger timing is a separate top-level dispatch, so an `insert` against a
handler registered on both before- and after-insert fires post-actions twice, and N top-level DML statements multiply that again. Write them idempotent or
gate on `touchedSObjectTypes`. They do not fire at all when the object is bypassed or when a trigger action threw.

Registration record — `kern__PostTriggerAction.{Name}.md-meta.xml`. Fields: `kern__ApexClassName__c` (the implementing class) | `kern__Order__c` (ascending) |
`kern__TriggerSetting__c` (when set, the row runs only if that setting's object is in `touchedSObjectTypes`; omit for cross-object) | `kern__EntryCriteriaContextClassName__c` |
`kern__BypassExecution__c` (`false`) | `kern__RequiredFeatureFlag__c` / `kern__BypassFeatureFlag__c` | `kern__FailureAction__c` (`LogAndContinue`) |
`kern__PerformanceThresholdMs__c` (blank: the trigger setting's threshold, else `LogSetting__c`) | `kern__ForcePerformanceLogging__c` (`false`) | `kern__Description__c`. Gate order, cheapest first: bypass → feature flags →
trigger-setting scope → entry criteria.

```apex
public with sharing class TRG_EnqueueAccountSync implements kern.IF_Trigger.PostAction
{
	/**
	 * @description Enqueues one downstream sync job per dispatch when Account triggers participated.
	 *
	 * @param context The touched-type context for this dispatch.
	 */
	public void execute(kern.IF_Trigger.PostActionContext context)
	{
		if(!context.touchedSObjectTypes.contains(Account.SObjectType))
		{
			return;
		}

		System.enqueueJob(new AccountSyncQueueable());
	}
}
```

### Bypass

Object: `kern.TRG_Base.bypass(SObjectType)` / `.isBypassed(SObjectType)` / `.clearBypass(SObjectType)` / `.clearAllBypasses()` — each single-argument call
also takes a `String` object API name
Action: `.bypassAction(String)` / `.isActionBypassed(String)` / `.clearActionBypass(String)` / `.clearAllActionBypasses()` — names match case-insensitively
Either surface: `.bypass(String, BypassType)` / `.isBypassed(String, BypassType)` / `.clearBypass(String, BypassType)` / `.clearAllBypasses(BypassType)` —
one call site for both sets, routed by `kern.TRG_Base.BypassType.OBJECT_NAME` or `.CLASS_NAME`. Parse a string into the enum with
`kern.TRG_Base.resolveBypassType(String)`.
Declarative: `TriggerSetting__mdt.BypassExecution__c`
Audit: every `bypass*()` / `clear*Bypass()` call emits a `LogEntryEvent__e` with category `BypassEvent` — the runtime audit trail is on by default;
the `BypassAudit_Enabled` feature flag turns it off. Set a free-text reason for the whole
transaction via `kern.TRG_Base.setBypassReason(String)` and it attaches to every bypass emission that follows. (The underlying `BypassAction` enum and `resolveBypassAction(String)`
resolver are framework-internal — `public`, not `global` — and drive the declarative `FLOW_BypassTrigger` invocable; subscribers do not call them directly.)

The object and action sets are independent — `clearAllBypasses()` does not clear action bypasses, and vice versa.

### Trigger Test Pattern

```apex
@SuppressWarnings('PMD.ApexUnitTestClassShouldHaveRunAs')
@IsTest(seeAllData=false isParallel=true)
private class TRG_SetAccountDefaults_TEST
{
	@IsTest
	private static void shouldSetDefaultWhenDescriptionBlank()
	{
		Account record = (Account)kern.TST_Builder.of(Account.SObjectType)
			.withoutInsertion()
			.build();

		new TRG_SetAccountDefaults().beforeInsert(new List<SObject>{ record });

		Assert.isNotNull(record.Description, 'Default should be set');
	}
}
```

---

## HTTP Client (UTIL_HttpClient)

Static factories only — **never `new UTIL_HttpClient()`**.

```apex
kern.UTIL_HttpClient.post('PaymentGateway', '/charges').body(chargeRequest).send();
kern.UTIL_HttpClient.get('CRM', '/accounts/{id}').pathParam('id', accountId).asMap();
kern.UTIL_HttpClient.post('EmailService', '/send').body(payload).timeout(30000)
	.withRetry(3).withCircuitBreaker().onFailure(kern.UTIL_HttpClient.FailureAction.LOG_FAILURE)
	.withTriggeringRecord(record.Id).send();
```

**Factories:** `.get()` / `.post()` / `.put()` / `.del()` / `.patch()` / `.useHandler(Type)`

**Builder:** `.body()` | `.header()` | `.headers()` | `.queryParam()` | `.pathParam()` | `.timeout()` | `.withRetry(n)` | `.withExponentialBackoff(n, base)` |
`.retryOn(Set<Integer>)` | `.onFailure(FailureAction)` | `.withCircuitBreaker()` | `.withTriggeringRecord(Id)` | `.withCorrelationId()` | `.skipLogging()` | `.withParameter()` |
`.withParameters()`

**Terminal:** `.send()` → `HttpResponse` | `.asString()` | `.asMap()` | `.deserialize(Type)` | `.invoke()`

Every failure the framework handles for a call (a refused call, a transport failure, a handler exception, an unsaved call record, a blocked masking rule) comes back with the response: check `getStatusCode()` (0 means no exchange happened) and never wrap `send()` in try/catch for those failures. A governor limit is the platform's exception and cannot be caught.

---

## Outbound Web Services (API_Outbound)

```apex
public with sharing class API_SendNotification extends kern.API_Outbound
{
	@TestVisible
	private static final String PARAM_RECIPIENT = 'recipient';

	private static final String ERROR_NO_EMAIL = 'Record does not have an email address';

	/**
	 * @description Sets the request and response DTOs and the body the mock returns.
	 */
	public override void configure()
	{
		super.configure();
		requestPayload = new DTO_Request();
		responsePayload = new DTO_Response();
		defaultMockBody = '{"messageId": "msg-12345"}';
	}

	/**
	 * @description Adds the recipient to the inputs every call must carry.
	 *
	 * @return The names of the required inputs.
	 */
	public override Set<String> getRequiredInputs()
	{
		Set<String> requiredInputs = super.getRequiredInputs();
		requiredInputs.add(PARAM_RECIPIENT);
		return requiredInputs;
	}

	/**
	 * @description Stops the call when the triggering Contact has no email address.
	 *
	 * @return The validation errors; an empty list when the call may go ahead.
	 */
	public override List<String> getValidationErrors()
	{
		List<String> errors = new List<String>();
		Contact record = (Contact)new SEL_Contacts().findById(apiCall.kern__TriggeringRecordId__c);

		if(String.isBlank(record.Email))
		{
			errors.add(ERROR_NO_EMAIL);
		}

		return errors;
	}

	@JsonAccess(serializable='always' deserializable='always')
	public class DTO_Request extends kern.DTO_JsonBase
	{
		/** @description The recipient address. */
		private String recipient;

		/**
		 * @description Fills the request from the triggering Contact.
		 *
		 * @param recordId The Id of the triggering record.
		 *
		 * @param params The call's input parameters.
		 */
		public override void populate(Id recordId, kern.DTO_NameValues params)
		{
			super.populate(recordId, params);
			Contact record = (Contact)new SEL_Contacts().findById(recordId);
			this.recipient = record.Email;
		}
	}

	@JsonAccess(serializable='always' deserializable='always')
	public class DTO_Response extends kern.DTO_JsonBase
	{
		/** @description The message ID from the gateway. */
		private String messageId;
	}
}
```

**Rules:** `with sharing` | Default POST for outbound (override `getHttpMethod()` if different) | `super.configure()` first | `super.getRequiredInputs()` and add | `@TestVisible`
param constants | `defaultMockBody` in configure | DTO props `private` + ApexDoc | `@JsonAccess` on all DTOs | Extend `kern.DTO_JsonBase` | `super.populate()` first

**Triggering record:** the inherited `apiCall` property (`kern__ApiCall__c`, populated before `getValidationErrors()` runs) carries the triggering record id. Note the
field is namespaced from your org: `apiCall.kern__TriggeringRecordId__c`, not `apiCall.TriggeringRecordId__c`. Other inherited members you can read: `setting` |
`request` | `response` | `requestPayload` | `responsePayload` | `requiresTriggeringRecord` | `baseUrl` | `defaultMockBody` | `result` | `errorText` | `correlationId` |
`inputs`. Your selector must declare every field you then read — `findById` selects only the selector's declared fields, so a `SEL_Contacts` that omits
`Contact.Email` throws `SObjectException: SObject row was retrieved via SOQL without querying the requested field`.

**Refusal in a success body:** when the external system answers a success status but its body says it refused the request (an order answered 200 with
status `REJECTED`), throw `kern.UTIL_Exceptions.RequestRefusedException` from `parseResponse()`. The call ends `Failed` at once and is not retried on its own, and
the issue it leaves says the external system did not act, so Retry Selected on the API Issues list can run it again once the cause is fixed. Thrown anywhere
else it stops automatic retries as `kern.UTIL_Exceptions.PermanentFailureException` does; wherever it is thrown,
it never ticks the call's Permanent Failure box. Set `responsePayload` in `configure()` so `super.parseResponse()` reads the body into it.

### API Custom Metadata Configuration (REQUIRED for both Inbound and Outbound)

**An API service will NOT execute without an `ApiSetting__mdt` record.** Always generate it alongside the API class.

**File naming:** `kern__ApiSetting.{ServiceName}.md-meta.xml`

**ApiSetting fields** (same XML wrapper as trigger metadata):

| Field                     | Outbound                          | Inbound                                   |
|---------------------------|-----------------------------------|-------------------------------------------|
| `kern__ClassName__c`      | Handler class name (no namespace) | Same                                      |
| `kern__Direction__c`      | `Outbound`                        | `Inbound`                                 |
| `kern__EndpointPath__c`   | API path (e.g., `/notifications`) | REST route pattern (e.g., `/v1/person/*`) |
| `kern__IsActive__c`       | `true`                            | `true`                                    |
| `kern__MockingEnabled__c` | `false`                           | `false`                                   |
| `kern__LogIssues__c`      | `true`                            | `true`                                    |
| `kern__Priority__c`       | `100.0`                           | `100.0`                                   |
| `kern__ApiCredential__c`  | Named Credential DeveloperName    | —                                         |

`kern__LogIssues__c` `true` on an inbound setting writes a `kern__ApiIssue__c` per failed request; set it `false` when the caller handles failures
itself.

Leave `kern__MockingEnabled__c` `false`. The box picks a service for mocking, inbound or outbound, and it takes effect only for users the
`MockSelectedAPIs` feature flag is on for. For them an inbound service returns a mock response (a matching API Mock record, or a default
body when none matches) instead of running its handler, and an outbound service answers a matching API Mock record or the handler's
`defaultMockBody` instead of calling the real system (with neither, it fails with a configuration error). The box alone, or the flag alone,
mocks nothing. Set it only while testing, never in production.

DeveloperName (filename) should match class without `API_` prefix (e.g., `kern__ApiSetting.SendNotification`).

**Copy-paste XML reference** (ApiSetting — outbound).

```xml
<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <label>Send Notification</label>
    <protected>false</protected>
    <values><field>kern__ClassName__c</field><value xsi:type="xsd:string">API_SendNotification</value></values>
    <values><field>kern__Direction__c</field><value xsi:type="xsd:string">Outbound</value></values>
    <values><field>kern__EndpointPath__c</field><value xsi:type="xsd:string">/notifications</value></values>
    <values><field>kern__IsActive__c</field><value xsi:type="xsd:boolean">true</value></values>
    <values><field>kern__MockingEnabled__c</field><value xsi:type="xsd:boolean">false</value></values>
    <values><field>kern__LogIssues__c</field><value xsi:type="xsd:boolean">true</value></values>
    <values><field>kern__Priority__c</field><value xsi:type="xsd:double">100.0</value></values>
</CustomMetadata>
```

**Copy-paste XML reference** (ApiSetting — inbound).

```xml
<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <label>Get Person</label>
    <protected>false</protected>
    <values><field>kern__ClassName__c</field><value xsi:type="xsd:string">API_PersonRetrieve</value></values>
    <values><field>kern__Direction__c</field><value xsi:type="xsd:string">Inbound</value></values>
    <values><field>kern__EndpointPath__c</field><value xsi:type="xsd:string">/v1/person/*</value></values>
    <values><field>kern__IsActive__c</field><value xsi:type="xsd:boolean">true</value></values>
    <values><field>kern__LogIssues__c</field><value xsi:type="xsd:boolean">true</value></values>
    <values><field>kern__Priority__c</field><value xsi:type="xsd:double">100.0</value></values>
</CustomMetadata>
```

### Outbound Test Pattern

```apex
@SuppressWarnings('PMD.ApexUnitTestClassShouldHaveRunAs')
@IsTest(seeAllData=false isParallel=true)
private class API_SendNotification_TEST
{
	private static final String SERVICE_NAME = API_SendNotification.class.getName();

	@IsTest
	private static void shouldCompleteSuccessfully()
	{
		Contact record = (Contact)kern.TST_Builder.of(Contact.SObjectType)
			.withOverride(Contact.Email, 'test@example.com').build();
		Map<String, String> parameters = new Map<String, String>
		{
			API_SendNotification.PARAM_RECIPIENT => 'recipient@example.com'
		};
		kern.API_OutboundTestHelper.assertCallSuccessful(SERVICE_NAME, record.Id, parameters);
	}
	// Abort: build record missing required data → assertCallAborted(SERVICE_NAME, record.Id, parameters)

	@IsTest
	private static void shouldFailWhenApiReturnsError()
	{
		kern.API_MockFactory.registerErrorMock(SERVICE_NAME);
		Contact record = (Contact)kern.TST_Builder.of(Contact.SObjectType)
			.withOverride(Contact.Email, 'test@example.com').build();
		kern__ApiCall__c apiCall = kern.TST_Factory.newOutboundApiCall(SERVICE_NAME, record.Id);
		kern.API_OutboundTestHelper.assertCallFailed(new List<kern__ApiCall__c>{ apiCall });
	}
}
```

### API_MockFactory

```apex
kern.API_MockFactory.forService(SERVICE_NAME).body('{"id":"123"}').statusCode(200).register();
kern.API_MockFactory.registerErrorMock(SERVICE_NAME);
kern.API_MockFactory.wasCalled(SERVICE_NAME);
```

---

## Inbound Web Services

**Two-class:** `REST_*` (routing, `global with sharing`) + `API_*` (logic, `public with sharing`, extends `kern.API_Inbound`).

### REST Routing Class

```apex
@RestResource(urlMapping='/v1/contact-form/*')
global with sharing class REST_ContactForm
{
	@HttpPost
	global static void submitForm()
	{
		kern.API_Dispatcher.processInboundService(API_ContactFormSubmit.class.getName());
	}
}
```

### API Handler

`public with sharing class API_* extends kern.API_Inbound`. Same pattern as Outbound (`configure()`, `getValidationErrors()`, DTOs extend `kern.DTO_JsonBase`) plus:

- **`onSuccess()`** — DML via inherited `doInsert()`/`doUpdate()`/`doDelete()` (NOT `kern.DML_Builder`). These saves run in `SYSTEM_MODE` (object and field
  permissions not checked); when a save must enforce the running user's permissions, use `kern.DML_Builder.newTransaction().withUserMode()…execute()` in
  its own transaction
- **`updateResponseDTO()`** — runs after commit, populate response DTO from `result.isSuccess`
- Both Request and Response DTOs: `@JsonAccess(serializable='always' deserializable='always')`, `public` props
- No manual `JSON.serialize()` — framework serializes DTOs

**Failed requests and API issues:** every request leaves a `kern__ApiCall__c` that keeps the request (a body too long for `kern__Request__c` is kept whole
in a file on the call; `kern__IdempotencyKeyBodyHash__c` holds the body's SHA-256 on every inbound call). With `kern__LogIssues__c` true, a request that
fails (`processRequest()` or `onSuccess()` throws, the commit rolls back, the setting's switches refuse it, `getValidationErrors()` returns errors or
throws, or a `handleError()` override throws) also leaves one Open `kern__ApiIssue__c` linked to the call; it holds no copy of the request. No issue
for a body that cannot be read (for example JSON that does not parse: the call ends Aborted with 500 before any handler runs), a 409, a stored answer,
a mock, an error status the handler answers on purpose, or Safe Mode. The issue never changes the caller's HTTP status.
Throw `kern.UTIL_Exceptions.PermanentFailureException` from `processRequest()`, `onSuccess()` or `getValidationErrors()` for a request that can never
work: the call is ticked `kern__IsPermanentFailure__c` and Retry refuses it. Its subclass `kern.UTIL_Exceptions.RequestRefusedException` does not tick
it, so the call stays open to Retry. Returned validation errors are not permanent.

**Key link:** the caller owns the retry. A retry is linked to the earlier failure only when it sends the same `Idempotency-Key` and the service has
`kern__IdempotencyEnabled__c` true; without a key nothing is linked. A key belongs to its service and to the user who sent it: the same key from
another user is a new request (no link, no resolve, no stored answer). A same-body retry sets `kern__PreviousAttempt__c` to the failed call; a 2xx success
with the same key, with `kern__ResolveIssues__c` also true, resolves every earlier attempt's open issue, whatever its body; a keyed retry that fails
while an earlier attempt has an open issue writes none. Tell callers to send a fresh UUID per request and reuse it only to resend that request.

**Replay (opt-in):** Retry on an inbound issue runs the request again in the org only when `kern__RetryIssues__c` is true; leave it false when the
caller retries. It reads the request from the issue's call, sends it to the issue's service and links the new call through `kern__PreviousAttempt__c`. It
refuses, with a label and nothing run, a service that is paused, a call ticked `kern__IsPermanentFailure__c`, a stored body whose hash differs from the
recorded one (masked or cut), a cut address or parameters, and an issue with no call and no request of its own. When the service has `kern__IdempotencyEnabled__c`
true, the key is checked as the original sender, so a request the caller already completed gets its stored answer. A failed replay writes no new issue.
Outbound Retry also refuses a permanent
call and links its new call through `kern__PreviousAttempt__c`. **Dismiss** on an issue marks it Resolved without running anything (Retry API Issue
permission). A handler that saves outside its inherited `doInsert()`/`doUpdate()`/`doDelete()` is not safe to replay.

**Delete guard:** no user and no purge can delete a `kern__ApiCall__c` with an Open issue (label `DeleteApiCall_OpenIssue`); resolve or dismiss the
issue first. The purge leaves such calls out when its user can read every open issue (Kern Administrator), and does not start for calls when its
user cannot read API issues. `TRG_Base.bypass(...)` on the trigger lifts the guard, as it lifts the delete permission check.

### Inbound Test Pattern

```apex
kern.API_InboundTestHelper.assertCallSuccessful(SERVICE_NAME, request);
kern.API_InboundTestHelper.assertCallAborted(SERVICE_NAME, new DTO_Request(), 'error message');
```

**REST routing test** (separate class, suppress `PMD.ApexUnitTestClassShouldHaveAsserts`):

```apex
kern.API_InboundTestHelper.setupRestContext(request);
Test.startTest();
REST_ContactForm.submitForm();
Test.stopTest();
kern.SEL_ApiCall.assertServiceCompleted(API_ContactFormSubmit.class.getName());
```

---

## Flow Invocables (FLOW_*)

```apex
public with sharing class FLOW_CreateAccount
{
	@InvocableMethod(category='Account Management' label='Create Account' description='Creates an Account.')
	public static List<DTO_Response> execute(List<DTO_Request> requests)
	{
		if(requests == null || requests.size() != 1)
		{
			throw new IllegalArgumentException('FLOW_CreateAccount expects a single request');
		}
		DTO_Request request = requests.iterator().next();

		Account account = new Account(Name = request.accountName);
		kern.DML_Builder.TransactionResult result = kern.DML_Builder.newTransaction().doInsert(account).execute();

		DTO_Response response = new DTO_Response();
		response.accountId = account.Id;
		response.success = result.isSuccess();
		return new List<DTO_Response>{ response };
	}

	public class DTO_Request
	{
		@InvocableVariable(label='Account Name' description='The name for the new Account' required=true)
		public String accountName;
	}

	public class DTO_Response
	{
		@InvocableVariable(label='Account ID' description='The ID of the created Account')
		public Id accountId;

		@InvocableVariable(label='Success' description='Whether the operation succeeded')
		public Boolean success;
	}
}
```

**Rules:** `public with sharing` on class + DTOs | guard `requests.size() == 1` with a platform-native `IllegalArgumentException` | `@InvocableVariable` with Label/Description/Required |
`@InvocableMethod` with Category/Label/Description | `kern.DML_Builder` for DML | Method takes `List<DTO_Request>`, returns `void` or `List<DTO_Response>`

**Shipped action you may call:** `kern.FLOW_RetryApiIssues.retryApiIssues` (Flow label **Retry API Issues**, category **Api Callouts**) runs the failed calls of
the API issues you pass again, in one background job. Pass exactly one `kern.FLOW_RetryApiIssues.DTO_Request` with `apiIssueIds` (`List<String>`); it answers
one `DTO_Response` with `jobId`, `queuedCount`, `success` and `message`. The running user needs the Retry API Issue permission, or nothing is queued.

### Flow Test Pattern

```apex
@SuppressWarnings('PMD.ApexUnitTestClassShouldHaveRunAs')
@IsTest(seeAllData=false isParallel=true)
private class FLOW_CreateAccount_TEST
{
	@IsTest
	private static void shouldCreateAccount()
	{
		FLOW_CreateAccount.DTO_Request request = new FLOW_CreateAccount.DTO_Request();
		request.accountName = 'Test Account';

		Test.startTest();
		List<FLOW_CreateAccount.DTO_Response> responses =
			FLOW_CreateAccount.execute(new List<FLOW_CreateAccount.DTO_Request>{ request });
		Test.stopTest();

		Assert.isTrue(responses[0].success, 'Should succeed');
	}

	@IsTest
	private static void shouldThrowWhenNoRequests()
	{
		try
		{
			FLOW_CreateAccount.execute(new List<FLOW_CreateAccount.DTO_Request>());
			Assert.fail('Should throw IllegalArgumentException');
		}
		catch(Exception error)
		{
			Assert.isInstanceOfType(error, IllegalArgumentException.class, 'Incorrect Exception Type');
		}
	}
}
```

---

## Logging (LOG_Builder)

**Never `System.debug()`.** Use platform event logging:

```apex
kern.LOG_Builder.build().error(e).emitAt('MyClass.myMethod');
kern.LOG_Builder.build().info('Done').emitAt('MyClass.myMethod');
kern.LOG_Builder.build().warn('Threshold exceeded').emitAt('MyClass.myMethod');

// Long form
kern.LOG_Builder.build()
	.error('Payment failed')
	.at('PaymentService.charge')
	.forRecord(paymentId)
	.withContext('amount', payment.Amount__c)
	.emit();

// Scoped
kern.LOG_Builder.LogScope scope = kern.LOG_Builder.scope();
kern.LOG_Builder.build().info('Step 1').emitAt('MyClass.step');
scope.close();
```

**Levels:** `.error(Exception/String)` | `.warn(String)` | `.info(String)` | `.debug(String)` (also `List<String>`)
**Chain:** `.at(String)` | `.forRecord(Id)` | `.withContext(key, value)` | `.withSummary(String)`
**Terminal:** `.emitAt(String)` (shorthand) | `.emit()`

**Attribution:** the engine stamps `Origin__c` (FRAMEWORK, APEX, FLOW, COMPONENT) and `Source__c` (the writing class, Flow or component, as a plain name) on every entry from what you pass to `.at()` and the context it runs in. Never set them yourself; group reports by them.

---

## Testing

### Structure

`@IsTest(seeAllData=false isParallel=true) private class MyClass_TEST` — Constants → @IsTest methods → helpers → inner classes.

### TST_Builder

```apex
Account account = (Account)kern.TST_Builder.of(Account.SObjectType).build();                           // inserted
Account inMemory = (Account)kern.TST_Builder.of(Account.SObjectType).withoutInsertion().build();        // in-memory
Account mockId = (Account)kern.TST_Builder.of(Account.SObjectType).withoutInsertion(true).build();      // mock ID
Account custom = (Account)kern.TST_Builder.of(Account.SObjectType)
	.withOverride(Account.Industry, 'Tech').build();                                                     // override
List<SObject> bulk = kern.TST_Builder.of(Account.SObjectType).withCount(5).buildList();                  // bulk
Account parent = (Account)kern.TST_Builder.of(Account.SObjectType)
	.withChildren(Contact.SObjectType, 3).build();                                                       // children
```

### TST_Mock (DML-free)

```apex
Account mock = (Account)kern.TST_Mock.of(Account.SObjectType)
	.withOverride(Account.Name, 'Test').build();
// Selector queries now return mock data
```

**Negative-path:** `kern.TST_Mock.throwsException(SObjectType[, Exception/String])` makes any query against the
type throw -- use to exercise catch blocks without mocking at a different layer. Exception fires before record
path when both are registered; cleared by `kern.TST_Mock.clear()` / `kern.TST_Mock.clear(SObjectType)`.

```apex
kern.TST_Mock.throwsException(Account.SObjectType, new QueryException('Simulated failure'));
try
{
	new SEL_Accounts().findById(someAccountId);
	Assert.fail('Expected QueryException');
}
catch(QueryException error)
{
	Assert.areEqual('Simulated failure', error.getMessage(), 'Caught the simulated failure');
}
```

**Consecutive queries, different answers:** `kern.TST_Mock.registerNext(SObjectType, List<SObject>)` (and a single-record
overload) scripts the NEXT query or count only; answers serve in registration order, one query each, then the type returns to
its registered records or the database. An empty list scripts "finds nothing". A registered exception fires first and leaves
the queue in place. `clear()` / `clear(SObjectType)` drop queued answers and remove the registration, so a cleared type queries
the database.

```apex
kern.TST_Mock.registerNext(Account.SObjectType, new List<SObject>()); // the next read misses
// the read after that: registered records, else the database
```

**Aggregate queries:** `kern.TST_Mock.registerAggregateRows(SObjectType, List<Map<String, Object>>)` (or one `Map` for `getFirstAggregate()`) answers every aggregate read
on the type, and a second call adds rows (`QRY_Builder.setAggregateMock` replaces them); `registerNextAggregateRows` (same overloads) answers the next one only. Keys are the aliases (`count(Account.Id, 'total')` → `'total'`; default alias
`<function>_<field API name>`, namespace prefix included); only `LIMIT` applies. Record mocks alone make an aggregate read throw: register aggregate rows (an empty list for
"finds nothing"). The terminal `.count()` reads record mocks, never aggregate rows. A `null` list throws; drop rows with `clear()` / `clear(SObjectType)`.

```apex
kern.TST_Mock.registerAggregateRows(Account.SObjectType, new Map<String, Object>{ 'total' => 3 });
Integer total = new SEL_Accounts().query.count(Account.Id, 'total').getFirstAggregate().getInteger('total');
```

### TST_Factory

`kern.TST_Factory.newFeatureFlag(flagName)` | `.newOutboundApiCall(service, recordId[, params])` | `.newInboundApiCall(service)` | `.newUser(profileName[, companyName])` |
`.insertUser(profileName[, companyName])`

For trigger-action tests, invoke the handler directly on in-memory records built with `kern.TST_Builder.of(SObjectType).withoutInsertion().build()` (see the Trigger Test Pattern
above). For custom-validation tests, deploy the rule as Custom Metadata, then assert with `kern.UTIL_ValidationTestHelper.assertRuleFails(record, ruleName)` /
`.assertRulePasses(record, ruleName)`.

### Exception Testing

```apex
try
{
	methodThatShouldThrow();
	Assert.fail('Should throw IllegalArgumentException');
}
catch(Exception error)
{
	Assert.isInstanceOfType(error, IllegalArgumentException.class, 'Incorrect Exception Type');
}
```

**Never use `Boolean exceptionThrown`.**

---

## Lightning Web Components

**Never `LightningElement`.** Always `ComponentBuilder`.

**⚠ CRITICAL: The import MUST use the package namespace, not `c/`:**

```javascript
WRONG: import { ComponentBuilder } from 'c/componentBuilder';     // WILL NOT RESOLVE
RIGHT: import { ComponentBuilder } from 'kern/componentBuilder';  // Correct namespace
```

```javascript
import { ComponentBuilder } from 'kern/componentBuilder';  // MUST be kern/, not c/

export default class MyComponent extends ComponentBuilder('notification', 'controller')
{
	async handleSave()
	{
		try
		{
			await this.callControllerMethod('saveRecord', { account: this.account });
			this.showSuccessToast('Saved');
		}
		catch(error)
		{
			this.showErrorToast(error);
		}
	}
}
```

**Modules:** `notification` (showSuccess/Error/Warning/InfoToast) | `controller` (callControllerMethod, handleWireResponse) | `navigation` (redirectToRecordPage,
generateRecordPageURL) | `flow-navigation` (dispatchFlowNext/Back/FinishEvent) | `lightning-message` (addMessageChannelSubscription, publishLightningMessage) | `all`

**Base (always):** `dispatchCustomEvent()` | `consoleLog()` | `consoleError()` | `isLoading`

**HTML:** Lightning base components only (not raw HTML). **Meta:** apiVersion 68.0, isExposed true.

### Jest Test Pattern

```javascript
jest.mock('kern/componentBuilder', () => ({
	ComponentBuilder: jest.fn().mockImplementation(() =>
	{
		const { LightningElement } = require('lwc');
		return class extends LightningElement
		{
			showSuccessToast = jest.fn();
			showErrorToast = jest.fn();
			callControllerMethod = jest.fn().mockResolvedValue({});
		};
	})
}), { virtual: true });
```

---

## DTOs

Extend `kern.DTO_JsonBase` + `@JsonAccess(serializable='always' deserializable='always')`.

- **Standalone** (separate file, exposed to UI): `@AuraEnabled public` props
- **Nested** (inside API class): `private` props + ApexDoc
- Always `super.populate()` first in `populate()` overrides
- Use `SEL_*` in `populate()` — no inline SOQL

---

## Framework Utilities

`kern.UTIL_Exceptions` (IllegalState/Configuration/NotFoundException) | `kern.UTIL_Cache` | `kern.UTIL_CircuitBreaker` | `kern.UTIL_Retry` |
`kern.UTIL_FeatureFlag.isEnabled(flagName)` | `kern.UTIL_TypeResolver` | `kern.UTIL_String` | `kern.UTIL_Date` | `kern.UTIL_List` | `kern.UTIL_Map` |
`kern.UTIL_SObject` | `kern.UTIL_Email` | `kern.UTIL_Random` | `kern.UTIL_SObjectDescribe` (request-cached describe wrapper — `getDescribe(sObjectType)` **or `getDescribe(String objectApiName)`** — BOTH return a `kern.UTIL_SObjectDescribe` instance (the wrapper itself, NOT a native `Schema.DescribeSObjectResult`); the String overload returns null for an unknown/blank name, resolving an object API name to the wrapper WITHOUT raw `Schema.getGlobalDescribe()`. On the returned wrapper call `.getField(name)` (namespace-aware by default), `.getFieldDescribe(name)`
returns cached `DescribeFieldResult` with `isUpdateable`/`isCreateable`; static `getCachedFieldDescribe(SObjectField)` / `getCachedFieldName(SObjectField)` for token-keyed lookups;
never use raw `Schema.getGlobalDescribe()` / `fields.getMap()` from package code — namespace handling is the trap that bites)

**The roster above is a selection, not the whole surface** — other pillars in this document cover `kern.UTIL_AsyncChain`, `kern.UTIL_HttpClient`,
`kern.UTIL_ValidationRule`, `kern.UTIL_System`, `kern.UTIL_Limits` and more. The reference-page rule at the top of this document is the authority.
**Some `UTIL_*` classes read like general-purpose helpers but are framework-internal and will not compile from a subscriber org:** `UTIL_Set`,
`UTIL_Comparators`, `UTIL_Crypto`, `UTIL_CronExpression`, `UTIL_NumberRange`, `UTIL_Boolean`, `UTIL_Character`. Check for a
`docs/reference/apex/<ClassName>.md` page before reaching for any `UTIL_*` name you have not seen used here. There is no `UTIL_Number` or
`UTIL_Security` in any version.

### Framework-shipped Feature Flags

These pre-built `FeatureFlag__mdt` records ship with the package. Query via `kern.UTIL_FeatureFlag.isEnabled('FlagDeveloperName')`; flip values by deploying an override record that
sets `IsEnabledByDefault__c` (and, if strategies are attached, `ResultOnNoMatch__c`).

| Flag                       | Default | Purpose                                                                                                                                                                                                          |
|----------------------------|:-------:|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `UserModeQueries_Enabled`  | `true`  | Drives the default `AccessLevel` on `kern.QRY_Builder` / `kern.SEL_Base`. When `true` queries run USER_MODE (CRUD+FLS+sharing enforced); when `false` they fall back to SYSTEM_MODE. Emergency kill switch only. |
| `UserModeDml_Enabled`      | `true`  | Same for `kern.DML_Builder` writes (insert/update/delete/upsert/undelete).                                                                                                                                       |
| `MaskingFramework_Enabled` | `true`  | Master switch for the data-masking framework (`MaskingRule__mdt` + `MaskingTarget__mdt`).                                                                                                                        |
| `AsyncChain`               | `true`  | Master kill switch for `kern.UTIL_AsyncChain`. When `false` new chain executions abort immediately.                                                                                                              |
| `DisableAllAPIs`           | `false` | Disables both inbound and outbound calls through the web-services framework.                                                                                                                                     |
| `DisableAllInboundAPIs`    | `false` | Disables inbound `kern.API_Inbound` routing only.                                                                                                                                                                |
| `DisableAllOutboundAPIs`   | `false` | Disables outbound `kern.API_Outbound` calls only.                                                                                                                                                                |
| `MockAllAPIs`              | `false` | Returns mock responses for every outbound call (tests + dry runs).                                                                                                                                               |
| `MockAllInboundAPIs`       | `false` | Returns mock responses for every inbound call.                                                                                                                                                                   |
| `MockSelectedAPIs`         | `false` | Returns mock responses, inbound and outbound, only for services whose `kern__ApiSetting__mdt` has `kern__MockingEnabled__c` ticked, for the users the flag is on for. Ships active with no strategies. In a test, `kern.TST_Factory.newFeatureFlag('MockSelectedAPIs')` turns it on. Never create a same-named flag record in your own namespace: it would decide the flag in place of the packaged one. |
| `BypassApiRecordDeleteGuard` | `false` | Decides who may delete `ApiCall__c` / `ApiIssue__c` (UI, flow, Apex and `SCHED_PurgeRecords` alike). A built-in protected strategy turns it on for holders of the `DeleteApiRecords` custom permission (Kern Administrator). Widen it with a strategy per profile/permission set/user, or `ResultOnNoMatch__c = true` for everyone (`IsEnabledByDefault__c` is ignored, a strategy exists). Deactivated, it refuses every delete and Health Check warns. |
| `AsyncChainAbort_Enabled`  | `false` | Gates the abort action in the Chain Monitor. A built-in protected strategy turns it on for holders of the `AbortAsyncChain` custom permission. Deactivate the record to switch it off. |
| `AsyncChainKillSwitch_Enabled` | `false` | Gates the suspend and resume controls in the Chain Monitor. A built-in protected strategy turns it on for holders of the `ManageAsyncChainKillSwitch` custom permission. Deactivate the record to switch it off. |
| `AsyncChainRedrive_Enabled` | `false` | Gates the re-drive actions in the Chain Monitor. A built-in protected strategy turns it on for holders of the `RedriveAsyncChain` custom permission. Deactivate the record to switch it off. |
| `BypassAudit_Enabled`      | `true`  | Kill switch for the bypass audit: when `true`, every bypass call emits a log entry with category `BypassEvent`.                                                                                                      |
| `ScheduledJobRunner`       | `true`  | Turns the shared job runner off without deleting anything: while disabled it still checks on schedule but starts no job, and every job on the runner waits.                                                      |
| `TestFeatureFlag`          | `true`  | Example / smoke-test flag. Safe to leave as-is.                                                                                                                                                                  |

---

## Data Masking (declarative, no subscriber code)

Sensitive-data redaction is declarative — subscribers configure `MaskingRule__mdt` + `MaskingTarget__mdt` records, there is no subscriber-written Apex class. The framework runs
masking as a before-insert / before-update pre-step on the trigger dispatcher for package-owned objects (`ApiCall__c`, `ApiIssue__c`, `AsyncChainExecution__c`, `LogEntryEvent__e` /
`LogEntry__c`).

**Ship set:** 18 `MaskingRule__mdt` records (3 active by default: `MaskSecretKeys` JSON-key redaction, `MaskPaymentCard` Luhn-validated card redaction and `MaskJwt` JSON Web
Token redaction; 15 inactive: templates for SSN, email, phone, IBAN, SWIFT, Medicare, AWS keys, postal address, free text, IPv4, etc., plus `MaskCreditCard`, the original card
rule that `MaskPaymentCard` replaces). 14 `MaskingTarget__mdt` wildcard records: the card and secret rules on all four logged objects, and `MaskJwt` on `ApiCall__c` and
`ApiIssue__c`; the four `*_All_Card` targets of `MaskCreditCard` ship inactive, and the rule and its targets are switched on or off together. Where the payment-card and
credit-card rules are both active on the same object, the payment-card rule does the work unless a setting that decides what either rule masks was changed (a changed
`FailureAction__c` does not count). Both card rules ship with `WriteFailureMarker`.
**Caller-class scope:** a target with `CallerClass__c` set fires only on `ApiCall__c` and `ApiIssue__c` records whose service's API setting names that handler class (and in the
Advisor preview); saves of every other object have no caller, so only targets with a blank `CallerClass__c` apply there.

**Mode picklist values on `MaskingRule__mdt.Mode__c`:** `Regex`, `JsonKey`, `ExactMatch`, `CreditCard`.
**Optional short-circuit fields:** `MinInputLength__c` (skip rule for shorter values; a `JsonKey` rule ignores it) and `ApplicableFieldTypes__c` (semicolon-delimited `System.DisplayType` names — e.g.,
`STRING;TEXTAREA;ENCRYPTEDSTRING`).
**Failure handling:** `MaskingRule__mdt.FailureAction__c` = `LogAndContinue` (the value is saved unmasked and the rule is skipped for the rest of the transaction) /
`WriteFailureMarker` (the default and the shipped choice: `[MASKING_FAILURE]` is saved in place of each value the rule fails on, the rule keeps running on the others, and a pattern
that cannot compile marks every value it covers) / `BlockDml` (throws `kern.UTIL_Exceptions.MaskingBlockedException`: a record save fails, an outbound call attaches no payload
files, a log entry is dropped).
**Kill switch:** `FeatureFlag.MaskingFramework_Enabled` (default `true`). Per-object opt-out: `TriggerSetting__mdt.ApplyMasking__c`.
**Performance logging (opt-in):** `LogSetting__c.EnableMaskerPerformanceLogging__c = true` with `LogSetting__c.MaskerPerformanceThresholdMs__c` (default 100 ms) emits
`LogEntryEvent__e` for batches exceeding the threshold.

Subscribers extend the default ship set by deploying additional `MaskingRule__mdt` + `MaskingTarget__mdt` records; no Apex needed.

---

## Async Chain Orchestration

`kern.UTIL_AsyncChain` — sequences steps across Queueable transactions with shared state, error handling, and progress tracking.

```apex
kern.UTIL_AsyncChain.newChain('DataMigration')
	.then(new LoadDataStep())
	.then(new TransformDataStep(), true)
	.withInitialContext('batchSize', 200)
	.onError(new NotifyAdminStep())
	.execute();
```

**IF_Chain.Step interface:** Implement `kern.UTIL_AsyncChain.StepResult work(kern.UTIL_AsyncChain.ChainContext context)` or extend `kern.UTIL_AsyncChain.ChainStep` (abstract, adds
the `stepName` field and the `isIdempotent()` declaration). **Never declare a constructor on a step class** — the framework recreates every step by class name in
each hop, and from inside the package only the implicit constructor of a class that declares none (or a global constructor on a global class) is reachable; a step
with its own `public` constructor fails on its first hop. Set `stepName` on the instance before handing it to the builder (`MyStep step = new MyStep(); step.stepName =
'Load accounts'; ...then(step)`); the builder records it at build time.

```apex
public with sharing class LoadDataStep extends kern.UTIL_AsyncChain.ChainStep
{
	public override kern.UTIL_AsyncChain.StepResult work(kern.UTIL_AsyncChain.ChainContext context)
	{
		List<Account> accounts = new SEL_Accounts().toList();
		context.put('accountCount', accounts.size());
		return kern.UTIL_AsyncChain.succeeded('Loaded ' + accounts.size() + ' accounts');
	}
}
```

**ChainBuilder:** `.then(step)`/`.then(step, continueOnError)`/`.withInitialContext(key, value)`/`.withMaxSteps(n)`/`.withMaxContextSize(n)`/`.withDelayMinutes(n)`/`.withDeduplicationKey(key)`/`.allowRestart()`/`.withAsyncOptions(opts)`/`.onError(step)`/`.onComplete(step)`/`.execute()`/`.execute(correlationId)`
**Re-run declarations (both default off, except an `ApiStep` whose request is safe to repeat, which declares `isIdempotent()` itself; neither changes a normal run):** `public override Boolean isIdempotent() { return true; }` on a `ChainStep` (an override, never a constructor; declares the step safe to re-run, gating the Chain Monitor's retry-from-failed-step AND the watchdog's recovery after a stall) / `.allowRestart()` on the builder (declares the whole chain safe to restart from step 1 and captures the as-built context snapshot for the restart to replay)
**Stalled-step recovery:** the watchdog (`SCHED_ChainWatchdog`, and the Chain Monitor's Clear stalled button) re-runs a stalled step only if it never started or `isIdempotent()` returns true; a started step without the declaration ends the chain `Failed` (category Stalled) with a message telling the operator to check whether the step's work landed, then start a replacement. Declare `isIdempotent()` on every step that is safe to run twice. An `ApiStep` declares it by itself when its handler sends GET, PUT or DELETE, or its service setting has `IdempotencyEnabled__c`. On a slow queue, raise the watchdog's `StaleThresholdMinutes` (default 30): a step that waits in the queue past it also ends the chain `Failed`.
**ChainContext:** `.put(key, value)`/`.get(key)`/`.getAs(key, Type)`/`.has(key)`/`.getChainExecutionId()`/`.getCorrelationId()`/`.getPreviousStepResult()`/`.getCurrentStepIndex()`/`.idempotencyKey()`/`.idempotencyKey(recordId)`/`.idempotencyKey(grain)`/`.getAttempt()`/`.isFinalAttempt()`/`.isFinalAttempt(error)`
**StepResult:** `kern.UTIL_AsyncChain.succeeded()`/`.succeeded(msg)`/`.succeeded(msg, data)`/`.failed(msg)`/`.failed(exception)`/`.failedPermanently(msg)`/`.failedPermanently(exception)` — properties: `success`, `message`, `data`, `error`, `permanentFailure`
**ApiStep:** Wraps `kern.API_Outbound` handler as a chain step:

```apex
new kern.UTIL_AsyncChain.ApiStep(API_SendEmail.class)
	.credential('Gateway')
	.withParameter(API_SendEmail.PARAM_RECIPIENT, 'test@example.com')
	.withParameterFrom('subject', 'emailSubject')
	.triggeringRecordFrom('recordId')
	.withRetry(3, 30).retryOn(new Set<Integer>{500, 503})
```

**Status:** `kern.UTIL_AsyncChain.getStatus(chainExecutionId)` → `Map<String, Object>`

---

## Schedulable Framework

Subscriber schedulable classes use `inherited sharing` and extend `kern.SCHED_Base`. The framework creates them by name, so make the class
`global` (as below), or keep it `public` and set up a Type Resolver (see the Access rule under Sharing & Access by Class Type).

```apex
@SuppressWarnings('PMD.AvoidGlobalModifier')
global inherited sharing class SCHED_PurgeOldRecords extends kern.SCHED_Base
{
	/**
	 * @description Declares the parameters an administrator sets on the scheduled job.
	 *
	 * @return The parameter definitions.
	 */
	public override List<kern.DTO_ScheduledParameterDefinition> getParameterDefinitions()
	{
		return new List<kern.DTO_ScheduledParameterDefinition>
		{
			kern.DTO_ScheduledParameterDefinition.of('objectName').required(),
			kern.DTO_ScheduledParameterDefinition.of('batchSize').asNumeric().withDefault('2000')
		};
	}

	/**
	 * @description Reads the parameters and runs the purge.
	 *
	 * @param context The context the platform passes to a scheduled job.
	 */
	public void execute(SchedulableContext context)
	{
		String objectName = getTextParameter('objectName');
		Integer batchSize = getNumericParameter('batchSize');
	}
}
```

**SCHED_Base accessors:** `getTextParameter(name)`/`getNumericParameter(name)`/`getBooleanParameter(name)`
**DTO_ScheduledParameterDefinition:** `.of(name)` → `.required()`/`.asNumeric()`/`.asBoolean()`/`.withDefault(value)`/`.withDescription(text)`

**Job runner (1.8):** a `ScheduledJob__c` record with `ExecutionMode__c = 'JobRunner'` runs on the shared runner (no `CronTrigger` of its own;
minutes may be `*/N`, lists or ranges; runs as the runner's activator; needs the `ManageJobRunner` custom permission to enter). Framework-owned fields,
never write them: `NextRunAt__c`, `LastRunAt__c`, `LastRunOutcome__c`, `LastRunReason__c`, `LastRunJobId__c`. Admin fields: `RunPriority__c`,
`OverlapPolicy__c` (`Skip` default, `Allow`). A job on the runner receives a `SchedulableContext` whose `getTriggerId()` is the run's `AsyncApexJob` id;
never pass it to `System.abortJob`. The runner's own records name `kern.SCHED_JobRunner` and are created only by Health Check.

---

## Common Agent Mistakes (beyond Critical Rules table above)

| #  | Wrong                                  | Right                                                                       |
|----|----------------------------------------|-----------------------------------------------------------------------------|
| 1  | DTO missing `@JsonAccess`              | `@JsonAccess(serializable='always' deserializable='always')`                |
| 2  | Missing `super.configure()`            | Always call `super.configure()` first                                       |
| 3  | Missing `super.populate()`             | Always call `super.populate()` first                                        |
| 4  | Missing `super.getRequiredInputs()`    | Call super and add to returned set                                          |
| 5  | `.toList()` on semi-join subquery      | Pass Builder directly to `.isIn()`/`.notIn()`                               |
| 6  | `new UTIL_HttpClient()`                | `kern.UTIL_HttpClient.post('Cred', '/path')`                                |
| 7  | `Boolean exceptionThrown`              | `Assert.fail` + `Assert.isInstanceOfType`                                   |
| 8  | Namespace missing in subscriber        | `kern.QRY_Builder`, `kern.SEL_Base`, `kern.TRG_Base`                        |
| 9  | `inherited sharing` in subscriber code | `with sharing` — except `SCHED_*` which uses `inherited sharing`            |
| 10 | `global` on selectors, services, flows | `public`; `global` only for `REST_*` and classes created by name (`SCHED_*` too) |
| 11 | Manual JSON.serialize in response      | Use `updateResponseDTO()` — framework serializes                            |
| 12 | `[SELECT ...]` in test classes         | Use the object's `SEL_*` selector even in tests                             |
| 13 | Missing `@SuppressWarnings` on tests   | `@SuppressWarnings('PMD.ApexUnitTestClassShouldHaveRunAs')` on test classes |
| 14 | `import from 'c/componentBuilder'`     | `import from 'kern/componentBuilder'` — must use package namespace          |
| 15 | Line break after `kern.Class` in a chain | Keep the first `.method()` on the class's line — a break compiles `kern` as a variable (`Variable does not exist: kern`) |
| 16 | `.cls` written without its `.cls-meta.xml` | Always create the paired `*-meta.xml` — a lone `.cls` is silently skipped (`No local changes to deploy`) |
| 17 | `triggerOldMap.get(id)` to pair old/new in an action | Build `new Map<Id, SObject>(oldRecords)` from the parameter — `triggerOldMap` is null outside live trigger context (`NullPointerException` in direct-invocation tests) |
| 18 | `Schema.getGlobalDescribe().get(name)` to resolve an object | `kern.UTIL_SObjectDescribe d = kern.UTIL_SObjectDescribe.getDescribe(name)` — returns the wrapper (type `kern.UTIL_SObjectDescribe`, NOT `Schema.DescribeSObjectResult`), null for an unknown name; then `d.getField(name)` |
| 19 | `request.headers.get('X-Partner-Id')` to read a request header | `(String)new kern.UTIL_Map.CaseInsensitiveMap(request.headers).get('X-Partner-Id')` — header names carry no case and many clients send them lower-case, so an exact-case lookup misses them |

---

## KernDX vs fflib

| Concept   | fflib                                        | KernDX                                               |
|-----------|----------------------------------------------|------------------------------------------------------|
| Selectors | `extends fflib_SObjectSelector`              | `extends kern.SEL_Base`                              |
| Queries   | `Database.query(newQueryFactory().toSOQL())` | `query.condition(...).toList()` inside the selector  |
| DML       | `fflib_SObjectUnitOfWork`                    | `kern.DML_Builder.newTransaction().execute()`        |
| Triggers  | `fflib_SObjectDomain`                        | `extends kern.TRG_Base implements kern.IF_Trigger.*` |
| Logging   | `System.debug()`                             | `kern.LOG_Builder.build().error(e).emitAt()`         |
