certal 0.1.1 → 0.1.3

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.1",
3
+ "version": "0.1.3",
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,5 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3
4
+
5
+ Fixes from an audit of 0.1.2. The kernel and the Lean model are unchanged.
6
+
7
+ ### Security
8
+
9
+ - A start checked the policy and the operator keys of a changed manifest and nothing else, so an edited manifest could bring a new deliver command that ran after a restart. The first start now records a fingerprint of the whole manifest in the operator home, and a start with another manifest is refused until the operator runs `certal accept-manifest`.
10
+ - The text that a deliver or preflight command printed on a refusal was written to the log. An error message of an external system could carry an API key there. Only a reason code in capitals is kept.
11
+ - The approval webhook must be `https`, or `http` on this machine.
12
+
13
+ ### Changed
14
+
15
+ - `certal init` adds `.certal/` to `.gitignore`.
16
+ - New command `certal accept-manifest`.
17
+
18
+ ### Upgrade
19
+
20
+ - A project that ran on an earlier version records its current manifest at the first start on 0.1.3. Check `certal.json` before that start.
21
+ - A deliver or preflight command that explained a refusal in a sentence on stderr now gives `REFUSED_BY_COMMAND` or `PREFLIGHT_EXIT_<code>`. Start stderr with a word in capitals to name the reason.
22
+
23
+ ## 0.1.2
24
+
25
+ Fixes from an audit of 0.1.1. The kernel and the Lean model are unchanged.
26
+
27
+ ### Security
28
+
29
+ - A pinned scope could still lose a file. The rule that let a whole-directory pattern give way compared the text of two patterns, not the files they match, so a pinned `policies/**` gave `policies/a.md` to a scope with `policies/*.md`, `policies/*` or `policies/**/**`. A pinned scope now wins every overlap with a scope without a pin. The text rule only orders scopes that no pin covers.
30
+ - `**.sql` was read as `*.sql` and covered the top directory only. A `**` joined to other text is now refused when the manifest is loaded.
31
+ - Patterns and paths are compared in one Unicode form. An id with a long s or a full-width letter, or a pattern typed with a combining accent, no longer falls outside the scope of the plain spelling.
32
+ - Object ids may not hold zero-width characters, line and paragraph separators, the Arabic letter mark, the byte order mark or Hangul fillers. The limit of 1,024 characters is counted in the stored form.
33
+ - `certal verify --offline` compares the index columns of the log with the stored entries.
34
+
35
+ ### Changed
36
+
37
+ - The `destructive-migrations` scope of the `vibeops` preset covers every `migrations` directory. Its pin says that it reads the file name.
38
+ - A refusal for a link carries a `detail` sentence.
39
+ - A manifest with a mistake in one field no longer reports missing witness stages that are declared.
40
+
3
41
  ## 0.1.1
4
42
 
5
43
  Fixes from two audits of 0.1.0. The kernel and the Lean model are unchanged.
package/README.md CHANGED
@@ -146,7 +146,7 @@ console.log(undo.report.skippedConflicts.map((c) => c.reason));
146
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
147
 
148
148
  ```bash
149
- certal init --preset sdk # certal.json, the operator key, .mcp.json
149
+ certal init --preset sdk # certal.json, the operator key, .mcp.json, .gitignore
150
150
  certal mcp # MCP server over stdio, one agent
151
151
  certal mcp --transport http --agents alice,bob # several agents, one bearer token each
152
152
  certal status # scope epochs, leases, autonomy tiers, pending approvals
@@ -159,13 +159,20 @@ 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
+ **A changed manifest.** A manifest names the commands that run: the deliver command of a tool, the witness stages, the approval address. The first start of a project records a fingerprint of the manifest in the operator home, outside the project. A later start with another manifest is refused and names the sections that changed, whatever the change is: a new command, a new scope or a new pin. The operator reads the change and runs `certal accept-manifest`, which needs the operator key of that machine. The layout of the file does not count, and `certal status` reads the state without this check.
163
+
162
164
  **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
165
 
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.
166
+ **Which scope owns a path.** The order of the scopes in the manifest does not matter. Two rules decide, in this order.
167
+
168
+ 1. A pinned scope wins. When a scope with a pin matches a path, a scope without a pin never owns that path, whatever the two patterns look like. With a pinned `access: policies/**`, the file `policies/a.md` belongs to `access` also when another scope lists `policies/*.md`, `policies/*` or `**`. When two pinned scopes match the same path, nobody owns it.
169
+ 2. Among scopes without a pin, a whole-directory pattern (`dir/**`, `**` or a pattern without a wildcard) is a fallback: it gives way to a pattern of another scope that starts inside that directory. This rule reads the text of the patterns, and it only orders scopes that no pin covers.
165
170
 
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.
171
+ A path that still has two owners is refused with `OBJECT_SCOPE_AMBIGUOUS` under either lease. The same pattern in two scopes is refused when the manifest is loaded.
167
172
 
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`.
173
+ **Patterns and object ids.** A pattern has `*` and `?` inside one path segment and `**` for any number of segments. `**` must be a whole segment: write `**/*.sql` for the SQL files of every directory, because `**.sql` is refused. A pattern without a wildcard names a file or a directory with everything below it, so `policies` and `policies/**` cover the same files. Braces, brackets, a backslash, a trailing `/` and an absolute path are refused when the manifest is loaded, because such a pattern would match nothing and a pin behind it would protect nothing. A pattern and a path are compared without letter case and in one Unicode form on every platform, so `Policies/x.sql`, a name typed with a combining accent and a name with a long s or a full-width letter all fall in the scope of the plain spelling. On a case-sensitive file system this also puts `SRC/a` in the scope of `src/**`. An object id is at most 1,024 characters, is stored in Unicode form NFC, and may not hold a control character, an invisible character or a text-direction mark. A scope without paths takes plain ids only: an id with a `/` is refused there.
174
+
175
+ **Links.** In a scope that lists paths, the gate resolves the real path of every object when a batch is proposed and again when it is finalized. A symbolic link, also in a parent directory, that leads into another scope or out of the project is refused with `OBJECT_OUT_OF_SCOPE`. A file with a second hard link is refused with `OBJECT_HARD_LINKED`, also when the second name is a harmless backup: the other name cannot be found without reading the whole disk. The answer carries a `detail` sentence that says so.
169
176
 
170
177
  **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
178
 
@@ -178,6 +185,8 @@ certal verify --offline .certal/certal.db
178
185
  | 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
186
  | 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
187
 
188
+ The text that a deliver or preflight command prints is not stored, because it may hold a key or the data of a customer. A command names the reason of a refusal with one word in capitals at the start of stderr, such as `INSUFFICIENT_FUNDS`, and only that word reaches the log.
189
+
181
190
  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
191
 
183
192
  **What an agent reads.** Every answer has the same six fields, so the agent knows whether to go on, wait or stop:
@@ -192,20 +201,25 @@ Witness stages run as child processes. The time limit of a stage is the smaller
192
201
 
193
202
  **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
203
 
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.
204
+ **Approval channels.** The webhook address must be `https`, or `http` on this machine only. The default channel waits for `certal approve`. The webhook channel posts the binding hash, a summary of the change and the expiry to a URL, and accepts back only a token with a valid operator signature over the same binding.
196
205
 
197
206
  **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
207
 
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.
208
+ **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. `verify` proves that the stored entries are the ones that the stored events give. It does not prove that a field of an event which does not change the outcome, such as a label of the login method, is the one that was first written.
200
209
 
201
210
  Limits of this layer:
202
211
 
203
212
  - 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.
213
+ - A changed manifest needs `certal accept-manifest`. Even an accepted manifest may only tighten the log. A looser policy or a new operator key stops the start, and the way out is a new state directory. A pin declared while the task is halted is set right after the reset.
205
214
  - 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
215
  - 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.
216
+ - The `destructive-migrations` pin of the `vibeops` preset is a rule on the file name. It covers a file with `drop` or `truncate` in its name in any `migrations` directory. It does not cover `007_cleanup.sql` with a `DROP` inside, or `009_dr0p.sql`. In file mode no check can read the SQL, because the file is written after the verdict. To check the statement itself, send migrations through a tool with a `deliverCommand` and read the SQL in a witness command.
217
+ - The default budget is 20 attempts for a task (`policy.maxAttempts`). A long session reaches it and pauses. Set a higher value in the manifest for long work.
218
+ - An undo of a batch with an applied effect compensates the effect only when its tool declares `"supportsCas": true`. Without it the effect is marked for manual compensation.
207
219
  - 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
220
  - The key file gets mode `0600`. On Windows the mode has no effect, and the profile directory protects the file.
221
+ - The record of the accepted manifest is safe from a process that can write only the project. A process that can write the operator home can replace it, as it can read the operator key.
222
+ - A payload of an effect is stored after the redaction of known secret shapes. Data that has no such shape, such as the e-mail address of a customer, is stored as it was sent. Keep personal data out of payloads, or send a reference.
209
223
  - 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
224
  - 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
225
  - 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`.
@@ -270,7 +284,7 @@ More limits are listed in [formal/README.md](formal/README.md).
270
284
  ## Checks
271
285
 
272
286
  ```bash
273
- npm run check # structure, lint, typecheck, 68 tests, 47 mutants
287
+ npm run check # structure, lint, typecheck, 79 tests, 47 mutants
274
288
  npm run check:formal # token scan, clean lake build, axiom audit, 5,005 vectors, 3 model mutations
275
289
  npm run check:all # both
276
290
  npm run test:bench # latency of the human lane under agent load
@@ -142,13 +142,21 @@ export class CommandWitness {
142
142
  return { verifyId: ctx.verifyId, stage: ctx.stage, verdict, cpuMs: spent, nearMissPassed };
143
143
  }
144
144
  }
145
+ /**
146
+ * The reason that a command gives for a refusal. What a command prints may hold a secret or the
147
+ * data of a customer, and a reason is written to the log, so the text is not kept. A command can
148
+ * name its reason with one word in capitals at the start of stderr, such as `INSUFFICIENT_FUNDS`.
149
+ */
150
+ function reasonCode(stderr) {
151
+ return /^\s*([A-Z][A-Z0-9_]{2,63})(?=[\s:]|$)/.exec(stderr)?.[1] ?? null;
152
+ }
145
153
  function outcomeOf(result) {
146
154
  if (result.timedOut || result.exitCode === null)
147
155
  return { status: 'UNKNOWN', reason: result.timedOut ? 'COMMAND_TIMEOUT' : 'COMMAND_NOT_STARTED' };
148
156
  if (result.exitCode === 0)
149
157
  return { status: 'APPLIED' };
150
158
  if (result.exitCode === 2)
151
- return { status: 'REFUSED', reason: result.stderr.trim().slice(0, 200) || 'REFUSED_BY_COMMAND' };
159
+ return { status: 'REFUSED', reason: reasonCode(result.stderr) ?? 'REFUSED_BY_COMMAND' };
152
160
  return { status: 'UNKNOWN', reason: `EXIT_${result.exitCode}` };
153
161
  }
