certal
v0.3.0
Published
Deterministic execution firewall and runtime for AI agents. Zero dependencies, SQLite WAL, write-ahead outbox, human-priority undo, and Lean 4 proofs.
Maintainers
Readme
Certal
A deterministic execution firewall and runtime for AI agents.
Timeouts do not double-charge. Human edits do not get clobbered. Runaway agent loops hit a hard halt.
Certal sits between untrusted agents and real state. An agent submits typed proposals to a pure decision kernel, which is modelled and proven in Lean 4 and backed by a single-writer SQLite WAL log, a write-ahead outbox and signed operator approvals. A side effect that a tool declares is fired by Certal, not by the agent. Where an agent writes files itself, Certal coordinates leases, epochs and the audit log, and the limits of that mode are stated below.
| | |
|---|---|
| Runtime dependencies | None. Node.js 24 built-ins only, including node:sqlite and node:crypto. |
| Machine-checked core | 37 theorems in Lean 4.34.0, no Mathlib, no sorry. The model is checked against the TypeScript kernel on 5,354 conformance vectors. |
| Hostile agents | Origin-restricted ports stop agent code from forging human edits, witness verdicts or approvals. |
| License | MIT |
Agent (untrusted) Witness (System) Operator (Human)
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────────────────┐
│ CertalRuntime (single writer) │
│ agent queue ◄──────────── human priority lane (skips the queue) │
│ secret redaction, blob offload │
│ │ │
│ ▼ │
│ pure decision kernel: step(state, envelope, hooks) │
│ leases · pins · budgets · signed approvals · Lean 4 model │
└──────────────────────────┬─────────────────────────────┬────────────────┘
▼ ▼
SQLite WAL log write-ahead outbox
RFC 8785 JSON + SHA-256 chain INTENT → IN_FLIGHT → APPLIED
atomic per step, replayable crash or timeout → reconcile onlyWhy Certal exists
Prompt guardrails stop working when an agent meets a real production edge case.
The timeout double-send. A call to an external API times out after it succeeded on the remote side. A retry charges or trades twice. Certal records every external effect before sending it, moves a crash or a timeout to UNKNOWN, and from there allows only Reconcile. It never delivers the same effect a second time. An agent that tries again with the same effect key gets a refusal, not a second delivery.
The human overwrite. An operator fixes a record while an agent is mid-flight, and the agent overwrites the fix two seconds later. In Certal a human edit skips the queue, evicts the colliding agent lease, raises the epoch of that scope and invalidates the agent's stale work. Other scopes keep running.
The silent undo trap. Rolling back an agent's changes often wipes later human edits. Certal's undo restores only the fields that still belong to that agent batch and keeps what the human changed. When a field conflicts, compensation of the external effect goes to the operator instead of firing on its own.
The approval bypass. A human-in-the-loop flag is useless if the agent can change the payload after approval or replay an old token. Certal binds each approval to the exact diff, scope hash and input snapshot. A token is single-use, it expires, and by default it must carry the operator's signature.
Guarantees
| Mechanism | What the kernel enforces |
|---|---|
| Fresh proof | A batch closes only with a PASS witness verdict that matches the live scope hash, scope epoch and input snapshot. |
| Human priority | A human edit bypasses the agent queue, evicts colliding leases and invalidates stale work in its scope. Other scopes are untouched. |
| Signed consent | An approval binds diffHash, scopeHash and inputSnapshotHash. It is single-use, time-bounded and signature-checked by default. |
| Autonomy ladder | A new tool starts in SHADOW: external effects are blocked and every batch needs a signed approval. Clean history raises the tier, a violation drops it. |
| Pins | A hard pin blocks agent writes. A timed pin blocks them until it expires. A human edit sets a timed pin on its scope that ends after policy.autoPinTtlMs, 10 minutes by default. A soft pin adds cost or escalates to approval. An agent manages only its own soft pins and cannot replace or remove a pin of another owner. |
| Hard budgets | Attempt, CPU and cost limits pause the task. A fail streak moves it to HALTED, which only a human HumanReset clears. |
| Crash-safe effects | Every external call goes through the write-ahead outbox. An unknown outcome can only be reconciled. An effect key of one recipient is delivered once: a later batch with the same key is refused. |
| Undo by origin | A human reverts an agent batch field by field. Later human edits stay. A delivered effect of the batch is compensated or handed to the operator, never passed over. The operator chooses what happens on a field conflict: abort the undo, pause for a decision (the default), or compensate anyway. |
| Policy in the log | The starting policy is the first log entry, and every later change is a logged event. A replay needs only the log. |
Quick start
Requires Node.js 24 or newer.
npm install certal
npx certal init --preset sdkinit writes certal.json, creates the operator key and adds .mcp.json. The rest of this section uses the library directly.
An agent changes two fields, a human corrects one of them, and the undo reverts only what is still the agent's.
import { CertalRuntime, InMemoryStore } from 'certal/runtime';
import { EmbeddedToolSdk, InMemoryReferenceAdapter } from 'certal/adapters';
const adapter = new InMemoryReferenceAdapter();
const runtime = new CertalRuntime({
store: new InMemoryStore(),
hooks: adapter.hooks,
// Demo settings. The default policy starts a new tool in SHADOW,
// which blocks external effects and requires a signed approval.
policyOverrides: {
enforceAutonomyLadder: false,
requiredWitnessStages: ['L0'],
},
});
const sdk = new EmbeddedToolSdk(runtime, adapter);
// 1. The agent proposes a batch. The kernel checks the lease,
// the base revisions and the witness verdict.
const outcome = await sdk.agent.executeToolCall({
opId: 'call-1',
attemptId: 'attempt-1',
taskId: 'task-1',
toolId: 'crm',
domainObjectId: 'order-42',
executorId: 'agent-a',
scopeId: 'orders',
classId: 'order-fields',
rawInputs: { source: 'demo' },
confidence: 'exact',
ops: [
{
opIndex: 0,
objectId: 'order-42',
classId: 'order-fields',
field: 'status',
expectedBeforeRev: 0,
beforeValue: null,
afterValue: 'booked',
reversibility: 'REVERSIBLE',
},
{
opIndex: 1,
objectId: 'order-42',
classId: 'order-fields',
field: 'note',
expectedBeforeRev: 0,
beforeValue: null,
afterValue: 'booked by agent',
reversibility: 'REVERSIBLE',
},
],
});
console.log(outcome.finalized, outcome.reason);
// true BATCH_FINALIZED
// 2. A human overrides one field, then rolls back the agent's batch.
await sdk.operator.humanEdit(
'alice', 'orders', 'order-fields', 'order-42', 'note', 'call the customer first',
);
const undo = await sdk.originUndo('alice', 'attempt-1', 'orders', 'wrong booking');
console.log(undo.report.appliedFields);
// [ { objectId: 'order-42', field: 'status' } ]
console.log(undo.report.skippedConflicts.map((c) => c.reason));
// [ 'HUMAN_OVERWRITE' ]status goes back to null. Alice's note is untouched.
Command line and MCP gate
The certal command puts the runtime in front of any agent that speaks MCP. With a local install, run it as npx certal. From a checkout, run it as node bin/certal.mjs.
certal init --preset sdk # certal.json, the operator key, .mcp.json, .gitignore
certal mcp # MCP server over stdio, one agent
certal mcp --transport http --agents alice,bob # several agents, one bearer token each
certal status # scope epochs, leases, autonomy tiers, pins, pending approvals
certal approve <attemptId> --ttl 300s
certal undo <batchId> --policy abort|all-reverted|force
certal halt <scopeId> --reason "..."
certal reset <scopeId> --reason "..."
certal unpin <pinId> # end the pin of a manual edit before its time
certal verify --offline .certal/certal.db
certal witness-input --tool <id> --scope <id> --ops <file.json> # dry run: what a witness command would readManifest. certal.json declares the policy, scopes, hard pins, tools and witness stages. It is plain JSON with a schema, certal.schema.json. Certal merges the manifests it finds from the working directory up to the filesystem root. A subdirectory may add pins and lower budgets. It cannot remove a pin, raise a limit, switch off a check, change a declared command, add an approver or bring a tool of its own (unless the outermost manifest sets allowSubdirectoryTools). A merge that would relax anything fails and lists every violation. Four presets are in presets/: sdk, solver, exchange-firewall and vibeops. Their commands are templates that you point at your own checks.
A changed manifest. A manifest names the commands that run: the deliver command of a tool, the witness stages, the approval address. The first start of a project records a fingerprint of the manifest in the operator home, outside the project. A later start with another manifest is refused and names the sections that changed, whatever the change is: a new command, a new scope or a new pin. The operator reads the change and runs certal accept-manifest, which needs the operator key of that machine. The layout of the file does not count, and certal status reads the state without this check.
What an agent can call. Five MCP tools: certal_lease_acquire, certal_lease_release, certal_propose_batch, certal_finalize_batch and certal_status. There is no tool to approve, undo, halt, reset or change a pin. When the manifest declares scopes, an agent can lease only a declared scope, and every object of a batch must belong to that scope. Object ids are normalized as paths: ./a, a and a\\..\\a cannot name the same file in two ways, and an absolute path or a .. segment is refused.
Which scope owns a path. The order of the scopes in the manifest does not matter. Two rules decide, in this order.
- A pinned scope wins. When a scope with a pin matches a path, a scope without a pin never owns that path, whatever the two patterns look like. With a pinned
access: policies/**, the filepolicies/a.mdbelongs toaccessalso when another scope listspolicies/*.md,policies/*or**. When two pinned scopes match the same path, nobody owns it. - Among scopes without a pin, a whole-directory pattern (
dir/**,**or a pattern without a wildcard) is a fallback: it gives way to a pattern of another scope that starts inside that directory. This rule reads the text of the patterns, and it only orders scopes that no pin covers.
A path that still has two owners is refused with OBJECT_SCOPE_AMBIGUOUS under either lease. The same pattern in two scopes is refused when the manifest is loaded.
Patterns and object ids. A pattern has * and ? inside one path segment and ** for any number of segments. ** must be a whole segment: write **/*.sql for the SQL files of every directory, because **.sql is refused. A pattern without a wildcard names a file or a directory with everything below it, so policies and policies/** cover the same files. Braces, brackets, a backslash, a trailing / and an absolute path are refused when the manifest is loaded, because such a pattern would match nothing and a pin behind it would protect nothing. A pattern and a path are compared without letter case and in one Unicode form on every platform, so Policies/x.sql, a name typed with a combining accent and a name with a long s or a full-width letter all fall in the scope of the plain spelling. On a case-sensitive file system this also puts SRC/a in the scope of src/**. An object id is at most 1,024 characters, is stored in Unicode form NFC, and may not hold a control character, an invisible character or a text-direction mark. A scope without paths takes plain ids only: an id with a / is refused there.
Links. In a scope that lists paths, the gate resolves the real path of every object when a batch is proposed and again when it is finalized. A symbolic link, also in a parent directory, that leads into another scope or out of the project is refused with OBJECT_OUT_OF_SCOPE. A file with a second hard link is refused with OBJECT_HARD_LINKED, also when the second name is a harmless backup: the other name cannot be found without reading the whole disk. The answer carries a detail sentence that says so.
A pin covers a scope. A lease on a declared scope always has the class of that scope, so a pin must name that class or *. A pin on another class would never apply, and the manifest is refused. To protect some objects of a scope, give them a scope of their own and pin it: the vibeops preset does this for migration files with drop or truncate in the name. That rule reads the file name, not the SQL in the file.
Two ways to change state. They give different guarantees, so choose one per tool.
| | Effect mode | File mode |
|---|---|---|
| How it is declared | The tool has a deliverCommand | The scope has paths, usually with "watch": true |
| Who writes | Certal. certal_propose_batch hands the proposed ops to the witness on stdin, and after certal_finalize_batch the outbox runs deliverCommand. The agent never touches the target. | The agent, after certal_finalize_batch answers ALLOW. It declares the SHA-256 hash of the new content in the batch first. |
| What the witness checks | The proposal that will be delivered: ops[].effect on stdin | The declaration on stdin: ops[].value is the declared hash. It runs before the file is written, so it does not see the file. |
| What Certal guarantees | The effect is sent once, only after a fresh verdict and a valid approval, and an unknown outcome is only reconciled | Leases, scope epochs, pins and the audit log. It does not guarantee that the file on disk matches the declared hash. |
Effect keys. An operation with an effect carries a key that the agent chooses, effect.key. The key names one delivery to one tool, for good. A later batch that uses the same key for the same tool is refused: with EFFECT_KEY_ALREADY_USED when the payload is the same, with EFFECT_KEY_CONFLICT when it differs. The first delivery stands in every state, also UNKNOWN, refused or compensated, and nothing is sent again. To send again after a refused or expired delivery, use a new key. The same key twice in one batch gives DUPLICATE_EFFECT_KEY. The check runs at the proposal and again at the finalize, and it holds after a restart, because the store keeps an index of every key. The deliver, reconcile and preflight commands get the key on stdin as effectKey, next to effectId, toolId and payload, so a command can pass it to the recipient as an idempotency key. A compensate command gets the key of its effect with the suffix /undo or /comp.
The text that a deliver or preflight command prints is not stored, because it may hold a key or the data of a customer. A command names the reason of a refusal with one word in capitals at the start of stderr, such as INSUFFICIENT_FUNDS, and only that word reaches the log.
What a command reads. Every declared command gets one JSON document on stdin and answers with its exit code. A witness command and its near-miss probe get the same document:
| Field | Meaning |
|---|---|
| verifyId, attemptId | The verification and the attempt it belongs to |
| stage | L0, L1, L2 or L3 |
| scopeId, classId, toolId | Where the batch applies and which tool proposed it |
| binding | diffHash, scopeHash and inputSnapshotHash: the content that the verdict will be bound to |
| budgetCpuMs | The time that is left for this command, in milliseconds |
| requireNearMiss | True when the kernel itself asks for a near-miss proof at this stage |
| ops | The proposed operations, in the order of the batch |
An operation in ops:
| Field | Meaning |
|---|---|
| opIndex | Position in the batch, from 0 |
| objectId, classId, field | The slot that the operation writes. In file mode objectId is the relative path and field is sha256. |
| value | The proposed value, as the agent sent it in certal_propose_batch. In file mode it is the declared SHA-256 hash of the new content. |
| afterValue | The same value under the name that the kernel uses |
| beforeValue, expectedBeforeRev | The value and the revision of the slot when the batch was proposed. null and 0 for a new slot. |
| reversibility | REVERSIBLE, COMPENSABLE or IRREVERSIBLE, from the tool |
| effect | Present only for an operation with an effect: key, payload and, when given, inversePayload, as the agent sent them |
| externalEffect | The same effect under the names of the kernel: effectKey, recipientId, supportsCas, actionPayload, inversePayload |
For a batch that declares one file, the document looks like this:
{
"verifyId": "…", "attemptId": "agent-1-12-3-a1b2c3", "stage": "L0",
"scopeId": "frontend", "classId": "file", "toolId": "edit",
"binding": { "diffHash": "…", "scopeHash": "…", "inputSnapshotHash": "…" },
"budgetCpuMs": 5000, "requireNearMiss": false,
"ops": [
{ "opIndex": 0, "objectId": "src/app.ts", "classId": "file", "field": "sha256",
"value": "9f86d081…", "afterValue": "9f86d081…",
"beforeValue": null, "expectedBeforeRev": 0, "reversibility": "REVERSIBLE" }
]
}A witness command answers 0 for PASS and 1 for FAIL. A timeout, a crash or any other exit code is UNKNOWN, which the kernel does not take as proof. A failed check counts against the tool on the autonomy ladder, so write the check to fail when a field it needs is missing. A check that treats a missing field as "nothing to check" passes every batch.
Try a witness command without a batch. certal witness-input --tool <id> --scope <id> --ops <file.json> prints this document for a batch that nobody proposed. The file holds the ops list of certal_propose_batch: objectId, field, value and, where the operation has one, effect. The command is a dry run. It starts no check, writes nothing to the log or to the state directory, and needs no server. With --agent the document is one line, so it can go straight to a check:
certal witness-input --tool edit --scope frontend --ops ops.json --agent | node check.mjs
echo $? # 0 is PASS, 1 is FAILThe operations go through the same check and the same mapping as in the gate, and the same function builds the document. A batch that the gate would refuse is refused here with the same reason, such as OBJECT_OUT_OF_SCOPE or UNKNOWN_TOOL, and the command ends with exit code 1. Some fields exist only in a live attempt. A dry run fills them like this:
| Field | In a dry run |
|---|---|
| verifyId, attemptId | The text "dry-run". No attempt exists. |
| binding | "dry-run" in each of the three hashes |
| beforeValue, expectedBeforeRev | null and 0, as for a new slot. The command does not read the state. |
| stage | The first stage of policy.requiredWitnessStages in the manifest, or the stage given with --stage |
| budgetCpuMs, requireNearMiss | The values of that stage in the manifest. A live run can give a stage less time. |
A check that compares a hash of binding, or the value that a slot had before, needs a live attempt to be tested.
A deliver, reconcile, compensate or preflight command gets the effect, not the batch: effectId, effectKey, effectKind (Deliver or Compensate), batchId, scopeId, classId, toolId and payload. A preflight command also gets nowMs. Exit code 0 means applied, 2 means refused, and anything else means that the outcome is unknown.
Witness stages run as child processes. The time limit of a stage is the smaller of the manifest budget and the budget that the kernel grants, and a timeout kills the whole process tree. A preflight command runs without holding the write loop, so a human event never waits behind it.
What an agent reads. Every answer has the same six fields, so the agent knows whether to go on, wait or stop:
{ "decision": "PAUSE", "reason": "APPROVAL_REQUIRED", "scopeId": "orders", "scopeEpoch": 4, "nextLegalAction": "wait_for_operator_approval", "retryable": true }--agent makes every CLI command print the same one-line form.
The operator. certal init creates an Ed25519 key in ~/.certal/operator.key and writes the public key to the manifest. certal approve signs an approval token for the exact content of one attempt. Every operator command that reaches a running server is signed with the same key, carries a timestamp and a nonce, and is refused without a valid signature. The operator keys are fixed by the first start of a log: a later manifest edit cannot add an approver.
Agents over HTTP. The HTTP transport listens on a loopback address only. Every agent named in --agents gets a bearer token of its own, and the token alone decides who the caller is. The tokens are files in the operator home, ~/.certal/run/<project id>/agents/<agentId>.token, not in the project. certal mcp prints the directory and removes it when it stops. A request whose x-certal-agent header names another agent is refused with 403. A request above 4 MiB gets 413 after its body was read and dropped (a body above 32 MiB is cut off without an answer), and a request whose content type is not application/json gets 415. A tools/call without an id is not run, because the caller could not receive its answer.
Approval channels. The webhook address must be https, or http on this machine only. The default channel waits for certal approve. The webhook channel posts the binding hash, a summary of the change and the expiry to a URL, and accepts back only a token with a valid operator signature over the same binding.
File watcher. With "watch": true, a file in a declared scope that changes without a matching batch becomes a human edit: it raises the epoch of that scope and evicts a colliding agent lease. A deleted file counts too. Other scopes are not touched. A write that matches the hash declared in a finalized batch is the agent's own and is not reported.
The pin of a manual edit. A human edit also sets a timed pin on its scope and class, so an agent does not write over work in progress. The pin ends after policy.autoPinTtlMs milliseconds, 600000 (10 minutes) by default, counted from the last edit in that scope. An agent that meets it gets PIN_TEMP_BLOCKED with nextLegalAction: "wait_for_pin_expiry". certal status lists the pin with the time left, and certal unpin <pinId> ends it at once. A pin that the manifest declares is not removed this way. A subdirectory manifest may make the time longer, not shorter.
Offline audit. certal verify --offline <db> replays a copy of the database from the first entry. It compares every stored entry with the replayed one, field by field, checks the chain between entries, compares every stored checkpoint with the replayed state at its position, and compares the operation, approval and effect key indexes with the log. A log entry holds a hash of its whole stored envelope: the event, the time, the origin, the roles and the auth method. A change of any of these fields is found as REPLAY_ENTRY_HASH_MISMATCH. It needs no manifest: the operator public keys are stored in the database. A running server starts from its newest checkpoint and does not repeat this audit, so run verify on a database that someone else could write. A repeated request with the same operation id is answered from the record of the first one. It leaves no log entry and does not change the state, so the state of a running server is always the state that the log gives, and verify compares a checkpoint in full.
Database schema. A database is read by the schema that wrote it. This version writes schema 2 and refuses a database of 0.1.x with STORE_SCHEMA_UNSUPPORTED. See "Upgrade" in the changelog. verify proves that the stored entries are the ones that the stored events give. It does not prove that a field of an event which does not change the outcome, such as a label of the login method, is the one that was first written.
Limits of this layer:
- One process owns a state directory. A second server on the same directory is refused. Several agents share one server over HTTP.
- A changed manifest needs
certal accept-manifest. Even an accepted manifest may only tighten the log. A looser policy or a new operator key stops the start, and the way out is a new state directory. A pin declared while the task is halted is set right after the reset. - The watcher cannot tell who wrote a file. A process that writes a file without a batch, or with content other than it declared, is treated as the human: the write raises the scope epoch and is logged as a human edit. Certal does not treat a hash change during a lease as an agent violation, because it could not tell it from a real human edit. Use file mode where agents write through the gate, and effect mode where the agent must not touch the target at all.
- The
sdkpreset accepts every batch at stageL0without a check ("builtin": "accept"). It is a starting point. Declare a witness command that checks the proposal on stdin before you rely on a verdict. - The
destructive-migrationspin of thevibeopspreset is a rule on the file name. It covers a file withdroportruncatein its name in anymigrationsdirectory. It does not cover007_cleanup.sqlwith aDROPinside, or009_dr0p.sql. In file mode no check can read the SQL, because the file is written after the verdict. To check the statement itself, send migrations through a tool with adeliverCommandand read the SQL in a witness command. - The default budget is 20 attempts for a task (
policy.maxAttempts). A long session reaches it and pauses. Set a higher value in the manifest for long work. - An undo of a batch with an applied effect compensates the effect only when its tool declares
"supportsCas": true. Such a tool must name acompensateCommand: a manifest with"supportsCas": trueand nocompensateCommandis refused. WithoutsupportsCasthe effect is marked for manual compensation and the task pauses withMANUAL_COMPENSATION_REQUIRED. This holds for every tool, also one declaredREVERSIBLE. - An effect key is compared by tool and key. Two tools may use the same key. A payload is compared after the redaction of secrets, so two payloads that differ only in a redacted secret count as the same.
- An attempt that waits for approval after its witness verdict pauses the whole task, not one scope. Other agents continue after the approval or a
certal resume. - The key file gets mode
0600. On Windows the mode has no effect, and the profile directory protects the file. - The record of the accepted manifest is safe from a process that can write only the project. A process that can write the operator home can replace it, as it can read the operator key.
- A payload of an effect is stored after the redaction of known secret shapes. Data that has no such shape, such as the e-mail address of a customer, is stored as it was sent. Keep personal data out of payloads, or send a reference.
- File mode coordinates agents. It does not confine them. The link check runs at the proposal and at the finalize, and the agent writes the file afterwards: an agent that writes files itself can still create a link, or write a pinned file directly. The watcher records such a write as a human edit when it sees it, and it does not see a write through a hard link. Where an agent must not be able to reach a target, use effect mode and keep the target outside the agent's file access.
- In file mode an undo changes the record, not the files. The slots return to the earlier hashes, and the files on disk stay as they are until someone writes them back.
- Tokens and the operator key are protected from an agent only when the agent cannot read the operator home. An agent that runs as the same operating-system user with access to the whole disk can read both. Give each agent its token through its own configuration, and run agents under an account or a sandbox that does not see
~/.certal. - A command that ends takes its background processes with it on Linux and macOS. On Windows a process that the command left in the background keeps running. A timeout kills the whole process tree on every platform.
- Commands run without a shell. On Windows,
npmandnpxare batch files: call them throughnodeor use the.cmdname. - The audit shows that a database is consistent with itself. Compare the last entry hash with a value kept elsewhere to detect a log rewritten from scratch.
Trust boundary
The SDK has three parts. Each one holds a runtime port that accepts a single origin kind and rejects anything else before it reaches the log.
| Part | Port | Can do |
|---|---|---|
| AgentGateway | Agent | Acquire a lease, open an attempt, submit and finalize a batch. It cannot issue human or witness events. |
| WitnessService | System | Run verification stages and submit verdicts. |
| OperatorConsole | Human | Edit, set and remove pins, approve and sign, cancel an attempt, halt, reset, resume, undo. |
EmbeddedToolSdk wires all three in one process for local runs and tests. The separation is between objects, not processes. In production give agent code only an AgentGateway, and run the operator and witness ports in a separate process with its own authentication.
Architecture
Imports go one way: kernel → runtime → adapters → mcp → cli → tests. A static check enforces the direction.
| Layer | Contents |
|---|---|
| core/kernel/ | Pure transition function step(state, envelope, hooks). No I/O, no system clock, no randomness. RFC 8785 canonical JSON and SHA-256 with the certal:v1: domain prefix. |
| core/runtime/ | CertalRuntime single-writer engine with a human priority lane, SQLiteStore (WAL) and InMemoryStore, secret redaction before persistence, blob offload, outbox worker with crash recovery. |
| core/adapters/ | Domain adapter contracts, a reference in-memory adapter and the SDK. |
| core/mcp/ | Host for one state directory (manifest, SQLite log, runtime, outbox, signed operator endpoint) and the MCP server over stdio and local HTTP. |
| core/cli/ | The certal command. |
| formal/CertalKernel/ | Lean 4 model of the kernel, module by module, with proofs and the certal_conformance runner. |
The repository layout follows axiomatic design: one functional requirement, one design parameter, one directory. The decomposition and its dependency matrices are in docs/DESIGN.md.
Formal verification
The model in formal/CertalKernel/ uses Lean 4.34.0 without Mathlib. Every theorem depends only on propext, Classical.choice and Quot.sound.
| Theorems | Property (short form) |
|---|---|
| T01, R01 | HALTED is absorbing. No sequence of events without a human HumanReset leaves it. |
| T02 | A clock that goes back returns REJECT with CLOCK_REGRESSION and changes no slots, epoch, status, batches or effects. |
| T03, T04 | A repeated opId with the same payload is an idempotent replay that leaves the state as it is. With another payload it ends in REJECT or HALT, and nothing is applied. |
| T05, T06 | Finalizing a batch requires a verified attempt, a fresh scope epoch and a matching scope hash. A verdict that does not match the pending verification is rejected. |
| T16, T23, T24 | An accepted human edit leaves no colliding lease, raises the epoch of its own scope by one and does not change the epoch of any other scope. |
| T12 | An agent cannot set, replace or remove a hard or timed pin. Every such pin is still in place after the step. |
| T25 | A batch that uses an effect key that the state already holds for the same recipient is not finalized. |
| T26 | The pin that an accepted human edit sets has an end: the time of the event, otherwise the time of the policy. |
| T27 | An applied undo of a batch with a delivered effect queues its compensation or hands it to the operator. It does not report that nothing was needed. |
| I01–I05 | The same guarantees at every step of a trace of any length: fresh proof at each finalize, single-use approvals, no agent mutation and no delivery in HALTED, no re-delivery from an effect transition, and undo that keeps slots written by a human. |
| V01–V04 | Non-vacuity: the assumptions of the theorems can be satisfied. |
Exact statements of all 37 are in Challenge.lean and Inductive.lean.
Proof boundaries
Read these before you rely on the formal claims.
- Hashes, identifiers and signature checks enter the Lean model through an oracle. The theorems hold for any oracle. SHA-256, canonical JSON and signature verification are tested in TypeScript, not proven.
T01–T27describe a single step.R01andI01–I05hold along traces of any length under one fixed oracle. The kernel keeps a bounded window of spent approvals, so beyond that window single use of an approval depends on the durable store, which the model sees as the oracle.- The model and the TypeScript kernel are compared on 5,354 deterministic vectors that cover all 20 event kinds. That is a test. The TypeScript code is not extracted from the model.
More limits are listed in formal/README.md.
Checks
npm run check # structure, lint, typecheck, 103 tests, 62 mutants
npm run check:formal # token scan, clean lake build, axiom audit, 5,354 vectors, 6 model mutations
npm run check:all # both
npm run test:bench # latency of the human lane under agent load
npm run test:bench:cli # cold start of `certal status --agent` and MCP round tripscheck:formal uses a local lake when it finds one. Otherwise it runs Docker with --network none and the image named in CERTAL_LEAN_IMAGE (default certal-lean:4.34.0).
Documentation
- docs/DESIGN.md: functional requirements, design parameters, dependency matrices, kernel laws
- core/README.md: layers and modules
- formal/README.md: what is proven, limits of the model, the conformance check
License
MIT. See LICENSE.
