Skip to content
v1.12Apache 2.0API 68.0

Every Salesforce framework your team keeps rebuilding, in one Apex & LWC library.

Spend your team on the features that move the business, not on rebuilding the trigger framework, logging, security, and the rest of the plumbing every Salesforce org writes anyway. One managed package with the safe behaviour on automatically, open source on GitHub.

You write the line you expect. You get the depth you didn't: the safe behaviour on automatically, with logging, performance, and traceability built in.

Built to stay consistent after years of changes and dozens of contributors.

109global API classes
204production classes
78LWC components
100%Apex coverage · 6,380 tests

What it prevents

What happens when…

  • the trigger framework you copied into fifteen orgs has drifted in all fifteen, and the bug only reproduces in the one you didn't touch?
  • a query runs in system mode, skips the user's field permissions, and the security reviewer asks you to prove it didn't, with no single place to look?
  • a clean deploy finishes before the test suite that's supposed to guard it does, so the suite stops being a gate and starts being a formality?
  • the AI assistant writes Apex that compiles, passes review, and ignores every naming and bypass rule your team agreed on last quarter?

KernDX makes each one hard to reach: permissions on by default, one trigger path every org shares, every shortcut logged with the reason it was taken, and a standards file your AI assistant actually reads before it writes.

Why it exists

An accelerator you own, not a product you rent.

Most enterprise Salesforce orgs spend three to five years rebuilding the same foundations: selectors, trigger handling, logging, web services, async, masking, and field-level security (FLS) enforcement. They take on tech debt at every layer. The aim of KernDX is to skip the rebuild cycle, not pay to rent your way around it.

KernDX is the integrated package those teams would have built with the budget and design discipline upfront: one library of frameworks for Apex and Lightning Web Components (LWC), plus the onboarding docs, continuous-integration (CI) tooling, and enforced defaults (permissions on by default, audit-logged bypasses, a coverage gate run on every release) that keep those guarantees true after a dozen contributors.

And the architecture stays yours. The source is public under the Apache License 2.0, so you can read it, fork it, deploy it unmanaged, or repackage it under your own namespace. No black box and no lock-in: if you ever move off the managed package, the framework stays in your org as your code, not a vendor's.

What you get on day one

One install. The whole stack.

Each name opens its example below: the plain Salesforce way on the left, the KernDX way on the right. The guide for each feature is linked from its example.

Read and save data

Automate

Integrate

Build, test and run

Take only what you need. Every layer is opt-in: you can install KernDX for logging and the Log Console alone, and leave every existing trigger, query and class as it is.

Two parts lean on others. The code-scanning rules expect the other layers: they flag inline SOQL, hand-written DML, System.debug, raw Http calls and plain Schedulable classes, but they only report until you set a severity threshold. A Flow callout action needs one outbound service class to call.

The same task, with and without KernDX

You write the line you expect. You get the depth you didn't.

Plain Salesforce on the left, KernDX on the right. The KernDX samples use the managed package's kern. prefix, and every read in them goes through a selector.

The KernDX samples here use the managed package's kern. and kern__ prefixes. Samples in the guides sometimes leave them off: how to read the code samples.

Read and save data5 examples

Back to all features ↑

Paginate past 2,000 rows, and know when the data shifts under youSelectors Guide → Pagination

Plain Apex Manual

apex
// Page 82 of 25-row pages = OFFSET 2025 → governor blow-up
Integer offset = (pageNumber - 1) * pageSize; // over the 2,000 cap
List<Account> rows = [
	SELECT Id, Name FROM Account WHERE Type = 'Customer'
	ORDER BY Name ASC LIMIT :pageSize OFFSET :offset // ☠
];
Integer total = [SELECT COUNT() FROM Account]; // 2nd query
// FLS by hand. Rows deleted under you? You'll never know.

KernDX Included

apex
// SEL_Accounts is your own selector: a with sharing class extending kern.SEL_Base.
kern.QRY_Builder.QueryPage page = new SEL_Accounts().query
	.condition(Account.Type).equals('Customer')
	.orderBy(Account.Name).ascending()
	.getPage(82, 25); // no OFFSET wall, USER_MODE FLS on

page.records; // this page
page.totalRecords; // count came back — no 2nd query
page.totalPages; // computed for you
page.hasMorePages; // wire to a "Next" button
page.deletedRecords; // rows the cursor saw deleted

What you also get

5lines→8capabilities you didn't write

Reliability

Cursor paginationClears the 2,000-row OFFSET ceiling that plain LIMIT/OFFSET hits: getPage() runs and wires a pagination cursor for you.
Total count, no 2nd querypage.totalRecords folds into the same cursor call, with no separate COUNT() query.
Deleted-row trackingpage.deletedRecords flags rows the cursor saw deleted mid-fetch, not silently dropped.

Governance

USER_MODE by defaultRuns the running user's object and field permissions (CRUD and FLS) plus record sharing, with no hand-rolled checks.
Audited bypasswithSystemMode() opt-outs are logged to an audit trail.

Observability

Slow-query telemetryAny query at 1000ms or slower (the default) logs a performance entry. Fast queries stay silent.

Performance

Cache the read inlinewithCache(ttlSeconds) keeps this read in memory for the rest of the transaction, so a repeat costs no query. A system-mode read that states its sharing can be kept in Platform Cache for the chosen lifetime.

Testing

Inject mock recordsTST_Mock.of(type).build() serves mock records (with mock Ids and no DML) from the next query for that type.
What's actually happening

Salesforce exposes query cursors, but you normally wire one by hand. getPage() runs a pagination cursor for you, folds the row count into that same call instead of a second query, and reports what the cursor saw deleted mid-fetch. All of it runs in the running user's CRUD, FLS and sharing mode by default.

Create an Account, Opportunity, and Contact in a single atomic saveDML Fast Start → Parent-Child Insert

Plain Apex Manual

apex
Account newAccount = new Account(Name = name);
insert newAccount; // committed immediately
Opportunity newOpportunity = new Opportunity(
	Name = dealName, StageName = 'Prospecting',
	CloseDate = Date.today().addDays(30),
	AccountId = newAccount.Id); // manual FK stitch
Contact newContact = new Contact(
	LastName = lastName, AccountId = newAccount.Id);
insert newOpportunity;
insert newContact; // if this throws and the service catches it,
// the Account + Opportunity stay committed — orphaned. Safe means a
// Savepoint + try/catch + Database.rollback(savepoint). Every time.

KernDX Included

apex
kern.DML_Builder.newTransaction()
	.doInsert(newAccount)
	.doInsert(newOpportunity, Opportunity.AccountId, newAccount)
	.doInsert(newContact, Contact.AccountId, newAccount)
	.execute(); // one savepoint, all-or-nothing.
// FKs auto-wired after each parent inserts; any failure rolls back
// the whole graph. USER_MODE FLS by default.

What you also get

5lines→7capabilities you didn't write

Reliability

Atomic graphOne savepoint. Any insert failure rolls the whole graph back, so no orphaned parent leaks.
Auto-wired foreign keysEach foreign key is set from the new parent's Id after it inserts, with no manual AccountId stitching.
Dependency orderingParents insert before children, so the Account always saves before its Opportunity and Contact.
DML-row-limit guardGuards the per-transaction DML-row limit before committing. It fails fast and points you to .async().
Match-or-create on an external keydoUpsert(record, externalIdField) matches on a stable external ID, so a replayed integration write updates the existing record instead of duplicating it.

Governance

USER_MODE by defaultInserts run in USER_MODE, so the running user's FLS and CRUD are enforced on every row.

Observability

Per-row error resultsReturns a TransactionResult; switch to .allowPartial() and per-row failures come back on the result instead of throwing.
What's actually happening

Each foreign key is set from the new parent's Id the moment that parent inserts, and all three rows commit on a single savepoint. So if any insert fails, the whole graph rolls back and a half-saved parent never leaks.

Read a JSON body into a typed class: a typo in a field name is a compile error, not a nullDTOs Guide →

Why: a DTO is a small class holding exactly the fields to move in or out, which turns itself into JSON and back. If your code reads a field by a misspelt name, the class will not compile, and the outside format stays apart from your objects, so an API change touches one class.

Plain Apex Manual

apex
Map<String, Object> customer = (Map<String, Object>)
	JSON.deserializeUntyped(response.getBody());
String email = (String)customer.get('emial'); // typo: null, no error
Map<String, Object> address = (Map<String, Object>)customer.get('address');
String city = (String)address.get('city');
// Every caller casts and guesses the shape again.
// The JSON shape leaks into every class that touches it.

KernDX Included

apex
// public is enough: getObjectType() names the class, so KernDX does not look it up by name
@JsonAccess(serializable='always' deserializable='always')
public inherited sharing class DTO_Customer extends kern.DTO_JsonBase
{
	public String email;
	public DTO_Address address;
	public override Type getObjectType()
	{
		return DTO_Customer.class;
	}
	@JsonAccess(serializable='always' deserializable='always')
	public class DTO_Address
	{
		public String city;
	}
}

