certal 0.1.1 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "certal",
3
- "version": "0.1.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,5 +1,23 @@
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
+
3
21
  ## 0.1.1
4
22
 
5
23
  Fixes from two audits of 0.1.0. The kernel and the Lean model are unchanged.
package/README.md CHANGED
@@ -161,11 +161,16 @@ certal verify --offline .certal/certal.db
161
161
 
162
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
163
 
164
- **Which scope owns a path.** The order of the scopes in the manifest does not matter, and letter case is ignored on every platform. A whole-directory pattern (`dir/**` or `**`) is a fallback: it gives way to a pattern of another scope that lies inside that directory. So with `workspace: **` and `access: policies/**`, the file `policies/x.sql` belongs to `access` wherever the two scopes stand in the manifest, and a pin on `access` holds. Every other overlap has no winner. With `src/**` and `**/*.secret`, the file `src/a.secret` is claimed by both, and a batch that names it is refused with `OBJECT_SCOPE_AMBIGUOUS` under either lease. The same pattern in two scopes is refused when the manifest is loaded.
164
+ **Which scope owns a path.** The order of the scopes in the manifest does not matter. Two rules decide, in this order.
165
165
 
166
- **Patterns and object ids.** A pattern has `*` and `?` inside one path segment and `**` for any number of segments. A pattern without a wildcard names a file or a directory with everything below it, so `policies` and `policies/**` cover the same files. Braces, brackets, a backslash, a trailing `/` and an absolute path are refused when the manifest is loaded, because such a pattern would match nothing and a pin behind it would protect nothing. An object id is at most 1,024 characters, is stored in Unicode form NFC, and may not hold a control character or a text-direction mark. A scope without paths takes plain ids only: an id with a `/` is refused there.
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.
167
168
 
168
- **Links.** In a scope that lists paths, the gate resolves the real path of every object when a batch is proposed and again when it is finalized. A symbolic link, also in a parent directory, that leads into another scope or out of the project is refused with `OBJECT_OUT_OF_SCOPE`. A file with a second hard link is refused with `OBJECT_HARD_LINKED`.
169
+ 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.
169
174
 
170
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.
171
176
 
@@ -196,7 +201,7 @@ Witness stages run as child processes. The time limit of a stage is the smaller
196
201
 
197
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.
198
203
 
199
- **Offline audit.** `certal verify --offline <db>` replays a copy of the database from the first entry. It compares every stored entry with the replayed one, field by field, checks the chain between entries, compares every stored checkpoint with the replayed state at its position, and compares the operation and approval indexes with the log. It needs no manifest: the operator public keys are stored in the database. A running server starts from its newest checkpoint and does not repeat this audit, so run `verify` on a database that someone else could write.
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.
200
205
 
201
206
  Limits of this layer:
202
207
 
@@ -204,6 +209,9 @@ Limits of this layer:
204
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.
205
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.
206
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.
207
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`.
208
216
  - The key file gets mode `0600`. On Windows the mode has no effect, and the profile directory protects the file.
209
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.
@@ -270,7 +278,7 @@ More limits are listed in [formal/README.md](formal/README.md).
270
278
  ## Checks
271
279
 
272
280
  ```bash
273
- npm run check # structure, lint, typecheck, 68 tests, 47 mutants
281
+ npm run check # structure, lint, typecheck, 75 tests, 47 mutants
274
282
  npm run check:formal # token scan, clean lake build, axiom audit, 5,005 vectors, 3 model mutations
275
283
  npm run check:all # both
276
284
  npm run test:bench # latency of the human lane under agent load
@@ -18,8 +18,10 @@ export declare const MAX_OBJECT_ID_LENGTH = 1024;
18
18
  * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
19
19
  * names a file or a directory with everything below it.
20
20
  *
21
- * The match ignores letter case on every platform, so `Policies/x.sql` and `policies/x.sql`, which
22
- * are one file on Windows and macOS, always belong to the same scope. It uses no regular expression:
21
+ * The match ignores letter case and the Unicode form on every platform, so `Policies/x.sql` and
22
+ * `policies/x.sql`, which are one file on Windows and macOS, always belong to the same scope. On a
23
+ * case-sensitive file system this also puts `SRC/a` in the scope of `src/**`: a scope can only get
24
+ * wider by it, never lose a file. It uses no regular expression:
23
25
  * the time grows with the product of the two lengths, so no input can stall it.
24
26
  */
25
27
  export declare function matchGlob(pattern: string, relativePath: string): boolean;
