certal 0.1.2 → 0.1.4

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.2",
3
+ "version": "0.1.4",
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,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Fixed
6
+
7
+ - `certal verify --offline` reported `CHECKPOINT_STATE_MISMATCH` for an untouched database after a repeated request, for example an approval that was sent twice. The kernel counts a repeated request in the state and writes no log entry for it, so the checkpoint and the replayed state differed in that counter. Since 0.1.1 the audit compared them in full. It now leaves out the two counters that the log cannot give back. Any other difference is still an error.
8
+
9
+ ## 0.1.3
10
+
11
+ Fixes from an audit of 0.1.2. The kernel and the Lean model are unchanged.
12
+
13
+ ### Security
14
+
15
+ - 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`.
16
+ - 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.
17
+ - The approval webhook must be `https`, or `http` on this machine.
18
+
19
+ ### Changed
20
+
21
+ - `certal init` adds `.certal/` to `.gitignore`.
22
+ - New command `certal accept-manifest`.
23
+
24
+ ### Upgrade
25
+
26
+ - 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.
27
+ - 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.
28
+
3
29
  ## 0.1.2
4
30
 
5
31
  Fixes from an audit of 0.1.1. 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,6 +159,8 @@ 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
166
  **Which scope owns a path.** The order of the scopes in the manifest does not matter. Two rules decide, in this order.
@@ -183,6 +185,8 @@ A path that still has two owners is refused with `OBJECT_SCOPE_AMBIGUOUS` under
183
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. |
184
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. |
185
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
+
186
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.
187
191
 
188
192
  **What an agent reads.** Every answer has the same six fields, so the agent knows whether to go on, wait or stop:
@@ -197,16 +201,16 @@ Witness stages run as child processes. The time limit of a stage is the smaller
197
201
 
198
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.
199
203
 
200
- **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.
201
205
 
202
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.
203
207
 
204
- **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.
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. A repeated request with the same operation id is answered from the record of the first one and leaves no log entry. The kernel counts such requests in the state, so the state hash of a running server can differ from the one that `verify` prints, in two counters only. `verify` leaves these two counters out when it compares a checkpoint. `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.
205
209
 
206
210
  Limits of this layer:
207
211
 
208
212
  - One process owns a state directory. A second server on the same directory is refused. Several agents share one server over HTTP.
209
- - 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.
210
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.
211
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.
212
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.
@@ -214,6 +218,8 @@ Limits of this layer:
214
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.
215
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`.
216
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.
217
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.
218
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.
219
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`.
@@ -278,7 +284,7 @@ More limits are listed in [formal/README.md](formal/README.md).
278
284
  ## Checks
279
285
 
280
286
  ```bash
281
- npm run check # structure, lint, typecheck, 75 tests, 47 mutants
287
+ npm run check # structure, lint, typecheck, 80 tests, 47 mutants
282
288
  npm run check:formal # token scan, clean lake build, axiom audit, 5,005 vectors, 3 model mutations
283
289
  npm run check:all # both
284
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
  }
@@ -111,3 +111,17 @@ export declare function pinnedScopeIds(manifest: {
111
111
  readonly scopes: readonly ManifestScope[];
112
112
  readonly pins: readonly ManifestPin[];
113
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
  }
@@ -478,3 +484,51 @@ export function pinnedScopeIds(manifest) {
478
484
  return new Set(manifest.scopes.map((s) => s.id));
479
485
  return new Set(manifest.pins.map((pin) => pin.scopeId));
480
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, pinnedScopeIds, 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 });
@@ -741,8 +741,15 @@ export function replayFromStore(store, hooks, options) {
741
741
  if (!stored)
742
742
  return;
743
743
  checkpointAt.delete(state.serverSeq);
744
- const replayedHash = computeStateHash(state);
745
- if (stored.stateHash !== replayedHash || computeStateHash(stored.state) !== replayedHash) {
744
+ // A repeated request is answered from the record of the first one and leaves no log entry, but the
745
+ // kernel counts it, and it counts the secrets that were redacted in it. The log cannot give these two
746
+ // counters back, so they are left out of the comparison. A live state can only be ahead in them.
747
+ const withoutReplayCounters = (s) => computeStateHash({ ...s, metrics: { ...s.metrics, idempotentReplays: 0, redactedSecretsTotal: 0 } });
748
+ const selfConsistent = computeStateHash(stored.state) === stored.stateHash;
749
+ const sameState = withoutReplayCounters(stored.state) === withoutReplayCounters(state);
750
+ const countersAhead = stored.state.metrics.idempotentReplays >= state.metrics.idempotentReplays &&
751
+ stored.state.metrics.redactedSecretsTotal >= state.metrics.redactedSecretsTotal;
752
+ if (!selfConsistent || !sameState || !countersAhead) {
746
753
  throw new Error(`CHECKPOINT_STATE_MISMATCH at seq=${stored.serverSeq}: the stored snapshot is not the state that the log gives`);
747
754
  }
748
755
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "certal",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
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/ownership.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/ownership.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",