DTO_Customer customer = (DTO_Customer)new DTO_Customer().deserialize(response.getBody());
String email = customer.email;        // a typo here will not compile
String city = customer.address?.city; // the nested part is typed too
String body = customer.serialize();   // and back to JSON

You write: 1 Apex class (the DTO). You configure: nothing.

What you also get

1class→7capabilities you didn't write

Safety

Typed fieldsdeserialize and serialize work on your own class, so a shape mistake shows up when you save it.kern.DTO_JsonBase

Shape

Fill it from a recordOverride populate(recordId) to fill the DTO, reading through your selector.kern.DTO_Base
Reshape in one placetransform copies one DTO into another, so changing an API contract leaves your objects alone.kern.DTO_Base
Read one value by pathUTIL_JsonPath finds a value deep in a JSON body without a class for every level.kern.UTIL_JsonPath

Integrate

The body of an API callInbound and outbound API handlers carry their request and response as DTOs, so the same class reads the JSON in and writes it out.kern.API_Inbound · kern.API_Outbound
Sent to a component as JSONA controller takes the DTO as one JSON string and turns it back into your class, the pattern used throughout KernDX.kern.DTO_JsonBase · kern/moduleController

Ready-made

DTOs that shipName-value pairs, picklists, tables and change-event headers are already written.kern.DTO_NameValues · kern.DTO_PickList · kern.DTO_BaseTable · kern.DTO_ChangeEventHeader
Encrypt a value for this session, and choose sharing per read, without key handling codeSecurity Guide →

Why: one call encrypts and one decrypts; the key is made, kept per user and replaced for you, and every value carries a tamper check. It is for values you hold during a session: keys expire within 8 hours, so it is not long-term storage.

Plain Apex Manual

apex
Blob key = Crypto.generateAesKey(256);
// ...now store the key somewhere safe, per user, and replace it yourself
Blob cipher = Crypto.encryptWithManagedIV('AES256', key, Blob.valueOf(cardToken));
String sealed = EncodingUtil.base64Encode(cipher);
// No tamper check: a changed value fails late, or decrypts to rubbish.

// Sharing is fixed by the class keyword, for every query in it:
public without sharing class CaseReader { }

KernDX Included

apex
String sealed = kern.UTIL_SessionEncryption.encrypt(cardToken);
String plain = kern.UTIL_SessionEncryption.decrypt(sealed);
// Key made and kept per user in Platform Cache, replaced after 8 hours.
// Each value carries a tamper check (HMAC-SHA256), checked on decrypt.

// Sharing chosen per read: past sharing, field checks still on.
// SEL_Cases is your own selector: a with sharing class extending kern.SEL_Base.
List<SObject> openCases = new SEL_Cases().query
	.condition(Case.IsClosed).equals(false)
	.bypassSharing() // written to the bypass audit trail
	.toList();

You write: 2 calls, and your own selector class. You configure: space in the package's kern.Library cache partition, where the keys are kept.

What you also get

2calls→12capabilities you didn't write

Encryption

No key handling in your codeThe key is made, cached with an expiry and found again for you.kern.UTIL_SessionEncryption
Tamper check on every valueA random starting value plus an HMAC-SHA256 check, verified on decrypt.kern.UTIL_SessionEncryption
A key per user, replaced after 8 hoursKeys are kept apart per user and expire on their own.kern.UTIL_SessionEncryption
The cache is picked for youKeys go to the session cache, or to the org cache when there is no session.kern.UTIL_SessionEncryption
Check before you rely on itisAvailable() says whether Platform Cache is ready for encryption.kern.UTIL_SessionEncryption

Sharing and field security

User mode on every read and saveQueries and saves check the running user's object access, field access and record sharing unless you say otherwise.kern.QRY_Builder · kern.DML_Builder
Sharing per read or savewithSharing() and bypassSharing() on a read, bypassSharing() on a save, while field and object checks stay on.kern.QRY_Builder · kern.DML_Builder
Hidden fields removedstripInaccessible() drops fields the user cannot read from the rows.kern.QRY_Builder
System mode stated once per selectorA selector that must read past the user's access says so in one method, not at every read.kern.SEL_Base
Permission check from a FlowCheck Object Permissions answers read, create, edit and delete for the running user.kern.FLOW_CheckObjectPermissions

Governance

Bypasses written downEach time code turns sharing, a security mode, a trigger or a validation rule off through the framework, an audit log entry says who, when and what, and the reason you set, if you set one.kern.TRG_Base · kern__FeatureFlag__mdt
An org-wide switch backOne flag record each turns user mode off for all queries or all saves, with no deployment.kern__FeatureFlag__mdt
Scrub card numbers from your logs without shredding your order IDsData Masking Guide → Shipped Rules

Plain Apex Manual

apex
// Hand-rolled redaction in the log message: any long digit run goes.
String body = '{"card":"4111 1111 1111 1111","orderId":"1234567890123456"}';

String safe = body.replaceAll('\\b(?:\\d[ -]?){13,19}\\b', '[REDACTED]');
// Now BOTH are gone:
//   {"card":"[REDACTED]","orderId":"[REDACTED]"}
// The order ID was never a card — but the regex can't tell, so support
// loses the one ID they needed. Loosen it to spare the order ID and a
// real card slips through. There is no win.
insert new Error_Log__c(Message__c = safe);

KernDX Included

apex
// Just log it. The framework redacts the payment card on the way out.
String body = '{"card":"4111 1111 1111 1111","orderId":"1234567890123456"}';

kern.LOG_Builder.build()
	.info(body)
	.at('PaymentService.charge')
	.emit();

// The persisted LogEntry message reads:
//   {"card":"[CARD_REDACTED]","orderId":"1234567890123456"}
// 4111 1111 1111 1111 passes the Luhn check, so it is redacted.
// The 16-digit order ID FAILS Luhn, so it survives untouched.

What you also get

4lines→8capabilities you didn't write

Governance

Checks the card checksumEach match was checked with the card-number checksum (the Luhn check): the card was redacted, and the 16-digit order ID survived.
On by defaultOn by default when you log. You configured nothing to get this.
Pre-wired ruleThe replacement reads [CARD_REDACTED], and the rule ships pre-wired, with no Apex.
Covers framework recordsThe same rule also masks the framework's outbound-API, API-issue, async-chain, and log records.
Point at your own objectsAim the same engine at your object with config: a masking target plus the object's toggle, no Apex.
Master off-switchOne master off-switch turns off all framework masking while you diagnose a problem.
14 dormant rule templatesSSN, AWS keys, IBAN, SWIFT, private IPs and more ship as proven patterns. Activate one by wiring a target and flipping its IsActive flag, with no regex to write.

Performance

Bulk-safe regexThe card regex compiles once per transaction, then is reused across every record.
What's actually happening

A blunt regex can't tell a card from any other 16-digit number: it either shreds the order ID alongside the card or, loosened to spare the order ID, lets a real card through.

The shipped rule runs in CreditCard mode and checks each candidate match against a Luhn (mod-10) checksum first. So the valid card (4111 1111 1111 1111) is redacted, while the order ID, which fails Luhn, passes through untouched.

The masking runs on the framework's own LogEntryEvent__e before it is published, with nothing to configure.

Automate6 examples: triggers, validation rules, background chains, scheduled jobs, Flow actions, feature flags

Back to all features ↑

One trigger. Metadata-ordered actions. No hand-rolled recursion guards.Triggers Guide →

Plain Apex Manual

apex
// Plain Apex: one fat trigger, inline logic, hand-rolled recursion guard.
trigger AccountTrigger on Account(before update)
{
	if(AccountTriggerHandler.alreadyRan) // static re-entry guard
	{
		return;
	}
	AccountTriggerHandler.alreadyRan = true;

	for(Account a : Trigger.new)
	{
		Account prior = Trigger.oldMap.get(a.Id);
		// rating + naming + territory logic all crammed here, in an
		// order nobody can change without editing + redeploying Apex.
		if(a.AnnualRevenue != prior.AnnualRevenue)
		{
			a.Rating = a.AnnualRevenue > 1000000 ? 'Hot' : 'Warm';
		}
		// ...next dev appends here; ordering is "whoever edited last"...
	}
}
// Disable in an incident: comment it out + deploy. Reorder: edit + deploy.
// Unit-test one rule alone: you can't — it's welded to the loop + guard.

KernDX Included

apex
// 1. The trigger is one line — forever.
trigger AccountTrigger on Account(before update)
{
	new kern.TRG_Dispatcher().run();
}