@@ -28,34 +30,43 @@ export declare function patternProblem(pattern: string): string | null;
28
30
  /**
29
31
  * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
30
32
  * segments, Unicode form NFC. Returns null for an absolute path, for a path with a `..` segment, for
31
- * an id longer than 1024 characters and for an id with a control or text-direction character, so two
32
- * spellings can never name the same file, no id can leave the project directory, and an id reads in
33
- * a log the way it is stored.
33
+ * an id longer than 1024 characters in its stored form and for an id with a control, invisible or
34
+ * text-direction character, so two spellings can never name the same file, no id can leave the
35
+ * project directory, and an id reads in a log the way it is stored.
34
36
  */
35
37
  export declare function normalizeObjectPath(input: string): string | null;
36
38
  /**
37
39
  * The scopes that claim a path. The order of the scopes in the manifest does not matter.
38
40
  *
39
- * A whole-directory pattern (`dir/**` or `**`) is a fallback. It gives way to a pattern of another
40
- * scope that lies inside that directory: a deeper whole-directory pattern, or any other pattern
41
- * that starts there. So `**` gives way to `policies/**`, and `src/**` gives way to `src/db/**`
42
- * and to `src/*.sql`.
41
+ * 1. A pinned scope wins. When a scope with a pin matches the path, only pinned scopes claim it:
42
+ * a scope without a pin never takes a file that a pin covers, whatever the patterns look like.
43
+ * Two pinned scopes that match the same path both claim it.
44
+ * 2. Among scopes without a pin, a whole-directory pattern (`dir/**`, `**` or a pattern without a
45
+ * wildcard) is a fallback. It gives way to a pattern of another scope that starts inside that
46
+ * directory. This rule looks at the text of the patterns. It only orders scopes that no pin
47
+ * covers, so a wrong guess moves a file between two unprotected scopes and nothing more.
43
48
  *
44
- * Every other overlap is left as it is: `src/**` and a pattern like `**` + `/*.secret` both claim
45
- * `src/a.secret`, and the result has two scopes. A caller must treat such a path as owned by nobody.
49
+ * A result with more than one scope means that nobody owns the path. A caller must refuse it.
46
50
  */
47
- export declare function claimantsOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope[];
51
+ export declare function claimantsOfPath(scopes: readonly ManifestScope[], relativePath: string, pinned?: ReadonlySet<string>): ManifestScope[];
48
52
  /** The one scope that owns the path, or null when no scope or more than one scope claims it. */
49
- export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope | null;
53
+ export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string, pinned?: ReadonlySet<string>): ManifestScope | null;
54
+ export interface LinkProblem {
55
+ readonly reason: 'OBJECT_OUT_OF_SCOPE' | 'OBJECT_HARD_LINKED';
56
+ /** One sentence for the agent and the operator. */
57
+ readonly detail: string;
58
+ }
50
59
  /**
51
60
  * Checks where a write to an object of a file scope would really land. Returns the reason for a
52
61
  * refusal, or null.
53
62
  *
54
63
  * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
55
64
  * the project: the real path must belong to the leased scope. A file with a second hard link has
56
- * another name that this check cannot see, so it is refused.
65
+ * another name that this check cannot find without reading the whole disk. The other name may be in
66
+ * a pinned scope or outside the project, so the file is refused, also when the second name is a
67
+ * harmless backup.
57
68
  */
58
- export declare function linkProblem(baseDir: string, scopes: readonly ManifestScope[], scopeId: string, objectId: string): 'OBJECT_OUT_OF_SCOPE' | 'OBJECT_HARD_LINKED' | null;
69
+ export declare function linkProblem(baseDir: string, scopes: readonly ManifestScope[], scopeId: string, objectId: string, pinned?: ReadonlySet<string>): LinkProblem | null;
59
70
  export declare function hashFile(file: string): string | null;