154
162
  function recordInput(record) {
@@ -204,6 +212,6 @@ export function createCommandPreflight(tools, cwd, timeoutMs = 10_000) {
204
212
  const result = await runCommand(command, { ...recordInput(record), nowMs }, cwd, timeoutMs);
205
213
  if (!result.timedOut && result.exitCode === 0)
206
214
  return { ok: true };
207
- return { ok: false, reason: result.timedOut ? 'PREFLIGHT_TIMEOUT' : result.stderr.trim().slice(0, 200) || `PREFLIGHT_EXIT_${String(result.exitCode)}` };
215
+ return { ok: false, reason: result.timedOut ? 'PREFLIGHT_TIMEOUT' : (reasonCode(result.stderr) ?? `PREFLIGHT_EXIT_${String(result.exitCode)}`) };
208
216
  };
209
217
  }
@@ -18,8 +18,10 @@ export declare const MAX_OBJECT_ID_LENGTH = 1024;
18
18
  * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
19
19
  * names a file or a directory with everything below it.
20
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:
21
+ * The match ignores letter case and the Unicode form on every platform, so `Policies/x.sql` and
22
+ * `policies/x.sql`, which are one file on Windows and macOS, always belong to the same scope. On a
23
+ * case-sensitive file system this also puts `SRC/a` in the scope of `src/**`: a scope can only get
24
+ * wider by it, never lose a file. It uses no regular expression:
23
25
  * the time grows with the product of the two lengths, so no input can stall it.
24
26
  */
25
27
  export declare function matchGlob(pattern: string, relativePath: string): boolean;
@@ -28,34 +30,43 @@ export declare function patternProblem(pattern: string): string | null;
28
30
  /**
29
31
  * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
30
32
  * 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.
33
+ * an id longer than 1024 characters in its stored form and for an id with a control, invisible or
34
+ * text-direction character, so two spellings can never name the same file, no id can leave the
35
+ * project directory, and an id reads in a log the way it is stored.
34
36
  */
35
37
  export declare function normalizeObjectPath(input: string): string | null;
36
38
  /**
37
39
  * The scopes that claim a path. The order of the scopes in the manifest does not matter.
38
40
  *
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`.
41
+ * 1. A pinned scope wins. When a scope with a pin matches the path, only pinned scopes claim it:
42
+ * a scope without a pin never takes a file that a pin covers, whatever the patterns look like.
43
+ * Two pinned scopes that match the same path both claim it.
44
+ * 2. Among scopes without a pin, a whole-directory pattern (`dir/**`, `**` or a pattern without a
45
+ * wildcard) is a fallback. It gives way to a pattern of another scope that starts inside that
46
+ * directory. This rule looks at the text of the patterns. It only orders scopes that no pin
47
+ * covers, so a wrong guess moves a file between two unprotected scopes and nothing more.
43
48
  *
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.
49
+ * A result with more than one scope means that nobody owns the path. A caller must refuse it.
46
50
  */
47
- export declare function claimantsOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope[];
51
+ export declare function claimantsOfPath(scopes: readonly ManifestScope[], relativePath: string, pinned?: ReadonlySet<string>): ManifestScope[];
48
52
  /** The one scope that owns the path, or null when no scope or more than one scope claims it. */