// 2. Each rule is its own class, testable in isolation, ordered by metadata.
public inherited sharing class TRG_SetAccountRating
	extends kern.TRG_Base implements kern.IF_Trigger.BeforeUpdate
{
	public void beforeUpdate(List<SObject> newRecords, List<SObject> oldRecords)
	{
		for(Account a : (List<Account>) newRecords)
		{
			Account prior = (Account) triggerOldMap.get(a.Id); // TRG_Base helper
			if(a.AnnualRevenue != prior.AnnualRevenue)
			{
				a.Rating = a.AnnualRevenue > 1000000 ? 'Hot' : 'Warm';
			}
		}
	}
}

// 3. Order, kill switch, and recursion are CONFIG, not code — kern__TriggerAction__mdt:
//    kern__ApexClassName__c   = TRG_SetAccountRating
//    kern__Event__c           = Before Update
//    kern__Order__c           = 20        // reorder without a deploy
//    kern__BypassExecution__c = false     // flip to true to kill it mid-incident
//    kern__AllowRecursion__c  = false     // shield re-entry (defaults to true)

What you also get

a 1-line trigger→9capabilities you didn't write

Governance

Config, not codeActions dispatch in Order__c sequence, so you reorder them without a deploy.
Per-action off-switchFlip BypassExecution__c to switch one action off, with no deployment.
Object-level bypassDisable every trigger action for an object in one call with TRG_Base.bypass().
Feature-flag gatingGate an action on a feature flag without touching code.
Flow as a stepRegister a Flow as an ordered step in the same pipeline.

Reliability

Recursion guardSet AllowRecursion__c = false to stop the action re-firing on re-entry.
Failure strategyOn action failure, choose Block DML or Log and Continue.

Observability

Bypass audit trailProgrammatic bypass calls write to the shared audit trail.

Testing

DML-free action testsCall an action directly on in-memory rows (TST_Builder/TST_Mock) and mock its selector reads, so you unit-test one rule with no DML.
What's actually happening

A one-line trigger hands off to TRG_Dispatcher().run(). It queries the TriggerAction__mdt rows for that object and event, sorts them by Order__c, and dispatches each to a small single-purpose class through the matching IF_Trigger interface.

Because order, bypass, recursion, and flag-gating are rows rather than Apex, they change with no redeploy. And because each action just takes a record list, you unit-test one in isolation.

Roll out a validation rule to production that logs violations but never blocks a saveCustom Validations Fast Start → Shadow Mode

Plain Apex Manual

apex
// Native Salesforce validation rule. It has exactly two states:
// off, or blocking EVERY save the instant you mark it Active —
// including the historical, dirty data you haven't cleaned yet.
//
//   Rule:    Customer_Requires_Contact
//   Formula: AND(ISPICKVAL(Type, "Customer"), ISBLANK(Phone))
//   Active:  [x]   <-- day one, prod saves start failing
//
// There is no "log it, don't block it" switch. To preview the
// blast radius you hand-roll a Flow that writes to a custom log
// object, or you flip Active on and brace for the support tickets.
update accounts;   // some now throw FIELD_CUSTOM_VALIDATION_EXCEPTION

KernDX Included

apex
// 1. AUTHOR two CMDT records, no Apex: a kern__ValidationRuleGroup__mdt that
//    binds the object + timing (Account · Before · Insert/Update), then a
//    kern__ValidationRule__mdt under it. kern__RuleFormula__c returns TRUE when INVALID.
//
//   customMetadata/kern__ValidationRule.Customer_Requires_Contact.md-meta.xml
//   <values><field>kern__ValidationRuleGroup__c</field>
//     <value xsi:type="xsd:string">Account_Before_Save</value></values>
//   <values><field>kern__RuleFormula__c</field>
//     <value xsi:type="xsd:string">AND(ISPICKVAL(newRecord.Type, "Customer"), ISBLANK(newRecord.Phone))</value></values>
//   <values><field>kern__ErrorMessage__c</field>
//     <value xsi:type="xsd:string">Customer accounts need a phone</value></values>
//   <values><field>kern__Severity__c</field><value xsi:type="xsd:string">Error</value></values>
//   <values><field>kern__Order__c</field><value xsi:type="xsd:double">1</value></values>

// 2. Turn on Shadow Mode — ONE field. The live rule still fires on
//    every in-scope save and evaluates the SAME formula, but each
//    would-be violation is logged instead of calling addError().
//    The save commits — even with Severity = Error.
//
//   <values><field>kern__ShadowMode__c</field>
//     <value xsi:type="xsd:boolean">true</value></values>

// 3. Watch the blast radius accumulate, then flip kern__ShadowMode__c to
//    false to enforce. Violations land in kern__LogEntry__c tagged [SHADOW].
//    SEL_LogEntries is your own selector: a with sharing class extending kern.SEL_Base.
List<kern__LogEntry__c> shadowViolations = new SEL_LogEntries().query
	.fields(new List<SObjectField>{ kern__LogEntry__c.kern__ShortMessage__c, kern__LogEntry__c.CreatedDate })
	.condition(kern__LogEntry__c.kern__LogLevel__c).equals('WARN')
	.andCondition(kern__LogEntry__c.kern__ShortMessage__c).contains('[SHADOW]')
	.orderBy(kern__LogEntry__c.CreatedDate).descending()
	.withLimit(100)
	.toList();
// Each kern__ShortMessage__c reads: "[SHADOW] Customer_Requires_Contact:
// Customer accounts need a phone". Zero blocked saves.

What you also get

2 custom metadata records + a checkbox→8capabilities you didn't write

Reliability

Shadow modeSave never blocked: even with Severity = Error, a shadow violation is logged, not raised.
Same deployed formulaFires on every in-scope save against the SAME formula, and one checkbox flips shadow to enforce.
Throw-safe evaluationA formula that throws still won't block the save. The error is logged and swallowed, not rethrown.
Same rules, callable from FlowAn Execute Validation Rules invocable runs the very same formula rules from a Flow and returns errors/warnings without blocking the save.

Observability

[SHADOW] in ShortMessage__cEach would-be violation logged as a WARN tagged [SHADOW] in ShortMessage__c for you to query.
Query through a selectorInspect shadow rows through a selector, the same way you read everything else.

Governance

Three documented outcomesSeverity Error blocks the save, Warning logs it, Shadow logs it regardless of severity.
USER_MODE log readThe log read runs in USER_MODE by default. Log entries are private on a new install, so run it as someone who can see every entry, such as a holder of the Kern Administrator permission set.
What's actually happening

A native validation rule has two states only: off, or blocking every offending save the instant it is Active. So a new rule meets your dirty production data as a wall of FIELD_CUSTOM_VALIDATION_EXCEPTION errors.

With ShadowMode__c = true the rule still fires on every in-scope save and evaluates the very same deployed formula, but each would-be violation is written to LogEntry__c as a [SHADOW] WARN instead of calling addError(), so nothing is blocked.

The log shows how many records the rule would affect. When you are happy with that, flip one checkbox to enforce it.

A governor-limit crash won't leave your chain stuck "Running"Async Processing Fast Start →

Plain Apex Manual

apex
// Hand-rolled Queueable chain
public class Step1 implements Queueable
{
	public void execute(QueueableContext context)
	{
		doWork(); // a CPU/heap limit here and the job just dies
		System.enqueueJob(new Step2()); // never reached — no error row, no status
	}
}
// AsyncApexJob says "Failed", detail-free. Your tracking record sits
// in "Running" forever. You find out from an angry user, not a query.

KernDX Included

apex
kern.UTIL_AsyncChain.newChain('OrderSync')
	.then(new Step1())
	.then(new Step2())
	.onError(new NotifyAdminStep())
	.execute();

// Each step runs in its own transaction (fresh limits).
// A Finalizer is attached to EVERY step, so even an
// uncatchable governor-limit crash marks the run Failed —
// with a reason + correlation id + a durable log. Never a zombie.

What you also get

5lines→10capabilities you didn't write

Reliability

Durable recoveryAn uncatchable governor-limit crash still flips the run to Failed, so no run is left stuck on Running.
Fresh limits per stepEach step ran in its own Queueable transaction, with a fresh set of governor limits.
Callout-capable onErrorAn onError handler runs in its own callout-capable transaction, even after the failed step did DML.

Observability

Real-time Chain MonitorA live UI surfaces running and failed chains without writing a query.
Queryable statusStatus persists to an AsyncChainExecution__c row at every transition (Running → Completed/Failed/Aborted).
The whole action in one searchEvery chain run has its own tracking ID, and every entry also carries the ID of the action that started it, so one search brings back the action and every chain it launched.
Field-history auditStatus__c, CompletedSteps__c, CurrentStepName__c, and CompletedAt__c carry field-history, giving a step-by-step trail.
Durable crash logOn crash the Finalizer wrote a durable Error log stamped with the failed chain-execution id.
Quiet when cleanLogs are reserved for actionable events, so a clean, fast, successful run emits no noise.

Performance

Per-step timingEach step is timed; a slow step emits a structured performance log with CPU, heap, SOQL, and DML deltas.
What's actually happening

