certal 0.1.0 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "certal",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Work through the Certal gate: leases, verified batches and operator approvals for every change.",
5
5
  "author": { "name": "Paweł Olszewski" },
6
6
  "repository": "https://github.com/polszewski-pl/certal",
package/CHANGELOG.md CHANGED
@@ -1,8 +1,32 @@
1
1
  # Changelog
2
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
+
3
27
  ## 0.1.0
4
28
 
5
- First release.
29
+ First release. Published by hand, without a provenance attestation.
6
30
 
7
31
  ### Kernel
8
32
 
package/README.md CHANGED
@@ -159,7 +159,15 @@ certal verify --offline .certal/certal.db
159
159
 
160
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
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. A path that several scopes match belongs to the first of them in the manifest.
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.
163
171
 
164
172
  **Two ways to change state.** They give different guarantees, so choose one per tool.
165
173
 
@@ -182,13 +190,13 @@ Witness stages run as child processes. The time limit of a stage is the smaller
182
190
 
183
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.
184
192
 
185
- **Agents over HTTP.** The HTTP transport listens on a loopback address only. Every agent named in `--agents` gets a bearer token of its own in `.certal/agents/<agentId>.token`, and the token alone decides who the caller is. A request whose `x-certal-agent` header names another agent is refused with `403`.
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.
186
194
 
187
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.
188
196
 
189
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.
190
198
 
191
- **Offline audit.** `certal verify --offline <db>` replays a copy of the database from the first entry and checks every entry hash and the chain between entries. It needs no manifest: the operator public keys are stored in the database.
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.
192
200
 
193
201
  Limits of this layer:
194
202
 
@@ -198,6 +206,10 @@ Limits of this layer:
198
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.
199
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`.
200
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.
201
213
  - Commands run without a shell. On Windows, `npm` and `npx` are batch files: call them through `node` or use the `.cmd` name.
202
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.
203
215
 
@@ -258,7 +270,7 @@ More limits are listed in [formal/README.md](formal/README.md).
258
270
  ## Checks
259
271
 
260
272
  ```bash
261
- npm run check # structure, typecheck, 56 tests, 47 mutants
273
+ npm run check # structure, lint, typecheck, 68 tests, 47 mutants
262
274
  npm run check:formal # token scan, clean lake build, axiom audit, 5,005 vectors, 3 model mutations
263
275
  npm run check:all # both
264
276
  npm run test:bench # latency of the human lane under agent load