60
71
  export interface FileEditSink {
61
72
  /** Current value of the slot of a file, or undefined when the slot does not exist. */
@@ -66,6 +77,7 @@ export interface FileEditSink {
66
77
  export declare class HumanFileWatcher {
67
78
  private readonly baseDir;
68
79
  private readonly scopes;
80
+ private readonly pinned;
69
81
  private readonly sink;
70
82
  private readonly ignore;
71
83
  private readonly debounceMs;
@@ -75,6 +87,7 @@ export declare class HumanFileWatcher {
75
87
  constructor(options: {
76
88
  readonly baseDir: string;
77
89
  readonly scopes: readonly ManifestScope[];
90
+ readonly pinned?: ReadonlySet<string>;
78
91
  readonly sink: FileEditSink;
79
92
  readonly ignore?: readonly string[];
80
93
  readonly debounceMs?: number;
@@ -15,6 +15,15 @@ import path from 'node:path';
15
15
  export const FILE_FIELD = 'sha256';
16
16
  /** Longest object id that the gate reads. */
17
17
  export const MAX_OBJECT_ID_LENGTH = 1024;
18
+ /**
19
+ * One form for comparing a pattern with a path: compatibility characters are replaced by their plain
20
+ * letters (the long s, the Kelvin sign and full-width letters read as `s`, `k` and ASCII), and letter
21
+ * case is dropped. Two texts that a case-insensitive file system could take for the same name fold to
22
+ * the same text. The fold is used for matching only. An object id is stored as it was written, in NFC.
23
+ */
24
+ function fold(text) {
25
+ return text.normalize('NFKC').toLowerCase().normalize('NFKC');
26
+ }
18
27
  /** Matches one path segment against a segment pattern with `*` and `?`. Linear in practice, never exponential. */
19
28
  function matchSegment(pattern, text) {
20
29
  let p = 0;
@@ -48,13 +57,15 @@ function matchSegment(pattern, text) {
48
57
  * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
49
58
  * names a file or a directory with everything below it.
50
59
  *
51
- * The match ignores letter case on every platform, so `Policies/x.sql` and `policies/x.sql`, which
52
- * are one file on Windows and macOS, always belong to the same scope. It uses no regular expression:
60
+ * The match ignores letter case and the Unicode form on every platform, so `Policies/x.sql` and
61
+ * `policies/x.sql`, which are one file on Windows and macOS, always belong to the same scope. On a
62
+ * case-sensitive file system this also puts `SRC/a` in the scope of `src/**`: a scope can only get
63
+ * wider by it, never lose a file. It uses no regular expression:
53
64
  * the time grows with the product of the two lengths, so no input can stall it.
54
65
  */
55
66
  export function matchGlob(pattern, relativePath) {
56
- const glob = pattern.toLowerCase();
57
- const text = relativePath.toLowerCase();
67
+ const glob = fold(pattern);
68
+ const text = fold(relativePath);
58
69
  if (!/[*?]/.test(glob))
59
70
  return text === glob || text.startsWith(`${glob}/`);
60
71
  const segments = text.split('/');
@@ -95,15 +106,29 @@ export function patternProblem(pattern) {
95
106
  return `ends with "/"; write "${pattern}**" for everything in the directory`;
96
107
  if (pattern.split('/').some((segment) => segment === '..' || segment === '.' || segment === ''))
97
108
  return 'has an empty, "." or ".." segment';
109
+ if (pattern.split('/').some((segment) => segment.includes('**') && segment !== '**')) {
110
+ return 'has "**" joined to other text; "**" must be a whole segment, as in "**/*.sql" for files in every directory';
111
+ }
98
112
  return null;
99
113
  }
100
- /** True for a control character and for a mark that changes the direction of the text around it. */
114
+ /** Characters that do not show, or that change how the text around them shows. */
115
+ const UNSAFE_RANGES = [
116
+ [0x0000, 0x001f], // C0 controls
117
+ [0x007f, 0x009f], // DEL and C1 controls
118
+ [0x00ad, 0x00ad], // soft hyphen
119
+ [0x061c, 0x061c], // Arabic letter mark
120
+ [0x115f, 0x1160], // Hangul fillers
121
+ [0x200b, 0x200f], // zero-width characters and direction marks
122
+ [0x2028, 0x202e], // line and paragraph separators, direction embeddings and overrides
123
+ [0x2060, 0x206f], // word joiner, invisible operators, direction isolates
124
+ [0x3164, 0x3164], // Hangul filler
125
+ [0xfeff, 0xfeff], // byte order mark
126
+ [0xffa0, 0xffa0], // half-width Hangul filler
127
+ ];
101
128
  function hasUnsafeCharacter(text) {
102
129
  for (let i = 0; i < text.length; i += 1) {
103
130
  const code = text.charCodeAt(i);
104
- if (code <= 0x1f || (code >= 0x7f && code <= 0x9f))
105
- return true;
106
- if (code === 0x200e || code === 0x200f || (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069))
131
+ if (UNSAFE_RANGES.some(([from, to]) => code >= from && code <= to))
107
132
  return true;
108
133
  }
109
134
  return false;
@@ -111,16 +136,19 @@ function hasUnsafeCharacter(text) {
111
136
  /**
112
137
  * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
113
138
  * segments, Unicode form NFC. Returns null for an absolute path, for a path with a `..` segment, for
114
- * an id longer than 1024 characters and for an id with a control or text-direction character, so two
115
- * spellings can never name the same file, no id can leave the project directory, and an id reads in
116
- * a log the way it is stored.
139
+ * an id longer than 1024 characters in its stored form and for an id with a control, invisible or
140
+ * text-direction character, so two spellings can never name the same file, no id can leave the
141
+ * project directory, and an id reads in a log the way it is stored.
117
142
  */
118
143
  export function normalizeObjectPath(input) {
119
- if (typeof input !== 'string' || input === '' || input.length > MAX_OBJECT_ID_LENGTH)
144
+ // A combining sequence shrinks in NFC, so the first limit is loose and the exact one comes after.
145
+ if (typeof input !== 'string' || input === '' || input.length > MAX_OBJECT_ID_LENGTH * 4)
120
146
  return null;
121
147
  if (hasUnsafeCharacter(input))
122
148
  return null;
123
149
  const slashed = input.normalize('NFC').replace(/\\/g, '/');
150
+ if (slashed.length > MAX_OBJECT_ID_LENGTH)
151
+ return null;
124
152
  if (slashed.startsWith('/') || /^[A-Za-z]:(\/|$)/.test(slashed))
125
153
  return null;
126
154
  const parts = slashed.split('/').filter((segment) => segment !== '' && segment !== '.');
@@ -134,35 +162,41 @@ function wholeDirectory(pattern) {
134
162
  return '';
135
163
  // A pattern without a wildcard covers that path and everything below it.
136
164
  if (!/[*?]/.test(pattern))
137
- return `${pattern.toLowerCase()}/`;
165
+ return `${fold(pattern)}/`;
138
166
  if (!pattern.endsWith('/**'))
139
167
  return null;
140
168
  const dir = pattern.slice(0, -2);
141
- return /[*?]/.test(dir) ? null : dir.toLowerCase();
169
+ return /[*?]/.test(dir) ? null : fold(dir);
142
170
  }
143
171
  /** The text of a pattern before its first wildcard. */
144
172
  function literalPrefix(pattern) {
145
173
  const at = pattern.search(/[*?]/);
146
- return (at < 0 ? pattern : pattern.slice(0, at)).toLowerCase();
174
+ return fold(at < 0 ? pattern : pattern.slice(0, at));
147
175
  }
176
+ const NO_PINS = new Set();
148
177
  /**
149
178
  * The scopes that claim a path. The order of the scopes in the manifest does not matter.
150
179
  *
151
- * A whole-directory pattern (`dir/**` or `**`) is a fallback. It gives way to a pattern of another
152
- * scope that lies inside that directory: a deeper whole-directory pattern, or any other pattern
153
- * that starts there. So `**` gives way to `policies/**`, and `src/**` gives way to `src/db/**`
154
- * and to `src/*.sql`.
180
+ * 1. A pinned scope wins. When a scope with a pin matches the path, only pinned scopes claim it:
181
+ * a scope without a pin never takes a file that a pin covers, whatever the patterns look like.
182
+ * Two pinned scopes that match the same path both claim it.
183
+ * 2. Among scopes without a pin, a whole-directory pattern (`dir/**`, `**` or a pattern without a
184
+ * wildcard) is a fallback. It gives way to a pattern of another scope that starts inside that
185
+ * directory. This rule looks at the text of the patterns. It only orders scopes that no pin
186
+ * covers, so a wrong guess moves a file between two unprotected scopes and nothing more.
155
187
  *
156
- * Every other overlap is left as it is: `src/**` and a pattern like `**` + `/*.secret` both claim
157
- * `src/a.secret`, and the result has two scopes. A caller must treat such a path as owned by nobody.
188
+ * A result with more than one scope means that nobody owns the path. A caller must refuse it.
158
189
  */
159
- export function claimantsOfPath(scopes, relativePath) {
190
+ export function claimantsOfPath(scopes, relativePath, pinned = NO_PINS) {
160
191
  const normalized = normalizeObjectPath(relativePath);
161
192
  if (normalized === null)
162
193
  return [];
163
194
  const matches = scopes
164
195
  .map((scope) => ({ scope, patterns: scope.paths.filter((pattern) => matchGlob(pattern, normalized)) }))
165
196
  .filter((entry) => entry.patterns.length > 0);
197
+ const pinnedMatches = matches.filter((entry) => pinned.has(entry.scope.id));
198
+ if (pinnedMatches.length > 0)
199
+ return pinnedMatches.map((entry) => entry.scope);
166
200
  const givesWay = (wide, narrow) => wide.patterns.every((pattern) => {
167
201
  const dir = wholeDirectory(pattern);
168
202
  if (dir === null)
@@ -177,8 +211,8 @@ export function claimantsOfPath(scopes, relativePath) {
177
211
  .map((entry) => entry.scope);
178
212
  }
179
213
  /** The one scope that owns the path, or null when no scope or more than one scope claims it. */
180
- export function scopeOfPath(scopes, relativePath) {
181
- const claimants = claimantsOfPath(scopes, relativePath);
214
+ export function scopeOfPath(scopes, relativePath, pinned = NO_PINS) {
215
+ const claimants = claimantsOfPath(scopes, relativePath, pinned);
182
216
  return claimants.length === 1 ? claimants[0] : null;
183
217
  }
184
218
  /**
@@ -187,9 +221,11 @@ export function scopeOfPath(scopes, relativePath) {
187
221
  *
188
222
  * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
189
223
  * the project: the real path must belong to the leased scope. A file with a second hard link has
190
- * another name that this check cannot see, so it is refused.
224
+ * another name that this check cannot find without reading the whole disk. The other name may be in
225
+ * a pinned scope or outside the project, so the file is refused, also when the second name is a
226
+ * harmless backup.
191
227
  */
192
- export function linkProblem(baseDir, scopes, scopeId, objectId) {
228
+ export function linkProblem(baseDir, scopes, scopeId, objectId, pinned = NO_PINS) {
193
229
  const parts = objectId.split('/');
194
230
  let existing = parts.length;
195
231
  // The deepest part of the path that exists. A link below it cannot exist.
@@ -204,19 +240,25 @@ export function linkProblem(baseDir, scopes, scopeId, objectId) {
204
240
  real = fs.realpathSync.native(path.join(baseDir, ...parts.slice(0, existing)));
205
241
  }
206
242
  catch {
207
- // A link that leads nowhere, or a path that cannot be read.
208
- return 'OBJECT_OUT_OF_SCOPE';
243
+ return { reason: 'OBJECT_OUT_OF_SCOPE', detail: `${objectId} is behind a link that leads nowhere or cannot be read` };
209
244
  }
210
245
  const relative = path.relative(realBase, path.join(real, ...parts.slice(existing)));
211
- if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative))
212
- return 'OBJECT_OUT_OF_SCOPE';
213
- const claimants = claimantsOfPath(scopes, relative.split(path.sep).join('/'));
214
- if (claimants.length !== 1 || claimants[0]?.id !== scopeId)
215
- return 'OBJECT_OUT_OF_SCOPE';
246
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
247
+ return { reason: 'OBJECT_OUT_OF_SCOPE', detail: `${objectId} is behind a link that leads out of the project` };
248
+ }
249
+ const realId = relative.split(path.sep).join('/');
250
+ const claimants = claimantsOfPath(scopes, realId, pinned);
251
+ if (claimants.length !== 1 || claimants[0]?.id !== scopeId) {
252
+ return { reason: 'OBJECT_OUT_OF_SCOPE', detail: `${objectId} is a link to ${realId}, which does not belong to the scope ${scopeId}` };
253
+ }
216
254
  if (existing === parts.length) {
217
255
  const stat = fs.statSync(real, { throwIfNoEntry: false });
218
- if (stat?.isFile() && stat.nlink > 1)
219
- return 'OBJECT_HARD_LINKED';
256
+ if (stat?.isFile() && stat.nlink > 1) {
257
+ return {
258
+ reason: 'OBJECT_HARD_LINKED',
259
+ detail: `${objectId} has ${stat.nlink} names (hard links), and the other names cannot be found from here. Replace it with a copy that has one name, or remove the other names`,
260
+ };
261
+ }
220
262
  }
221
263
  return null;
222
264
  }
@@ -231,6 +273,7 @@ export function hashFile(file) {
231
273
  export class HumanFileWatcher {
232
274
  baseDir;
233
275
  scopes;
276
+ pinned;
234
277
  sink;
235
278
  ignore;
236
279
  debounceMs;
@@ -240,6 +283,7 @@ export class HumanFileWatcher {
240
283
  constructor(options) {
241
284
  this.baseDir = options.baseDir;
242
285
  this.scopes = options.scopes;
286
+ this.pinned = options.pinned ?? NO_PINS;
243
287
  this.sink = options.sink;
244
288
  this.ignore = options.ignore ?? ['.git', 'node_modules', '.certal'];
245
289
  this.debounceMs = options.debounceMs ?? 50;
@@ -267,7 +311,7 @@ export class HumanFileWatcher {
267
311
  const file = path.join(this.baseDir, relativePath);
268
312
  const hash = hashFile(file);
269
313
  // A file that several scopes claim is reported to each of them: the human edit wins everywhere.
270
- for (const scope of claimantsOfPath(this.scopes, relativePath)) {
314
+ for (const scope of claimantsOfPath(this.scopes, relativePath, this.pinned)) {
271
315
  const known = this.sink.currentHash(scope, relativePath);
272
316
  if (hash === null) {
273
317
  // A directory or an unreadable file is not a change. A file that is gone is one, when its slot holds a hash.
@@ -103,3 +103,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>;
@@ -366,6 +366,8 @@ export function loadManifest(startDir) {
366
366
  throw new ManifestError([`no ${MANIFEST_FILE} found in ${path.resolve(startDir)} or above it. Run \`certal init\`.`]);
367
367
  const problems = [];
368
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;
369
371
  for (const [index, file] of files.entries()) {
370
372
  let raw;
371
373
  try {
@@ -373,15 +375,19 @@ export function loadManifest(startDir) {
373
375
  }
374
376
  catch (err) {
375
377
  problems.push(`${file}: not valid JSON (${err.message})`);
378
+ unread = true;
376
379
  continue;
377
380
  }
378
381
  const shape = validateManifest(raw, file);
379
382
  if (shape.length > 0) {
380
383
  problems.push(...shape);
384
+ unread = true;
381
385
  continue;
382
386
  }
383
387
  layer = mergeLayer(layer, raw, file, problems, index === 0);
384
388
  }
389
+ if (unread)
390
+ throw new ManifestError(problems);
385
391
  const required = (layer.policy.requiredWitnessStages ?? DEFAULT_POLICY.requiredWitnessStages);
386
392
  for (const stage of required) {
387
393
  if (layer.witness[stage] === undefined)
@@ -463,3 +469,12 @@ export function policyDifference(current, next) {
463
469
  }
464
470
  return diff;
465
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
+ }
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,
@@ -22,6 +22,8 @@ export interface AgentReply {
22
22
  readonly retryable: boolean;
23
23
  readonly attemptId?: string;
24
24
  readonly batchId?: string;
25
+ /** One sentence that explains a refusal, where the reason code alone does not. */
26
+ readonly detail?: string;
25
27
  }
26
28
  interface ToolDefinition {
27
29
  readonly name: string;
@@ -4,6 +4,7 @@ import http from 'node:http';
4
4
  import path from 'node:path';
5
5
  import { computeScopeHash, computeToolAutonomy, hashCanonical, pendingVerifyEpoch, scopeEpochOf, slotKey } from '../kernel/index.js';
6
6
  import { claimantsOfPath, linkProblem, normalizeObjectPath } from '../adapters/file-watcher.js';
7
+ import { pinnedScopeIds } from '../adapters/manifest.js';
7
8
  import { computeClusterId } from '../adapters/tool-sdk.js';
8
9
  /**
9
10
  * MCP gate for agents. The tool surface is narrow on purpose: an agent can take and release a
@@ -112,7 +113,7 @@ export class McpGateway {
112
113
  const scope = this.host.manifest.scopes.find((s) => s.id === scopeId);
113
114
  if (!scope || scope.paths.length === 0)
114
115
  return null;
115
- return linkProblem(this.host.manifest.baseDir, this.host.manifest.scopes, scopeId, objectId);
116
+ return linkProblem(this.host.manifest.baseDir, this.host.manifest.scopes, scopeId, objectId, pinnedScopeIds(this.host.manifest));
116
117
  }
117
118
  classOf(scopeId, requested) {
118
119
  return requested || this.host.manifest.scopes.find((s) => s.id === scopeId)?.classId || 'default';
@@ -175,7 +176,7 @@ export class McpGateway {
175
176
  const objectIds = [];
176
177
  for (const raw of rawOps) {
177
178
  const objectId = normalizeObjectPath(str(raw, 'objectId'));
178
- const claimants = objectId === null ? [] : claimantsOfPath(this.host.manifest.scopes, objectId);
179
+ const claimants = objectId === null ? [] : claimantsOfPath(this.host.manifest.scopes, objectId, pinnedScopeIds(this.host.manifest));
179
180
  // Two scopes claim the object and neither lies inside the other: a pin on one of them must hold, so nobody may write it.
180
181
  if (claimants.length > 1)
181
182
  return this.reply('REJECT', 'OBJECT_SCOPE_AMBIGUOUS', scopeId, '', { attemptId });
@@ -188,7 +189,7 @@ export class McpGateway {
188
189
  return this.reply('REJECT', 'OBJECT_OUT_OF_SCOPE', scopeId, '', { attemptId });
189
190
  const linked = this.linkProblemOf(scopeId, objectId);
190
191
  if (linked)
191
- return this.reply('REJECT', linked, scopeId, '', { attemptId });
192
+ return this.reply('REJECT', linked.reason, scopeId, '', { attemptId, detail: linked.detail });
192
193
  objectIds.push(objectId);
193
194
  }
194
195
  const auth = this.auth(agentId, attemptId, taskId);
@@ -301,7 +302,7 @@ export class McpGateway {
301
302
  for (const stateOp of attempt.ops) {
302
303
  const linked = this.linkProblemOf(attempt.scopeId, stateOp.objectId);
303
304
  if (linked)
304
- return this.reply('REJECT', linked, attempt.scopeId, '', { attemptId });
305
+ return this.reply('REJECT', linked.reason, attempt.scopeId, '', { attemptId, detail: linked.detail });
305
306
  }
306
307
  if (attempt.status === 'VERIFIED' && this.needsApproval(attempt)) {
307
308
  // Asked here, before the kernel sees the finalize, so a missing approval does not pause the task for other agents.
@@ -51,6 +51,8 @@ export interface EventStore {
51
51
  loadLatestCheckpoint(): CheckpointSnapshot | null;
52
52
  /** Every stored checkpoint, oldest first. */
53
53
  readCheckpoints(): readonly CheckpointSnapshot[];
54
+ /** The first place where an index column of the log disagrees with the entry it belongs to, or null. */
55
+ findLogColumnMismatch(): string | null;
54
56
  replay(hooks?: DeterministicHooks): {
55
57
  readonly state: KernelState;
56
58
  readonly stateHash: string;
@@ -104,6 +106,7 @@ export declare class InMemoryStore implements UnifiedStore {
104
106
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
105
107
  loadLatestCheckpoint(): CheckpointSnapshot | null;
106
108
  readCheckpoints(): readonly CheckpointSnapshot[];
109
+ findLogColumnMismatch(): string | null;
107
110
  listActionable(nowMs: number): readonly OutboxRecord[];
108
111
  getOutboxRecord(effectId: string): OutboxRecord | null;
109
112
  recoverInFlight(nowMs: number): readonly OutboxRecord[];
@@ -175,6 +178,7 @@ export declare class SQLiteStore implements UnifiedStore {
175
178
  saveCheckpoint(snapshot: CheckpointSnapshot): void;
176
179
  loadLatestCheckpoint(): CheckpointSnapshot | null;
177
180
  readCheckpoints(): readonly CheckpointSnapshot[];
181
+ findLogColumnMismatch(): string | null;
178
182
  private mapOutboxRow;
179
183
  listActionable(nowMs: number): readonly OutboxRecord[];
180
184
  getOutboxRecord(effectId: string): OutboxRecord | null;
@@ -228,6 +228,9 @@ export class InMemoryStore {
228
228
  readCheckpoints() {
229
229
  return [...this.checkpoints];
230
230
  }
231
+ findLogColumnMismatch() {
232
+ return null;
233
+ }
231
234
  listActionable(nowMs) {
232
235
  const out = [];
233
236
  for (const rec of this.outbox.values()) {
@@ -568,6 +571,21 @@ export class SQLiteStore {
568
571
  const rows = this.db.prepare('SELECT snapshot_json FROM checkpoints ORDER BY server_seq').all();
569
572
  return rows.map((row) => JSON.parse(row.snapshot_json));
570
573
  }
574
+ findLogColumnMismatch() {
575
+ const rows = this.db.prepare('SELECT server_seq, op_id, entry_hash, prev_entry_hash, entry_json FROM log_entries ORDER BY server_seq').all();
576
+ for (const row of rows) {
577
+ const entry = JSON.parse(row.entry_json);
578
+ if (entry.serverSeq !== Number(row.server_seq))
579
+ return `server_seq at seq=${row.server_seq}`;
580
+ if (entry.opId !== row.op_id)
581
+ return `op_id at seq=${row.server_seq}`;
582
+ if (entry.entryHash !== row.entry_hash)
583
+ return `entry_hash at seq=${row.server_seq}`;
584
+ if (entry.prevEntryHash !== row.prev_entry_hash)
585
+ return `prev_entry_hash at seq=${row.server_seq}`;
586
+ }
587
+ return null;
588
+ }
571
589
  mapOutboxRow(row) {
572
590
  return {
573
591
  effectId: String(row.effect_id),
@@ -768,6 +786,9 @@ export function replayFromStore(store, hooks, options) {
768
786
  checkCheckpoint();
769
787
  }
770
788
  if (audit) {
789
+ const column = store.findLogColumnMismatch();
790
+ if (column !== null)
791
+ throw new Error(`LOG_COLUMN_MISMATCH: the column ${column} differs from the stored entry`);
771
792
  const orphan = [...checkpointAt.keys()][0];
772
793
  if (orphan !== undefined)
773
794
  throw new Error(`CHECKPOINT_STATE_MISMATCH at seq=${orphan}: no log entry has this position`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "certal",
3
- "version": "0.1.1",
3
+ "version": "0.1.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,12 +69,12 @@
69
69
  "build": "node tools/build.mjs",
70
70
  "typecheck": "node tools/typecheck.mjs",
71
71
  "lint": "biome check core tools bin",
72
- "test": "node --test core/tests/kernel.laws.test.ts core/tests/interleavings.bfs.test.ts core/tests/sqlite.replay.test.ts core/tests/e2e.sdk.test.ts core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/gate.hardening.test.ts core/tests/adversarial.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
72
+ "test": "node --test core/tests/kernel.laws.test.ts core/tests/interleavings.bfs.test.ts core/tests/sqlite.replay.test.ts core/tests/e2e.sdk.test.ts core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/gate.hardening.test.ts core/tests/adversarial.hardening.test.ts core/tests/ownership.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
73
73
  "test:laws": "node --test core/tests/kernel.laws.test.ts",
74
74
  "test:bfs": "node --test core/tests/interleavings.bfs.test.ts",
75
75
  "test:replay": "node --test core/tests/sqlite.replay.test.ts",
76
76
  "test:e2e": "node --test core/tests/e2e.sdk.test.ts",
77
- "test:cli": "node --test core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/gate.hardening.test.ts core/tests/adversarial.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
77
+ "test:cli": "node --test core/tests/manifest.federation.test.ts core/tests/host.hardening.test.ts core/tests/audit.hardening.test.ts core/tests/gate.hardening.test.ts core/tests/adversarial.hardening.test.ts core/tests/ownership.hardening.test.ts core/tests/e2e.cli-mcp.test.ts",
78
78
  "test:mutations": "node core/tests/probe.mutations.ts",
79
79
  "test:bench": "node core/tests/bench.human-lane.ts",
80
80
  "test:bench:cli": "node core/tests/bench.cli.ts",
@@ -9,12 +9,12 @@
9
9
  "scopes": [
10
10
  { "id": "frontend", "classId": "file", "paths": ["src/**", "app/**", "public/**"] },
11
11
  { "id": "database", "classId": "migration", "paths": ["migrations/**", "supabase/migrations/**"] },
12
- { "id": "destructive-migrations", "classId": "destructive", "paths": ["migrations/**/*drop*", "migrations/**/*truncate*", "supabase/migrations/**/*drop*", "supabase/migrations/**/*truncate*"] },
12
+ { "id": "destructive-migrations", "classId": "destructive", "paths": ["**/migrations/**/*drop*", "**/migrations/**/*truncate*"] },
13
13
  { "id": "access", "classId": "rls", "paths": ["policies/**", "supabase/policies/**"] }
14
14
  ],
15
15
  "pins": [
16
16
  { "id": "rls-human-only", "kind": "H", "scopeId": "access", "classId": "*", "rule": "row level security policies are changed by a human" },
17
- { "id": "destructive-migrations", "kind": "H", "scopeId": "destructive-migrations", "classId": "*", "rule": "migration files with drop or truncate in the name are written by a human" }
17
+ { "id": "destructive-migrations", "kind": "H", "scopeId": "destructive-migrations", "classId": "*", "rule": "migration files with drop or truncate in the file name are written by a human; the rule reads the name, not the SQL" }
18
18
  ],
19
19
  "tools": {
20
20
  "edit": { "reversibility": "REVERSIBLE", "supportsCas": false },
@@ -42,7 +42,7 @@ Do what `nextLegalAction` says.
42
42
 
43
43
  - In file mode, never write a file in a declared scope before the finalize answers `ALLOW`, and never write content other than you declared. Such a write is recorded as a human edit and invalidates your own lease.
44
44
  - In effect mode, never touch the target yourself. Certal delivers the effect.
45
- - Use plain relative paths. An absolute path, a `..` segment or an object of another scope is refused with `OBJECT_OUT_OF_SCOPE`. A file that two scopes claim is refused with `OBJECT_SCOPE_AMBIGUOUS`: report it, the operator must fix the manifest. A file with a second hard link is refused with `OBJECT_HARD_LINKED`: report it and do not copy the file to get around it.
45
+ - Use plain relative paths. An absolute path, a `..` segment or an object of another scope is refused with `OBJECT_OUT_OF_SCOPE`. A file that two scopes claim is refused with `OBJECT_SCOPE_AMBIGUOUS`: report it, the operator must fix the manifest. A file with a second hard link is refused with `OBJECT_HARD_LINKED`: report it and do not copy the file to get around it. When an answer has a `detail` field, pass it to the user as it is.
46
46
  - Never retry when `retryable` is `false`.
47
47
  - You have no tool to approve, reset, undo or change pins. Those belong to the operator. If you need one, ask the user.
48
48
  - A human edit always wins. When a scope epoch rises under you, your attempt is stale: start again from the current state.