49
- export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope | null;
53
+ export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string, pinned?: ReadonlySet<string>): ManifestScope | null;
54
+ export interface LinkProblem {
55
+ readonly reason: 'OBJECT_OUT_OF_SCOPE' | 'OBJECT_HARD_LINKED';
56
+ /** One sentence for the agent and the operator. */
57
+ readonly detail: string;
58
+ }
50
59
  /**
51
60
  * Checks where a write to an object of a file scope would really land. Returns the reason for a
52
61
  * refusal, or null.
53
62
  *
54
63
  * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
55
64
  * 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.
65
+ * another name that this check cannot find without reading the whole disk. The other name may be in
66
+ * a pinned scope or outside the project, so the file is refused, also when the second name is a
67
+ * harmless backup.
57
68
  */
58
- export declare function linkProblem(baseDir: string, scopes: readonly ManifestScope[], scopeId: string, objectId: string): 'OBJECT_OUT_OF_SCOPE' | 'OBJECT_HARD_LINKED' | null;
69
+ export declare function linkProblem(baseDir: string, scopes: readonly ManifestScope[], scopeId: string, objectId: string, pinned?: ReadonlySet<string>): LinkProblem | null;
59
70
  export declare function hashFile(file: string): string | null;
60
71
  export interface FileEditSink {
61
72
  /** Current value of the slot of a file, or undefined when the slot does not exist. */
@@ -66,6 +77,7 @@ export interface FileEditSink {
66
77
  export declare class HumanFileWatcher {
67
78
  private readonly baseDir;
68
79
  private readonly scopes;
80
+ private readonly pinned;
69
81
  private readonly sink;
70
82
  private readonly ignore;
71
83
  private readonly debounceMs;
@@ -75,6 +87,7 @@ export declare class HumanFileWatcher {
75
87
  constructor(options: {
76
88
  readonly baseDir: string;
77
89
  readonly scopes: readonly ManifestScope[];
90
+ readonly pinned?: ReadonlySet<string>;
78
91
  readonly sink: FileEditSink;
79
92
  readonly ignore?: readonly string[];
80
93
  readonly debounceMs?: number;
@@ -15,6 +15,15 @@ import path from 'node:path';
15
15
  export const FILE_FIELD = 'sha256';
16
16
  /** Longest object id that the gate reads. */
17
17
  export const MAX_OBJECT_ID_LENGTH = 1024;
18
+ /**
19
+ * One form for comparing a pattern with a path: compatibility characters are replaced by their plain
20
+ * letters (the long s, the Kelvin sign and full-width letters read as `s`, `k` and ASCII), and letter
21
+ * case is dropped. Two texts that a case-insensitive file system could take for the same name fold to
22
+ * the same text. The fold is used for matching only. An object id is stored as it was written, in NFC.
23
+ */
24
+ function fold(text) {
25
+ return text.normalize('NFKC').toLowerCase().normalize('NFKC');
26
+ }
18
27
  /** Matches one path segment against a segment pattern with `*` and `?`. Linear in practice, never exponential. */
19
28
  function matchSegment(pattern, text) {
20
29
  let p = 0;
@@ -48,13 +57,15 @@ function matchSegment(pattern, text) {
48
57
  * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
49
58
  * names a file or a directory with everything below it.
50
59
  *
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:
60
+ * The match ignores letter case and the Unicode form on every platform, so `Policies/x.sql` and
61
+ * `policies/x.sql`, which are one file on Windows and macOS, always belong to the same scope. On a
62
+ * case-sensitive file system this also puts `SRC/a` in the scope of `src/**`: a scope can only get
63
+ * wider by it, never lose a file. It uses no regular expression:
53
64
  * the time grows with the product of the two lengths, so no input can stall it.
54
65
  */
55
66
  export function matchGlob(pattern, relativePath) {
56
- const glob = pattern.toLowerCase();
57
- const text = relativePath.toLowerCase();
67
+ const glob = fold(pattern);
68
+ const text = fold(relativePath);
58
69
  if (!/[*?]/.test(glob))
59
70
  return text === glob || text.startsWith(`${glob}/`);
60
71
  const segments = text.split('/');
@@ -95,15 +106,29 @@ export function patternProblem(pattern) {
95
106
  return `ends with "/"; write "${pattern}**" for everything in the directory`;
96
107
  if (pattern.split('/').some((segment) => segment === '..' || segment === '.' || segment === ''))
97
108
  return 'has an empty, "." or ".." segment';
109
+ if (pattern.split('/').some((segment) => segment.includes('**') && segment !== '**')) {
110
+ return 'has "**" joined to other text; "**" must be a whole segment, as in "**/*.sql" for files in every directory';
111
+ }
98
112
  return null;
99
113
  }
100
- /** True for a control character and for a mark that changes the direction of the text around it. */
114
+ /** Characters that do not show, or that change how the text around them shows. */
115
+ const UNSAFE_RANGES = [
116
+ [0x0000, 0x001f], // C0 controls
117
+ [0x007f, 0x009f], // DEL and C1 controls
118
+ [0x00ad, 0x00ad], // soft hyphen
119
+ [0x061c, 0x061c], // Arabic letter mark
120
+ [0x115f, 0x1160], // Hangul fillers
121
+ [0x200b, 0x200f], // zero-width characters and direction marks
122
+ [0x2028, 0x202e], // line and paragraph separators, direction embeddings and overrides
123
+ [0x2060, 0x206f], // word joiner, invisible operators, direction isolates
124
+ [0x3164, 0x3164], // Hangul filler
125
+ [0xfeff, 0xfeff], // byte order mark
126
+ [0xffa0, 0xffa0], // half-width Hangul filler
127
+ ];
101
128
  function hasUnsafeCharacter(text) {
102
129
  for (let i = 0; i < text.length; i += 1) {
103
130
  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))
131
+ if (UNSAFE_RANGES.some(([from, to]) => code >= from && code <= to))
107
132
  return true;
108
133
  }
109
134
  return false;
@@ -111,16 +136,19 @@ function hasUnsafeCharacter(text) {
111
136
  /**
112
137
  * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
113
138
  * 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.
139
+ * an id longer than 1024 characters in its stored form and for an id with a control, invisible or
140
+ * text-direction character, so two spellings can never name the same file, no id can leave the
141
+ * project directory, and an id reads in a log the way it is stored.
117
142
  */
118
143
  export function normalizeObjectPath(input) {
119
- if (typeof input !== 'string' || input === '' || input.length > MAX_OBJECT_ID_LENGTH)
144
+ // A combining sequence shrinks in NFC, so the first limit is loose and the exact one comes after.
145
+ if (typeof input !== 'string' || input === '' || input.length > MAX_OBJECT_ID_LENGTH * 4)
120
146
  return null;
121
147
  if (hasUnsafeCharacter(input))
122
148
  return null;
123
149
  const slashed = input.normalize('NFC').replace(/\\/g, '/');
150
+ if (slashed.length > MAX_OBJECT_ID_LENGTH)
151
+ return null;
124
152
  if (slashed.startsWith('/') || /^[A-Za-z]:(\/|$)/.test(slashed))
125
153
  return null;
126
154
  const parts = slashed.split('/').filter((segment) => segment !== '' && segment !== '.');
@@ -134,35 +162,41 @@ function wholeDirectory(pattern) {
134
162
  return '';
135
163
  // A pattern without a wildcard covers that path and everything below it.
136
164
  if (!/[*?]/.test(pattern))
137
- return `${pattern.toLowerCase()}/`;
165
+ return `${fold(pattern)}/`;
138
166
  if (!pattern.endsWith('/**'))
139
167
  return null;
140
168
  const dir = pattern.slice(0, -2);
141
- return /[*?]/.test(dir) ? null : dir.toLowerCase();
169
+ return /[*?]/.test(dir) ? null : fold(dir);
142
170
  }
143
171
  /** The text of a pattern before its first wildcard. */
144
172
  function literalPrefix(pattern) {
145
173
  const at = pattern.search(/[*?]/);
146
- return (at < 0 ? pattern : pattern.slice(0, at)).toLowerCase();
174
+ return fold(at < 0 ? pattern : pattern.slice(0, at));
147
175
  }
176
+ const NO_PINS = new Set();
148
177
  /**
149
178
  * The scopes that claim a path. The order of the scopes in the manifest does not matter.
150
179
  *
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`.
180
+ * 1. A pinned scope wins. When a scope with a pin matches the path, only pinned scopes claim it:
181
+ * a scope without a pin never takes a file that a pin covers, whatever the patterns look like.
182
+ * Two pinned scopes that match the same path both claim it.
183
+ * 2. Among scopes without a pin, a whole-directory pattern (`dir/**`, `**` or a pattern without a
184
+ * wildcard) is a fallback. It gives way to a pattern of another scope that starts inside that
185
+ * directory. This rule looks at the text of the patterns. It only orders scopes that no pin
186
+ * covers, so a wrong guess moves a file between two unprotected scopes and nothing more.
155
187
  *
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.
188
+ * A result with more than one scope means that nobody owns the path. A caller must refuse it.
158
189
  */
159
- export function claimantsOfPath(scopes, relativePath) {
190
+ export function claimantsOfPath(scopes, relativePath, pinned = NO_PINS) {
160
191
  const normalized = normalizeObjectPath(relativePath);
161
192
  if (normalized === null)
162
193
  return [];
163
194
  const matches = scopes
164
195
  .map((scope) => ({ scope, patterns: scope.paths.filter((pattern) => matchGlob(pattern, normalized)) }))
165
196
  .filter((entry) => entry.patterns.length > 0);
197
+ const pinnedMatches = matches.filter((entry) => pinned.has(entry.scope.id));
198
+ if (pinnedMatches.length > 0)
199
+ return pinnedMatches.map((entry) => entry.scope);
166
200
  const givesWay = (wide, narrow) => wide.patterns.every((pattern) => {
167
201
  const dir = wholeDirectory(pattern);
168
202
  if (dir === null)
@@ -177,8 +211,8 @@ export function claimantsOfPath(scopes, relativePath) {
177
211
  .map((entry) => entry.scope);
178
212
  }
179
213
  /** 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);
214
+ export function scopeOfPath(scopes, relativePath, pinned = NO_PINS) {
215
+ const claimants = claimantsOfPath(scopes, relativePath, pinned);
182
216
  return claimants.length === 1 ? claimants[0] : null;
183
217
  }
184
218
  /**
@@ -187,9 +221,11 @@ export function scopeOfPath(scopes, relativePath) {
187
221
  *
188
222
  * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
189
223
  * 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.
224
+ * another name that this check cannot find without reading the whole disk. The other name may be in
225
+ * a pinned scope or outside the project, so the file is refused, also when the second name is a
226
+ * harmless backup.
191
227
  */
192
- export function linkProblem(baseDir, scopes, scopeId, objectId) {
228
+ export function linkProblem(baseDir, scopes, scopeId, objectId, pinned = NO_PINS) {
193
229
  const parts = objectId.split('/');
194
230
  let existing = parts.length;
195
231
  // The deepest part of the path that exists. A link below it cannot exist.
@@ -204,19 +240,25 @@ export function linkProblem(baseDir, scopes, scopeId, objectId) {
204
240
  real = fs.realpathSync.native(path.join(baseDir, ...parts.slice(0, existing)));
205
241
  }
206
242
  catch {
207
- // A link that leads nowhere, or a path that cannot be read.
208
- return 'OBJECT_OUT_OF_SCOPE';
243
+ return { reason: 'OBJECT_OUT_OF_SCOPE', detail: `${objectId} is behind a link that leads nowhere or cannot be read` };
209
244
  }
210
245
  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';
246
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
247
+ return { reason: 'OBJECT_OUT_OF_SCOPE', detail: `${objectId} is behind a link that leads out of the project` };
248
+ }
249
+ const realId = relative.split(path.sep).join('/');
250
+ const claimants = claimantsOfPath(scopes, realId, pinned);
251
+ if (claimants.length !== 1 || claimants[0]?.id !== scopeId) {
252
+ return { reason: 'OBJECT_OUT_OF_SCOPE', detail: `${objectId} is a link to ${realId}, which does not belong to the scope ${scopeId}` };
253
+ }
216
254
  if (existing === parts.length) {
217
255
  const stat = fs.statSync(real, { throwIfNoEntry: false });
218
- if (stat?.isFile() && stat.nlink > 1)
219
- return 'OBJECT_HARD_LINKED';
256
+ if (stat?.isFile() && stat.nlink > 1) {
257
+ return {
258
+ reason: 'OBJECT_HARD_LINKED',
259
+ detail: `${objectId} has ${stat.nlink} names (hard links), and the other names cannot be found from here. Replace it with a copy that has one name, or remove the other names`,
260
+ };
261
+ }
220
262
  }
221
263
  return null;
222
264
  }
@@ -231,6 +273,7 @@ export function hashFile(file) {
231
273
  export class HumanFileWatcher {
232
274
  baseDir;
233
275
  scopes;
276
+ pinned;
234
277
  sink;
235
278
  ignore;
236
279
  debounceMs;
@@ -240,6 +283,7 @@ export class HumanFileWatcher {
240
283
  constructor(options) {
241
284
  this.baseDir = options.baseDir;
242
285
  this.scopes = options.scopes;
286
+ this.pinned = options.pinned ?? NO_PINS;
243
287
  this.sink = options.sink;
244
288
  this.ignore = options.ignore ?? ['.git', 'node_modules', '.certal'];
245
289
  this.debounceMs = options.debounceMs ?? 50;
@@ -267,7 +311,7 @@ export class HumanFileWatcher {
267
311
  const file = path.join(this.baseDir, relativePath);
268
312
  const hash = hashFile(file);
269
313
  // 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)) {
314
+ for (const scope of claimantsOfPath(this.scopes, relativePath, this.pinned)) {
271
315
  const known = this.sink.currentHash(scope, relativePath);
272
316
  if (hash === null) {
273
317
  // A directory or an unreadable file is not a change. A file that is gone is one, when its slot holds a hash.
@@ -103,3 +103,25 @@ export declare function loadManifest(startDir: string): ResolvedManifest;
103
103
  export declare function policyRelaxations(current: PolicyConfig, next: Partial<PolicyConfig>): string[];
104
104
  /** The part of `next` that differs from `current`. Empty when the manifest policy is already in force. */
105
105
  export declare function policyDifference(current: PolicyConfig, next: Partial<PolicyConfig>): Partial<PolicyConfig>;
106
+ /**
107
+ * The ids of the scopes that a pin of the manifest covers. A pin on the scope `*` covers every
108
+ * scope. Such a scope wins every overlap with a scope without a pin.
109
+ */
110
+ export declare function pinnedScopeIds(manifest: {
111
+ readonly scopes: readonly ManifestScope[];
112
+ readonly pins: readonly ManifestPin[];
113
+ }): ReadonlySet<string>;
114
+ export interface ManifestFingerprint {
115
+ /** Hash of everything the manifest declares. */
116
+ readonly hash: string;
117
+ /** One hash per top-level section, to tell which part changed. */
118
+ readonly sections: Readonly<Record<string, string>>;
119
+ }
120
+ /**
121
+ * A fingerprint of what a resolved manifest declares: policy, scopes, pins, tools with their
122
+ * commands, witness stages, the approval channel, the operator and the rest. The layout of the
123
+ * file and the place of the project on the disk do not count.
124
+ */
125
+ export declare function manifestFingerprint(manifest: ResolvedManifest): ManifestFingerprint;
126
+ /** The names of the sections in which two fingerprints differ. */
127
+ export declare function changedSections(before: ManifestFingerprint, after: ManifestFingerprint): string[];
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import fs from 'node:fs';
2
3
  import { patternProblem } from './file-watcher.js';
3
4
  import path from 'node:path';
@@ -181,6 +182,11 @@ export function validateManifest(raw, label = MANIFEST_FILE) {
181
182
  bad('"approvals.channel" must be "local-cli" or "webhook"');
182
183
  else if (a.channel === 'webhook' && !isText(a.url))
183
184
  bad('"approvals.url" is required for the webhook channel');
185
+ else if (a.channel === 'webhook') {
186
+ const problem = webhookUrlProblem(a.url);
187
+ if (problem)
188
+ bad(`"approvals.url" ${problem}`);
189
+ }
184
190
  }
185
191
  return problems;
186
192
  }
@@ -366,6 +372,8 @@ export function loadManifest(startDir) {
366
372
  throw new ManifestError([`no ${MANIFEST_FILE} found in ${path.resolve(startDir)} or above it. Run \`certal init\`.`]);
367
373
  const problems = [];
368
374
  let layer = emptyLayer();
375
+ // A file that could not be read leaves holes. The checks of the whole would then report what is not wrong.
376
+ let unread = false;
369
377
  for (const [index, file] of files.entries()) {
370
378
  let raw;
371
379
  try {
@@ -373,15 +381,19 @@ export function loadManifest(startDir) {
373
381
  }
374
382
  catch (err) {
375
383
  problems.push(`${file}: not valid JSON (${err.message})`);
384
+ unread = true;
376
385
  continue;
377
386
  }
378
387
  const shape = validateManifest(raw, file);
379
388
  if (shape.length > 0) {
380
389
  problems.push(...shape);
390
+ unread = true;
381
391
  continue;
382
392
  }
383
393
  layer = mergeLayer(layer, raw, file, problems, index === 0);
384
394
  }
395
+ if (unread)
396
+ throw new ManifestError(problems);
385
397
  const required = (layer.policy.requiredWitnessStages ?? DEFAULT_POLICY.requiredWitnessStages);
386
398
  for (const stage of required) {
387
399
  if (layer.witness[stage] === undefined)
@@ -463,3 +475,60 @@ export function policyDifference(current, next) {
463
475
  }
464
476
  return diff;
465
477
  }
478
+ /**
479
+ * The ids of the scopes that a pin of the manifest covers. A pin on the scope `*` covers every
480
+ * scope. Such a scope wins every overlap with a scope without a pin.
481
+ */
482
+ export function pinnedScopeIds(manifest) {
483
+ if (manifest.pins.some((pin) => pin.scopeId === '*'))
484
+ return new Set(manifest.scopes.map((s) => s.id));
485
+ return new Set(manifest.pins.map((pin) => pin.scopeId));
486
+ }
487
+ /**
488
+ * An approval request carries a summary of the change, so it must not travel in clear text over a
489
+ * network. `https` is accepted for any host, `http` only for this machine.
490
+ */
491
+ function webhookUrlProblem(text) {
492
+ let url;
493
+ try {
494
+ url = new URL(text);
495
+ }
496
+ catch {
497
+ return 'is not a URL';
498
+ }
499
+ if (url.username !== '' || url.password !== '')
500
+ return 'must not carry a user name or a password';
501
+ if (url.protocol === 'https:')
502
+ return null;
503
+ if (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
504
+ return null;
505
+ return 'must be an https URL, or an http URL of this machine (127.0.0.1, localhost or [::1])';
506
+ }
507
+ /** Canonical text of a JSON value: object keys in order, no layout. */
508
+ function canonical(value) {
509
+ if (Array.isArray(value))
510
+ return `[${value.map(canonical).join(',')}]`;
511
+ if (value !== null && typeof value === 'object') {
512
+ const record = value;
513
+ return `{${Object.keys(record).filter((k) => record[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${canonical(record[k])}`).join(',')}}`;
514
+ }
515
+ return JSON.stringify(value) ?? 'null';
516
+ }
517
+ /**
518
+ * A fingerprint of what a resolved manifest declares: policy, scopes, pins, tools with their
519
+ * commands, witness stages, the approval channel, the operator and the rest. The layout of the
520
+ * file and the place of the project on the disk do not count.
521
+ */
522
+ export function manifestFingerprint(manifest) {
523
+ const sections = {};
524
+ for (const [name, value] of Object.entries(manifest)) {
525
+ if (name === 'baseDir' || name === 'stateDir' || name === 'sources')
526
+ continue;
527
+ sections[name] = createHash('sha256').update(canonical(value)).digest('hex');
528
+ }
529
+ return { hash: createHash('sha256').update(canonical(sections)).digest('hex'), sections };
530
+ }
531
+ /** The names of the sections in which two fingerprints differ. */
532
+ export function changedSections(before, after) {
533
+ return [...new Set([...Object.keys(before.sections), ...Object.keys(after.sections)])].filter((name) => before.sections[name] !== after.sections[name]).sort();
534
+ }
@@ -29,6 +29,13 @@ export declare function operatorKeyPath(): string;
29
29
  * the token of another agent there.
30
30
  */
31
31
  export declare function agentTokenDir(projectDir: string): string;
32
+ /** A short id of a project directory, for the files that the operator home keeps about it. */
33
+ export declare function projectId(projectDir: string): string;
34
+ /**
35
+ * File that records which manifest the operator last accepted for a project. It is in the
36
+ * operator home, so a process that can only write the project cannot change it.
37
+ */
38
+ export declare function manifestPinPath(projectDir: string): string;
32
39
  export declare function keyIdOf(publicKeyPem: string): string;
33
40
  /** Reads the operator key. Returns null when there is none. */
34
41
  export declare function loadOperatorKey(file?: string): OperatorKey | null;
@@ -19,8 +19,18 @@ export function operatorKeyPath() {
19
19
  * the token of another agent there.
20
20
  */
21
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');
22
+ return path.join(operatorHome(), 'run', projectId(projectDir), 'agents');
23
+ }
24
+ /** A short id of a project directory, for the files that the operator home keeps about it. */
25
+ export function projectId(projectDir) {
26
+ return createHash('sha256').update(path.resolve(projectDir)).digest('hex').slice(0, 16);
27
+ }
28
+ /**
29
+ * File that records which manifest the operator last accepted for a project. It is in the
30
+ * operator home, so a process that can only write the project cannot change it.
31
+ */
32
+ export function manifestPinPath(projectDir) {
33
+ return path.join(operatorHome(), 'manifests', `${projectId(projectDir)}.json`);
24
34
  }
25
35
  export function keyIdOf(publicKeyPem) {
26
36
  const der = createPublicKey(publicKeyPem).export({ type: 'spki', format: 'der' });
package/dist/cli/main.js CHANGED
@@ -4,9 +4,9 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { createKeyringSignatureVerifier } from '../kernel/index.js';
6
6
  import { SQLiteStore, replayFromStore } from '../runtime/index.js';
7
- import { MANIFEST_FILE, ManifestError, loadManifest } from '../adapters/manifest.js';
7
+ import { MANIFEST_FILE, ManifestError, changedSections, loadManifest, manifestFingerprint } from '../adapters/manifest.js';
8
8
  import { agentTokenDir, ensureOperatorKey, loadOperatorKey, operatorKeyPath, signApprovalToken, signOperatorCommand } from '../adapters/operator-auth.js';
9
- import { CertalHost, DB_FILE, readRuntimeInfo, readStatus, readStoredOperatorKeys } from '../mcp/host.js';
9
+ import { CertalHost, DB_FILE, readManifestPin, readRuntimeInfo, readStatus, readStoredOperatorKeys, writeManifestPin } from '../mcp/host.js';
10
10
  import { AGENT_ID_PATTERN, McpGateway, packageVersion, serveHttp, serveStdio } from '../mcp/server.js';
11
11
  /**
12
12
  * The `certal` command line. Operator commands (`approve`, `undo`, `halt`, `reset`, `resume`)
@@ -27,6 +27,7 @@ const HELP = `certal ${packageVersion()}
27
27
  certal reset <scopeId> --reason "..."
28
28
  certal resume <scopeId>
29
29
  certal stop
30
+ certal accept-manifest
30
31
  certal verify --offline <dbPath>
31
32
 
32
33
  Options for every command: --agent (one JSON line per answer), --cwd <dir>, --help`;
@@ -115,6 +116,41 @@ function printReply(out, reply, cwd, scopeId, onAllow, extra = {}) {
115
116
  }
116
117
  return reply.ok ? 0 : 1;
117
118
  }
119
+ /** Adds the state directory to `.gitignore`, once. The log and the tokens of a run do not belong in a repository. */
120
+ function ignoreStateDir(cwd) {
121
+ const file = path.join(cwd, '.gitignore');
122
+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
123
+ if (text.split(/\r?\n/).some((line) => /^\/?\.certal\/?$/.test(line.trim())))
124
+ return false;
125
+ fs.writeFileSync(file, `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}.certal/\n`);
126
+ return true;
127
+ }
128
+ /**
129
+ * Records the current manifest as the accepted one. Only the operator can do it: the command needs
130
+ * the operator key of this machine, and the key must be one that the manifest names.
131
+ */
132
+ function cmdAcceptManifest(cwd, out) {
133
+ const key = loadOperatorKey();
134
+ if (!key)
135
+ throw new UsageError(`no operator key at ${operatorKeyPath()}. Only the operator accepts a manifest.`);
136
+ const manifest = loadManifest(cwd);
137
+ if (manifest.operator?.publicKeys[key.keyId] !== key.publicKeyPem) {
138
+ throw new UsageError(`the operator key ${key.keyId} of this machine is not named in the manifest. Only an operator of the project accepts its manifest.`);
139
+ }
140
+ const current = manifestFingerprint(manifest);
141
+ const accepted = readManifestPin(manifest.baseDir);
142
+ const changed = accepted ? changedSections(accepted, current) : [];
143
+ writeManifestPin(manifest.baseDir, current);
144
+ const live = readRuntimeInfo(manifest.stateDir) !== null;
145
+ if (out.agent)
146
+ out.json({ decision: 'ALLOW', reason: 'MANIFEST_ACCEPTED', changed, manifestHash: current.hash, serverRunning: live });
147
+ else {
148
+ out.line(accepted === null ? 'Recorded the manifest.' : changed.length === 0 ? 'The manifest is the accepted one. Nothing changed.' : `Accepted the manifest. Changed: ${changed.join(', ')}.`);
149
+ if (live)
150
+ out.line('A server is running with the earlier manifest. Stop it and start it again.');
151
+ }
152
+ return 0;
153
+ }
118
154
  function cmdInit(cwd, flags, out) {
119
155
  const preset = typeof flags.preset === 'string' ? flags.preset : 'sdk';
120
156
  const presetFile = PRESETS[preset];
@@ -132,13 +168,15 @@ function cmdInit(cwd, flags, out) {
132
168
  const wroteMcp = !fs.existsSync(mcpFile);
133
169
  if (wroteMcp)
134
170
  fs.writeFileSync(mcpFile, `${JSON.stringify({ mcpServers: { certal: { command: 'npx', args: ['--no-install', 'certal', 'mcp'] } } }, null, 2)}\n`);
171
+ const ignored = ignoreStateDir(cwd);
135
172
  if (out.agent)
136
- out.json({ decision: 'ALLOW', reason: 'INITIALISED', preset, operatorKeyId: key.keyId, keyCreated: created, mcpConfigWritten: wroteMcp });
173
+ out.json({ decision: 'ALLOW', reason: 'INITIALISED', preset, operatorKeyId: key.keyId, keyCreated: created, mcpConfigWritten: wroteMcp, gitignoreUpdated: ignored });
137
174
  else {
138
175
  out.line(`Wrote ${MANIFEST_FILE} (preset ${preset}).`);
139
176
  out.line(created ? `Created the operator key ${key.keyId} at ${operatorKeyPath()}. Keep this file out of every repository.` : `Using the operator key ${key.keyId}.`);
140
177
  out.line(wroteMcp ? 'Wrote .mcp.json.' : '.mcp.json exists and was left as it is.');
141
- out.line('Add .certal/ to .gitignore. Commands in the preset are templates: point them at your own checks.');
178
+ out.line(ignored ? 'Added .certal/ to .gitignore.' : '.gitignore already lists .certal/.');
179
+ out.line('Commands in the preset are templates: point them at your own checks.');
142
180
  if (preset === 'sdk')
143
181
  out.line('The sdk preset accepts every batch at stage L0 without a check. Declare a witness command before you rely on it.');
144
182
  }
@@ -369,6 +407,7 @@ export async function main(argv) {
369
407
  case 'reset':
370
408
  case 'resume': return await cmdScope(cwd, parsed.command, parsed, out);
371
409
  case 'stop': return printReply(out, await operatorCall(cwd, 'shutdown', {}), cwd, '*', 'done');
410
+ case 'accept-manifest': return cmdAcceptManifest(cwd, out);
372
411
  case 'verify': return cmdVerify(parsed, out);
373
412
  default: throw new UsageError(`unknown command: ${parsed.command}\n\n${HELP}`);
374
413
  }
@@ -2,6 +2,7 @@ import type { ApprovalToken, KernelState, StepResult } from '../kernel/index.ts'
2
2
  import { CertalRuntime } from '../runtime/index.ts';
3
3
  import type { RuntimePort } from '../runtime/index.ts';
4
4
  import { CommandWitness } from '../adapters/commands.ts';
5
+ import type { ManifestFingerprint } from '../adapters/manifest.ts';
5
6
  import type { ResolvedManifest } from '../adapters/manifest.ts';
6
7
  /**
7
8
  * One Certal host per state directory: the manifest, the SQLite log, the runtime with its single
@@ -68,6 +69,9 @@ export declare class HostBusyError extends Error {
68
69
  export declare function readRuntimeInfo(stateDir: string): RuntimeInfo | null;
69
70
  /** Operator public keys that the database carries, so an audit needs no other file. */
70
71
  export declare function readStoredOperatorKeys(dbPath: string): Record<string, string>;
72
+ /** The fingerprint of the manifest that the operator last accepted for this project, or null. */
73
+ export declare function readManifestPin(baseDir: string): ManifestFingerprint | null;
74
+ export declare function writeManifestPin(baseDir: string, fingerprint: ManifestFingerprint): void;
71
75
  export declare function describeOps(ops: readonly {
72
76
  readonly objectId: string;
73
77
  readonly field: string;
package/dist/mcp/host.js CHANGED
@@ -7,7 +7,8 @@ import { CertalRuntime, OutboxWorker, SQLiteStore } from '../runtime/index.js';
7
7
  import { LocalCliApprovalChannel, WebhookApprovalChannel } from '../adapters/approval-channel.js';
8
8
  import { CommandTransport, CommandWitness, createCommandPreflight } from '../adapters/commands.js';
9
9
  import { FILE_FIELD, HumanFileWatcher } from '../adapters/file-watcher.js';
10
- import { loadManifest, policyDifference, policyRelaxations } from '../adapters/manifest.js';
10
+ import { changedSections, loadManifest, manifestFingerprint, pinnedScopeIds, policyDifference, policyRelaxations } from '../adapters/manifest.js';
11
+ import { manifestPinPath } from '../adapters/operator-auth.js';
11
12
  import { COMMAND_MAX_AGE_MS, verifyOperatorCommand } from '../adapters/operator-auth.js';
12
13
  /**
13
14
  * One Certal host per state directory: the manifest, the SQLite log, the runtime with its single
@@ -110,6 +111,38 @@ function pinOperatorKeys(dbPath, publicKeys) {
110
111
  db.close();
111
112
  }
112
113
  }
114
+ /** The fingerprint of the manifest that the operator last accepted for this project, or null. */
115
+ export function readManifestPin(baseDir) {
116
+ try {
117
+ const stored = JSON.parse(fs.readFileSync(manifestPinPath(baseDir), 'utf8'));
118
+ return typeof stored.hash === 'string' && typeof stored.sections === 'object' && stored.sections !== null ? stored : null;
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ export function writeManifestPin(baseDir, fingerprint) {
125
+ const file = manifestPinPath(baseDir);
126
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
127
+ fs.writeFileSync(file, `${JSON.stringify(fingerprint, null, 2)}\n`, { mode: 0o600 });
128
+ }
129
+ /**
130
+ * The first start of a project records its manifest. A later start with another manifest is
131
+ * refused: a manifest names the commands that run, so an edit could bring a new deliver command,
132
+ * a weaker witness or another approval address. The operator reads the change and accepts it.
133
+ */
134
+ function checkManifestPin(manifest) {
135
+ const current = manifestFingerprint(manifest);
136
+ const accepted = readManifestPin(manifest.baseDir);
137
+ if (accepted === null) {
138
+ writeManifestPin(manifest.baseDir, current);
139
+ return;
140
+ }
141
+ if (accepted.hash === current.hash)
142
+ return;
143
+ throw new Error(`The manifest changed since this project was last started or accepted. Changed: ${changedSections(accepted, current).join(', ')}. ` +
144
+ 'Read the change. If it is yours, run `certal accept-manifest` as the operator and start again.');
145
+ }
113
146
  export function describeOps(ops) {
114
147
  return ops.slice(0, 20).map((op) => `${op.objectId}.${op.field} ${op.reversibility}${op.externalEffect ? ' +effect' : ''}`);
115
148
  }
@@ -211,6 +244,7 @@ export class CertalHost {
211
244
  }
212
245
  static async open(options) {
213
246
  const manifest = loadManifest(options.cwd);
247
+ checkManifestPin(manifest);
214
248
  fs.mkdirSync(manifest.stateDir, { recursive: true });
215
249
  claimDirectory(manifest.stateDir);
216
250
  const release = () => fs.rmSync(path.join(manifest.stateDir, RUNTIME_FILE), { force: true });
@@ -409,6 +443,7 @@ export class CertalHost {
409
443
  this.watcher = new HumanFileWatcher({
410
444
  baseDir: this.manifest.baseDir,
411
445
  scopes: this.manifest.scopes,
446
+ pinned: pinnedScopeIds(this.manifest),
412
447
  ignore: ['.git', 'node_modules', path.relative(this.manifest.baseDir, this.manifest.stateDir).split(path.sep).join('/') || '.certal'],
413
448
  sink: {
414
449
  currentHash: (scope, relativePath) => this.runtime.getState().slots[slotKey(scope.id, classOf.get(scope.id) ?? scope.classId, relativePath, FILE_FIELD)]?.value,
@@ -22,6 +22,8 @@ export interface AgentReply {
22
22
  readonly retryable: boolean;
23
23
  readonly attemptId?: string;
24
24
  readonly batchId?: string;
25
+ /** One sentence that explains a refusal, where the reason code alone does not. */
26
+ readonly detail?: string;
25
27
  }
26
28
  interface ToolDefinition {
27
29
  readonly name: string;
@@ -4,6 +4,7 @@ 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
6
  import { claimantsOfPath, linkProblem, normalizeObjectPath } from '../adapters/file-watcher.js';
7
+ import { pinnedScopeIds } from '../adapters/manifest.js';
7
8
  import { computeClusterId } from '../adapters/tool-sdk.js';
8
9
  /**
9
10
  * MCP gate for agents. The tool surface is narrow on purpose: an agent can take and release a
@@ -112,7 +113,7 @@ export class McpGateway {
112
113
  const scope = this.host.manifest.scopes.find((s) => s.id === scopeId);
113
114
  if (!scope || scope.paths.length === 0)
114
115
  return null;
115
- return linkProblem(this.host.manifest.baseDir, this.host.manifest.scopes, scopeId, objectId);
116
+ return linkProblem(this.host.manifest.baseDir, this.host.manifest.scopes, scopeId, objectId, pinnedScopeIds(this.host.manifest));
116
117
  }
117
118
  classOf(scopeId, requested) {
118
119
  return requested || this.host.manifest.scopes.find((s) => s.id === scopeId)?.classId || 'default';
@@ -175,7 +176,7 @@ export class McpGateway {
175
176
  const objectIds = [];
176
177
  for (const raw of rawOps) {
177
178
  const objectId = normalizeObjectPath(str(raw, 'objectId'));
178
- const claimants = objectId === null ? [] : claimantsOfPath(this.host.manifest.scopes, objectId);
179
+ const claimants = objectId === null ? [] : claimantsOfPath(this.host.manifest.scopes, objectId, pinnedScopeIds(this.host.manifest));
179
180
  // 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
181
  if (claimants.length > 1)
181
182
  return this.reply('REJECT', 'OBJECT_SCOPE_AMBIGUOUS', scopeId, '', { attemptId });
@@ -188,7 +189,7 @@ export class McpGateway {
188
189
  return this.reply('REJECT', 'OBJECT_OUT_OF_SCOPE', scopeId, '', { attemptId });
189
190
  const linked = this.linkProblemOf(scopeId, objectId);
190
191
  if (linked)
191
- return this.reply('REJECT', linked, scopeId, '', { attemptId });
192
+ return this.reply('REJECT', linked.reason, scopeId, '', { attemptId, detail: linked.detail });
192
193
  objectIds.push(objectId);
193
194
  }
194
195
  const auth = this.auth(agentId, attemptId, taskId);
@@ -301,7 +302,7 @@ export class McpGateway {
301
302
  for (const stateOp of attempt.ops) {
302
303
  const linked = this.linkProblemOf(attempt.scopeId, stateOp.objectId);
303
304
  if (linked)
304
- return this.reply('REJECT', linked, attempt.scopeId, '', { attemptId });
305
+ return this.reply('REJECT', linked.reason, attempt.scopeId, '', { attemptId, detail: linked.detail });
305
306
  }
306
307
  if (attempt.status === 'VERIFIED' && this.needsApproval(attempt)) {
307
308
  // Asked here, before the kernel sees the finalize, so a missing approval does not pause the task for other agents.
@@ -51,6 +51,8 @@ export interface EventStore {
51
51
  loadLatestCheckpoint(): CheckpointSnapshot | null;
52
52
  /** Every stored checkpoint, oldest first. */
53
53
  readCheckpoints(): readonly CheckpointSnapshot[];
54
+ /** The first place where an index column of the log disagrees with the entry it belongs to, or null. */
55
+ findLogColumnMismatch(): string | null;
54
56
  replay(hooks?: DeterministicHooks): {
55
57
  readonly state: KernelState;
56
58
  readonly stateHash: string;
@@ -104,6 +106,7 @@ export declare class InMemoryStore implements UnifiedStore {
104
106
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
105
107
  loadLatestCheckpoint(): CheckpointSnapshot | null;
106
108
  readCheckpoints(): readonly CheckpointSnapshot[];
109
+ findLogColumnMismatch(): string | null;
107
110
  listActionable(nowMs: number): readonly OutboxRecord[];
108
111
  getOutboxRecord(effectId: string): OutboxRecord | null;
109
112
  recoverInFlight(nowMs: number): readonly OutboxRecord[];
@@ -175,6 +178,7 @@ export declare class SQLiteStore implements UnifiedStore {
175
178
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
176
179
  loadLatestCheckpoint(): CheckpointSnapshot | null;
177
180
  readCheckpoints(): readonly CheckpointSnapshot[];
181
+ findLogColumnMismatch(): string | null;
178
182
  private mapOutboxRow;
179
183
  listActionable(nowMs: number): readonly OutboxRecord[];
180
184
  getOutboxRecord(effectId: string): OutboxRecord | null;
@@ -228,6 +228,9 @@ export class InMemoryStore {
228
228
  readCheckpoints() {
229
229
  return [...this.checkpoints];
230
230
  }
231
+ findLogColumnMismatch() {
232
+ return null;
233
+ }
231
234
  listActionable(nowMs) {
232
235
  const out = [];
233
236
  for (const rec of this.outbox.values()) {
@@ -568,6 +571,21 @@ export class SQLiteStore {
568
571
  const rows = this.db.prepare('SELECT snapshot_json FROM checkpoints ORDER BY server_seq').all();
569
572
  return rows.map((row) => JSON.parse(row.snapshot_json));
570
573
  }
574
+ findLogColumnMismatch() {
575
+ const rows = this.db.prepare('SELECT server_seq, op_id, entry_hash, prev_entry_hash, entry_json FROM log_entries ORDER BY server_seq').all();
576
+ for (const row of rows) {
577
+ const entry = JSON.parse(row.entry_json);
578
+ if (entry.serverSeq !== Number(row.server_seq))
579
+ return `server_seq at seq=${row.server_seq}`;
580
+ if (entry.opId !== row.op_id)
581
+ return `op_id at seq=${row.server_seq}`;
582
+ if (entry.entryHash !== row.entry_hash)
583
+ return `entry_hash at seq=${row.server_seq}`;
584
+ if (entry.prevEntryHash !== row.prev_entry_hash)
585
+ return `prev_entry_hash at seq=${row.server_seq}`;
586
+ }
587
+ return null;
588
+ }
571
589
  mapOutboxRow(row) {
572
590
  return {
573
591
  effectId: String(row.effect_id),
@@ -768,6 +786,9 @@ export function replayFromStore(store, hooks, options) {
768
786
  checkCheckpoint();
769
787
  }
770
788
  if (audit) {
789
+ const column = store.findLogColumnMismatch();
790
+ if (column !== null)
791
+ throw new Error(`LOG_COLUMN_MISMATCH: the column ${column} differs from the stored entry`);
771
792
  const orphan = [...checkpointAt.keys()][0];
772
793
  if (orphan !== undefined)
773
794
  throw new Error(`CHECKPOINT_STATE_MISMATCH at seq=${orphan}: no log entry has this position`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "certal",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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,12 +69,12 @@
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/gate.hardening.test.ts core/tests/adversarial.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/ownership.hardening.test.ts core/tests/startup.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/gate.hardening.test.ts core/tests/adversarial.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/ownership.hardening.test.ts core/tests/startup.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",
@@ -9,12 +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
+ { "id": "destructive-migrations", "classId": "destructive", "paths": ["**/migrations/**/*drop*", "**/migrations/**/*truncate*"] },
13
13
  { "id": "access", "classId": "rls", "paths": ["policies/**", "supabase/policies/**"] }
14
14
  ],
15
15
  "pins": [
16
16
  { "id": "rls-human-only", "kind": "H", "scopeId": "access", "classId": "*", "rule": "row level security policies are changed 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
+ { "id": "destructive-migrations", "kind": "H", "scopeId": "destructive-migrations", "classId": "*", "rule": "migration files with drop or truncate in the file name are written by a human; the rule reads the name, not the SQL" }
18
18
  ],
19
19
  "tools": {
20
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`. 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.
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. When an answer has a `detail` field, pass it to the user as it is.
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.