@@ -18,6 +18,10 @@ export interface CommandResult {
18
18
  * Runs one command with a hard wall-clock limit. When the limit passes, the whole process tree is
19
19
  * killed and the call returns as soon as the process is gone, also when a grandchild still holds
20
20
  * the output pipes.
21
+ *
22
+ * A command that ends in time takes its background processes with it on POSIX, where the command
23
+ * leads a process group. On Windows such a process cannot be found after its parent is gone: it
24
+ * keeps running, but it does not hold the caller, because the output pipes are closed here.
21
25
  */
22
26
  export declare function runCommand(command: Command, input: unknown, cwd: string, timeoutMs: number): Promise<CommandResult>;
23
27
  export interface WitnessContext {
@@ -17,10 +17,25 @@ function killTree(child) {
17
17
  child.kill('SIGKILL');
18
18
  }
19
19
  }
20
+ /** Kills what a command that has ended left in its process group. Only POSIX has such a group. */
21
+ function killLeftovers(child) {
22
+ if (child.pid === undefined || process.platform === 'win32')
23
+ return;
24
+ try {
25
+ process.kill(-child.pid, 'SIGKILL');
26
+ }
27
+ catch {
28
+ // The group is empty: nothing was left.
29
+ }
30
+ }
20
31
  /**
21
32
  * Runs one command with a hard wall-clock limit. When the limit passes, the whole process tree is
22
33
  * killed and the call returns as soon as the process is gone, also when a grandchild still holds
23
34
  * the output pipes.
35
+ *
36
+ * A command that ends in time takes its background processes with it on POSIX, where the command
37
+ * leads a process group. On Windows such a process cannot be found after its parent is gone: it
38
+ * keeps running, but it does not hold the caller, because the output pipes are closed here.
24
39
  */
25
40
  export function runCommand(command, input, cwd, timeoutMs) {
26
41
  return new Promise((resolve) => {
@@ -59,11 +74,20 @@ export function runCommand(command, input, cwd, timeoutMs) {
59
74
  stderr += chunk.toString('utf8'); });
60
75
  child.on('error', (err) => { stderr += String(err); finish(null); });
61
76
  child.on('exit', (code) => {
62
- if (timedOut)
77
+ if (timedOut) {
63
78
  finish(null);
64
- // `close` brings the rest of the output. A grandchild that keeps the pipes open must not hold the answer.
65
- else if (!drain)
66
- drain = setTimeout(() => finish(code), 200);
79
+ return;
80
+ }
81
+ killLeftovers(child);
82
+ // `close` brings the rest of the output. A process that keeps the pipes open must not hold the answer,
83
+ // and the open pipes must not keep the event loop of the caller alive.
84
+ if (!drain) {
85
+ drain = setTimeout(() => {
86
+ child.stdout.destroy();
87
+ child.stderr.destroy();
88
+ finish(code);
89
+ }, 200);
90
+ }
67
91
  });
68
92
  child.on('close', (code) => finish(code));
69
93
  child.stdin.on('error', () => { });
@@ -11,16 +11,51 @@ import type { ManifestScope } from './manifest.ts';
11
11
  * is treated as the human. Use the watcher only where agents write through the gate.
12
12
  */
13
13
  export declare const FILE_FIELD = "sha256";
14
- /** Converts a glob pattern with `**`, `*` and `?` to a regular expression over `/`-separated paths. */
15
- export declare function globToRegExp(glob: string): RegExp;
14
+ /** Longest object id that the gate reads. */
15
+ export declare const MAX_OBJECT_ID_LENGTH = 1024;
16
+ /**
17
+ * Tells whether a `/`-separated path matches a glob pattern. `*` and `?` stay inside one segment,
18
+ * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
19
+ * names a file or a directory with everything below it.
20
+ *
21
+ * The match ignores letter case on every platform, so `Policies/x.sql` and `policies/x.sql`, which
22
+ * are one file on Windows and macOS, always belong to the same scope. It uses no regular expression:
23
+ * the time grows with the product of the two lengths, so no input can stall it.
24
+ */
25
+ export declare function matchGlob(pattern: string, relativePath: string): boolean;
26
+ /** The reason why a text cannot be a path pattern of a scope, or null. */
27
+ export declare function patternProblem(pattern: string): string | null;
16
28
  /**
17
29
  * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
18
- * segments. Returns null for an absolute path and for a path with a `..` segment, so two spellings
19
- * can never name the same file and no id can leave the project directory.
30
+ * segments, Unicode form NFC. Returns null for an absolute path, for a path with a `..` segment, for
31
+ * an id longer than 1024 characters and for an id with a control or text-direction character, so two
32
+ * spellings can never name the same file, no id can leave the project directory, and an id reads in
33
+ * a log the way it is stored.
20
34
  */
21
35
  export declare function normalizeObjectPath(input: string): string | null;
22
- /** The first declared scope whose patterns match the path, or null. The order of the scopes in the manifest decides. */
36
+ /**
37
+ * The scopes that claim a path. The order of the scopes in the manifest does not matter.
38
+ *
39
+ * A whole-directory pattern (`dir/**` or `**`) is a fallback. It gives way to a pattern of another
40
+ * scope that lies inside that directory: a deeper whole-directory pattern, or any other pattern
41
+ * that starts there. So `**` gives way to `policies/**`, and `src/**` gives way to `src/db/**`
42
+ * and to `src/*.sql`.
43
+ *
44
+ * Every other overlap is left as it is: `src/**` and a pattern like `**` + `/*.secret` both claim
45
+ * `src/a.secret`, and the result has two scopes. A caller must treat such a path as owned by nobody.
46
+ */
47
+ export declare function claimantsOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope[];
48
+ /** The one scope that owns the path, or null when no scope or more than one scope claims it. */
23
49
  export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope | null;
50
+ /**
51
+ * Checks where a write to an object of a file scope would really land. Returns the reason for a
52
+ * refusal, or null.
53
+ *
54
+ * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
55
+ * the project: the real path must belong to the leased scope. A file with a second hard link has
56
+ * another name that this check cannot see, so it is refused.
57
+ */
58
+ export declare function linkProblem(baseDir: string, scopes: readonly ManifestScope[], scopeId: string, objectId: string): 'OBJECT_OUT_OF_SCOPE' | 'OBJECT_HARD_LINKED' | null;
24
59
  export declare function hashFile(file: string): string | null;
25
60
  export interface FileEditSink {
26
61
  /** Current value of the slot of a file, or undefined when the slot does not exist. */
@@ -13,40 +13,114 @@ import path from 'node:path';
13
13
  * is treated as the human. Use the watcher only where agents write through the gate.
14
14
  */
15
15
  export const FILE_FIELD = 'sha256';
16
- /** Converts a glob pattern with `**`, `*` and `?` to a regular expression over `/`-separated paths. */
17
- export function globToRegExp(glob) {
18
- let out = '';
19
- for (let i = 0; i < glob.length; i += 1) {
20
- const ch = glob[i];
21
- if (ch === '*') {
22
- if (glob[i + 1] === '*') {
23
- i += 1;
24
- if (glob[i + 1] === '/') {
25
- i += 1;
26
- out += '(?:.*/)?';
27
- }
28
- else
29
- out += '.*';
30
- }
31
- else
32
- out += '[^/]*';
16
+ /** Longest object id that the gate reads. */
17
+ export const MAX_OBJECT_ID_LENGTH = 1024;
18
+ /** Matches one path segment against a segment pattern with `*` and `?`. Linear in practice, never exponential. */
19
+ function matchSegment(pattern, text) {
20
+ let p = 0;
21
+ let t = 0;
22
+ let star = -1;
23
+ let mark = 0;
24
+ while (t < text.length) {
25
+ if (p < pattern.length && (pattern[p] === '?' || pattern[p] === text[t])) {
26
+ p += 1;
27
+ t += 1;
28
+ }
29
+ else if (p < pattern.length && pattern[p] === '*') {
30
+ star = p;
31
+ mark = t;
32
+ p += 1;
33
+ }
34
+ else if (star >= 0) {
35
+ p = star + 1;
36
+ mark += 1;
37
+ t = mark;
33
38
  }
34
- else if (ch === '?')
35
- out += '[^/]';
36
39
  else
37
- out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
40
+ return false;
38
41
  }
39
- return new RegExp(`^${out}$`);
42
+ while (p < pattern.length && pattern[p] === '*')
43
+ p += 1;
44
+ return p === pattern.length;
45
+ }
46
+ /**
47
+ * Tells whether a `/`-separated path matches a glob pattern. `*` and `?` stay inside one segment,
48
+ * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
49
+ * names a file or a directory with everything below it.
50
+ *
51
+ * The match ignores letter case on every platform, so `Policies/x.sql` and `policies/x.sql`, which
52
+ * are one file on Windows and macOS, always belong to the same scope. It uses no regular expression:
53
+ * the time grows with the product of the two lengths, so no input can stall it.
54
+ */
55
+ export function matchGlob(pattern, relativePath) {
56
+ const glob = pattern.toLowerCase();
57
+ const text = relativePath.toLowerCase();
58
+ if (!/[*?]/.test(glob))
59
+ return text === glob || text.startsWith(`${glob}/`);
60
+ const segments = text.split('/');
61
+ // `reach[i]` is true when the pattern read so far matches the first `i` segments of the path.
62
+ let reach = new Array(segments.length + 1).fill(false);
63
+ reach[0] = true;
64
+ for (const part of glob.split('/')) {
65
+ const next = new Array(segments.length + 1).fill(false);
66
+ if (part === '**') {
67
+ let open = false;
68
+ for (let i = 0; i <= segments.length; i += 1) {
69
+ open = open || reach[i] === true;
70
+ next[i] = open;
71
+ }
72
+ }
73
+ else {
74
+ const segmentPattern = part.replace(/\*+/g, '*');
75
+ for (let i = 0; i < segments.length; i += 1) {
76
+ if (reach[i] === true && matchSegment(segmentPattern, segments[i]))
77
+ next[i + 1] = true;
78
+ }
79
+ }
80
+ reach = next;
81
+ }
82
+ return reach[segments.length] === true;
83
+ }
84
+ /** The reason why a text cannot be a path pattern of a scope, or null. */
85
+ export function patternProblem(pattern) {
86
+ if (pattern === '')
87
+ return 'is empty';
88
+ if (/[{}[\]]/.test(pattern))
89
+ return 'uses "{", "}", "[" or "]", which the matcher does not have; write one pattern per alternative';
90
+ if (pattern.includes('\\'))
91
+ return 'uses "\\"; write "/" between directories';
92
+ if (pattern.startsWith('/') || /^[A-Za-z]:/.test(pattern))
93
+ return 'is absolute; write it relative to the manifest';
94
+ if (pattern.endsWith('/'))
95
+ return `ends with "/"; write "${pattern}**" for everything in the directory`;
96
+ if (pattern.split('/').some((segment) => segment === '..' || segment === '.' || segment === ''))
97
+ return 'has an empty, "." or ".." segment';
98
+ return null;
99
+ }
100
+ /** True for a control character and for a mark that changes the direction of the text around it. */
101
+ function hasUnsafeCharacter(text) {
102
+ for (let i = 0; i < text.length; i += 1) {
103
+ const code = text.charCodeAt(i);
104
+ if (code <= 0x1f || (code >= 0x7f && code <= 0x9f))
105
+ return true;
106
+ if (code === 0x200e || code === 0x200f || (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069))
107
+ return true;
108
+ }
109
+ return false;
40
110
  }
41
111
  /**
42
112
  * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
43
- * segments. Returns null for an absolute path and for a path with a `..` segment, so two spellings
44
- * can never name the same file and no id can leave the project directory.
113
+ * segments, Unicode form NFC. Returns null for an absolute path, for a path with a `..` segment, for
114
+ * an id longer than 1024 characters and for an id with a control or text-direction character, so two
115
+ * spellings can never name the same file, no id can leave the project directory, and an id reads in
116
+ * a log the way it is stored.
45
117
  */
46
118
  export function normalizeObjectPath(input) {
47
- if (typeof input !== 'string' || input === '')
119
+ if (typeof input !== 'string' || input === '' || input.length > MAX_OBJECT_ID_LENGTH)
48
120
  return null;
49
- const slashed = input.replace(/\\/g, '/');
121
+ if (hasUnsafeCharacter(input))
122
+ return null;
123
+ const slashed = input.normalize('NFC').replace(/\\/g, '/');
50
124
  if (slashed.startsWith('/') || /^[A-Za-z]:(\/|$)/.test(slashed))
51
125
  return null;
52
126
  const parts = slashed.split('/').filter((segment) => segment !== '' && segment !== '.');
@@ -54,14 +128,95 @@ export function normalizeObjectPath(input) {
54
128
  return null;
55
129
  return parts.join('/');
56
130
  }
57
- /** The first declared scope whose patterns match the path, or null. The order of the scopes in the manifest decides. */
58
- export function scopeOfPath(scopes, relativePath) {
131
+ /** The directory of a whole-directory pattern: `''` for `**`, `'src/'` for `src/**`. Null for any other pattern. */
132
+ function wholeDirectory(pattern) {
133
+ if (pattern === '**')
134
+ return '';
135
+ // A pattern without a wildcard covers that path and everything below it.
136
+ if (!/[*?]/.test(pattern))
137
+ return `${pattern.toLowerCase()}/`;
138
+ if (!pattern.endsWith('/**'))
139
+ return null;
140
+ const dir = pattern.slice(0, -2);
141
+ return /[*?]/.test(dir) ? null : dir.toLowerCase();
142
+ }
143
+ /** The text of a pattern before its first wildcard. */
144
+ function literalPrefix(pattern) {
145
+ const at = pattern.search(/[*?]/);
146
+ return (at < 0 ? pattern : pattern.slice(0, at)).toLowerCase();
147
+ }
148
+ /**
149
+ * The scopes that claim a path. The order of the scopes in the manifest does not matter.
150
+ *
151
+ * A whole-directory pattern (`dir/**` or `**`) is a fallback. It gives way to a pattern of another
152
+ * scope that lies inside that directory: a deeper whole-directory pattern, or any other pattern
153
+ * that starts there. So `**` gives way to `policies/**`, and `src/**` gives way to `src/db/**`
154
+ * and to `src/*.sql`.
155
+ *
156
+ * Every other overlap is left as it is: `src/**` and a pattern like `**` + `/*.secret` both claim
157
+ * `src/a.secret`, and the result has two scopes. A caller must treat such a path as owned by nobody.
158
+ */
159
+ export function claimantsOfPath(scopes, relativePath) {
59
160
  const normalized = normalizeObjectPath(relativePath);
60
161
  if (normalized === null)
162
+ return [];
163
+ const matches = scopes
164
+ .map((scope) => ({ scope, patterns: scope.paths.filter((pattern) => matchGlob(pattern, normalized)) }))
165
+ .filter((entry) => entry.patterns.length > 0);
166
+ const givesWay = (wide, narrow) => wide.patterns.every((pattern) => {
167
+ const dir = wholeDirectory(pattern);
168
+ if (dir === null)
169
+ return false;
170
+ return narrow.patterns.some((other) => {
171
+ const otherDir = wholeDirectory(other);
172
+ return literalPrefix(other).startsWith(dir) && (otherDir === null || otherDir.length > dir.length);
173
+ });
174
+ });
175
+ return matches
176
+ .filter((entry) => !matches.some((other) => other !== entry && givesWay(entry, other)))
177
+ .map((entry) => entry.scope);
178
+ }
179
+ /** The one scope that owns the path, or null when no scope or more than one scope claims it. */
180
+ export function scopeOfPath(scopes, relativePath) {
181
+ const claimants = claimantsOfPath(scopes, relativePath);
182
+ return claimants.length === 1 ? claimants[0] : null;
183
+ }
184
+ /**
185
+ * Checks where a write to an object of a file scope would really land. Returns the reason for a
186
+ * refusal, or null.
187
+ *
188
+ * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
189
+ * the project: the real path must belong to the leased scope. A file with a second hard link has
190
+ * another name that this check cannot see, so it is refused.
191
+ */
192
+ export function linkProblem(baseDir, scopes, scopeId, objectId) {
193
+ const parts = objectId.split('/');
194
+ let existing = parts.length;
195
+ // The deepest part of the path that exists. A link below it cannot exist.
196
+ while (existing > 0 && fs.lstatSync(path.join(baseDir, ...parts.slice(0, existing)), { throwIfNoEntry: false }) === undefined)
197
+ existing -= 1;
198
+ if (existing === 0)
61
199
  return null;
62
- for (const scope of scopes) {
63
- if (scope.paths.some((pattern) => globToRegExp(pattern).test(normalized)))
64
- return scope;
200
+ let real;
201
+ let realBase;
202
+ try {
203
+ realBase = fs.realpathSync.native(baseDir);
204
+ real = fs.realpathSync.native(path.join(baseDir, ...parts.slice(0, existing)));
205
+ }
206
+ catch {
207
+ // A link that leads nowhere, or a path that cannot be read.
208
+ return 'OBJECT_OUT_OF_SCOPE';
209
+ }
210
+ const relative = path.relative(realBase, path.join(real, ...parts.slice(existing)));
211
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative))
212
+ return 'OBJECT_OUT_OF_SCOPE';
213
+ const claimants = claimantsOfPath(scopes, relative.split(path.sep).join('/'));
214
+ if (claimants.length !== 1 || claimants[0]?.id !== scopeId)
215
+ return 'OBJECT_OUT_OF_SCOPE';
216
+ if (existing === parts.length) {
217
+ const stat = fs.statSync(real, { throwIfNoEntry: false });
218
+ if (stat?.isFile() && stat.nlink > 1)
219
+ return 'OBJECT_HARD_LINKED';
65
220
  }
66
221
  return null;
67
222
  }
@@ -109,22 +264,22 @@ export class HumanFileWatcher {
109
264
  }
110
265
  /** Compares one file with its slot and reports a human edit when they differ. */
111
266
  async inspect(relativePath) {
112
- const scope = scopeOfPath(this.scopes, relativePath);
113
- if (!scope)
114
- return;
115
267
  const file = path.join(this.baseDir, relativePath);
116
268
  const hash = hashFile(file);
117
- const known = this.sink.currentHash(scope, relativePath);
118
- if (hash === null) {
119
- // A directory or an unreadable file is not a change. A file that is gone is one, when its slot holds a hash.
120
- if (fs.existsSync(file) || known === undefined || known === null)
121
- return;
122
- await this.sink.humanEdit(scope, relativePath, null);
123
- return;
269
+ // A file that several scopes claim is reported to each of them: the human edit wins everywhere.
270
+ for (const scope of claimantsOfPath(this.scopes, relativePath)) {
271
+ const known = this.sink.currentHash(scope, relativePath);
272
+ if (hash === null) {
273
+ // A directory or an unreadable file is not a change. A file that is gone is one, when its slot holds a hash.
274
+ if (fs.existsSync(file) || known === undefined || known === null)
275
+ continue;
276
+ await this.sink.humanEdit(scope, relativePath, null);
277
+ continue;
278
+ }
279
+ if (known === hash)
280
+ continue;
281
+ await this.sink.humanEdit(scope, relativePath, hash);
124
282
  }
125
- if (known === hash)
126
- return;
127
- await this.sink.humanEdit(scope, relativePath, hash);
128
283
  }
129
284
  /** Resolves when every change seen so far has been handled. */
130
285
  async settled() {
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { patternProblem } from './file-watcher.js';
2
3
  import path from 'node:path';
3
4
  import { DEFAULT_POLICY, validatePolicyBounds } from '../kernel/index.js';
4
5
  /**
@@ -102,8 +103,14 @@ export function validateManifest(raw, label = MANIFEST_FILE) {
102
103
  }
103
104
  else if (scopeIds.has(s.id))
104
105
  bad(`scopes[${i}]: duplicate id "${s.id}"`);
105
- else
106
+ else {
106
107
  scopeIds.add(s.id);
108
+ for (const pattern of s.paths) {
109
+ const problem = patternProblem(pattern);
110
+ if (problem)
111
+ bad(`scope "${s.id}": the pattern "${pattern}" ${problem}`);
112
+ }
113
+ }
107
114
  }
108
115
  }
109
116
  }
@@ -382,8 +389,28 @@ export function loadManifest(startDir) {
382
389
  }
383
390
  const scopeIds = new Set(layer.scopes.map((s) => s.id));
384
391
  for (const pin of layer.pins) {
392
+ const pinned = layer.scopes.find((s) => s.id === pin.scopeId);
385
393
  if (pin.scopeId !== '*' && !scopeIds.has(pin.scopeId))
386
394
  problems.push(`pin "${pin.id}" names the unknown scope "${pin.scopeId}"`);
395
+ // A lease on a declared scope always has the class of that scope, so a pin on another class would never apply.
396
+ else if (pinned && pin.classId !== '*' && pin.classId !== pinned.classId) {
397
+ problems.push(`pin "${pin.id}" names the class "${pin.classId}", but the scope "${pin.scopeId}" has the class "${pinned.classId}": the pin would never apply. Use "*" or give those objects a scope of their own`);
398
+ }
399
+ else if (pin.scopeId === '*' && pin.classId !== '*' && layer.scopes.length > 0 && !layer.scopes.some((s) => s.classId === pin.classId)) {
400
+ problems.push(`pin "${pin.id}" names the class "${pin.classId}", which no declared scope has: the pin would never apply`);
401
+ }
402
+ }
403
+ // The same pattern in two scopes gives every matching file two owners, and such a file is refused.
404
+ const patternOwner = new Map();
405
+ for (const scope of layer.scopes) {
406
+ for (const pattern of scope.paths) {
407
+ const key = pattern.toLowerCase();
408
+ const other = patternOwner.get(key);
409
+ if (other !== undefined && other !== scope.id)
410
+ problems.push(`scopes "${other}" and "${scope.id}" both list the pattern "${pattern}"`);
411
+ else
412
+ patternOwner.set(key, scope.id);
413
+ }
387
414
  }
388
415
  if (problems.length > 0)
389
416
  throw new ManifestError(problems);
@@ -23,6 +23,12 @@ export declare const COMMAND_MAX_AGE_MS = 60000;
23
23
  /** Directory of operator secrets. `CERTAL_HOME` overrides the default `~/.certal`. */
24
24
  export declare function operatorHome(): string;
25
25
  export declare function operatorKeyPath(): string;
26
+ /**
27
+ * Directory of the per-agent bearer tokens of the HTTP transport for one project. It is in the
28
+ * operator home, not in the project, so an agent that can read the project files does not find
29
+ * the token of another agent there.
30
+ */
31
+ export declare function agentTokenDir(projectDir: string): string;
26
32
  export declare function keyIdOf(publicKeyPem: string): string;
27
33
  /** Reads the operator key. Returns null when there is none. */
28
34
  export declare function loadOperatorKey(file?: string): OperatorKey | null;
@@ -13,6 +13,15 @@ export function operatorHome() {
13
13
  export function operatorKeyPath() {
14
14
  return path.join(operatorHome(), 'operator.key');
15
15
  }
16
+ /**
17
+ * Directory of the per-agent bearer tokens of the HTTP transport for one project. It is in the
18
+ * operator home, not in the project, so an agent that can read the project files does not find
19
+ * the token of another agent there.
20
+ */
21
+ export function agentTokenDir(projectDir) {
22
+ const id = createHash('sha256').update(path.resolve(projectDir)).digest('hex').slice(0, 16);
23
+ return path.join(operatorHome(), 'run', id, 'agents');
24
+ }
16
25
  export function keyIdOf(publicKeyPem) {
17
26
  const der = createPublicKey(publicKeyPem).export({ type: 'spki', format: 'der' });
18
27
  return `op-${createHash('sha256').update(der).digest('hex').slice(0, 16)}`;
package/dist/cli/main.js CHANGED
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { createKeyringSignatureVerifier } from '../kernel/index.js';
6
6
  import { SQLiteStore, replayFromStore } from '../runtime/index.js';
7
7
  import { MANIFEST_FILE, ManifestError, loadManifest } from '../adapters/manifest.js';
8
- import { ensureOperatorKey, loadOperatorKey, operatorKeyPath, signApprovalToken, signOperatorCommand } from '../adapters/operator-auth.js';
8
+ import { agentTokenDir, ensureOperatorKey, loadOperatorKey, operatorKeyPath, signApprovalToken, signOperatorCommand } from '../adapters/operator-auth.js';
9
9
  import { CertalHost, DB_FILE, readRuntimeInfo, readStatus, readStoredOperatorKeys } from '../mcp/host.js';
10
10
  import { AGENT_ID_PATTERN, McpGateway, packageVersion, serveHttp, serveStdio } from '../mcp/server.js';
11
11
  /**
@@ -15,8 +15,6 @@ import { AGENT_ID_PATTERN, McpGateway, packageVersion, serveHttp, serveStdio } f
15
15
  */
16
16
  const PRESETS = { sdk: 'sdk.json', exchange: 'exchange-firewall.json', vibeops: 'vibeops.json', solver: 'solver.json' };
17
17
  const UNDO_POLICIES = { abort: 'ABORT_ON_CONFLICT', 'all-reverted': 'COMPENSATE_ONLY_IF_ALL_REVERTED', force: 'FORCE_COMPENSATE' };
18
- /** Directory of the per-agent bearer tokens of the HTTP transport, inside the state directory. */
19
- const TOKEN_DIR = 'agents';
20
18
  const HELP = `certal ${packageVersion()}
21
19
 
22
20
  certal init [--preset sdk|exchange|vibeops|solver] [--force]
@@ -184,7 +182,7 @@ async function cmdMcp(cwd, flags) {
184
182
  host.close();
185
183
  return 0;
186
184
  }
187
- const tokenDir = path.join(host.manifest.stateDir, TOKEN_DIR);
185
+ const tokenDir = agentTokenDir(host.manifest.baseDir);
188
186
  let served;
189
187
  try {
190
188
  served = await serveHttp(gateway, listen.host, listen.port, agents);
@@ -205,7 +203,7 @@ async function cmdMcp(cwd, flags) {
205
203
  const stop = () => {
206
204
  served.server.close();
207
205
  served.server.closeAllConnections();
208
- fs.rmSync(tokenDir, { recursive: true, force: true });
206
+ fs.rmSync(path.dirname(tokenDir), { recursive: true, force: true });
209
207
  host.close();
210
208
  resolve();
211
209
  };
@@ -317,12 +315,12 @@ function cmdVerify(parsed, out) {
317
315
  const keys = readStoredOperatorKeys(copy);
318
316
  const store = new SQLiteStore(copy);
319
317
  try {
320
- const replayed = replayFromStore(store, { signatureVerifier: createKeyringSignatureVerifier({ ed25519PublicKeysPem: keys }) }, { fromGenesis: true });
318
+ const replayed = replayFromStore(store, { signatureVerifier: createKeyringSignatureVerifier({ ed25519PublicKeysPem: keys }) }, { fromGenesis: true, audit: true });
321
319
  const report = { entries: replayed.replayedEntries, lastEntryHash: replayed.lastEntryHash, stateHash: replayed.stateHash, taskStatus: replayed.state.taskStatus, operatorKeys: Object.keys(keys) };
322
320
  if (out.agent)
323
321
  out.json({ decision: 'ALLOW', reason: 'LOG_VERIFIED', ...report });
324
322
  else {
325
- out.line(`OK: ${report.entries} log entries, hash chain intact, replay matches every entry hash.`);
323
+ out.line(`OK: ${report.entries} log entries, hash chain intact, replay matches every entry, every checkpoint and both indexes.`);
326
324
  out.line(`last entry hash ${report.lastEntryHash}`);
327
325
  out.line(`state hash ${report.stateHash}`);
328
326
  out.line(`task status ${report.taskStatus}`);
@@ -38,6 +38,8 @@ export declare class McpGateway {
38
38
  private auth;
39
39
  private reply;
40
40
  private fromStep;
41
+ /** Symbolic and hard links matter only where objects are files: in a scope that lists paths. */
42
+ private linkProblemOf;
41
43
  private classOf;
42
44
  leaseAcquire(agentId: string, args: Args): Promise<AgentReply>;
43
45
  leaseRelease(agentId: string, args: Args): Promise<AgentReply>;
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import http from 'node:http';
4
4
  import path from 'node:path';
5
5
  import { computeScopeHash, computeToolAutonomy, hashCanonical, pendingVerifyEpoch, scopeEpochOf, slotKey } from '../kernel/index.js';
6
- import { normalizeObjectPath, scopeOfPath } from '../adapters/file-watcher.js';
6
+ import { claimantsOfPath, linkProblem, normalizeObjectPath } from '../adapters/file-watcher.js';
7
7
  import { computeClusterId } from '../adapters/tool-sdk.js';
8
8
  /**
9
9
  * MCP gate for agents. The tool surface is narrow on purpose: an agent can take and release a
@@ -31,7 +31,7 @@ function nextAction(code, reason, onAllow) {
31
31
  return { nextLegalAction: 'wait_for_pin_expiry', retryable: true };
32
32
  if (/STALE|LEASE|CONFLICT|EPOCH|NOT_HELD|CAPACITY|BUSY/.test(reason))
33
33
  return { nextLegalAction: 'certal_lease_acquire', retryable: true };
34
- if (/PIN|FORBIDDEN|SCHEMA|UNKNOWN_TOOL|NOT_YOUR|SCOPE_UNDECLARED|CLASS_MISMATCH|OUT_OF_SCOPE/.test(reason))
34
+ if (/PIN|FORBIDDEN|SCHEMA|UNKNOWN_TOOL|NOT_YOUR|SCOPE_UNDECLARED|CLASS_MISMATCH|OUT_OF_SCOPE|SCOPE_AMBIGUOUS|HARD_LINKED/.test(reason))
35
35
  return { nextLegalAction: 'stop', retryable: false };
36
36
  return { nextLegalAction: 'fix_request', retryable: false };
37
37
  }
@@ -107,6 +107,13 @@ export class McpGateway {
107
107
  fromStep(res, scopeId, onAllow, extra = {}) {
108
108
  return this.reply(res.decision.code, res.decision.reason, scopeId, onAllow, extra);
109
109
  }
110
+ /** Symbolic and hard links matter only where objects are files: in a scope that lists paths. */
111
+ linkProblemOf(scopeId, objectId) {
112
+ const scope = this.host.manifest.scopes.find((s) => s.id === scopeId);
113
+ if (!scope || scope.paths.length === 0)
114
+ return null;
115
+ return linkProblem(this.host.manifest.baseDir, this.host.manifest.scopes, scopeId, objectId);
116
+ }
110
117
  classOf(scopeId, requested) {
111
118
  return requested || this.host.manifest.scopes.find((s) => s.id === scopeId)?.classId || 'default';
112
119
  }
@@ -168,10 +175,20 @@ export class McpGateway {
168
175
  const objectIds = [];
169
176
  for (const raw of rawOps) {
170
177
  const objectId = normalizeObjectPath(str(raw, 'objectId'));
171
- const owner = objectId === null ? null : scopeOfPath(this.host.manifest.scopes, objectId);
178
+ const claimants = objectId === null ? [] : claimantsOfPath(this.host.manifest.scopes, objectId);
179
+ // Two scopes claim the object and neither lies inside the other: a pin on one of them must hold, so nobody may write it.
180
+ if (claimants.length > 1)
181
+ return this.reply('REJECT', 'OBJECT_SCOPE_AMBIGUOUS', scopeId, '', { attemptId });
182
+ const owner = claimants[0] ?? null;
172
183
  const outside = objectId === null || (owner !== null && owner.id !== scopeId) || (owner === null && leased !== undefined && leased.paths.length > 0);
173
184
  if (outside)
174
185
  return this.reply('REJECT', 'OBJECT_OUT_OF_SCOPE', scopeId, '', { attemptId });
186
+ // A scope without paths holds plain ids. An id that reads as a path could name a file that no scope lists.
187
+ if (leased !== undefined && leased.paths.length === 0 && objectId.includes('/'))
188
+ return this.reply('REJECT', 'OBJECT_OUT_OF_SCOPE', scopeId, '', { attemptId });
189
+ const linked = this.linkProblemOf(scopeId, objectId);
190
+ if (linked)
191
+ return this.reply('REJECT', linked, scopeId, '', { attemptId });
175
192
  objectIds.push(objectId);
176
193
  }
177
194
  const auth = this.auth(agentId, attemptId, taskId);
@@ -280,6 +297,12 @@ export class McpGateway {
280
297
  return this.reply('REJECT', 'ATTEMPT_NOT_FOUND', '*', '', { attemptId });
281
298
  if (attempt.executorId !== agentId)
282
299
  return this.reply('REJECT', 'NOT_YOUR_ATTEMPT', attempt.scopeId, '', { attemptId });
300
+ // The files are checked again: a link may have appeared since the proposal.
301
+ for (const stateOp of attempt.ops) {
302
+ const linked = this.linkProblemOf(attempt.scopeId, stateOp.objectId);
303
+ if (linked)
304
+ return this.reply('REJECT', linked, attempt.scopeId, '', { attemptId });
305
+ }
283
306
  if (attempt.status === 'VERIFIED' && this.needsApproval(attempt)) {
284
307
  // Asked here, before the kernel sees the finalize, so a missing approval does not pause the task for other agents.
285
308
  await this.host.announceApproval(attemptId);
@@ -333,6 +356,9 @@ export async function handleRpc(gateway, agentId, message) {
333
356
  const fail = (code, text) => ({ jsonrpc: '2.0', id: req.id ?? null, error: { code, message: text } });
334
357
  if (req.jsonrpc !== '2.0' || typeof req.method !== 'string')
335
358
  return fail(-32600, 'invalid request');
359
+ // A call without an id gets no answer, so the caller could not learn an attempt id. It is not run.
360
+ if (req.method === 'tools/call' && (req.id === undefined || req.id === null))
361
+ return null;
336
362
  try {
337
363
  let result;
338
364
  switch (req.method) {
@@ -476,16 +502,31 @@ export function serveHttp(gateway, listenHost, listenPort, agents = ['agent-1'])
476
502
  const claimed = req.headers['x-certal-agent'];
477
503
  if (claimed !== undefined && claimed !== agentId)
478
504
  return send(403, { error: 'AGENT_IDENTITY_MISMATCH' });
505
+ if (!/^application\/json\s*(;|$)/i.test(String(req.headers['content-type'] ?? ''))) {
506
+ return send(415, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'the content type must be application/json' } });
507
+ }
479
508
  const chunks = [];
480
509
  let size = 0;
510
+ let tooLarge = false;
481
511
  req.on('data', (chunk) => {
512
+ if (tooLarge)
513
+ return;
482
514
  size += chunk.length;
483
- if (size > MAX_MESSAGE_BYTES)
484
- req.destroy();
485
- else
515
+ if (size <= MAX_MESSAGE_BYTES) {
486
516
  chunks.push(chunk);
517
+ return;
518
+ }
519
+ // Answer at once and keep nothing more. The rest of the body is read and dropped for a moment,
520
+ // so the client can receive the answer, and then the connection is closed.
521
+ tooLarge = true;
522
+ chunks.length = 0;
523
+ res.writeHead(413, { 'content-type': 'application/json', connection: 'close' });
524
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: `request too large: the limit is ${MAX_MESSAGE_BYTES} bytes` } }));
525
+ setTimeout(() => req.destroy(), 1000).unref();
487
526
  });
488
527
  req.on('end', () => {
528
+ if (tooLarge)
529
+ return;
489
530
  let message;
490
531
  try {
491
532
  message = JSON.parse(Buffer.concat(chunks).toString('utf8'));
@@ -49,6 +49,8 @@ export interface EventStore {
49
49
  readLogFrom(fromSeqExclusive: number): readonly StoredLogRow[];
50
50
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
51
51
  loadLatestCheckpoint(): CheckpointSnapshot | null;
52
+ /** Every stored checkpoint, oldest first. */
53
+ readCheckpoints(): readonly CheckpointSnapshot[];
52
54
  replay(hooks?: DeterministicHooks): {
53
55
  readonly state: KernelState;
54
56
  readonly stateHash: string;
@@ -101,6 +103,7 @@ export declare class InMemoryStore implements UnifiedStore {
101
103
  readLogFrom(fromSeqExclusive: number): readonly StoredLogRow[];
102
104
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
103
105
  loadLatestCheckpoint(): CheckpointSnapshot | null;
106
+ readCheckpoints(): readonly CheckpointSnapshot[];
104
107
  listActionable(nowMs: number): readonly OutboxRecord[];
105
108
  getOutboxRecord(effectId: string): OutboxRecord | null;
106
109
  recoverInFlight(nowMs: number): readonly OutboxRecord[];
@@ -171,6 +174,7 @@ export declare class SQLiteStore implements UnifiedStore {
171
174
  readLogFrom(fromSeqExclusive: number): readonly StoredLogRow[];
172
175
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
173
176
  loadLatestCheckpoint(): CheckpointSnapshot | null;
177
+ readCheckpoints(): readonly CheckpointSnapshot[];
174
178
  private mapOutboxRow;
175
179
  listActionable(nowMs: number): readonly OutboxRecord[];
176
180
  getOutboxRecord(effectId: string): OutboxRecord | null;
@@ -195,7 +199,13 @@ export declare class SQLiteStore implements UnifiedStore {
195
199
  * other starting policy is the first log entry (see CertalRuntime), so a replay needs no configuration.
196
200
  */
197
201
  export declare function replayFromStore(store: EventStore, hooks?: DeterministicHooks, options?: {
202
+ /** Ignore checkpoints and replay every entry from the first one. */
198
203
  readonly fromGenesis?: boolean;
204
+ /**
205
+ * With `fromGenesis`: also compare every stored checkpoint with the replayed state at its
206
+ * position, and the operation and approval indexes with the log.
207
+ */
208
+ readonly audit?: boolean;
199
209
  }): {
200
210
  readonly state: KernelState;
201
211
  readonly stateHash: string;
@@ -225,6 +225,9 @@ export class InMemoryStore {
225
225
  loadLatestCheckpoint() {
226
226
  return this.checkpoints[this.checkpoints.length - 1] ?? null;
227
227
  }
228
+ readCheckpoints() {
229
+ return [...this.checkpoints];
230
+ }
228
231
  listActionable(nowMs) {
229
232
  const out = [];
230
233
  for (const rec of this.outbox.values()) {
@@ -561,6 +564,10 @@ export class SQLiteStore {
561
564
  const row = this.stmtLoadLatestCheckpoint.get();
562
565
  return row ? JSON.parse(row.snapshot_json) : null;
563
566
  }
567
+ readCheckpoints() {
568
+ const rows = this.db.prepare('SELECT snapshot_json FROM checkpoints ORDER BY server_seq').all();
569
+ return rows.map((row) => JSON.parse(row.snapshot_json));
570
+ }
564
571
  mapOutboxRow(row) {
565
572
  return {
566
573
  effectId: String(row.effect_id),
@@ -706,6 +713,23 @@ export function replayFromStore(store, hooks, options) {
706
713
  isApprovalSpent: (approvalId) => spentSet.has(approvalId),
707
714
  lookupClusterOutcome: (toolId, clusterId) => clusterMap.get(`${toolId}\0${clusterId}`) ?? null,
708
715
  };
716
+ const audit = options?.fromGenesis === true && options.audit === true;
717
+ const checkpointAt = new Map();
718
+ if (audit)
719
+ for (const stored of store.readCheckpoints())
720
+ checkpointAt.set(stored.serverSeq, stored);
721
+ const checkCheckpoint = () => {
722
+ const stored = checkpointAt.get(state.serverSeq);
723
+ if (!stored)
724
+ return;
725
+ checkpointAt.delete(state.serverSeq);
726
+ const replayedHash = computeStateHash(state);
727
+ if (stored.stateHash !== replayedHash || computeStateHash(stored.state) !== replayedHash) {
728
+ throw new Error(`CHECKPOINT_STATE_MISMATCH at seq=${stored.serverSeq}: the stored snapshot is not the state that the log gives`);
729
+ }
730
+ };
731
+ const loggedOps = new Set();
732
+ checkCheckpoint();
709
733
  const rows = store.readLogFrom(state.serverSeq);
710
734
  for (const row of rows) {
711
735
  if (row.entry.hashAlg !== HASH_ALG) {
@@ -721,6 +745,11 @@ export function replayFromStore(store, hooks, options) {
721
745
  if (res.logEntry.entryHash !== row.entry.entryHash) {
722
746
  throw new Error(`REPLAY_ENTRY_HASH_MISMATCH at seq=${row.entry.serverSeq}: expected ${row.entry.entryHash}, got ${res.logEntry.entryHash}`);
723
747
  }
748
+ // The entry hash does not cover every field, so the whole stored entry is compared.
749
+ if (jcs(res.logEntry) !== jcs(row.entry)) {
750
+ throw new Error(`REPLAY_ENTRY_MISMATCH at seq=${row.entry.serverSeq}: the stored entry differs from the replayed one`);
751
+ }
752
+ loggedOps.add(row.entry.opId);
724
753
  if (!seenOps.has(row.entry.opId)) {
725
754
  seenOps.set(row.entry.opId, toOpIndexRecord(row.entry));
726
755
  }
@@ -736,6 +765,19 @@ export function replayFromStore(store, hooks, options) {
736
765
  }
737
766
  }
738
767
  state = res.state;
768
+ checkCheckpoint();
769
+ }
770
+ if (audit) {
771
+ const orphan = [...checkpointAt.keys()][0];
772
+ if (orphan !== undefined)
773
+ throw new Error(`CHECKPOINT_STATE_MISMATCH at seq=${orphan}: no log entry has this position`);
774
+ const sameSet = (left, right) => left.size === new Set(right).size && right.every((item) => left.has(item));
775
+ if (!sameSet(loggedOps, store.readOpIndexUpTo(Number.MAX_SAFE_INTEGER).map((record) => record.opId))) {
776
+ throw new Error('INDEX_MISMATCH: the operation index does not hold the same operations as the log');
777
+ }
778
+ if (!sameSet(spentSet, store.readSpentApprovalsUpTo(Number.MAX_SAFE_INTEGER))) {
779
+ throw new Error('INDEX_MISMATCH: the approval index does not hold the same approvals as the log');
780
+ }
739
781
  }
740
782
  return {
741
783
  state,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "certal",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Deterministic execution firewall and runtime for AI agents. Zero dependencies, SQLite WAL, write-ahead outbox, human-priority undo, and Lean 4 proofs.",
5
5
  "license": "MIT",
6
6
  "author": "Paweł Olszewski",
@@ -69,19 +69,19 @@
69
69
  "build": "node tools/build.mjs",
70
70
  "typecheck": "node tools/typecheck.mjs",
71
71
  "lint": "biome check core tools bin",
72
- "test": "node --test core/tests/kernel.laws.test.ts core/tests/interleavings.bfs.test.ts core/tests/sqlite.replay.test.ts core/tests/e2e.sdk.test.ts core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
72
+ "test": "node --test core/tests/kernel.laws.test.ts core/tests/interleavings.bfs.test.ts core/tests/sqlite.replay.test.ts core/tests/e2e.sdk.test.ts core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/gate.hardening.test.ts core/tests/adversarial.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
73
73
  "test:laws": "node --test core/tests/kernel.laws.test.ts",
74
74
  "test:bfs": "node --test core/tests/interleavings.bfs.test.ts",
75
75
  "test:replay": "node --test core/tests/sqlite.replay.test.ts",
76
76
  "test:e2e": "node --test core/tests/e2e.sdk.test.ts",
77
- "test:cli": "node --test core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
77
+ "test:cli": "node --test core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/gate.hardening.test.ts core/tests/adversarial.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
78
78
  "test:mutations": "node core/tests/probe.mutations.ts",
79
79
  "test:bench": "node core/tests/bench.human-lane.ts",
80
80
  "test:bench:cli": "node core/tests/bench.cli.ts",
81
81
  "conformance:export": "node core/tests/export.conformance.ts .tmp-formal/vectors.jsonl",
82
82
  "check:structure": "node tools/check-structure.mjs",
83
83
  "check:formal": "node tools/check-formal.mjs",
84
- "check": "npm run check:structure && npm run typecheck && npm test && npm run test:mutations",
84
+ "check": "npm run check:structure && npm run lint && npm run typecheck && npm test && npm run test:mutations",
85
85
  "check:all": "npm run check && npm run check:formal",
86
86
  "prepack": "npm run build"
87
87
  },
@@ -11,11 +11,12 @@
11
11
  },
12
12
  "scopes": [
13
13
  { "id": "orders", "classId": "order", "paths": ["orders/**"] },
14
- { "id": "risk", "classId": "limit", "paths": ["risk/**"] }
14
+ { "id": "risk", "classId": "limit", "paths": ["risk/**"] },
15
+ { "id": "withdrawals", "classId": "withdrawal", "paths": ["withdrawals/**"] }
15
16
  ],
16
17
  "pins": [
17
18
  { "id": "risk-limits-human-only", "kind": "H", "scopeId": "risk", "classId": "*", "rule": "exposure and leverage limits are set by a human" },
18
- { "id": "no-withdrawals", "kind": "H", "scopeId": "orders", "classId": "withdrawal", "rule": "agents never move funds off the venue" }
19
+ { "id": "no-withdrawals", "kind": "H", "scopeId": "withdrawals", "classId": "*", "rule": "agents never move funds off the venue" }
19
20
  ],
20
21
  "tools": {
21
22
  "place-order": {
@@ -7,10 +7,11 @@
7
7
  "maxAttempts": 50
8
8
  },
9
9
  "scopes": [
10
- { "id": "plan", "classId": "assignment", "paths": ["plans/**"] }
10
+ { "id": "plan", "classId": "assignment", "paths": ["plans/**"] },
11
+ { "id": "constraints", "classId": "constraint", "paths": ["constraints/**"] }
11
12
  ],
12
13
  "pins": [
13
- { "id": "frozen-constraints", "kind": "H", "scopeId": "plan", "classId": "constraint", "rule": "hard constraints of the model are set by a human" }
14
+ { "id": "frozen-constraints", "kind": "H", "scopeId": "constraints", "classId": "*", "rule": "hard constraints of the model are set by a human" }
14
15
  ],
15
16
  "tools": {
16
17
  "solver": { "reversibility": "REVERSIBLE", "supportsCas": false }
@@ -9,11 +9,12 @@
9
9
  "scopes": [
10
10
  { "id": "frontend", "classId": "file", "paths": ["src/**", "app/**", "public/**"] },
11
11
  { "id": "database", "classId": "migration", "paths": ["migrations/**", "supabase/migrations/**"] },
12
+ { "id": "destructive-migrations", "classId": "destructive", "paths": ["migrations/**/*drop*", "migrations/**/*truncate*", "supabase/migrations/**/*drop*", "supabase/migrations/**/*truncate*"] },
12
13
  { "id": "access", "classId": "rls", "paths": ["policies/**", "supabase/policies/**"] }
13
14
  ],
14
15
  "pins": [
15
16
  { "id": "rls-human-only", "kind": "H", "scopeId": "access", "classId": "*", "rule": "row level security policies are changed by a human" },
16
- { "id": "destructive-migrations", "kind": "H", "scopeId": "database", "classId": "destructive", "rule": "DROP and TRUNCATE migrations are written by a human" }
17
+ { "id": "destructive-migrations", "kind": "H", "scopeId": "destructive-migrations", "classId": "*", "rule": "migration files with drop or truncate in the name are written by a human" }
17
18
  ],
18
19
  "tools": {
19
20
  "edit": { "reversibility": "REVERSIBLE", "supportsCas": false },
@@ -42,7 +42,7 @@ Do what `nextLegalAction` says.
42
42
 
43
43
  - In file mode, never write a file in a declared scope before the finalize answers `ALLOW`, and never write content other than you declared. Such a write is recorded as a human edit and invalidates your own lease.
44
44
  - In effect mode, never touch the target yourself. Certal delivers the effect.
45
- - Use plain relative paths. An absolute path, a `..` segment or an object of another scope is refused with `OBJECT_OUT_OF_SCOPE`.
45
+ - Use plain relative paths. An absolute path, a `..` segment or an object of another scope is refused with `OBJECT_OUT_OF_SCOPE`. A file that two scopes claim is refused with `OBJECT_SCOPE_AMBIGUOUS`: report it, the operator must fix the manifest. A file with a second hard link is refused with `OBJECT_HARD_LINKED`: report it and do not copy the file to get around it.
46
46
  - Never retry when `retryable` is `false`.
47
47
  - You have no tool to approve, reset, undo or change pins. Those belong to the operator. If you need one, ask the user.
48
48
  - A human edit always wins. When a scope epoch rises under you, your attempt is stale: start again from the current state.