certal 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +56 -0
  3. package/LICENSE +21 -0
  4. package/README.md +289 -2
  5. package/SECURITY.md +36 -0
  6. package/bin/certal.mjs +12 -0
  7. package/certal.schema.json +156 -0
  8. package/dist/adapters/approval-channel.d.ts +44 -0
  9. package/dist/adapters/approval-channel.js +74 -0
  10. package/dist/adapters/commands.d.ts +77 -0
  11. package/dist/adapters/commands.js +209 -0
  12. package/dist/adapters/contracts.d.ts +59 -0
  13. package/dist/adapters/contracts.js +1 -0
  14. package/dist/adapters/file-watcher.d.ts +88 -0
  15. package/dist/adapters/file-watcher.js +297 -0
  16. package/dist/adapters/in-memory.d.ts +53 -0
  17. package/dist/adapters/in-memory.js +165 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +8 -0
  20. package/dist/adapters/manifest.d.ts +105 -0
  21. package/dist/adapters/manifest.js +465 -0
  22. package/dist/adapters/operator-auth.d.ts +53 -0
  23. package/dist/adapters/operator-auth.js +81 -0
  24. package/dist/adapters/tool-sdk.d.ts +150 -0
  25. package/dist/adapters/tool-sdk.js +336 -0
  26. package/dist/cli/index.d.ts +1 -0
  27. package/dist/cli/index.js +1 -0
  28. package/dist/cli/main.d.ts +1 -0
  29. package/dist/cli/main.js +384 -0
  30. package/dist/kernel/common.d.ts +46 -0
  31. package/dist/kernel/common.js +238 -0
  32. package/dist/kernel/crypto.d.ts +35 -0
  33. package/dist/kernel/crypto.js +54 -0
  34. package/dist/kernel/effects.d.ts +4 -0
  35. package/dist/kernel/effects.js +178 -0
  36. package/dist/kernel/index.d.ts +9 -0
  37. package/dist/kernel/index.js +9 -0
  38. package/dist/kernel/jcs.d.ts +24 -0
  39. package/dist/kernel/jcs.js +93 -0
  40. package/dist/kernel/leases.d.ts +11 -0
  41. package/dist/kernel/leases.js +86 -0
  42. package/dist/kernel/step.d.ts +10 -0
  43. package/dist/kernel/step.js +967 -0
  44. package/dist/kernel/types.d.ts +538 -0
  45. package/dist/kernel/types.js +1 -0
  46. package/dist/kernel/undo.d.ts +4 -0
  47. package/dist/kernel/undo.js +180 -0
  48. package/dist/kernel/validation.d.ts +13 -0
  49. package/dist/kernel/validation.js +307 -0
  50. package/dist/kernel/witness.d.ts +34 -0
  51. package/dist/kernel/witness.js +279 -0
  52. package/dist/mcp/host.d.ts +141 -0
  53. package/dist/mcp/host.js +517 -0
  54. package/dist/mcp/index.d.ts +2 -0
  55. package/dist/mcp/index.js +2 -0
  56. package/dist/mcp/server.d.ts +72 -0
  57. package/dist/mcp/server.js +549 -0
  58. package/dist/runtime/dp1.d.ts +48 -0
  59. package/dist/runtime/dp1.js +229 -0
  60. package/dist/runtime/engine.d.ts +86 -0
  61. package/dist/runtime/engine.js +320 -0
  62. package/dist/runtime/index.d.ts +4 -0
  63. package/dist/runtime/index.js +4 -0
  64. package/dist/runtime/outbox.d.ts +69 -0
  65. package/dist/runtime/outbox.js +238 -0
  66. package/dist/runtime/store.d.ts +214 -0
  67. package/dist/runtime/store.js +788 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +41 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +23 -0
  72. package/presets/vibeops.json +35 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "certal",
