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