A hand-rolled Queueable that hits an uncatchable governor limit just dies: no finish() hook, no error row, status stuck on "Running." The framework attaches a Finalizer to every step, and a Finalizer is guaranteed to run with fresh limits even after that crash. So the run is marked Failed with a reason and a correlated log instead of vanishing.

A scheduled job an admin can time and tune from a recordScheduled Jobs Fast Start →

Why: saving a Scheduled Job record schedules your class, so nobody runs System.schedule or writes cron by hand. The job declares its settings, and an admin changes them on the record with no deployment.

Plain Apex Manual

apex
public class CaseArchiveJob implements Schedulable
{
	public void execute(SchedulableContext context)
	{
		CaseArchiveService.archiveOlderThan(90); // change 90? edit and deploy
	}
}
// Then, in anonymous Apex, by someone who knows cron:
System.schedule('Case archive', '0 0 2 * * ?', new CaseArchiveJob());
// To change the time: find the job, stop it, schedule it again.

KernDX Included

apex
// global: KernDX creates this class by name, from its Scheduled Job record
global inherited sharing class CaseArchiveJob extends kern.SCHED_Base
{
	public override List<kern.DTO_ScheduledParameterDefinition> getParameterDefinitions()
	{
		return new List<kern.DTO_ScheduledParameterDefinition>
		{
			kern.DTO_ScheduledParameterDefinition.of('daysToKeep', 'Days to keep').asNumeric().withDefault('90')
		};
	}
	public void execute(SchedulableContext context)
	{
		CaseArchiveService.archiveOlderThan(getNumericParameter('daysToKeep'));
	}
}
// An admin saves a Scheduled Job record: Class Name, Schedule, Days to keep.

You write: 1 Apex class. You configure: 1 ScheduledJob__c record.

What you also get

1 class + 1 record→14capabilities you didn't write

Operations

Scheduled by a recordSaving an active Scheduled Job record schedules the class; switching it off unschedules it.kern__ScheduledJob__c
Settings an admin can editEach declared parameter becomes a field in the Scheduled Jobs editor. Its value is stored on the record, and your code reads it with a typed getter.kern.SCHED_Base · kern.DTO_ScheduledParameterDefinition · kern__ScheduledJob__c
Next run shown before you saveThe editor fills in your time zone and previews when the job will run next.kern__ScheduledJob__c
Run nowA button on the record runs the job straight away, without moving its next run.kern/scheduledJobDetail

Limits

Many jobs, few scheduled-job slotsPut jobs on the job runner and they share its few slots, and may run as often as every five minutes.kern.SCHED_JobRunner
No run on top of a runA run that is due while the last one is still going is skipped and recorded as Skipped, unless you allow it.kern__ScheduledJob__c
The important job firstWhen several jobs are due together, a lower run priority starts first.kern__ScheduledJob__c

Observability

The outcome of every runEach run records Succeeded, Failed, Skipped or Parked on the record, and a failed run links to its log entry.kern__ScheduledJob__c
Health Check watches the runnerThree readings say whether the runner still checks, whether a job waits for a missing runner, and how many slots are in use.kern/healthCheck

Governance

Only some people use the runnerPutting a job on the runner, and Run now, need the Kern Job Runner Management permission set.

Ready-made jobs

Delete old recordsSCHED_PurgeRecords clears old rows on a schedule, set up with a record only.kern.SCHED_PurgeRecords
Deactivate unused usersSCHED_DeactivateUsers switches off users who have not logged in.kern.SCHED_DeactivateUsers
Send queued calloutsSCHED_PerformBatchedCallouts sends queued API calls in batches.kern.SCHED_PerformBatchedCallouts
Find stuck chainsSCHED_ChainWatchdog finds background chains that have stopped moving, marks them Stalled and runs their error handling once, so none stays Running for ever.kern.SCHED_ChainWatchdog
Give a Flow a callout, a feature check and a log entry, with no Apex of your ownWeb Services Guide → Flow actions

Why: the actions a Flow needs most ship ready to drag in. They run the same framework code as your Apex, so a callout from a Flow is retried, logged and masked exactly like one from Apex.

Plain Flow Builder Manual

text
Action: Create HTTP Callout     (External Services)
	Named Credential: Posts
	Method: GET     Path: /posts/1
	Sample response → Flow builds the output type
	                → the body as Flow variables

No Apex, and fine for a simple call. What it does not give you:
no retry, no circuit breaker, no API Call record of the request
and response, nothing masked, and no tracking ID shared with the
other log entries of the same Flow run.
A feature check or a log entry still needs an Apex action of your own.

KernDX in Flow Builder Included

text
Action: Start Flow Correlation
	Flow Name: Checkout                 → a tracking ID for this run
Action: Is Feature Flag Enabled
	flagNames: NewCheckout              → true or false for this user
Action: Invoke Callout Synchronously
	API Name: API_GetPost               → the same handler as the Apex call
	          → Response Body, API Call Id, success flag
Action: Log Flow Event
	Correlation ID: from the first action
	Message:        Post fetched        → a log entry tied to this run

No Apex class of your own. The callout uses the same handler,
API Setting, retries and masking as the Apex call.

You write: no Apex (the handler is the one from Outbound services). You configure: 4 actions in one Flow.

What you also get

0 lines of Apex→12ready-made actions and gains

Integrate

Callouts, now or laterInvoke Callout Synchronously waits for the answer; Invoke Callout Asynchronously queues the call and lets the Flow move on.kern.FLOW_CallApi · kern.FLOW_CallApiAsync
The same retries, record and maskingThe callout runs your Apex handler, so it is retried, kept as an API Call record and masked like a call from Apex.kern.FLOW_CallApi · kern.API_Outbound
Retry failed callsRetry API Issues runs the failed calls of the issues you pick again, in one background job.kern.FLOW_RetryApiIssues

Governance

Check a feature flagIs Feature Flag Enabled gives the same answer the Apex check gives, for the running user.kern.FLOW_CheckFeatureFlag
Check permissions firstCheck Object Permissions says whether the user can read, create, edit and delete an object, so a screen can hide what they cannot do.kern.FLOW_CheckObjectPermissions
Bypass a trigger, written downTrigger Bypass and Is Bypassed switch trigger actions off and on from a Flow; every bypass goes to the audit trail.kern.FLOW_BypassTrigger · kern.FLOW_CheckTriggerBypassed

Observability

Logs tied to one runStart Flow Correlation, Log Flow Event and End Flow Correlation give every entry of one Flow run the same tracking ID.kern.FLOW_LoggerStart · kern.FLOW_LoggerLog · kern.FLOW_LoggerEnd
One detailed log lineWrite Detailed Log Messages writes an entry with the level and details you choose, with no correlation setup.kern.FLOW_WriteLog

Validation

The same validation rulesExecute Validation Rules runs your formula rules from a Flow and returns errors and warnings without blocking the save.kern.FLOW_ExecuteValidationRules
Bypass a rule for one transactionBypass Validation and Clear Validation Bypass switch rules off for an object, a group or one rule, and the bypass is audited.kern.FLOW_BypassValidation · kern.FLOW_ClearValidationBypass

Everyday tasks

Picklist values for a screenGet PickList Values returns the values of a picklist field, ready for a choice list.kern.FLOW_GetPicklistValues
Email from a template, with an activitySend Email (Flow-Delegated) and Log Activity sends a template email and can log it as an activity.kern.FLOW_SendEmail
Turn a feature on for a pilot group first, with no deploymentFeature Flags Fast Start →

Why: a flag is a record, so switching it on, off or for a pilot group is a configuration change the next transaction sees. Apex, Flow and LWC ask the same question and get the same answer, and a flag that does not exist answers false.

Plain Apex Manual

apex
// A checkbox on your own hierarchy custom setting
Checkout_Settings__c settings = Checkout_Settings__c.getInstance();
if(settings.Use_New_Checkout__c)
{
	newCheckout();
}
// The setting holds an org value, a profile value and a user value,
// with no code. A permission set, a public group or a custom
// permission cannot hold a value, so a pilot is chosen by profile or user.
// The Flow and the LWC each read the setting their own way.

KernDX Included

apex
if(kern.UTIL_FeatureFlag.isEnabled('NewCheckout'))
{
	newCheckout(); // on for a profile, permission set or group, set in records
}
// The same flag, the same answer, everywhere:
//   Flow: the Is Feature Flag Enabled action
//   LWC:  await isFlagEnabled('NewCheckout') from kern/featureFlag
// A flag that does not exist returns false.

You write: 1 line of Apex. You configure: 1 FeatureFlag__mdt record, plus FeatureFlagStrategy__mdt records to choose the pilot group.

What you also get

1line→9capabilities you didn't write

Rollout

Pilot before going wideTarget a custom permission, a profile, a permission set, a public group, a custom setting or custom metadata.kern__FeatureFlagStrategy__mdt
No deployment to switchChange the record and the next transaction sees it.kern.UTIL_FeatureFlag
Safe when missingA flag name that matches no active flag returns false, so new code stays off.kern.UTIL_FeatureFlag
Ask for another userCheck a flag for a user by Id or username, not only the running user.kern.UTIL_FeatureFlag