3
+ "version": "0.1.1",
4
+ "description": "Work through the Certal gate: leases, verified batches and operator approvals for every change.",
5
+ "author": { "name": "Paweł Olszewski" },
6
+ "repository": "https://github.com/polszewski-pl/certal",
7
+ "license": "MIT",
8
+ "mcpServers": {
9
+ "certal": { "command": "npx", "args": ["--no-install", "certal", "mcp"] }
10
+ }
11
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,56 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ Fixes from two audits of 0.1.0. The kernel and the Lean model are unchanged.
6
+
7
+ ### Security
8
+
9
+ - The order of the scopes in a manifest no longer decides who owns a path. A catch-all scope such as `**` placed before a pinned scope took the files of that scope, and the pin did not apply. A whole-directory pattern now gives way to a pattern inside that directory, and a file that two scopes claim in any other way is refused with `OBJECT_SCOPE_AMBIGUOUS`.
10
+ - Path patterns ignore letter case on every platform, so `Policies/x.sql` cannot pass as an object of another scope.
11
+ - A scope without paths takes plain ids only. An id with a `/`, such as `.git/hooks/pre-commit`, is refused there.
12
+ - A pattern with braces, brackets, a backslash or a trailing `/` matched nothing without a warning. Such a manifest is now refused. A pattern without a wildcard covers a directory with everything below it.
13
+ - In a scope that lists paths, a symbolic link into another scope or out of the project and a file with a second hard link are refused, at the proposal and at the finalize.
14
+ - Paths are matched without regular expressions. A long object id could stall the server for more than a minute. Object ids are limited to 1,024 characters, may not hold control or text-direction characters and are stored in Unicode form NFC.
15
+ - `certal verify --offline` compares every stored entry with the replayed one in full, every checkpoint with the replayed state, and both indexes with the log. A changed `applied` field and a forged checkpoint passed before.
16
+ - A pin that names a class other than the class of its scope never applied. Such a manifest is now refused when it is loaded.
17
+ - The per-agent tokens of the HTTP transport moved from `.certal/agents/` in the project to the operator home.
18
+ - A command that ends no longer leaves its background processes running on Linux and macOS, and open pipes of such a process no longer hold the caller.
19
+
20
+ ### Changed
21
+
22
+ - Presets: `vibeops` has a pinned scope for migration files with `drop` or `truncate` in the name, `exchange-firewall` has a pinned `withdrawals` scope and `solver` a pinned `constraints` scope. Their old class pins never applied.
23
+ - The HTTP transport answers a request above 4 MiB with `413` and a JSON-RPC error, and a request that is not `application/json` with `415`. A `tools/call` without an id is not run.
24
+ - `npm run check` runs the linter.
25
+ - Releases are published from CI with npm trusted publishing and carry a provenance attestation.
26
+
27
+ ## 0.1.0
28
+
29
+ First release. Published by hand, without a provenance attestation.
30
+
31
+ ### Kernel
32
+
33
+ - Pure decision function `step(state, envelope, hooks)` with 20 event kinds.
34
+ - Leases on scope and class, fresh proof before a batch closes, single-use signed approvals (HMAC-SHA256 and Ed25519), hard, timed and soft pins, budgets, an autonomy ladder, per-scope epochs.
35
+ - Undo by origin with a compensation policy: abort on conflict, compensate only when every field was reverted, or compensate anyway.
36
+
37
+ ### Runtime
38
+
39
+ - Single writer with a human priority lane, `SQLiteStore` (WAL) and `InMemoryStore`.
40
+ - Hash-chained log. The starting policy is the first entry, so a replay needs only the log.
41
+ - Write-ahead outbox with reconciliation, compensation and an asynchronous preflight check.
42
+
43
+ ### Command line and MCP gate
44
+
45
+ - `certal.json` manifest with a JSON schema. Manifests in parent directories are merged, and a subdirectory may only tighten them.
46
+ - `certal init`, `mcp`, `status`, `approve`, `undo`, `halt`, `reset`, `resume`, `stop`, `verify --offline`, and one-line JSON output with `--agent`.
47
+ - MCP server over stdio and local HTTP with five agent tools. Over HTTP every agent has a bearer token of its own.
48
+ - An object of a batch must belong to the leased scope. Paths are normalized, and absolute paths and `..` segments are refused.
49
+ - Operator commands and approval tokens are signed with an Ed25519 key. The operator keys are fixed by the first start of a log.
50
+ - Witness stages and tool steps run as child processes. A timeout kills the whole process tree.
51
+ - Approval channels (local and webhook), an optional file watcher, four presets, a plugin manifest and a skill for agents.
52
+
53
+ ### Formal model
54
+
55
+ - Lean 4.34.0 model of the kernel without Mathlib: 34 theorems, including five over event traces of any length.
56
+ - Differential conformance of the model and the TypeScript kernel on 5,005 deterministic vectors.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paweł Olszewski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,290 @@
1
- # Temporary Holding Version
1
+ # Certal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A deterministic execution firewall and runtime for AI agents.
4
+
5
+ Timeouts do not double-charge. Human edits do not get clobbered. Runaway agent loops hit a hard halt.
6
+
7
+ 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.
8
+
9
+ | | |
10
+ |---|---|
11
+ | Runtime dependencies | None. Node.js 24 built-ins only, including `node:sqlite` and `node:crypto`. |
12
+ | Machine-checked core | 34 theorems in Lean 4.34.0, no Mathlib, no `sorry`. The model is checked against the TypeScript kernel on 5,005 conformance vectors. |
13
+ | Hostile agents | Origin-restricted ports stop agent code from forging human edits, witness verdicts or approvals. |
14
+ | License | MIT |
15
+
16
+ ```text
17
+ Agent (untrusted) Witness (System) Operator (Human)
18
+ │ │ │
19
+ ▼ ▼ ▼
20
+ ┌─────────────────────────────────────────────────────────────────────────┐
21
+ │ CertalRuntime (single writer) │
22
+ │ agent queue ◄──────────── human priority lane (skips the queue) │
23
+ │ secret redaction, blob offload │
24
+ │ │ │
25
+ │ ▼ │
26
+ │ pure decision kernel: step(state, envelope, hooks) │
27
+ │ leases · pins · budgets · signed approvals · Lean 4 model │
28
+ └──────────────────────────┬─────────────────────────────┬────────────────┘
29
+ ▼ ▼
30
+ SQLite WAL log write-ahead outbox
31
+ RFC 8785 JSON + SHA-256 chain INTENT → IN_FLIGHT → APPLIED
32
+ atomic per step, replayable crash or timeout → reconcile only
33
+ ```
34
+
35
+ ## Why Certal exists
36
+
37
+ Prompt guardrails stop working when an agent meets a real production edge case.
38
+
39
+ **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.
40
+
41
+ **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.
42
+
43
+ **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.
44
+
45
+ **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.
46
+
47
+ ## Guarantees
48
+
49
+ | Mechanism | What the kernel enforces |
50
+ |---|---|
51
+ | Fresh proof | A batch closes only with a `PASS` witness verdict that matches the live scope hash, scope epoch and input snapshot. |
52
+ | Human priority | A human edit bypasses the agent queue, evicts colliding leases and invalidates stale work in its scope. Other scopes are untouched. |
53
+ | Signed consent | An approval binds `diffHash`, `scopeHash` and `inputSnapshotHash`. It is single-use, time-bounded and signature-checked by default. |
54
+ | 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. |
55
+ | Pins | A hard pin blocks agent writes. A timed pin blocks them until it expires. 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. |
56
+ | Hard budgets | Attempt, CPU and cost limits pause the task. A fail streak moves it to `HALTED`, which only a human `HumanReset` clears. |
57
+ | Crash-safe effects | Every external call goes through the write-ahead outbox. An unknown outcome can only be reconciled. |
58
+ | Undo by origin | A human reverts an agent batch field by field. Later human edits stay. The operator chooses what happens on a field conflict: abort the undo, pause for a decision (the default), or compensate anyway. |
59
+ | 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. |
60
+
61
+ ## Quick start
62
+
63
+ Requires Node.js 24 or newer.
64
+
65
+ ```bash
66
+ npm install certal
67
+ npx certal init --preset sdk
68
+ ```
69
+
70
+ `init` writes `certal.json`, creates the operator key and adds `.mcp.json`. The rest of this section uses the library directly.
71
+
72
+ An agent changes two fields, a human corrects one of them, and the undo reverts only what is still the agent's.
73
+
74
+ ```js
75
+ import { CertalRuntime, InMemoryStore } from 'certal/runtime';
76
+ import { EmbeddedToolSdk, InMemoryReferenceAdapter } from 'certal/adapters';
77
+
78
+ const adapter = new InMemoryReferenceAdapter();
79
+ const runtime = new CertalRuntime({
80
+ store: new InMemoryStore(),
81
+ hooks: adapter.hooks,
82
+ // Demo settings. The default policy starts a new tool in SHADOW,
83
+ // which blocks external effects and requires a signed approval.
84
+ policyOverrides: {
85
+ enforceAutonomyLadder: false,
86
+ requiredWitnessStages: ['L0'],
87
+ },
88
+ });
89
+ const sdk = new EmbeddedToolSdk(runtime, adapter);
90
+
91
+ // 1. The agent proposes a batch. The kernel checks the lease,
92
+ // the base revisions and the witness verdict.
93
+ const outcome = await sdk.agent.executeToolCall({
94
+ opId: 'call-1',
95
+ attemptId: 'attempt-1',
96
+ taskId: 'task-1',
97
+ toolId: 'crm',
98
+ domainObjectId: 'order-42',
99
+ executorId: 'agent-a',
100
+ scopeId: 'orders',
101
+ classId: 'order-fields',
102
+ rawInputs: { source: 'demo' },
103
+ confidence: 'exact',
104
+ ops: [
105
+ {
106
+ opIndex: 0,
107
+ objectId: 'order-42',
108
+ classId: 'order-fields',
109
+ field: 'status',
110
+ expectedBeforeRev: 0,
111
+ beforeValue: null,
112
+ afterValue: 'booked',
113
+ reversibility: 'REVERSIBLE',
114
+ },
115
+ {
116
+ opIndex: 1,
117
+ objectId: 'order-42',
118
+ classId: 'order-fields',
119
+ field: 'note',
120
+ expectedBeforeRev: 0,
121
+ beforeValue: null,
122
+ afterValue: 'booked by agent',
123
+ reversibility: 'REVERSIBLE',
124
+ },
125
+ ],
126
+ });
127
+ console.log(outcome.finalized, outcome.reason);
128
+ // true BATCH_FINALIZED
129
+
130
+ // 2. A human overrides one field, then rolls back the agent's batch.
131
+ await sdk.operator.humanEdit(
132
+ 'alice', 'orders', 'order-fields', 'order-42', 'note', 'call the customer first',
133
+ );
134
+ const undo = await sdk.originUndo('alice', 'attempt-1', 'orders', 'wrong booking');
135
+
136
+ console.log(undo.report.appliedFields);
137
+ // [ { objectId: 'order-42', field: 'status' } ]
138
+ console.log(undo.report.skippedConflicts.map((c) => c.reason));
139
+ // [ 'HUMAN_OVERWRITE' ]
140
+ ```
141
+
142
+ `status` goes back to `null`. Alice's `note` is untouched.
143
+
144
+ ## Command line and MCP gate
145
+
146
+ 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`.
147
+
148
+ ```bash
149
+ certal init --preset sdk # certal.json, the operator key, .mcp.json
150
+ certal mcp # MCP server over stdio, one agent
151
+ certal mcp --transport http --agents alice,bob # several agents, one bearer token each
152
+ certal status # scope epochs, leases, autonomy tiers, pending approvals
153
+ certal approve <attemptId> --ttl 300s
154
+ certal undo <batchId> --policy abort|all-reverted|force
155
+ certal halt <scopeId> --reason "..."
156
+ certal reset <scopeId> --reason "..."
157
+ certal verify --offline .certal/certal.db
158
+ ```
159
+
160
+ **Manifest.** `certal.json` declares the policy, scopes, hard pins, tools and witness stages. It is plain JSON with a schema, [`certal.schema.json`](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/`](presets): `sdk`, `solver`, `exchange-firewall` and `vibeops`. Their commands are templates that you point at your own checks.
161
+
162
+ **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.
163
+
164
+ **Which scope owns a path.** The order of the scopes in the manifest does not matter, and letter case is ignored on every platform. A whole-directory pattern (`dir/**` or `**`) is a fallback: it gives way to a pattern of another scope that lies inside that directory. So with `workspace: **` and `access: policies/**`, the file `policies/x.sql` belongs to `access` wherever the two scopes stand in the manifest, and a pin on `access` holds. Every other overlap has no winner. With `src/**` and `**/*.secret`, the file `src/a.secret` is claimed by both, and a batch that names it is refused with `OBJECT_SCOPE_AMBIGUOUS` under either lease. The same pattern in two scopes is refused when the manifest is loaded.
165
+
166
+ **Patterns and object ids.** A pattern has `*` and `?` inside one path segment and `**` for any number of segments. 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. An object id is at most 1,024 characters, is stored in Unicode form NFC, and may not hold a control character or a text-direction mark. A scope without paths takes plain ids only: an id with a `/` is refused there.
167
+
168
+ **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`.
169
+
170
+ **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.
171
+
172
+ **Two ways to change state.** They give different guarantees, so choose one per tool.
173
+
174
+ | | Effect mode | File mode |
175
+ |---|---|---|
176
+ | How it is declared | The tool has a `deliverCommand` | The scope has `paths`, usually with `"watch": true` |
177
+ | 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. |
178
+ | What the witness checks | The proposal that will be delivered | The declaration on stdin. It runs before the file is written, so it does not see the file. |
179
+ | 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. |
180
+
181
+ 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.
182
+
183
+ **What an agent reads.** Every answer has the same six fields, so the agent knows whether to go on, wait or stop:
184
+
185
+ ```json
186
+ { "decision": "PAUSE", "reason": "APPROVAL_REQUIRED", "scopeId": "orders", "scopeEpoch": 4, "nextLegalAction": "wait_for_operator_approval", "retryable": true }
187
+ ```
188
+
189
+ `--agent` makes every CLI command print the same one-line form.
190
+
191
+ **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.
192
+
193
+ **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`, 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.
194
+
195
+ **Approval channels.** 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.
196
+
197
+ **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.
198
+
199
+ **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 and approval indexes with the log. 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.
200
+
201
+ Limits of this layer:
202
+
203
+ - One process owns a state directory. A second server on the same directory is refused. Several agents share one server over HTTP.
204
+ - A manifest that changes after the log has started may only tighten it. 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.
205
+ - 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.
206
+ - The `sdk` preset accepts every batch at stage `L0` without 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.
207
+ - 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`.
208
+ - The key file gets mode `0600`. On Windows the mode has no effect, and the profile directory protects the file.
209
+ - 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.
210
+ - 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.
211
+ - 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`.
212
+ - 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.
213
+ - Commands run without a shell. On Windows, `npm` and `npx` are batch files: call them through `node` or use the `.cmd` name.
214
+ - 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.
215
+
216
+ ## Trust boundary
217
+
218
+ 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.
219
+
220
+ | Part | Port | Can do |
221
+ |---|---|---|
222
+ | `AgentGateway` | `Agent` | Acquire a lease, open an attempt, submit and finalize a batch. It cannot issue human or witness events. |
223
+ | `WitnessService` | `System` | Run verification stages and submit verdicts. |
224
+ | `OperatorConsole` | `Human` | Edit, set and remove pins, approve and sign, cancel an attempt, halt, reset, resume, undo. |
225
+
226
+ `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.
227
+
228
+ ## Architecture
229
+
230
+ Imports go one way: `kernel → runtime → adapters → mcp → cli → tests`. A static check enforces the direction.
231
+
232
+ | Layer | Contents |
233
+ |---|---|
234
+ | [`core/kernel/`](core/kernel/index.ts) | 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. |
235
+ | [`core/runtime/`](core/runtime/index.ts) | `CertalRuntime` single-writer engine with a human priority lane, `SQLiteStore` (WAL) and `InMemoryStore`, secret redaction before persistence, blob offload, outbox worker with crash recovery. |
236
+ | [`core/adapters/`](core/adapters/index.ts) | Domain adapter contracts, a reference in-memory adapter and the SDK. |
237
+ | [`core/mcp/`](core/mcp/index.ts) | Host for one state directory (manifest, SQLite log, runtime, outbox, signed operator endpoint) and the MCP server over stdio and local HTTP. |
238
+ | [`core/cli/`](core/cli/main.ts) | The `certal` command. |
239
+ | [`formal/CertalKernel/`](formal/README.md) | Lean 4 model of the kernel, module by module, with proofs and the `certal_conformance` runner. |
240
+
241
+ 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](docs/DESIGN.md).
242
+
243
+ ## Formal verification
244
+
245
+ The model in [`formal/CertalKernel/`](formal/README.md) uses Lean 4.34.0 without Mathlib. Every theorem depends only on `propext`, `Classical.choice` and `Quot.sound`.
246
+
247
+ | Theorems | Property (short form) |
248
+ |---|---|
249
+ | `T01`, `R01` | `HALTED` is absorbing. No sequence of events without a human `HumanReset` leaves it. |
250
+ | `T02` | A clock that goes back returns `REJECT` with `CLOCK_REGRESSION` and changes no slots, epoch, status, batches or effects. |
251
+ | `T03`, `T04` | A repeated `opId` with the same payload is an idempotent replay. With another payload it ends in `REJECT` or `HALT`, and nothing is applied. |
252
+ | `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. |
253
+ | `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. |
254
+ | `T12` | An agent cannot set, replace or remove a hard or timed pin. Every such pin is still in place after the step. |
255
+ | `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. |
256
+ | `V01`–`V04` | Non-vacuity: the assumptions of the theorems can be satisfied. |
257
+
258
+ Exact statements of all 34 are in [`Challenge.lean`](formal/CertalKernel/Challenge.lean) and [`Inductive.lean`](formal/CertalKernel/Inductive.lean).
259
+
260
+ ### Proof boundaries
261
+
262
+ Read these before you rely on the formal claims.
263
+
264
+ - 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.
265
+ - `T01`–`T24` describe a single step. `R01` and `I01`–`I05` hold 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.
266
+ - The model and the TypeScript kernel are compared on 5,005 deterministic vectors that cover all 20 event kinds. That is a test. The TypeScript code is not extracted from the model.
267
+
268
+ More limits are listed in [formal/README.md](formal/README.md).
269
+
270
+ ## Checks
271
+
272
+ ```bash
273
+ npm run check # structure, lint, typecheck, 68 tests, 47 mutants
274
+ npm run check:formal # token scan, clean lake build, axiom audit, 5,005 vectors, 3 model mutations
275
+ npm run check:all # both
276
+ npm run test:bench # latency of the human lane under agent load
277
+ npm run test:bench:cli # cold start of `certal status --agent` and MCP round trips
278
+ ```
279
+
280
+ `check: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`).
281
+
282
+ ## Documentation
283
+
284
+ - [docs/DESIGN.md](docs/DESIGN.md): functional requirements, design parameters, dependency matrices, kernel laws
285
+ - [core/README.md](core/README.md): layers and modules
286
+ - [formal/README.md](formal/README.md): what is proven, limits of the model, the conformance check
287
+
288
+ ## License
289
+
290
+ MIT. See [LICENSE](LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,36 @@
1
+ # Security
2
+
3
+ ## Supported versions
4
+
5
+ The latest release on npm gets security fixes. There are no maintenance branches for older versions.
6
+
7
+ ## Scope
8
+
9
+ In scope:
10
+
11
+ - The kernel accepts an event that breaks one of its laws (see [docs/DESIGN.md](docs/DESIGN.md), "Kernel laws").
12
+ - An agent that talks to the MCP gate does something that belongs to the operator: approves, undoes, halts, resets, changes a pin, or acts as another agent.
13
+ - An agent with a lease on one scope changes an object of another scope.
14
+ - A subdirectory manifest relaxes what a parent manifest declares.
15
+ - A forged or replayed approval token or operator command is accepted.
16
+ - `certal verify --offline` passes a log whose entries were changed.
17
+ - A declared command outlives its time limit, or a path in a manifest or a request leaves the project directory.
18
+
19
+ Out of scope, because the design does not claim it:
20
+
21
+ - A process that runs as the operator's own user and reads the operator key or the state directory. Certal separates objects and ports, not operating system users.
22
+ - The file watcher treats a file written without a batch as a human edit. This is a documented limit of the watcher.
23
+ - A log that was rewritten from the first entry. The audit shows that a database is consistent with itself. Compare the last entry hash with a value kept elsewhere.
24
+ - The commands that a manifest declares. Certal runs them as written.
25
+
26
+ ## Reporting
27
+
28
+ Report a vulnerability privately through GitHub: open the **Security** tab of the repository and choose **Report a vulnerability**. Do not open a public issue for it.
29
+
30
+ Include the version, a minimal manifest or event sequence that shows the problem, and what you expected instead.
31
+
32
+ ## What to expect
33
+
34
+ - An answer within 7 days that says whether the report is accepted.
35
+ - A fix or a documented limit within 90 days of an accepted report, sooner for an issue that lets an agent bypass a pin, an approval or the trust boundary.
36
+ - Credit in the changelog, unless you ask not to be named.
package/bin/certal.mjs ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ // Entry point of the `certal` command. A checkout runs the TypeScript sources directly,
3
+ // an installed package runs the compiled files in dist/.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+
8
+ const root = path.resolve(import.meta.dirname, '..');
9
+ const source = path.join(root, 'core', 'cli', 'main.ts');
10
+ const entry = fs.existsSync(source) ? source : path.join(root, 'dist', 'cli', 'main.js');
11
+ const { main } = await import(pathToFileURL(entry).href);
12
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,156 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://raw.githubusercontent.com/polszewski-pl/certal/main/certal.schema.json",
4
+ "title": "Certal manifest",
5
+ "description": "Declarative manifest certal.json. Manifests in parent directories are merged, and a subdirectory may only tighten them.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["version", "profile"],
9
+ "properties": {
10
+ "$schema": { "type": "string" },
11
+ "version": { "const": 1 },
12
+ "profile": { "enum": ["sdk", "exchange", "vibeops", "solver", "custom"] },
13
+ "stateDir": { "type": "string", "minLength": 1, "description": "Directory of the log, relative to the manifest. Default: .certal" },
14
+ "operator": {
15
+ "type": "object",
16
+ "additionalProperties": false,
17
+ "required": ["humanId", "publicKeys"],
18
+ "properties": {
19
+ "humanId": { "type": "string", "minLength": 1 },
20
+ "publicKeys": {
21
+ "type": "object",
22
+ "description": "Ed25519 public keys in PEM format, by key id. Only the outermost manifest that declares an operator counts.",
23
+ "additionalProperties": { "type": "string", "minLength": 1 }
24
+ }
25
+ }
26
+ },
27
+ "policy": {
28
+ "type": "object",
29
+ "additionalProperties": false,
30
+ "description": "Overrides of the default policy. The policy is recorded in the log as the first entry.",
31
+ "properties": {
32
+ "maxAttempts": { "$ref": "#/$defs/positive" },
33
+ "maxFailStreak": { "$ref": "#/$defs/positive" },
34
+ "maxConflictStreak": { "$ref": "#/$defs/positive" },
35
+ "maxCpuMs": { "$ref": "#/$defs/positive" },
36
+ "maxCostMicroUnits": { "$ref": "#/$defs/count" },
37
+ "maxReconcileAttempts": { "$ref": "#/$defs/positive" },
38
+ "defaultLeaseTtlMs": { "$ref": "#/$defs/positive" },
39
+ "maxConcurrentPerScope": { "$ref": "#/$defs/positive" },
40
+ "maxEventBytes": { "type": "integer", "minimum": 1024 },
41
+ "minImprovementMicroUnits": { "$ref": "#/$defs/count" },
42
+ "undoWindowTtlMs": { "$ref": "#/$defs/count" },
43
+ "escalatePartialToC2": { "type": "boolean" },
44
+ "denyPartial": { "type": "boolean" },
45
+ "escalateSoftPinToC2": { "type": "boolean" },
46
+ "enforceApprovalSignature": { "type": "boolean" },
47
+ "enforceAutonomyLadder": { "type": "boolean" },
48
+ "resourcePoolCapacity": {
49
+ "type": "object",
50
+ "additionalProperties": false,
51
+ "properties": {
52
+ "inferenceSlots": { "$ref": "#/$defs/count" },
53
+ "witnessSlots": { "$ref": "#/$defs/count" },
54
+ "mutationSlots": { "$ref": "#/$defs/count" }
55
+ }
56
+ },
57
+ "requiredWitnessStages": {
58
+ "type": "array",
59
+ "minItems": 1,
60
+ "uniqueItems": true,
61
+ "items": { "$ref": "#/$defs/stage" }
62
+ }
63
+ }
64
+ },
65
+ "scopes": {
66
+ "type": "array",
67
+ "items": {
68
+ "type": "object",
69
+ "additionalProperties": false,
70
+ "required": ["id", "classId", "paths"],
71
+ "properties": {
72
+ "id": { "type": "string", "minLength": 1 },
73
+ "classId": { "type": "string", "minLength": 1 },
74
+ "paths": { "type": "array", "items": { "type": "string", "minLength": 1 }, "description": "Glob patterns with **, * and ?" }
75
+ }
76
+ }
77
+ },
78
+ "pins": {
79
+ "type": "array",
80
+ "items": {
81
+ "type": "object",
82
+ "additionalProperties": false,
83
+ "required": ["id", "kind", "scopeId", "classId", "rule"],
84
+ "properties": {
85
+ "id": { "type": "string", "minLength": 1 },
86
+ "kind": { "enum": ["H", "N"], "description": "H blocks agent writes. N adds cost or escalates to approval." },
87
+ "scopeId": { "type": "string", "minLength": 1 },
88
+ "classId": { "type": "string", "minLength": 1 },
89
+ "rule": { "type": "string", "minLength": 1 },
90
+ "costPenaltyMicroUnits": { "$ref": "#/$defs/count" }
91
+ }
92
+ }
93
+ },
94
+ "tools": {
95
+ "type": "object",
96
+ "additionalProperties": {
97
+ "type": "object",
98
+ "additionalProperties": false,
99
+ "required": ["reversibility", "supportsCas"],
100
+ "properties": {
101
+ "reversibility": { "enum": ["REVERSIBLE", "COMPENSABLE", "IRREVERSIBLE"] },
102
+ "supportsCas": { "type": "boolean" },
103
+ "preflightCommand": { "$ref": "#/$defs/command" },
104
+ "deliverCommand": { "$ref": "#/$defs/command" },
105
+ "reconcileCommand": { "$ref": "#/$defs/command" },
106
+ "compensateCommand": { "$ref": "#/$defs/command" }
107
+ }
108
+ }
109
+ },
110
+ "witness": {
111
+ "type": "object",
112
+ "additionalProperties": false,
113
+ "properties": {
114
+ "L0": { "$ref": "#/$defs/witnessStage" },
115
+ "L1": { "$ref": "#/$defs/witnessStage" },
116
+ "L2": { "$ref": "#/$defs/witnessStage" },
117
+ "L3": { "$ref": "#/$defs/witnessStage" }
118
+ }
119
+ },
120
+ "approvals": {
121
+ "type": "object",
122
+ "additionalProperties": false,
123
+ "required": ["channel"],
124
+ "properties": {
125
+ "channel": { "enum": ["local-cli", "webhook"] },
126
+ "url": { "type": "string", "minLength": 1 }
127
+ }
128
+ },
129
+ "watch": { "type": "boolean", "description": "Report manual file saves in declared scopes as human edits." },
130
+ "allowSubdirectoryTools": { "type": "boolean", "description": "Outermost manifest only. Lets a subdirectory declare tools of its own. Default: false." }
131
+ },
132
+ "$defs": {
133
+ "count": { "type": "integer", "minimum": 0 },
134
+ "positive": { "type": "integer", "minimum": 1 },
135
+ "stage": { "enum": ["L0", "L1", "L2", "L3"] },
136
+ "command": {
137
+ "type": "array",
138
+ "minItems": 1,
139
+ "items": { "type": "string", "minLength": 1 },
140
+ "description": "Program and arguments. Runs without a shell and reads one JSON document on stdin."
141
+ },
142
+ "witnessStage": {
143
+ "type": "object",
144
+ "additionalProperties": false,
145
+ "required": ["budgetCpuMs", "requireNearMiss"],
146
+ "oneOf": [{ "required": ["command"] }, { "required": ["builtin"] }],
147
+ "properties": {
148
+ "command": { "$ref": "#/$defs/command" },
149
+ "builtin": { "const": "accept" },
150
+ "budgetCpuMs": { "$ref": "#/$defs/count" },
151
+ "requireNearMiss": { "type": "boolean" },
152
+ "nearMissProbeCommand": { "$ref": "#/$defs/command" }
153
+ }
154
+ }
155
+ }
156
+ }
@@ -0,0 +1,44 @@
1
+ import type { ApprovalToken, Binding } from '../kernel/index.ts';
2
+ /**
3
+ * How a request for approval reaches a human. A channel only carries the request and, at most,
4
+ * brings back a signed token. The kernel checks every token again before it accepts it.
5
+ */
6
+ export interface ApprovalNotice {
7
+ readonly attemptId: string;
8
+ readonly scopeId: string;
9
+ readonly toolId: string;
10
+ readonly reason: string | null;
11
+ readonly binding: Binding;
12
+ readonly bindingHash: string;
13
+ readonly diffSummary: readonly string[];
14
+ /** The latest moment the requester is ready to wait for. A token may expire sooner. */
15
+ readonly expiresAtMs: number;
16
+ }
17
+ export interface ApprovalChannel {
18
+ readonly name: string;
19
+ /** Announces a pending approval. May return a signed token when the channel answers at once. */
20
+ notify(notice: ApprovalNotice): Promise<ApprovalToken | null>;
21
+ }
22
+ /**
23
+ * Default channel. It sends nothing: the attempt stays in the pending list of `certal status`
24
+ * until the operator runs `certal approve <attemptId>` with the local Ed25519 key.
25
+ */
26
+ export declare class LocalCliApprovalChannel implements ApprovalChannel {
27
+ readonly name = "local-cli";
28
+ notify(_notice: ApprovalNotice): Promise<ApprovalToken | null>;
29
+ }
30
+ /** True when `token` is an Ed25519-signed approval of exactly this attempt content by a known operator key. */
31
+ export declare function isValidSignedApproval(token: unknown, notice: ApprovalNotice, publicKeys: Readonly<Record<string, string>>): token is ApprovalToken;
32
+ /**
33
+ * Sends the binding hash, a summary of the change and the expiry to a webhook. The receiver may
34
+ * answer with `{ "approvalToken": ... }`. Only a token with a valid Ed25519 signature of a known
35
+ * operator key over this exact binding is passed on. Anything else is dropped.
36
+ */
37
+ export declare class WebhookApprovalChannel implements ApprovalChannel {
38
+ readonly name = "webhook";
39
+ private readonly url;
40
+ private readonly publicKeys;
41
+ private readonly timeoutMs;
42
+ constructor(url: string, publicKeys: Readonly<Record<string, string>>, timeoutMs?: number);
43
+ notify(notice: ApprovalNotice): Promise<ApprovalToken | null>;
44
+ }