One answer

Apex, Flow and LWC agreeAll three go through the same check for the running user.kern.FLOW_CheckFeatureFlag · kern/featureFlag
Gates triggers, rules and APIs tooTrigger actions, validation rules and API settings name a flag that must be on, or one that bypasses them, with no code.kern__TriggerAction__mdt · kern__ValidationRule__mdt · kern__ApiSetting__mdt

Performance

One query for every flagThe first check of a transaction loads all active flags at once; later checks reuse them.kern.UTIL_FeatureFlag

Testing

A flag made in the testTST_Factory makes an on or off flag in memory, so a test covers both paths with no metadata deployed.kern.TST_Factory
Integrate4 examples: outbound services, resilient callouts, inbound APIs, logging

Back to all features ↑

Write a service once as a handler class, and let every Apex caller and Flow share itOutbound APIs Fast Start →

Why: an API_Outbound handler is one small class for one service: what it sends and how it reads the answer. Its API Setting record (custom metadata) holds the endpoint path, the retry count and the circuit breaker switch.

Every caller, from Apex, a Flow or a background job, uses the same class and the same record, so a change is made once and needs no deployment. Every call is kept as an API Call record with its request and response.

Plain Apex Manual

apex
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Posts/posts/1');
request.setMethod('GET');
request.setTimeout(10000);
HttpResponse response = new Http().send(request);
String post = response.getBody();
// This block is copied into every class that calls the service,
// and a Flow needs an Apex action of its own around it.
// The path and timeout live in code: a change means a deploy.
// No saved record of the call, nothing masked.

KernDX Included

apex
// global: KernDX creates this class by name, from its API Setting record
global with sharing class API_GetPost extends kern.API_Outbound
{
	public override void configure()
	{
		super.configure();
		requiresTriggeringRecord = false; // no record starts this call
	}
	public override kern.API_Base.HttpMethod getHttpMethod()
	{
		return kern.API_Base.HttpMethod.GET;
	}
}
// Its API Setting record holds Class Name (API_GetPost), Endpoint Path (/posts/1),
// Max Retry Count and Circuit Breaker Enabled. Any Apex caller:
kern.API_Outbound handler = kern.UTIL_HttpClient.useHandler(API_GetPost.class).invoke();
String post = handler.result.responseBody; // kept as an API Call record
// A Flow calls the same class with Invoke Callout Synchronously.

You write: 1 Apex class. You configure: 1 ApiSetting__mdt record, and 1 ApiCredential__mdt record that names your Named Credential.

What you also get

1 class + 1 record→13capabilities you didn't write

Reliability

Retries set in configurationMax Retry Count and Retry Backoff (sec) on the API Setting record decide how often a failed call is sent again, for every caller at once.kern.API_Outbound · kern__ApiSetting__mdt
Circuit breaker by checkboxTick Circuit Breaker Enabled and the framework stops calling a failing system for a cool-off, then tries again.kern__ApiSetting__mdt
Callouts before savesThe dispatcher makes every callout first and saves after, so you never see "uncommitted work pending".kern.API_Dispatcher
A failure record when retries run outA call that still fails is saved as an API issue you can retry later.kern.API_Base · kern__ApiIssue__c

Observability

Every call keptEach call is saved as an API Call record with its request, its response and how long it took.kern.API_Base · kern.API_Dispatcher
A tracking ID on every callEach API Call record keeps the trace ID the call sent, and the log entries written while it ran carry that same ID, so you go from the call to its logs.kern.API_Outbound · kern__ApiCall__c
Every call timedThe call record keeps the callout, handler, save and total time in milliseconds.kern.API_Dispatcher · kern__ApiCall__c

Governance

Masked before it is savedCard numbers and secret keys are removed from the saved request and response.kern__MaskingRule__mdt: the Mask Secret Key Fields in JSON and Mask Payment Card Numbers rules
Emergency off switchOne feature flag stops all API calls, with no deployment. It reads the API Runtime Switch hierarchy setting, so you set it for one user, a profile or the whole org.kern.API_Base · kern__ApiRuntimeSwitch__c
Endpoint and credential out of codeThe path sits on the API Setting record and the credential in a Named Credential, so neither is in your class.kern__ApiSetting__mdt · kern__ApiCredential__mdt

Testing

Mock answers without codeTick Mocking Enabled on a service and it answers with mock data for chosen users, with no live endpoint.kern.API_Base

Background work

Same handler, in the backgroundSave a queued API Call record and the framework runs the same handler later, then logs the result.kern__ApiCall__c · Outbound APIs Fast Start
Typed request and responseThe handler's request and response are DTOs, so the body is a class, not a map.kern.API_Outbound
Retry, circuit breaker and a test mock for one callout, in one chainResilience Fast Start → Resilient Callout

Plain Apex Manual

apex
// Hand-rolled resilient POST — and you still own the test.
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:PaymentGateway/charges');
request.setMethod('POST');
request.setBody(JSON.serialize(chargeRequest));
Set<Integer> retryable = new Set<Integer>{ 500, 502, 503, 504 };
HttpResponse response;
Integer attempts = 0;
do
{
	attempts++;
	response = new Http().send(request);
}
while(retryable.contains(response.getStatusCode()) && attempts < 4);
// no circuit breaker · no masking before you log the body · no
// dead-letter — and to test it you hand-write an HttpCalloutMock
// class and wire Test.setMock yourself

KernDX Included

apex
HttpResponse charge = kern.UTIL_HttpClient
	.post('PaymentGateway', '/charges')
	.body(chargeRequest)
	.withIdempotencyKey(chargeRequest.orderNumber) // the same key on every attempt: any value unique to this charge, such as its order number
	.withRetry(5, 10)
	.withCircuitBreaker()
	.onFailure(kern.UTIL_HttpClient.FailureAction.RETRY_THEN_LOG)
	.send(); // a transient 5xx comes back ON the response — never thrown

// …and the whole mock + assertion in the test, one chain:
kern.API_MockFactory.forService('PaymentGateway')
	.body('{"error":"unavailable"}').statusCode(503).register();

What you also get

10lines→10capabilities you didn't write

Reliability

Retry that knows what is safeRe-sends a 408 or 503 at once, and a 500, 502 or 504 too, because the call carries an idempotency key (one ID sent with every attempt, so the other system can spot a repeat). You never typed the loop or the codes.
Sent again laterStill failing? The call is saved, and a scheduled Flow sends it again at its next retry date.
Cross-transaction breakerCircuit-breaker state lives in Platform Cache, keyed by the credential, shared across transactions.

Governance

Masked before saveCard and secret-key rules redact Request__c / Response__c before the ApiCall__c row is saved.
Large-payload overflowA body too large for the field overflows to a ContentVersion file, masked the same way.
Audit in SYSTEM_MODEThe whole audit write runs without the user's permission checks (SYSTEM_MODE). This is fixed up front, and no single call can change it.

Observability

Failure records on exhaustionOn retry exhaustion it persists an ApiIssue__c record (when failure logging is enabled).
Says when it may have landedWhen a request that is not safe to repeat fails after it may have reached the other system, its API issue is marked External System May Have Acted, so nobody sends it again without checking first.

Testing

One-line mockAPI_MockFactory.forService(...).register() replaces the whole HttpCalloutMock + Test.setMock.
Verify what was sentA test can assert that a mock was called, or never called, and that the last request body held the right field.
What's actually happening

The non-obvious part: a transient 5xx comes back on the response rather than thrown, and because the call carries an idempotency key, the framework knows a repeat is safe. Once in-transaction retries are spent, the call is saved so a scheduled Flow can send it again at a backoff date.

Without a key, a POST that got a 500, 502 or 504 is not sent again, because the other system may already have charged the card.

The resilience outlives the original transaction. After repeated failures the framework stops calling a failing dependency for a cool-off, then resumes (a circuit breaker). That state lives in Platform Cache keyed by the credential, so a dependency that's down stays shorted across transactions, not just within one.

Reject a replayed request with a changed body: HTTP 409, automaticallyInbound APIs Fast Start → Idempotency

Plain Apex Manual

apex
// Hand-rolled inbound endpoint — you own the dedupe, or you don't have it.
@RestResource(urlMapping='/charge/*')
global with sharing class ChargeApi
{
	@HttpPost
	global static void doPost()
	{
		String key = RestContext.request.headers.get('Idempotency-Key');
		String body = RestContext.request.requestBody.toString();

		// Naive dedupe: did we see this key already?
		List<Payment__c> prior =
		[
			SELECT Id
			FROM Payment__c
			WHERE IdempotencyKey__c = :key
			LIMIT 1
		];
		if(!prior.isEmpty())
		{
			RestContext.response.statusCode = 200;   // assume same request...
			return;                                  // ...never checked the BODY.
		}

		chargeCard(body);                            // a retry with a CHANGED body
		insert new Payment__c(IdempotencyKey__c = key);  // double-charges silently.
	}
}

KernDX Included

apex
// 1. A normal inbound handler — no dedupe code at all.
@RestResource(urlMapping='/charge/*')
global inherited sharing class REST_Charge
{
	@HttpPost
	global static void doPost()
	{
		kern.API_Dispatcher
			.processInboundService(API_Charge.class.getName());
	}
}

global inherited sharing class API_Charge extends kern.API_Inbound
{
	public override void processRequest()
	{
		chargeCard(requestBody);
	}
}

// 2. Flip ONE field on this service's kern__ApiSetting__mdt record:
//      kern__IdempotencyEnabled__c = true   (kern__Direction__c = Inbound)
//
// Now, for every caller that sends an Idempotency-Key header:
//   • same key + same body    → cached HTTP 200 (handler never re-runs)
//   • same key + CHANGED body → HTTP 409, names the original kern__ApiCall__c.Id
//   • new key                 → fresh processing
// All three outcomes, zero dedupe code. INBOUND, body-hash based.

What you also get

1 handler + a checkbox→9capabilities you didn't write

Reliability

Same key, changed body: refusedSame key + changed body → HTTP 409 naming the original ApiCall__c.Id.
Cached replaySame key + same body → cached HTTP 200, your handler never re-runs.
One-checkbox SHA-256The duplicate check compares a SHA-256 hash of the body, and one configuration checkbox turns it on.
Completed-only matchReplay matches the indexed Idempotency-Key, only against requests that completed successfully.
Inbound, not outboundThis is INBOUND body-hash idempotency. Outbound uses an explicit idempotency key you set, not a body hash.
Replay a failed request on purposeA failed inbound request is saved on an API issue (the error record KernDX keeps) with its path, method and body. Press Retry on the issue, or Retry Selected on the API Issues list for many at once, to run it through your handler again as a new call. Unlike Cached replay, this does re-run your handler.

Observability

Recorded on ApiCall__cThe hit is recorded on the ApiCall__c record (IsIdempotencyHit__c + body-hash).
Tracking ID firstOne tracking ID (in the W3C trace format) is set on every request, before the idempotency check runs.

Governance

Feature-flag-gated endpointName a flag in RequiredFeatureFlag__c and a disabled inbound API aborts automatically, so you can take a live endpoint offline by toggling a flag, with no redeploy.
What's actually happening

A naive hand-rolled dedupe checks only that the key was seen before, never that the body still matches, so a retry that mutates the payload under the same key double-charges in silence.

The framework instead stores a SHA-256 hash of the request body next to the (External-ID-indexed) Idempotency-Key, so a replay with a changed body is detectable: it returns HTTP 409 naming the original ApiCall__c.Id, while an identical replay returns the cached 200 without re-running your handler.

This is inbound body-hash idempotency. Outbound instead uses an explicit idempotency key you stamp via UTIL_HttpClient.withIdempotencyKey().

Log an error that survives the rollback that erased the recordLogging Fast Start →

Plain Apex Manual

apex
try
{
	chargeCard(payment);
}
catch(Exception error)
{
	// Write a trace so we know what failed...
	insert new Error_Log__c(
		Message__c = error.getMessage(),
		Stack__c = error.getStackTraceString(),
		Record__c = payment.Id);
	throw error; // ...then the rollback ERASES that Error_Log__c too.
}

KernDX Included

apex
try
{
	chargeCard(payment);
}
catch(Exception error)
{
	kern.LOG_Builder.build()
		.error(error)
		.forRecord(payment.Id)
		.emitAt('PaymentService.charge');
	throw error; // the log is a platform event — it OUTLIVES the rollback.
}

What you also get

4lines→8capabilities you didn't write

Reliability

Rollback-proofPublished as a platform event, so the saved log outlives the rollback that erases the payment.
ERROR flushes earlyAn ERROR-level entry is never held in the suspended-save buffer; it flushes before the re-throw.

Observability

Governor-limit snapshotSnapshots every limit (SOQL, DML, CPU, heap, callouts, each as used of maximum) onto the row.
Correlation idOne startCorrelation() stamps a shared id on every log, so you query the whole flow by that one id.
Correlation survives the async hopserializeContext() / hydrateContext() carry the correlation id across a Queueable, Batch, or Future, so one flow stays joinable.
Who wrote itRecords who wrote the entry (Framework, Apex, Flow or Component) and which class, Flow or component, plus the context (trigger, REST, batch…) and the running user.
Exception detailRecords the exception type, the full stack trace, and the failing line number.

Governance

Masked by defaultRuns the row through the masking framework before publish, on by default.
What's actually happening

The log is published as a platform event committed to the event bus immediately, independent of your transaction, so the rollback that erases the payment can't un-publish the record of why it failed. A plain insert Error_Log__c shares the failing transaction and is undone by the very rollback the re-throw triggers.

Build, test and run5 examples: Lightning web components, test data, code scanning, Platform Cache, admin consoles

Back to all features ↑

A component with toasts and navigation, without wiring eitherLWC Fast Start →

Why: ComponentBuilder is a base class with the common wiring already built in: toasts, Apex calls, navigation, the message service and Flow navigation. You name the parts a component uses, and each one is one method call.

Plain LWC Manual

js
import {LightningElement} from 'lwc';
import {NavigationMixin} from 'lightning/navigation';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class AccountCard extends NavigationMixin(LightningElement)
{
	handleSaved(event)
	{
		this.dispatchEvent(new ShowToastEvent({title: 'Success', message: 'Saved', variant: 'success'}));
		this[NavigationMixin.Navigate]({type: 'standard__recordPage',
			attributes: {recordId: event.detail.id, actionName: 'view'}});
	}
}

KernDX Included

js
import {ComponentBuilder} from 'kern/componentBuilder';

// Ask only for the parts this component uses
export default class AccountCard extends ComponentBuilder('notification', 'navigation')
{
	handleSaved(event)
	{
		this.showSuccessToast('Saved');
		this.redirectToRecordPage(event.detail.id);
	}
}

You write: 1 Lightning web component. You configure: nothing.

What you also get

1 base class→12capabilities you didn't write

Less code

Only the parts you nameComponentBuilder('notification', 'navigation') switches on those two modules and nothing else.kern/componentBuilder
Toasts in one callshowSuccessToast, showInfoToast, showWarningToast and showErrorToast; the error one also reads an Apex error for you.kern/moduleNotification
Navigation in one callredirectToRecordPage opens a record; generateRecordPageURL returns its link.kern/moduleNavigation
Apex calls that handle their errorscallControllerMethod logs a failure and shows an error toast, unless you ask it to throw.kern/moduleController

Built in too

Message service and Flow navigationAsk for 'lightning-message' or 'flow-navigation' and those are wired the same way.kern/moduleLightningMessageService · kern/moduleFlowNavigation
Feature flags in a componentisFlagEnabled gives the same answer as the Apex and Flow checks.kern/featureFlag
Everyday helpersReady-made string, array and error helpers, such as turning Apex errors into one readable message.kern/utilityString · kern/utilityArray · kern/utilitySystem
A ready-made tablepaginatedTable pages, sorts and selects rows for you.kern/paginatedTable
Flow screen partsA Flow footer and a JSON viewer drop into Flow screens as they are.kern/flowFooter · kern/jsonViewer

Observability

Browser logs joined to server logsThe logger saves component logs in Salesforce under the same tracking ID as the Apex they called.kern/utilityLogger
Time a step in the browserstartTimer measures how long a step takes and logs it with the other entries.kern/utilityLogger
Saved like an Apex logBrowser entries are written through the same Apex log builder, so they are masked and searchable like any other entry.kern/utilityLogger · kern.LOG_Builder
Two hundred test records in one line, or none at allTest Data Fast Start →

Why: Salesforce has no built-in test-data factory. Test.loadData loads rows from a CSV file kept as a static resource, but the file must carry every required field and is one more thing to keep in step with the org, so most teams build records by hand.

The builder fills required fields for you, saves a list with one save, and can skip the database by handing a selector pretend rows.

Plain Apex Manual

apex
List<Account> accounts = new List<Account>();
for(Integer i = 0; i < 200; i++)
{
	accounts.add(new Account(Name = 'Test ' + i, Industry = 'Technology'));
	// ...and every required field your org added, by hand
}
insert accounts;
// To test the code that reads them, the rows must really be saved:
// there is no way to hand a query pretend rows.

KernDX Included

apex
// 200 Accounts, required fields filled in, saved with one save
List<SObject> accounts = kern.TST_Builder.of(Account.SObjectType)
	.withOverride(Account.Industry, 'Technology')
	.withCount(200)
	.buildList();

// SEL_Accounts is your own selector: a with sharing class extending kern.SEL_Base.
// Or no database at all: the next Account read in this test gets these
kern.TST_Mock.of(Account.SObjectType).withCount(3).buildList();
List<SObject> found = new SEL_Accounts().query.toList(); // the 3 mock rows

You write: test code only. You configure: nothing.

What you also get

2chains→14capabilities you didn't write

Speed

Pretend query resultsTST_Mock rows come back from the next query for that object, with mock Ids and no save.kern.TST_Mock
Records without the databasewithoutInsertion(true) builds records in memory with valid mock Ids.kern.TST_Builder
One save for the whole listwithCount(n).buildList() saves many records together, so bulk tests stay inside the limits.kern.TST_Builder
Pretend totals and groupsregisterAggregateRows answers a grouped query (sums or counts per group) with the rows you give it.kern.TST_Mock

Less setup

Required fields filled inYou set only the fields your test is about.kern.TST_Builder
Parent and children togetherwithChildren builds the children and links them to the parent for you.kern.TST_Builder
Field typos caught when you save the classwithOverride takes a field token such as Account.Industry, so a wrong name will not compile.kern.TST_Builder
Values spread across the listwithCycle repeats a list of values over the records, so no index sums.kern.TST_Builder
A record type by namewithRecordType takes the developer name and finds the Id for you.kern.TST_Builder

Shared setup

Users with their permissionsTST_Factory makes users and assigns permission sets or groups in one or two calls.kern.TST_Factory
Feature flags on or offMake a flag in memory for the test, on or off, with nothing deployed.kern.TST_Factory

Failure paths

Make a read fail on purposethrowsException makes the next read of an object throw, so you can test your error handling.kern.TST_Mock
A callout answer in one lineAPI_MockFactory gives an API handler a pretend response, and tells you whether it was called.kern.API_MockFactory

Observability

Check what was loggedSet ignoreTestMode and the test keeps its log entries, written by the same code as in production.kern.LOG_Builder
Catch a query that skips the selector before it is merged, not in reviewCode Scanning Fast Start →

Why: KernDX ships PMD rules (checks that read your Apex and report a pattern) that know its own way of working. Salesforce Code Analyzer runs them next to its standard rules, in your editor or in CI, and each finding says what to write instead.

Plain Salesforce Code Analyzer and code review Manual

apex
// Your team agreed: every read goes through a selector.
public with sharing class CaseService
{
	public static List<Case> openCases()
	{
		return [SELECT Id, Subject FROM Case WHERE IsClosed = false WITH USER_MODE];
	}
}
// The standard rules check security and general style. This query
// runs in user mode, so the security rules have nothing to report:
// they do not know your team's rule. The rule lives in a wiki, and
// a reviewer has to spot every break of it, in every pull request.

KernDX rules in Code Analyzer Included

text
sf code-analyzer run --config-file code-analyzer.yml --target force-app/ --view detail

// The finding, shortened:
CaseService.cls line 6   KernNoInlineSOQL   severity 2 (High)
	Inline SOQL is not allowed. Read through a selector (SEL_*),
	or its query property for a custom query.

// What the message points you to. SEL_Cases is your own selector:
// a with sharing class extending kern.SEL_Base.
return (List<Case>)new SEL_Cases().query
	.condition(Case.IsClosed).equals(false)
	.toList();

You write: nothing. You configure: copy kerndx-pmd-ruleset.xml into a scanner folder and add a code-analyzer.yml file, or run the bundle's kerndx init, which writes both.

What you also get

1scan→16checks you didn't write

Framework patterns

Reads through selectorsKernNoInlineSOQL flags an inline query or Database.query, test classes too.KernNoInlineSOQL
Saves through DML_BuilderKernNoDirectDML flags insert, update, delete, upsert and undelete written by hand.KernNoDirectDML
Logs and callouts the KernDX wayKernNoSystemDebug points to LOG_Builder; KernNoRawHttp points to UTIL_HttpClient.KernNoSystemDebug · KernNoRawHttp
Jobs through SCHED_BaseKernUseSchedulerBase and KernNoRawSchedule flag a plain Schedulable and System.schedule.KernUseSchedulerBase · KernNoRawSchedule
One trigger, one lineA trigger that does more than hand over to the dispatcher is reported.KernTriggerMustDelegate
Cache, describes, crypto, email and eventsRaw platform calls for these are reported and pointed to the KernDX helper that wraps them.KernNoRawCache · KernNoRawDescribe · KernNoRawCrypto · KernNoRawEmail · KernNoRawEventPublish

Limits

Limits read through one helperA raw Limits call is reported, so every limit check goes through the same wrapper.KernLimitsThroughWrapper

Tests and security

Tests that really testKernNoCoverageTheatre flags a test with no assertion or an empty catch; KernNoBooleanExceptionThrown flags a flag set in a catch.KernNoCoverageTheatre · KernNoBooleanExceptionThrown
Exemptions need a reasonSwitching off the coverage check is itself reported, so a reviewer looks for the comment that says why.KernCoverageExemptRequiresReason
Test data through the builderHand-built test records and inline saves in tests are reported.KernUseTestBuilder · KernNoInlineDmlInTests
Bypasses marked for reviewKernSecurityBypassCallSite flags each place that bypasses sharing or field security, so someone confirms it.KernSecurityBypassCallSite
Problems that show only after installAn invocable class with no empty constructor, or a JSON class without JsonAccess, is reported before it fails in another org.KernInvocableClassNeedsNoArgConstructor · KernJsonReadClassNeedsJsonAccess

Beyond Apex

The same for componentsThe ESLint plugin asks for ComponentBuilder and flags text a user sees that is not in a label.kerndx/use-component-builder · kerndx/no-hardcoded-user-text
Flows and objects named one wayA naming check reads Flows and custom objects, which PMD and ESLint cannot.scanner/validate-naming.js
Your own naming rulesA shipped template shows how to add PMD rules for your org's names.scanner/subscriber-naming-pmd-ruleset.xml

Review and CI

Fail the build when you chooseA scan only reports until you add --severity-threshold; then findings at that level fail the CI job.Code Scanning Fast Start
Keep a slow result in Platform Cache, without key rules or a missing cache breaking the callUtilities Guide → Platform Cache

Why: Platform Cache keeps a value between requests, so you skip a slow query or callout the next time. UTIL_Cache puts a safe layer over it: it tries the session cache, then the org cache, accepts any key, zips large values, and returns null or false instead of throwing when no cache is there.

The package brings its own partition (a share of the cache), named Library and shown in Setup as LibraryCache.

Plain Apex Manual

apex
Cache.OrgPartition partition = Cache.Org.getPartition('local.Rates');
Object rates = partition.get('usdToEur');
if(rates == null)
{
	rates = RateService.fetch();
	partition.put('usdToEur', rates, 3600);
}
// A key may hold only letters and digits, 50 at most: 'usd-to-eur' fails.
// A value over 100KB is refused; nothing is zipped for you.
// A partition name that does not exist throws, at every call.
// A value per user? Build the key with the user Id yourself.

KernDX Included

apex
kern.UTIL_Cache.Store cache = kern.UTIL_Cache.auto(); // session cache, then org cache
Object rates = cache.get('usd-to-eur');               // any key: a long or odd one is hashed
if(rates == null)
{
	rates = RateService.fetch();
	cache.put('usd-to-eur', rates, 3600);             // zipped when it is large
}
// No cache space? get returns null and put returns false; nothing throws.
kern.UTIL_Cache.OperationResult result = cache.getLastOperationResult();
// result.status says what happened, and errorMessage says why.
// Your own partition instead: kern.UTIL_Cache.partition('local.Rates')

You write: a few calls in your own class. You configure: space for the kern.Library partition in Setup (Platform Cache).

What you also get

1store→11capabilities you didn't write

Reliability

Session first, then orgauto() uses the session cache when there is one and the org cache when there is not, for example in a background job.kern.UTIL_Cache
Nothing throwsA missing partition or no cache space gives null or false, and getLastOperationResult() says why.kern.UTIL_Cache
A soft fallback when you want oneautoWithTransactionFallback() keeps the value in memory for this transaction when Platform Cache has no space.kern.UTIL_Cache
Ask before you rely on itisAvailable and isAllocated say whether a cache is there and has space.kern.UTIL_Cache

Less code

Any key worksA key that is long or holds other characters is turned into one the platform accepts.kern.UTIL_Cache
Large values zippedA value over about 4KB of JSON is zipped before it is stored; JSON shrinks by 80 to 90%.kern.UTIL_Cache
A key per userwithUserScope(true) keeps each user's values apart without building the key yourself.kern.UTIL_Cache
Many keys in one callputAll and getAll store and read a map of values together.kern.UTIL_Cache
Lifetimes under five minutesThe platform keeps a value at least 300 seconds; the store honours a shorter lifetime by checking it on read.kern.UTIL_Cache

Set up

A partition that shipsThe Library partition comes with the package; isAvailable() and isAllocated() say whether it has space.kern.Library · kern.UTIL_Cache
Your own partition, or nonePoint the store at a partition of yours, or keep values in memory for one transaction with no Platform Cache.kern.UTIL_Cache
Find what failed overnight from a screen, not a pile of queriesAdministration Tools Guide →

Why: the Kern app watches your KernDX integrations, events and background chains (not your whole org) and puts the tools to act on them in one place: no Postman, no throwaway anonymous Apex, no streaming client of your own.

Plain Apex and other tools Manual

apex
// Something failed overnight. In anonymous Apex:
List<kern__LogEntry__c> errors = [
	SELECT kern__ShortMessage__c, CreatedDate FROM kern__LogEntry__c
	WHERE kern__LogLevel__c = 'ERROR' AND CreatedDate = TODAY
];
System.debug(errors.size()); // thousands of rows, mostly one error
// Which step of the chain broke? Read job records by hand.
// Replay the call? Postman. Watch events? Your own streaming client.
// Which fields hold sensitive data? A hand-written audit.

KernDX: App Launcher, then Kern Included

text
Kern Home
  Health Check             is the org set up right? many fixes in one click
  Log Console              repeats grouped into problems; one run, one timeline
  Chain Monitor            which step broke and how far it got; retry or abort
  API Test Harness         fire a real callout or endpoint, with Safe Mode
  Streaming Event Monitor  watch platform events arrive as they happen
  Data Masking Advisor     build a masking configuration from a scan

You write: nothing. You configure: a KernDX permission set for each user, such as Kern Administrator or Kern Read Only.

What you also get

0lines→10screens and actions you didn't build

Troubleshoot

Problems, not rowsThe Log Console folds repeats into "this error, N times" and lays one run out on a timeline.kern/logConsole
The step that brokeThe Chain Monitor shows each step's status and error, and offers retry or abort to the users you allow.kern/chainMonitor
Stop, retry or restart a chainFrom the Chain Monitor, stop a chain, retry it from the failed step, or start it again.kern/chainMonitor
Retry a failed call from its recordRetry on an API issue runs the original call again; Retry Selected does many at once.kern__ApiIssue__c
Fire a call from a formThe API Test Harness runs a real callout or endpoint; Safe Mode rolls back every save.kern/apiTestHarnessForm

Monitor and set up

Is the org ready?The Health Check banner on Kern Home sorts checks into action required, review and passing.kern/healthCheck
Events as they arriveThe Streaming Event Monitor subscribes, publishes test events and shows each payload.kern/streamingMonitor
Each scheduled job on its recordThe job page shows the last outcome, Run now and View log.kern/scheduledJobDetail

Governance

Masking from a scanThe Data Masking Advisor builds a masking configuration you can deploy, instead of a hand audit.kern/dataMaskingAdvisor
A list of regulated fieldsExport every field and its masking as CSV or JSON, or only the sensitive ones.kern/dataMaskingAdvisor

Pick your path

New to KernDX? From Plain Apex to KernDX shows the Apex you already write next to the KernDX version. Deciding whether to use it? Start with Why KernDX.

I need toTry it in minutesLearn it properlyLook up a method
Query recordsSOQL, selectors, counts and totalsFast Start: SelectorsSelectors guideQRY_Builder
Save recordsInsert, update, upsert, delete, unit of workFast Start: DMLDML guideDML_Builder
Run code on a triggerLogic before and after a saveFast Start: Trigger ActionsTriggers guideTRG_Base
Log what happenedInstead of System.debugFast Start: LoggingLogging guideLOG_Builder
Run work in the backgroundQueueable jobs in stepsFast Start: Async ProcessingAsync Processing guideUTIL_AsyncChain
Call another systemHTTP callouts and retriesFast Start: Outbound APIsWeb Services guideUTIL_HttpClient, API_Outbound
Run a scheduled jobSchedulable and the job runnerFast Start: Scheduled JobsAsync Processing guideSCHED_Base
Validate recordsRules that stop bad dataFast Start: Custom ValidationsValidation guideUTIL_ValidationRule
Control who can see recordsSharing, field security and user modeFast Start: SecuritySecurity guideQRY_Builder.Builder, UTIL_Sharing
Test my codeTest data and pretend query resultsFast Start: Test DataTest Data guideTST_Builder, TST_Mock

Built for AI-assisted development

Your AI assistant gets the standards before it writes.

KernDX ships its AI context as plain files in the public repo, with nothing to install, so Claude, Cursor, Copilot, or Gemini generate Apex and LWC that follow the framework (the naming, the secure defaults, the audited-bypass rule) instead of inventing their own.

KernDX is a library of Salesforce frameworks for Apex and LWC, open source under the Apache License 2.0. It is one managed package (namespace kern, API 68.0). It covers trigger handling, secure queries and saves, structured logging, background-job orchestration, scheduled jobs on a shared job runner, inbound and outbound REST, no-code feature flags and validation, and write-time data masking, plus the CI tooling (PMD rulesets, an ESLint plugin, secret scanning, and coverage gates).

What ships, and how to wire it up

  1. AGENTS.md sits at the repo root: the tool-neutral on-ramp that Claude Code, Cursor, Codex, and Cline read first. It orients your assistant and points it at the conventions and the full reference.
  2. AI Agent Instructions is the complete code-generation reference. Copy it into the rules file your tool auto-loads (AGENTS.md, CLAUDE.md, or .cursorrules), or reference it so a git pull keeps it current.
  3. From then on your assistant writes framework-correct Apex and LWC: the right namespace prefix, FLS-enforced reads and writes, the naming rules, and the audited-bypass pattern, instead of reinventing them.

AGENTS.md · /llms.txt · Code Conventions Guide · PMD + ESLint rules

Those same standards ship as PMD rulesets and an ESLint plugin, so what the assistant follows is also enforced where you already work: inline in VS Code or IntelliJ / Illuminated Cloud, and gated on every pull request in CI.

Open the AI Agent Instructions →

Ideas worth taking

Worth reading even if you never adopt KernDX.

These are design decisions, not feature names, so take the ideas with you. Each links to the guide that explains the thinking. The source is public under the Apache License 2.0.

How a request flows

Many ways in. One secure core. Optional layers.

An LWC call, a DML save, a trigger, a REST endpoint, a batch job: any of them starts the same way. The core transaction is always there; the rest snap in only when your code uses them, and one tracking ID (the correlation ID) ties whichever layers ran into a single trace.

Any entry point
LWC / AuraApex serviceTriggerREST endpointBatch / Scheduled
8f14e45f-… follows everything below
Always runsThe KernDX core transaction
🔒 Security & FLSQuery · QRY_Builder / SEL_BaseDML · DML_Builder📦 Atomic save🧵 Correlation ID
only the layers your code actually uses
Optional snap-ins
⚙️ Async · UTIL_AsyncChain🌐 Outbound REST · UTIL_HttpClient📝 Telemetry · LOG_Builder

Adopt one layer today (just the query library, say) and snap in the trigger framework or the async chain the day you need it. The correlation ID makes whatever ran traceable as one request, and every chain it launches keeps a link back to it.

Already using fflib, Trigger Actions, or rolling your own?

What's different by default.

  • Security is enforced on reads and writes, with an audit entry written when a call opts out through the builders, triggers or validation rules.
  • One integrated package: triggers, queries, transactions, logging, REST, async, and masking share one model, instead of you wiring separate libraries together.
  • 100% Apex coverage and PMD-clean, enforced on every build, not aspirational.
Full capability-by-capability comparison →

Honest about scope: where another library has something KernDX does not, the guide names it, capability by capability. For example, nebula-logger offers a choice of how each log is saved, all seven log levels, a retention date per log entry or scenario, and Big Object archiving. fflib-mocks can check how a mock was called and with what (behaviour verification).

Adopt at your own pace

Not all-or-nothing.

No rip-and-replace, and nothing you take all at once, which is what makes it low-risk to bring into an existing program. A typical path in: the query library first, then secure DML, then the trigger framework, adding async, masking, and the AI standards whenever you reach for them. Each layer stands alone, so adoption stays incremental and reversible.

A fit if…

  • more than one developer works in the org
  • AI is writing more of your Apex
  • consistency is getting expensive
  • onboarding a contributor takes too long
  • you need security you can show a reviewer

Not needed if…

  • your org has no Apex and none planned

Already running another framework? That is a cost to weigh, not a reason on its own. Staying has costs too, such as wiring separate libraries together or safety checks that can be switched off without a record. Moving has the cost of the migration. The capability-by-capability comparison sets out both.

Can't install a managed package, or would rather not? Because the source is available, you can deploy KernDX straight into your org as unmanaged code (no namespace, no Dev Hub), or repackage it under your own namespace. Installed unmanaged, its code counts toward your org's 6 MB Apex limit, and you update it by redeploying the source. There's a way in for every org.

Install KernDX v1.12