@holmes-lab/holmes-kit 0.40.1 → 0.41.0

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +11 -3
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-context.js +4 -3
  5. package/dist/holmes/cli/approve.js +22 -12
  6. package/dist/holmes/cli/autonomy.d.ts +21 -0
  7. package/dist/holmes/cli/autonomy.js +35 -5
  8. package/dist/holmes/cli/doctor.js +58 -6
  9. package/dist/holmes/cli/index.js +371 -250
  10. package/dist/holmes/cli/init.js +17 -6
  11. package/dist/holmes/cli/ledger-witness.d.ts +61 -0
  12. package/dist/holmes/cli/ledger-witness.js +212 -0
  13. package/dist/holmes/cli/playbook-skills.d.ts +3 -56
  14. package/dist/holmes/cli/playbook-skills.js +26 -349
  15. package/dist/holmes/config/config.d.ts +4 -0
  16. package/dist/holmes/config/config.js +10 -3
  17. package/dist/holmes/governance/approval-queue.d.ts +65 -1
  18. package/dist/holmes/governance/approval-queue.js +279 -9
  19. package/dist/holmes/governance/autonomous-shell.d.ts +13 -1
  20. package/dist/holmes/governance/autonomous-shell.js +157 -4
  21. package/dist/holmes/governance/autonomy.d.ts +209 -0
  22. package/dist/holmes/governance/autonomy.js +1127 -6
  23. package/dist/holmes/governance/install-manifest.d.ts +7 -4
  24. package/dist/holmes/governance/install-manifest.js +144 -14
  25. package/dist/holmes/governance/ledger-witness.d.ts +63 -0
  26. package/dist/holmes/governance/ledger-witness.js +296 -0
  27. package/dist/holmes/governance/provenance-chain.d.ts +8 -1
  28. package/dist/holmes/governance/provenance-chain.js +23 -4
  29. package/dist/holmes/governance/recorded-pairs.d.ts +4 -0
  30. package/dist/holmes/governance/recorded-pairs.js +25 -1
  31. package/dist/holmes/governance/session-context.d.ts +7 -0
  32. package/dist/holmes/governance/session-context.js +34 -6
  33. package/dist/holmes/guardrail/anchor-scope-text.d.ts +9 -0
  34. package/dist/holmes/guardrail/anchor-scope-text.js +7 -0
  35. package/dist/holmes/guardrail/command-traits.d.ts +102 -0
  36. package/dist/holmes/guardrail/command-traits.js +379 -0
  37. package/dist/holmes/guardrail/fixtures/manager-builtins.json +23 -0
  38. package/dist/holmes/guardrail/fixtures/npm-commands.json +7 -0
  39. package/dist/holmes/guardrail/outward-acts.d.ts +47 -0
  40. package/dist/holmes/guardrail/outward-acts.js +1102 -0
  41. package/dist/holmes/guardrail/refusal-codes.js +8 -1
  42. package/dist/holmes/guardrail/refusal-templates.d.ts +15 -0
  43. package/dist/holmes/guardrail/refusal-templates.js +71 -0
  44. package/dist/holmes/guardrail/risk-classifier.d.ts +22 -6
  45. package/dist/holmes/guardrail/risk-classifier.js +12 -118
  46. package/dist/holmes/guardrail/shell-lexer.d.ts +69 -0
  47. package/dist/holmes/guardrail/shell-lexer.js +567 -0
  48. package/dist/holmes/guardrail/write-target.js +7 -1
  49. package/dist/holmes/hooks/pre-tool-use.d.ts +60 -0
  50. package/dist/holmes/hooks/pre-tool-use.js +1423 -10
  51. package/dist/holmes/hooks/session-start.js +11 -1
  52. package/dist/holmes/hooks/stop.d.ts +7 -0
  53. package/dist/holmes/hooks/stop.js +39 -2
  54. package/dist/holmes/mcp/elicit-approval.d.ts +0 -21
  55. package/dist/holmes/mcp/elicit-approval.js +5 -2
  56. package/dist/holmes/mcp/handlers/approval-ask.js +3 -2
  57. package/dist/holmes/mcp/handlers/entity-integration.d.ts +1 -1
  58. package/dist/holmes/mcp/handlers/entity-integration.js +9 -6
  59. package/dist/holmes/mcp/handlers/entity-renumber.js +2 -1
  60. package/dist/holmes/mcp/handlers/entity-store.js +7 -2
  61. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -0
  62. package/dist/holmes/mcp/handlers/operator-inspection.js +25 -4
  63. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -1
  64. package/dist/holmes/mcp/handlers/spec-approval.js +28 -10
  65. package/dist/holmes/mcp/handlers/spec-lifecycle.js +10 -7
  66. package/dist/holmes/mcp/handlers/test-execution.js +4 -2
  67. package/dist/holmes/mcp/handlers.d.ts +5 -5
  68. package/dist/holmes/mcp/handlers.js +2 -1
  69. package/dist/holmes/mcp/tool-schemas.js +4 -4
  70. package/dist/holmes/project/playbook-reference.d.ts +50 -0
  71. package/dist/holmes/project/playbook-reference.js +259 -0
  72. package/dist/holmes/project/playbook-skill-states.d.ts +94 -0
  73. package/dist/holmes/project/playbook-skill-states.js +396 -0
  74. package/dist/holmes/project/root.d.ts +9 -1
  75. package/dist/holmes/project/root.js +23 -2
  76. package/dist/holmes/project/running-package.d.ts +15 -0
  77. package/dist/holmes/project/running-package.js +87 -0
  78. package/dist/holmes/review/test-runner.d.ts +2 -0
  79. package/dist/holmes/review/test-runner.js +27 -10
  80. package/dist/holmes/spec/entity-integration-transaction.d.ts +19 -2
  81. package/dist/holmes/spec/entity-integration-transaction.js +68 -7
  82. package/package.json +5 -2
@@ -33,7 +33,26 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.FULL_PROFILE_MEANING = exports.SESSION_AUTONOMY_MARKER = exports.AUTONOMY_ENV = void 0;
36
+ exports.FULL_PROFILE_MEANING = exports.SESSION_AUTONOMY_MARKER = exports.SEAL_WINDOW_MAX_HOURS = exports.PRINCIPLE7_WITNESS = exports.PRINCIPLE7_BASELINE_LOST = exports.PRINCIPLE7_GIT_UNREADABLE = exports.PRINCIPLE7_DIST_REFUSAL = exports.PRINCIPLE7_WRITE_REFUSAL = exports.PRINCIPLE7_SEEDS = exports.AUTONOMY_ENV = void 0;
37
+ exports.principle7Category = principle7Category;
38
+ exports.principle7WriteTarget = principle7WriteTarget;
39
+ exports.isPersonSealRow = isPersonSealRow;
40
+ exports.openSealWindows = openSealWindows;
41
+ exports.ownChainWitness = ownChainWitness;
42
+ exports.principle7GitEnv = principle7GitEnv;
43
+ exports.gitFailureOf = gitFailureOf;
44
+ exports.isHolmesKitOwnRepo = isHolmesKitOwnRepo;
45
+ exports.principle7Baseline = principle7Baseline;
46
+ exports.principle7Changes = principle7Changes;
47
+ exports.principle7FirstBaselineGaps = principle7FirstBaselineGaps;
48
+ exports.principle7Context = principle7Context;
49
+ exports.principle7OpenersIn = principle7OpenersIn;
50
+ exports.principle7OpenersFor = principle7OpenersFor;
51
+ exports.principle7Verdict = principle7Verdict;
52
+ exports.recordWindowBlobs = recordWindowBlobs;
53
+ exports.principle7RefusalText = principle7RefusalText;
54
+ exports.recordBaseline = recordBaseline;
55
+ exports.rootConfigToken = rootConfigToken;
37
56
  exports.isHighRiskPath = isHighRiskPath;
38
57
  exports.descendantAspecs = descendantAspecs;
39
58
  exports.specApprovalAutonomy = specApprovalAutonomy;
@@ -52,7 +71,7 @@ exports.autonomyBanner = autonomyBanner;
52
71
  exports.autonomyMarkerShouldPrune = autonomyMarkerShouldPrune;
53
72
  exports.versionBumpKind = versionBumpKind;
54
73
  exports.releaseAutonomy = releaseAutonomy;
55
- // @implements A-SPEC-794.55, A-SPEC-552.3, A-SPEC-552.4,A-SPEC-532.1, A-SPEC-718, A-SPEC-532.3, A-SPEC-532.4, A-SPEC-532.7, A-SPEC-792.7, A-SPEC-794.47, A-SPEC-794.49
74
+ // @implements A-SPEC-794.113, A-SPEC-794.111, A-SPEC-794.110, A-SPEC-794.107, A-SPEC-794.106, A-SPEC-794.97, A-SPEC-794.96, A-SPEC-794.95, A-SPEC-794.94, A-SPEC-794.91, A-SPEC-794.88, A-SPEC-794.55, A-SPEC-552.3, A-SPEC-552.4,A-SPEC-532.1, A-SPEC-718, A-SPEC-532.3, A-SPEC-532.4, A-SPEC-532.7, A-SPEC-792.7, A-SPEC-794.47, A-SPEC-794.49
56
75
  // Whether a spec approval may be sealed AUTONOMOUSLY by the agent, or must still ask a human through
57
76
  // the MCP elicitation TUI. The governance chain (REQ→H→A→T→CPG + RTM + taint + phase gate) already
58
77
  // forces quality structurally, so a low/mid-risk spec self-approving under an explicitly-enabled
@@ -66,6 +85,8 @@ exports.releaseAutonomy = releaseAutonomy;
66
85
  const fs = __importStar(require("node:fs"));
67
86
  const path = __importStar(require("node:path"));
68
87
  const scope_judgment_1 = require("../guardrail/scope-judgment");
88
+ const human_channel_1 = require("./human-channel"); // @implements A-SPEC-794.91 (round 2)
89
+ const succession_1 = require("../spec/succession"); // @implements A-SPEC-794.95 (round 2)
69
90
  /** The out-of-band switch. An agent cannot read or set it — the pre-tool-use gate blocks that
70
91
  * (A-SPEC-532.2), the same self-disarm protection HOLMES_APPROVAL and HOLMES_GATE_BYPASS have. */
71
92
  const delegation_1 = require("./delegation"); // @implements A-SPEC-771 — the run delegation, the third envelope
@@ -83,7 +104,1077 @@ const HIGH_RISK_PREFIXES = [
83
104
  'src/holmes/governance/',
84
105
  '.ax/roles',
85
106
  '.claude',
107
+ // @implements A-SPEC-794.88 — principle 7: the gate and approval-processing category is defined as "the entry points
108
+ // of the gate and its seams, and every module that reads or writes a grant, an actor, a seal or a decision judgement";
109
+ // these are its current instances, and the census test (principle7.test.ts) turns red on a module outside them that
110
+ // imports or defines a seed of PRINCIPLE7_SEEDS
111
+ 'src/holmes/cli/approve',
112
+ 'src/holmes/cli/autonomy.ts',
113
+ 'src/holmes/cli/index.ts',
114
+ 'src/holmes/cli/init.ts',
115
+ 'src/holmes/cli/runtime-binding-approval.ts',
116
+ 'src/holmes/mcp/approval-',
117
+ 'src/holmes/mcp/elicit-approval.ts',
118
+ 'src/holmes/mcp/harness-attestation.ts',
119
+ 'src/holmes/mcp/requirement-triage-evidence.ts',
120
+ 'src/holmes/mcp/handlers.ts',
121
+ 'src/holmes/mcp/handlers/approval-ask.ts',
122
+ 'src/holmes/mcp/handlers/entity-',
123
+ 'src/holmes/mcp/handlers/operator-inspection.ts',
124
+ 'src/holmes/mcp/handlers/review-evidence.ts',
125
+ 'src/holmes/mcp/handlers/review-verdict.ts',
126
+ 'src/holmes/mcp/handlers/risk-assessment.ts',
127
+ 'src/holmes/mcp/handlers/spec-approval.ts',
128
+ 'src/holmes/mcp/handlers/spec-lifecycle.ts',
129
+ 'src/holmes/review/verdicts.ts',
130
+ 'src/holmes/runtime/dispatch.ts',
131
+ 'src/holmes/spec/transition-policy.ts',
132
+ 'src/holmes/spec/approval-status.ts',
133
+ 'src/holmes/spec/approval-blockers.ts',
134
+ // @implements A-SPEC-794.94 (N3 = C) — the seams review A named, and the closure modules the four new seeds reach; the
135
+ // census in principle7.test.ts holds the rest of the entry points' import closure (a module there that uses a seed
136
+ // and is not listed turns it red)
137
+ 'src/holmes/spec/spec-parser.ts',
138
+ 'src/holmes/spec/succession.ts',
139
+ 'src/holmes/spec/succession-guard.ts',
140
+ 'src/holmes/spec/spec-digest.ts',
141
+ 'src/holmes/spec/spec-store.ts',
142
+ 'src/holmes/spec/validator.ts',
143
+ 'src/holmes/spec/entity-renumber.ts',
144
+ // @implements A-SPEC-794.106 — the product-installed judgement's reference and the modules that read it: in a
145
+ // development binding playbooks/ is the reference a workspace write would otherwise change (review A, critical C1)
146
+ 'playbooks/',
147
+ 'src/holmes/project/playbook-skill-states.ts',
148
+ 'src/holmes/project/installer-markers.ts',
149
+ // @implements A-SPEC-794.107 (A-M1) — the git reader the judgement's binding and baseline reads go through
150
+ 'src/holmes/project/bounded-io.ts',
151
+ // @implements A-SPEC-794.111 — the one fact principle 7's root predicate and the skills' binding read
152
+ 'src/holmes/project/running-package.ts',
153
+ // @implements A-SPEC-794.110 — the recovery skills' reference: doctor, init and the gate read it here
154
+ 'src/holmes/project/playbook-reference.ts',
155
+ // @implements A-SPEC-794.114 — a person's vouch for the ledger chain and the rechain guard (it writes the witness the
156
+ // judgement reads, so it is the gate's)
157
+ 'src/holmes/cli/ledger-witness.ts',
158
+ 'src/holmes/spec/entity-integration-transaction.ts',
159
+ 'src/holmes/spec/entity-integration.ts',
160
+ 'src/holmes/rtm/anchor-ids.ts',
161
+ 'src/holmes/config/config.ts',
162
+ 'src/holmes/config/project-caps.ts',
163
+ 'src/holmes/project/root.ts',
164
+ 'src/holmes/runtime/hook-process.ts',
165
+ 'src/holmes/mcp/maintenance-evidence.ts',
166
+ 'src/holmes/mcp/handlers/maintenance-evidence.ts',
167
+ 'src/holmes/mcp/server.ts',
168
+ 'src/holmes/mcp/supervisor.ts',
169
+ 'src/holmes/cli/interactive-prompt.ts',
170
+ 'src/holmes/mcp/handlers/runtime-binding-tool.ts',
171
+ 'bin/holmes-',
86
172
  ];
173
+ /**
174
+ * @implements A-SPEC-794.88 — the seed judgements of principle 7 (design §3-7, M2): a module that imports or defines one
175
+ * reads or writes a grant, an actor, a seal or a decision, so it is in the category. The census test reads this list.
176
+ */
177
+ exports.PRINCIPLE7_SEEDS = [
178
+ // the person-channel mint is named in two parts: its references are pinned by the TypeChecker census (A-SPEC-792.27),
179
+ // and a list of names is not a reference to it
180
+ 'approvalCovers', 'resolveApproval', 'recordProvenGrant', ['human', 'ChannelActor'].join(''), 'isMinted', 'spendApprovals',
181
+ 'claimGrant', 'grantSpend', 'withGrant', 'fullSealVerdict', 'readDelegation', 'delegationCovers', 'everSealedInLedger',
182
+ // @implements A-SPEC-794.94 — held by the closure census (the whole-tree walk keeps the thirteen above)
183
+ 'sealHolds', 'specDigest', 'elicitApproval', 'operatorActGuard',
184
+ ];
185
+ /**
186
+ * @implements A-SPEC-794.88 — the category path a spec's scope names: an A-SPEC's own Files to Touch, a REQ's or an
187
+ * H-SPEC's A-SPECs beneath it; null when none. A T-SPEC is not judged here: its A-SPEC already went to a person.
188
+ */
189
+ function principle7Category(spec, descendants) {
190
+ const of = (a) => (0, scope_judgment_1.fttPathTokens)(a.sections['Files to Touch'] ?? '').find(isHighRiskPath) ?? null;
191
+ if (spec.type === 'A-SPEC')
192
+ return of(spec);
193
+ if (spec.type === 'REQ' || spec.type === 'H-SPEC') {
194
+ for (const a of (descendants ?? []).filter((s) => s.type === 'A-SPEC')) {
195
+ const hit = of(a);
196
+ if (hit !== null)
197
+ return hit;
198
+ }
199
+ }
200
+ return null;
201
+ }
202
+ /** @implements A-SPEC-794.91 (N2) — the refusal a principle 7 write gets without a person-sealed spec naming the file. */
203
+ exports.PRINCIPLE7_WRITE_REFUSAL = 'a gate or approval-processing file is written only under a person-sealed spec that names it';
204
+ exports.PRINCIPLE7_DIST_REFUSAL = 'dist/ is written by the build (npm run build), not by Edit or Write';
205
+ /**
206
+ * @implements A-SPEC-794.91 (N2) — a file whose write principle 7 binds: Holmes-Kit's own gate source (a high-risk path
207
+ * under src/), its built gate (dist/holmes/) and its launchers (bin/holmes-*). Configuration paths (.claude, .ax/roles,
208
+ * .mcp.json) keep their own gates.
209
+ */
210
+ function principle7WriteTarget(relPath, opts = {}) {
211
+ const s = relPath.replace(/\\/g, '/').replace(/^(\.\/)+/, '').toLowerCase();
212
+ // @implements A-SPEC-794.96 (B-L2) — in Holmes-Kit's own repository the harness wiring is the gate's too; a consumer
213
+ // project's .claude and .mcp.json keep their own gates
214
+ // (A-SPEC-794.97 B-M3: the harness's own runtime state under .claude is not wiring)
215
+ if (opts.ownRepo && ((s.startsWith('.claude/') && !/^\.claude\/(?:settings\.local\.json$|worktrees\/|scheduled_tasks\.lock$)/.test(s)) || s === '.mcp.json'))
216
+ return 'source';
217
+ // A-SPEC-794.97 — the compiler's configuration decides what the build emits into the live gate
218
+ if (opts.ownRepo && /^tsconfig[^/]*\.json$/.test(s))
219
+ return 'source';
220
+ // @implements A-SPEC-794.107 — the recovery skills' reference: a write, a commit and Stop judge it (a high-risk
221
+ // classification alone did not stop an agent commit of playbooks/ — re-check of dbb526a3, A-C1')
222
+ if (opts.ownRepo && (s.startsWith('playbooks/') || s === 'playbooks'))
223
+ return 'source';
224
+ if (s.startsWith('dist/holmes/') || s === 'dist/holmes')
225
+ return 'dist';
226
+ if (/^bin\/holmes-[^/]*$/.test(s))
227
+ return 'source';
228
+ if (s.startsWith('src/') && isHighRiskPath(s))
229
+ return 'source';
230
+ return null;
231
+ }
232
+ /**
233
+ * @implements A-SPEC-794.91 (N2; round 2, reviews A-M2 and B-H2) — the approved A-SPECs whose current seal a person made:
234
+ * a trusted `spec-approved` event names the spec and its current digest, and its actor is a person channel the mint writes
235
+ * (human-channel.ts, the one judgement: `elicitation:` or `host-gated:`). An allow-list: autonomous-timeout, a plain name
236
+ * (an environment approval names its actor freely, and no row records a grant nonce) and any new agent prefix do not
237
+ * count. The caller passes trusted events only, so a claimed channel written as `unattested:` never arrives.
238
+ */
239
+ /**
240
+ * @implements A-SPEC-794.95 — a spec-approved row a person made: a person channel the mint writes (elicitation:,
241
+ * host-gated:), and nothing else. Round-2 review A (critical): a grant file can be written by a patch and spent by
242
+ * spec_approve, and the server cannot tell a grant the CLI minted behind operatorActGuard from one a file write made, so
243
+ * a `channel:cli-terminal` row (still recorded, for audit) is not a person's seal. Proving a grant's origin from the
244
+ * ledger (a trusted granted row of the same nonce by a minted decider) is a 0.42 candidate.
245
+ */
246
+ function isPersonSealRow(e) {
247
+ return e.kind === 'spec-approved' && Array.isArray(e.inputs) && (0, human_channel_1.isHumanChannelActor)(e.actor);
248
+ }
249
+ /**
250
+ * @implements A-SPEC-794.95 (H1 = D2) — the approved A-SPECs a person's seal opens now: the latest person seal of the
251
+ * spec's current digest, timed by the ledger (the server's ts, never git's or the file system's), no older than `hours`
252
+ * and not in the future. Each open spec maps to that seal's time and actor.
253
+ */
254
+ function openSealWindows(specs, events, nowMs, hours) {
255
+ const latest = new Map();
256
+ for (const e of events) {
257
+ if (!isPersonSealRow(e) || typeof e.ts !== 'string')
258
+ continue;
259
+ const [id, digest] = e.inputs.map(String);
260
+ const key = `${id}\u0000${digest}`;
261
+ const prev = latest.get(key);
262
+ if (!prev || prev.ts < e.ts)
263
+ latest.set(key, { ts: e.ts, actor: String(e.actor) });
264
+ }
265
+ const out = new Map();
266
+ // A-SPEC-794.113 (review A, M-1) — at most 12 hours, whatever the setting says: `autonomy.sealWindowHours` is a
267
+ // file in the workspace, and raising it to 24 reopened a window that had closed (measured). It can shorten a window;
268
+ // it cannot lengthen one past the default.
269
+ const windowMs = Math.min(exports.SEAL_WINDOW_MAX_HOURS, Math.max(1, Number.isFinite(hours) ? hours : 12)) * 3_600_000;
270
+ // A-SPEC-794.95 (round-2 review A, high-1) — only a seal that still holds opens a window (Files to Touch widened after
271
+ // the seal opens nothing), and an id two spec files carry opens nothing
272
+ const count = new Map();
273
+ for (const s of specs)
274
+ count.set(s.id, (count.get(s.id) ?? 0) + 1);
275
+ for (const s of specs) {
276
+ const digest = s.frontmatter.approved_digest;
277
+ if (s.type !== 'A-SPEC' || s.status !== 'approved' || typeof digest !== 'string')
278
+ continue;
279
+ if ((count.get(s.id) ?? 0) > 1 || !(0, succession_1.sealHolds)(s))
280
+ continue;
281
+ const seal = latest.get(`${s.id}\u0000${digest}`);
282
+ if (!seal)
283
+ continue;
284
+ const t = Date.parse(seal.ts);
285
+ if (Number.isFinite(t) && t <= nowMs + 60_000 && nowMs - t <= windowMs)
286
+ out.set(s.id, seal);
287
+ }
288
+ return out;
289
+ }
290
+ const P7_ROOTS = ['src', 'bin', 'dist/holmes', '.claude', '.mcp.json', 'tsconfig*.json', 'playbooks']; // A-SPEC-794.107: playbooks
291
+ /** @implements A-SPEC-794.97 (B-M3) — the harness's runtime state under .claude is not the gate's wiring. */
292
+ const P7_RUNTIME = /^\.claude\/(?:settings\.local\.json$|worktrees\/|scheduled_tasks\.lock$)/;
293
+ /** A-SPEC-794.113 — the one entry of a verdict that could not be reached because git cannot read the repository. */
294
+ exports.PRINCIPLE7_GIT_UNREADABLE = '(git cannot read this repository)';
295
+ /** A-SPEC-794.113 — the one entry of a verdict closed because the latest baseline's commit is not in the repository. */
296
+ exports.PRINCIPLE7_BASELINE_LOST = '(the baseline commit is not in this repository)';
297
+ /** A-SPEC-794.114 — the marker of a closed verdict: this writer's chain is not the one this repository wrote. */
298
+ exports.PRINCIPLE7_WITNESS = '(the provenance ledger is not the one this repository wrote)';
299
+ /**
300
+ * @implements A-SPEC-794.114 — the witness verdict of this writer's own chain (governance/ledger-witness.ts): the one
301
+ * computation the principle 7 judgement, the record and the skills' reference read.
302
+ */
303
+ function ownChainWitness(root) {
304
+ const { writerChainFile } = require('./ledger-store');
305
+ const { chainWitnessVerdict } = require('./ledger-witness');
306
+ return chainWitnessVerdict(writerChainFile(path.join(root, '.ax', 'ledger')));
307
+ }
308
+ /** A-SPEC-794.113 — the longest a person's seal opens a window, whatever `autonomy.sealWindowHours` says. */
309
+ exports.SEAL_WINDOW_MAX_HOURS = 12;
310
+ /**
311
+ * @implements A-SPEC-794.97 r4 (high-2) — git as the judgement reads it: replacement objects off (a `git replace` made the
312
+ * baseline read as the changed tree), and the repository the root's own (an inherited GIT_DIR, GIT_INDEX_FILE or object
313
+ * directory would answer for another).
314
+ */
315
+ const git = (root, args) => gitBytes(root, args).toString('utf8');
316
+ /**
317
+ * The environment of principle 7's git reads: the caller's without any inherited GIT_* variable but the two `gitEnv`
318
+ * keeps (one source, A-SPEC-792.42), with the judgment's own pins — no replace objects, no graft file, no prompt.
319
+ * A-SPEC-794.113.
320
+ */
321
+ function principle7GitEnv(env = process.env) {
322
+ const { gitEnv, judgmentPins } = require('../project/bounded-io');
323
+ return { ...gitEnv(env), ...judgmentPins() };
324
+ }
325
+ /**
326
+ * Git as principle 7 reads it, as bytes. What the judged workspace can set in the repository's configuration does not
327
+ * decide what is read (A-SPEC-794.113; each line was measured or is named there):
328
+ * - the work tree is the root's own, whatever `core.worktree` says — with it pointed at a clean copy the judgement read
329
+ * the copy, allowed the build of the real tree and recorded its playbooks (measured 2026-11-12); the option outranks
330
+ * the configuration, and the repository is still found from the root;
331
+ * - no filter the configuration names runs — a clean filter that returned the original bytes, with the path named in the
332
+ * untracked .git/info/attributes, made a forged file read as unchanged (measured); the names are read for every call
333
+ * (a long-lived process must not judge with the names of an earlier moment), and a read that failed is not "none";
334
+ * - a file is not taken as unchanged on its size and modification time alone (core.trustctime, core.checkStat);
335
+ * - no fsmonitor, no untracked cache (A-SPEC-794.97 r5 L1), no replacement objects (r4 high-2).
336
+ */
337
+ function gitBytes(root, args, input) {
338
+ const { execFileSync } = require('node:child_process');
339
+ const env = principle7GitEnv();
340
+ const own = ownWorkTree(root);
341
+ // within one judgement the names are read once (review B: a second process per call doubled git's count); between
342
+ // judgements nothing is kept
343
+ let inertArgs = judgementScope?.inert.get(root);
344
+ if (inertArgs === undefined) {
345
+ const { inertDriverArgs } = require('../project/bounded-io');
346
+ const inert = inertDriverArgs(root, env);
347
+ if (inert.error) {
348
+ lastGitFailure = { kind: /ETIMEDOUT/.test(inert.error) ? 'timeout' : /ENOENT/.test(inert.error) ? 'missing' : 'refused', detail: inert.error };
349
+ throw new Error(inert.error);
350
+ }
351
+ inertArgs = inert.args;
352
+ judgementScope?.inert.set(root, inertArgs);
353
+ }
354
+ try {
355
+ return execFileSync('git', ['--no-replace-objects', ...(own === null ? [] : [`--work-tree=${own}`]), '-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false',
356
+ '-c', 'core.trustctime=true', '-c', 'core.checkStat=default', ...inertArgs, ...args], { cwd: root, env, timeout: GIT_READ_TIMEOUT_MS, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024, ...(input === undefined ? {} : { input }) });
357
+ }
358
+ catch (e) { // [no-substitution: the failure is kept for the refusal's text and thrown on]
359
+ lastGitFailure = gitFailureOf(e);
360
+ throw e;
361
+ }
362
+ }
363
+ const GIT_READ_TIMEOUT_MS = 10_000;
364
+ function gitFailureOf(e) {
365
+ const err = e;
366
+ if (err?.code === 'ETIMEDOUT' || err?.killed === true || err?.signal === 'SIGTERM' || err?.signal === 'SIGKILL')
367
+ return { kind: 'timeout', detail: `no answer within ${GIT_READ_TIMEOUT_MS / 1000} s` };
368
+ if (err?.code === 'ENOENT')
369
+ return { kind: 'missing', detail: 'git was not found' };
370
+ const first = String(err?.stderr ?? '').split('\n').map((l) => l.trim()).find((l) => l !== '') ?? '';
371
+ return { kind: 'refused', detail: `exit ${String(err?.status ?? '?')}${first ? `: ${first.slice(0, 160)}` : ''}` };
372
+ }
373
+ let lastGitFailure = null;
374
+ /** What one judgement shares between its git reads; null outside a judgement. */
375
+ let judgementScope = null;
376
+ function inJudgement(fn) {
377
+ if (judgementScope === null)
378
+ judgementScope = { depth: 0, inert: new Map() };
379
+ judgementScope.depth++;
380
+ try {
381
+ return fn();
382
+ }
383
+ finally {
384
+ if (--judgementScope.depth === 0)
385
+ judgementScope = null;
386
+ }
387
+ }
388
+ /** The nearest directory at or above `root` that holds `.git` (a directory, or a linked worktree's or submodule's file): the tree the root is in. */
389
+ function ownWorkTree(root) {
390
+ let dir = path.resolve(root);
391
+ for (;;) {
392
+ try {
393
+ fs.lstatSync(path.join(dir, '.git'));
394
+ return dir;
395
+ }
396
+ catch { /* [no-substitution: no .git here → the parent is asked; none at all → null, and the verdict decides] */ }
397
+ const up = path.dirname(dir);
398
+ if (up === dir)
399
+ return null;
400
+ dir = up;
401
+ }
402
+ }
403
+ /**
404
+ * @implements A-SPEC-794.97 r4b (L5) — Holmes-Kit's own repository, where principle 7 applies: the one judgement.
405
+ * @implements A-SPEC-794.111 — the checkout the running gate is built from, read from the running package's real path.
406
+ * It was "a directory src/holmes exists under the root", which one shell line the hook allows (`mv src/holmes src/h2`)
407
+ * turned false, and with it the write judgement, the commit judgement and Stop (measured 2026-11-12). The module is
408
+ * read through its object at call time, and nothing here can be set (A-SPEC-794.112).
409
+ */
410
+ function isHolmesKitOwnRepo(root) {
411
+ const running = require('../project/running-package');
412
+ return running.ownRepoOf(root, running.RUNNING_PACKAGE_ROOT);
413
+ }
414
+ /**
415
+ * @implements A-SPEC-794.97 r4b (M3) — the latest baseline commit in the ledger's text, found without reading the ledger
416
+ * as rows (the full trusted read costs 0.7 s on a 29.7 MB ledger). Only the fast path reads it, and only where it changes
417
+ * nothing: the baseline is HEAD and no principle 7 file differs from HEAD. A forged row would need a ledger write, which
418
+ * the gate refuses (named limit: the fast path does not verify the row's chain).
419
+ */
420
+ function latestBaselineInText(root, opts = {}) {
421
+ return latestBaselineRowInText(root, opts)?.commit ?? null;
422
+ }
423
+ /** @implements A-SPEC-794.110 — the same row with the playbook digests it carries (sorted), for the duplicate check. */
424
+ function latestBaselineRowInText(root, opts = {}) {
425
+ const dir = path.join(root, '.ax', 'ledger');
426
+ let best = null;
427
+ // A-SPEC-794.97 r5 (A-M3, B-M1) — this replica's own chain only, and only when git tracks it (an untracked new file,
428
+ // another replica's chain or another ledger is not read), and only the gate's own rows
429
+ let file;
430
+ try {
431
+ file = require('./ledger-store').writerChainFile(dir);
432
+ if (!opts.untracked)
433
+ git(root, ['ls-files', '--error-unmatch', '--', path.relative(root, file)]);
434
+ }
435
+ catch {
436
+ return null;
437
+ } // [no-substitution: the chain is untracked or git cannot answer → no fast path]
438
+ for (const n of [file]) {
439
+ let text;
440
+ try {
441
+ text = fs.readFileSync(n, 'utf8');
442
+ }
443
+ catch {
444
+ continue;
445
+ } // [no-substitution: unreadable → no fast path]
446
+ let at = text.indexOf('"principle7-baseline"');
447
+ while (at >= 0) {
448
+ const start = text.lastIndexOf('\n', at) + 1;
449
+ const end = text.indexOf('\n', at);
450
+ try {
451
+ const row = JSON.parse(text.slice(start, end < 0 ? undefined : end));
452
+ const c = Array.isArray(row.inputs) ? row.inputs.map(String).find((i) => /^commit:[0-9a-f]{40,64}$/.test(i)) : undefined;
453
+ // A-SPEC-794.113 (review A, L-2) — the latest is the last row written (the file's order is the chain's
454
+ // sequence), not the greatest time
455
+ if (row.kind === 'principle7-baseline' && row.actor === 'holmes-kit' && c && typeof row.ts === 'string') {
456
+ best = { ts: row.ts, commit: c.slice(7), playbooks: row.inputs.map(String).filter((i) => i.startsWith('playbook:')).sort() };
457
+ }
458
+ }
459
+ catch {
460
+ // A-SPEC-794.113 — a baseline line that does not parse is not skipped: skipping it made an older row the
461
+ // "latest" one. [no-substitution: a torn line → no fast path]
462
+ return null;
463
+ }
464
+ at = end < 0 ? -1 : text.indexOf('"principle7-baseline"', end);
465
+ }
466
+ }
467
+ return best === null ? null : { commit: best.commit, playbooks: best.playbooks };
468
+ }
469
+ /** Whether this writer's chain file names a baseline row at all, parsed or not (it only closes: see the verdict). */
470
+ function ownChainNamesBaseline(root) {
471
+ try {
472
+ const file = require('./ledger-store').writerChainFile(path.join(root, '.ax', 'ledger'));
473
+ return fs.readFileSync(file, 'utf8').includes('"principle7-baseline"');
474
+ }
475
+ catch {
476
+ return false;
477
+ } // [no-substitution: no chain file → no row is claimed; .git decides whether to close]
478
+ }
479
+ /** The baseline rows of `events`, in the order the trusted read gives them (by time, replica, sequence): the last is the latest. */
480
+ function baselineRowsOf(events) {
481
+ const rows = [];
482
+ events.forEach((e, at) => {
483
+ if (e.kind !== 'principle7-baseline' || !Array.isArray(e.inputs) || typeof e.ts !== 'string')
484
+ return;
485
+ const c = e.inputs.map(String).find((i) => /^commit:[0-9a-f]{40,64}$/.test(i));
486
+ if (c)
487
+ rows.push({ at, ts: e.ts, commit: c.slice('commit:'.length) });
488
+ });
489
+ return rows;
490
+ }
491
+ function principle7Baseline(root, events) {
492
+ const rows = baselineRowsOf(events);
493
+ const latest = rows[rows.length - 1];
494
+ if (latest !== undefined) {
495
+ try {
496
+ git(root, ['cat-file', '-e', `${latest.commit}^{commit}`]);
497
+ return { commit: latest.commit, known: true, recorded: rows.length };
498
+ }
499
+ catch {
500
+ // A-SPEC-794.113 (review A, H-B) — the latest baseline's commit is not in this repository. A-SPEC-794.97 r4
501
+ // (medium-2) fell back here to the latest row whose commit it does hold; moving a ref back and collecting the
502
+ // newer commit then made an OLDER gate the baseline, and a rollback of gate source passed. No older row stands in:
503
+ // the baseline is lost, and the verdict closes on it. [no-substitution: lost commit → closed, or a person's
504
+ // windows over every principle 7 file]
505
+ // (a repository git cannot read at all is not a lost commit: the verdict says which it was)
506
+ try {
507
+ git(root, ['rev-parse', '--git-dir']);
508
+ }
509
+ catch {
510
+ return null;
511
+ } // [no-substitution: git cannot answer → the verdict closes]
512
+ return { commit: latest.commit, known: false, recorded: rows.length, lost: { commit: latest.commit, ts: latest.ts } };
513
+ }
514
+ }
515
+ // no baseline row at all: HEAD stands in and the hook's first-baseline rule decides the build (A-SPEC-794.97)
516
+ try {
517
+ return { commit: git(root, ['rev-parse', 'HEAD']).trim(), known: false, recorded: 0 };
518
+ }
519
+ catch {
520
+ return null;
521
+ } // [no-substitution: git cannot answer → the verdict closes]
522
+ }
523
+ const isP7File = (rel) => rel !== '' && !P7_RUNTIME.test(rel) && principle7WriteTarget(rel, { ownRepo: true }) !== null;
524
+ /** The blob each path has in a tree-ish (`ls-tree`) or in the index (`ls-files -s`, stage 0). */
525
+ function blobsIn(root, where, paths) {
526
+ const out = new Map();
527
+ if (paths.length === 0)
528
+ return out;
529
+ try {
530
+ const raw = where === 'index'
531
+ ? git(root, ['--literal-pathspecs', 'ls-files', '-s', '-z', '--', ...paths])
532
+ : git(root, ['--literal-pathspecs', 'ls-tree', '-r', '-z', where, '--', ...paths]);
533
+ for (const e of raw.split('\0')) {
534
+ const tab = e.indexOf('\t');
535
+ if (tab < 0)
536
+ continue;
537
+ const f = e.slice(0, tab).split(' ').filter(Boolean);
538
+ // ls-files -s: <mode> <sha> <stage>; ls-tree: <mode> <type> <sha>
539
+ const sha = where === 'index' ? f[1] : f[2];
540
+ if (where === 'index' && f[2] !== '0') {
541
+ out.set(e.slice(tab + 1), `conflict:${sha}`);
542
+ continue;
543
+ }
544
+ if (sha)
545
+ out.set(e.slice(tab + 1), sha);
546
+ }
547
+ }
548
+ catch { /* [no-substitution: unreadable → the path has no blob there, which reads as a difference the windows must cover] */ }
549
+ return out;
550
+ }
551
+ /**
552
+ * @implements A-SPEC-794.96, A-SPEC-794.97 — the principle 7 files changed since `base`: committed, staged and unstaged
553
+ * (`git diff --name-only <base>`, which also sees a file hidden with --skip-worktree) and untracked; the harness's runtime
554
+ * state excluded. Null when git cannot answer.
555
+ */
556
+ function principle7Changes(root, base) {
557
+ try {
558
+ const names = (args) => git(root, args).split('\0').filter((x) => x !== '');
559
+ // A-SPEC-794.97 r4 (critical-1) — what Stop, a commit and a build read are three trees: the working tree, the index
560
+ // and HEAD, each against the baseline (staging a change and restoring the working tree left it in the index)
561
+ const diff = names(['diff', '--name-only', '-z', base, '--', ...P7_ROOTS]);
562
+ const staged = names(['diff', '--cached', '--name-only', '-z', base, '--', ...P7_ROOTS]);
563
+ const committed = names(['diff', '--name-only', '-z', base, 'HEAD', '--', ...P7_ROOTS]);
564
+ const status = names(['status', '--porcelain=v1', '-z', '-uall', '--', ...P7_ROOTS])
565
+ .filter((e) => e.startsWith('?? ')).map((e) => e.slice(3));
566
+ // A-SPEC-794.97 r4 (medium-3) — source an ignore rule hides (the gate's own sources only: dist is the build's, .claude
567
+ // holds installed files)
568
+ // A-SPEC-794.113 (review A, H2) — and a playbook an ignore rule hides: a new playbooks/<x> listed in
569
+ // .git/info/exclude was not seen, and the first row of a chain recorded it as a reference
570
+ // (review A, L-1) and the gate's wiring and compiler configuration: a new tsconfig.x.json or .mcp.json an ignore
571
+ // rule hides. The harness's worktrees under .claude are whole checkouts and are not walked.
572
+ const ignored = names(['ls-files', '-z', '-o', '-i', '--exclude-standard', '--', 'src', 'bin', 'playbooks', ':(glob)tsconfig*.json', '.mcp.json', '.claude', ':(exclude).claude/worktrees']);
573
+ // A-SPEC-794.97 r4 (high-1) — an entry marked assume-unchanged (lowercase tag) or skip-worktree (S) hides its working
574
+ // tree from diff: its content is hashed and compared with the baseline's
575
+ const flagged = names(['ls-files', '-v', '-z', '--', ...P7_ROOTS])
576
+ .filter((e) => /^(?:[a-z]|S) /.test(e)).map((e) => e.slice(2)).filter(isP7File);
577
+ const hidden = [];
578
+ if (flagged.length > 0) {
579
+ const baseBlobs = blobsIn(root, base, flagged);
580
+ const present = flagged.filter((f) => fs.existsSync(path.join(root, f)));
581
+ const hashes = present.length === 0 ? [] : git(root, ['hash-object', '--', ...present]).trim().split('\n');
582
+ present.forEach((f, k) => { if (hashes[k] !== baseBlobs.get(f))
583
+ hidden.push(f); });
584
+ for (const f of flagged)
585
+ if (!present.includes(f) && baseBlobs.has(f))
586
+ hidden.push(f);
587
+ }
588
+ return [...new Set([...diff, ...staged, ...committed, ...status, ...ignored, ...hidden].filter(isP7File))].sort();
589
+ }
590
+ catch {
591
+ return null;
592
+ } // [no-substitution: git cannot answer → null, and the verdict closes]
593
+ }
594
+ /**
595
+ * @implements A-SPEC-794.97 r4 (medium-2) — with no baseline, the first one is recorded only when every principle 7 file
596
+ * the commits made since the oldest open window changed is named by an open window: the files no window names.
597
+ */
598
+ function principle7FirstBaselineGaps(root, ctx) {
599
+ const seals = [...ctx.open.values()].map((v) => v.ts).sort();
600
+ if (seals.length === 0)
601
+ return ['(no open window)'];
602
+ try {
603
+ const files = git(root, ['log', `--since=${seals[0]}`, '--format=', '--name-only', '-z', 'HEAD', '--', ...P7_ROOTS])
604
+ .split(/[\0\n]/).filter(isP7File);
605
+ return [...new Set(files)].filter((f) => principle7OpenersIn(ctx, f).length === 0).sort();
606
+ }
607
+ catch {
608
+ return ['(git log unreadable)'];
609
+ } // [no-substitution: unreadable → a gap, and no first baseline is recorded]
610
+ }
611
+ /**
612
+ * @implements A-SPEC-794.95, A-SPEC-794.96, A-SPEC-794.97 — whether `spec` names `rel` for its window: its Files to Touch
613
+ * names it, or (794.96 M-1, 794.97 B-M4) `rel` is a test file the A-SPEC or any T-SPEC depending on it names (a draft
614
+ * included: the test comes before the T-SPEC's seal), or a test file in a directory its Files to Touch names a file in.
615
+ */
616
+ function windowNames(spec, rel, specs) {
617
+ const { matchesFtt, isTestPath } = require('../guardrail/scope-judgment');
618
+ const ftt = (0, scope_judgment_1.fttPathTokens)(spec.sections['Files to Touch'] ?? '');
619
+ if (ftt.some((t) => matchesFtt(t, rel)))
620
+ return true;
621
+ if (!isTestPath(rel))
622
+ return false;
623
+ const text = (s) => Object.values(s.sections ?? {}).join('\n');
624
+ if (text(spec).includes(rel))
625
+ return true;
626
+ if (specs.some((t) => t.type === 'T-SPEC' && (t.dependsOn ?? []).includes(spec.id) && text(t).includes(rel)))
627
+ return true;
628
+ const dir = path.posix.dirname(rel);
629
+ return ftt.some((t) => !/[*?[{]/.test(t) && path.posix.dirname(t) === dir);
630
+ }
631
+ function principle7Context(root, specs, nowMs) {
632
+ const { loadConfig } = require('../config/config');
633
+ const hours = (() => { try {
634
+ return loadConfig(root).autonomy.sealWindowHours ?? 12;
635
+ }
636
+ catch {
637
+ return 12;
638
+ } })(); // [no-substitution: unreadable setting → the default]
639
+ let events = [];
640
+ let unread = false;
641
+ try {
642
+ events = require('./recorded-pairs').trustedLedgerEventsCached(root).events;
643
+ }
644
+ catch {
645
+ events = [];
646
+ unread = true;
647
+ } // [no-substitution: unreadable ledger → `unread`, and the verdict closes]
648
+ const open = openSealWindows(specs, events, nowMs, hours);
649
+ const blobs = new Map();
650
+ for (const e of events) {
651
+ if (e.kind !== 'principle7-window-blob' || !Array.isArray(e.inputs))
652
+ continue;
653
+ const i = e.inputs.map(String);
654
+ const b = i.find((x) => x.startsWith('blob:'));
655
+ if (!b)
656
+ continue;
657
+ const s = blobs.get(i[0]) ?? new Set();
658
+ s.add(b.slice(5));
659
+ blobs.set(i[0], s);
660
+ }
661
+ return { specs, events, hours, open, blobs, ...(unread ? { unread } : {}) };
662
+ }
663
+ /** @implements A-SPEC-794.95–794.97 — the open windows whose spec names `rel`, over a context built once. */
664
+ function principle7OpenersIn(ctx, rel) {
665
+ const out = [];
666
+ for (const [id, v] of ctx.open) {
667
+ const s = ctx.specs.find((x) => x.id === id);
668
+ if (s && windowNames(s, rel, ctx.specs))
669
+ out.push({ id, ...v });
670
+ }
671
+ return out;
672
+ }
673
+ /** The single-file form the file tools use (the ledger read only when an approved A-SPEC could name the file). */
674
+ function principle7OpenersFor(root, specs, nowMs, rel) {
675
+ if (!specs.some((s) => s.type === 'A-SPEC' && s.status === 'approved' && windowNames(s, rel, specs)))
676
+ return { openers: [], events: [], hours: 12 };
677
+ try {
678
+ const ctx = principle7Context(root, specs, nowMs);
679
+ return { openers: principle7OpenersIn(ctx, rel), events: ctx.events, hours: ctx.hours };
680
+ }
681
+ catch {
682
+ return { openers: [], events: [], hours: 12 };
683
+ } // [no-substitution: unreadable → no window is open, and the write is refused]
684
+ }
685
+ function principle7Verdict(root, specs, nowMs) {
686
+ openPlaybooksNow = null;
687
+ return inJudgement(() => principle7VerdictOf(root, specs, nowMs));
688
+ }
689
+ /**
690
+ * A-SPEC-794.113 — the playbooks a person's window names as open, as the last judgement of this process found them:
691
+ * the record that follows a build (recordBaseline, called by the hook with the same time) anchors a playbook's digest only
692
+ * when its window is open then. Nothing but a judgement sets it, and each judgement clears it first.
693
+ */
694
+ let openPlaybooksNow = null;
695
+ function principle7VerdictOf(root, specs, nowMs) {
696
+ if (!isHolmesKitOwnRepo(root))
697
+ return null;
698
+ // A-SPEC-794.114 — before anything is read from the ledger (the fast path included): this writer's chain must be the
699
+ // one this repository wrote. A tree move took it back with the tree, and a chain extended outside came in by git
700
+ // (measured 11-12). A root in no repository keeps the judgement below (it closes or is not judged by its own rules).
701
+ const witnessed = ownChainWitness(root);
702
+ if (!witnessed.ok && witnessed.kind !== 'no-repository') {
703
+ return { unopened: [`${exports.PRINCIPLE7_WITNESS.slice(0, -1)}: ${witnessed.kind} — ${witnessed.detail})`], byWindow: [],
704
+ base: { commit: '', known: false, recorded: 0 }, ctx: { specs, events: [], hours: 12, open: new Map(), blobs: new Map() }, headSeen: [], localOnly: [] };
705
+ }
706
+ // A-SPEC-794.97 r4b (M3) — nothing changed since a baseline at HEAD: answered without the ledger's trusted read
707
+ // r6 (B-L3) — the change list the fast path computed is handed to the full judgement when the baseline turns out the same
708
+ let early = null;
709
+ try {
710
+ // B-M1: the baseline need not be HEAD — nothing in the category changed since it (committed or not) is enough
711
+ const row = latestBaselineRowInText(root);
712
+ const candidate = row?.commit ?? null;
713
+ const changedSince = candidate === null ? null : principle7Changes(root, candidate);
714
+ if (candidate !== null && changedSince !== null)
715
+ early = { base: candidate, changed: changedSince };
716
+ // A-SPEC-794.113 — and the playbooks are the ones that row recorded: a playbook that differs from the recorded
717
+ // reference though not from the baseline commit (a change another replica's window saw) needs the windows read
718
+ const reference = require('../project/playbook-reference');
719
+ // (a row with no digests while the package ships playbooks is not "the same" either: the first digests are made by
720
+ // a person's window, which only the full judgement reads)
721
+ const sameReference = row !== null && reference.playbookDigestInputs(root).join('\n') === row.playbooks.join('\n');
722
+ if (candidate !== null && changedSince?.length === 0 && sameReference) {
723
+ return { unopened: [], byWindow: [], base: { commit: candidate, known: true, recorded: 1 }, headSeen: [], localOnly: [],
724
+ ctx: { specs, events: [], hours: 12, open: new Map(), blobs: new Map() } };
725
+ }
726
+ }
727
+ catch { /* [no-substitution: the fast path failed → the full judgement below] */ }
728
+ const ctx = principle7Context(root, specs, nowMs);
729
+ // A-SPEC-794.113 — a ledger the trusted read cannot give is not "no rows" (that made HEAD stand in for the
730
+ // baseline and closed every window): closed. [no-substitution: unreadable ledger → closed]
731
+ if (ctx.unread) {
732
+ // (when git itself cannot read the repository, that is the cause to name: the trusted read asks git for HEAD)
733
+ let gitAnswers = true;
734
+ try {
735
+ git(root, ['rev-parse', '--git-dir']);
736
+ }
737
+ catch {
738
+ gitAnswers = false;
739
+ } // [no-substitution: it only picks which cause the closed verdict names]
740
+ const what = gitAnswers ? `ledger — the provenance ledger under ${path.join(root, '.ax', 'ledger')} cannot be read`
741
+ : `${lastGitFailure?.kind ?? 'refused'}${lastGitFailure?.detail ? ` — ${lastGitFailure.detail}` : ''}`;
742
+ return { unopened: [`${exports.PRINCIPLE7_GIT_UNREADABLE.slice(0, -1)}: ${what})`], byWindow: [],
743
+ base: { commit: '', known: false, recorded: 0 }, ctx, headSeen: [], localOnly: [] };
744
+ }
745
+ let base = principle7Baseline(root, ctx.events);
746
+ // A-SPEC-794.113 (review A, H-B) — the latest baseline's commit is not here and no older row stands in. Closed,
747
+ // unless open person's windows name every principle 7 file git tracks at HEAD: a person saying "this tree is the
748
+ // baseline now". Then HEAD stands in and the hook's first-baseline rule lets the build record it.
749
+ if (base !== null && base.lost !== undefined) {
750
+ let unnamed = null;
751
+ try {
752
+ unnamed = git(root, ['ls-files', '-z', '--', ...P7_ROOTS]).split('\0').filter(isP7File).filter((f) => principle7OpenersIn(ctx, f).length === 0);
753
+ }
754
+ catch {
755
+ unnamed = null;
756
+ } // [no-substitution: the tracked files cannot be listed → closed as lost]
757
+ if (unnamed === null || unnamed.length > 0) {
758
+ return { unopened: [`${exports.PRINCIPLE7_BASELINE_LOST.slice(0, -1)}: ${base.lost.commit.slice(0, 12)} recorded ${base.lost.ts})`], byWindow: [], base, ctx, headSeen: [], localOnly: [] };
759
+ }
760
+ try {
761
+ base = { commit: git(root, ['rev-parse', 'HEAD']).trim(), known: false, recorded: base.recorded };
762
+ }
763
+ catch {
764
+ base = null;
765
+ } // [no-substitution: git cannot answer → the verdict closes]
766
+ }
767
+ // A-SPEC-794.113 (review A, H1) — content a window saw BEFORE the baseline in force is history, not leave: with
768
+ // every row counted, checking out an earlier version after the window closed opened the judgement and the build made
769
+ // the earlier gate (or playbook) the live one, with no person. Only rows recorded after the baseline row count — and
770
+ // the rows the same build wrote right before it (the uncommitted content that build saw is still in the tree).
771
+ if (base !== null && base.known)
772
+ ctx.blobs = windowBlobsAfter(ctx.events);
773
+ // A-SPEC-794.113 — a repository git cannot read is not "nothing to judge" where there is one to read: with
774
+ // `core.repositoryformatversion` set to a version git refuses, or .git moved away, this returned null and a build of a
775
+ // forged gate source was allowed (measured 2026-11-12). Closed when .git exists at or above the root, or this writer's
776
+ // chain holds a baseline row; a directory with neither (no repository was ever judged here) is not judged, as before.
777
+ const unreadable = () => {
778
+ const recorded = ownChainNamesBaseline(root);
779
+ if (ownWorkTree(root) === null && !recorded)
780
+ return null; // [no-substitution: no repository and no row was ever here → not judged, as before]
781
+ // review B (medium 3) — which failure it was goes with the verdict: a timeout under load is not a broken repository
782
+ const why = ownWorkTree(root) === null ? 'refused' : (lastGitFailure?.kind ?? 'refused');
783
+ const detail = ownWorkTree(root) === null ? 'no .git at or above this directory' : (lastGitFailure?.detail ?? '');
784
+ return { unopened: [`${exports.PRINCIPLE7_GIT_UNREADABLE.slice(0, -1)}: ${why}${detail ? ` — ${detail}` : ''})`], byWindow: [], base: base ?? { commit: '', known: false, recorded: recorded ? 1 : 0 }, ctx, headSeen: [], localOnly: [] };
785
+ };
786
+ if (base === null)
787
+ return unreadable();
788
+ const changed = early !== null && early.base === base.commit ? early.changed : principle7Changes(root, base.commit);
789
+ if (changed === null)
790
+ return unreadable();
791
+ const present = changed.filter((f) => fs.existsSync(path.join(root, f)));
792
+ const blobOf = new Map();
793
+ if (present.length > 0) {
794
+ try {
795
+ const out = git(root, ['hash-object', '--', ...present]).trim().split('\n');
796
+ present.forEach((f, k) => blobOf.set(f, out[k] ?? ''));
797
+ }
798
+ catch {
799
+ // A-SPEC-794.113 (the census of this judgement's failure branches) — this read "unhashed files are judged by
800
+ // window only": each file then read as deleted, and a NEW file — deleted at the baseline too — read as unchanged.
801
+ // One file git cannot open fails the whole list, so a new gate source beside it was not judged (measured
802
+ // 2026-11-12: the build was allowed). [no-substitution: unhashed → closed]
803
+ return unreadable();
804
+ }
805
+ }
806
+ // A-SPEC-794.97 r4 (critical-1) — a file's contents are those of its three trees that differ from the baseline's: each
807
+ // must be one a window saw (a window that saw the working tree did not see an index entry written apart from it)
808
+ const tracked = changed.filter((f) => principle7WriteTarget(f, { ownRepo: true }) !== 'dist');
809
+ const atBase = blobsIn(root, base.commit, tracked);
810
+ const atIndex = blobsIn(root, 'index', tracked);
811
+ const atHead = blobsIn(root, 'HEAD', tracked);
812
+ const unopened = [];
813
+ const headSeen = [];
814
+ const byWindow = [];
815
+ for (const f of changed) {
816
+ if (principle7WriteTarget(f, { ownRepo: true }) === 'dist') {
817
+ unopened.push(f);
818
+ continue;
819
+ }
820
+ const was = atBase.get(f) ?? 'deleted';
821
+ const states = [...new Set([blobOf.get(f) ?? 'deleted', atIndex.get(f) ?? 'deleted', atHead.get(f) ?? 'deleted'])].filter((b) => b !== was);
822
+ if (states.length === 0)
823
+ continue;
824
+ const openers = principle7OpenersIn(ctx, f);
825
+ if (openers.length > 0) {
826
+ const o = [...openers].sort((a, b) => (a.ts < b.ts ? 1 : -1))[0];
827
+ for (const blob of states)
828
+ byWindow.push({ file: f, id: o.id, ts: o.ts, blob });
829
+ continue;
830
+ }
831
+ if (states.every((b) => ctx.blobs.get(f)?.has(b)))
832
+ continue;
833
+ unopened.push(f);
834
+ // A-SPEC-794.97 r4b (L4) — its committed content is one a window saw: restoring from HEAD is enough
835
+ const h = atHead.get(f);
836
+ if (h !== undefined && ctx.blobs.get(f)?.has(h))
837
+ headSeen.push(f);
838
+ }
839
+ // A-SPEC-794.97 r5 (B-M2) — an unopened file marked skip-worktree or assume-unchanged is local-only: a stash or a
840
+ // restore does not reach its working-tree content, so only a person's seal frees it
841
+ let localOnly = [];
842
+ if (unopened.length > 0) {
843
+ try {
844
+ localOnly = git(root, ['--literal-pathspecs', 'ls-files', '-v', '-z', '--', ...unopened]).split('\0')
845
+ .filter((e) => /^(?:[a-z]|S) /.test(e)).map((e) => e.slice(2));
846
+ }
847
+ catch {
848
+ localOnly = [];
849
+ } // [no-substitution: the list only shapes the refusal's text; the files stay unopened]
850
+ }
851
+ // A-SPEC-794.113 — the playbooks a person's window names now (the record anchors only these), and those among
852
+ // them whose bytes are not the recorded reference's: seen by that window, whether or not they differ from the baseline
853
+ // commit (review B, medium 1: a change another replica's window saw arrives equal to the commit and was never recorded)
854
+ const playbooks = [];
855
+ const openFiles = new Set();
856
+ try {
857
+ const reference = require('../project/playbook-reference');
858
+ const own = ownChainRows(root);
859
+ const earlier = new Set(latestWithDigests(own.baselines)?.playbooks ?? []);
860
+ // review A (L-3) — for the reference a window is open only by a person's seal in THIS chain: another replica's seal
861
+ // rows come from HEAD's blob and do not move this chain's reference
862
+ const ownOpen = openSealWindows(ctx.specs, ctx.events.filter((e) => e.replicaId === own.id), nowMs, ctx.hours);
863
+ const openerOf = (file) => {
864
+ const named = [...ownOpen].filter(([id]) => { const s = ctx.specs.find((x) => x.id === id); return s !== undefined && windowNames(s, file, ctx.specs); })
865
+ .map(([id, v]) => ({ id, ts: v.ts })).sort((a, b) => (a.ts < b.ts ? 1 : -1));
866
+ return named[0] ?? null;
867
+ };
868
+ const present = new Set();
869
+ for (const input of reference.playbookDigestInputs(root)) {
870
+ const [, name, digest] = input.split(':');
871
+ const file = `playbooks/${name}/PLAYBOOK.md`;
872
+ present.add(name);
873
+ const o = openerOf(file);
874
+ if (o === null)
875
+ continue;
876
+ openFiles.add(file);
877
+ if (!earlier.has(input))
878
+ playbooks.push({ file, id: o.id, ts: o.ts, sha256: digest });
879
+ }
880
+ // a recorded playbook the tree no longer holds: its removal is open only when a window names it
881
+ for (const input of earlier) {
882
+ const name = input.split(':')[1];
883
+ const file = `playbooks/${name}/PLAYBOOK.md`;
884
+ if (!present.has(name) && openerOf(file) !== null)
885
+ openFiles.add(file);
886
+ }
887
+ }
888
+ catch { /* [no-substitution: unreadable → no playbook is named open, so nothing is anchored] */ }
889
+ openPlaybooksNow = { root, nowMs, files: openFiles };
890
+ return { unopened, byWindow, base, ctx, headSeen, localOnly, playbooks };
891
+ }
892
+ /**
893
+ * The window-blob rows that still open a file after their window closed: those recorded after the latest baseline row,
894
+ * in the trusted order (by time, replica, sequence) — and the rows the same chain wrote in the unbroken run right before
895
+ * that baseline row (a build writes the window rows of what it saw, then its baseline row: an uncommitted change that
896
+ * build saw is still in the tree and is not history). The run is told by sequence, not by time.
897
+ */
898
+ function windowBlobsAfter(events) {
899
+ const rows = events;
900
+ const baselines = baselineRowsOf(events);
901
+ const from = baselines.length === 0 ? -1 : baselines[baselines.length - 1].at;
902
+ const counted = new Set();
903
+ rows.forEach((e, k) => { if (k > from && e.kind === 'principle7-window-blob')
904
+ counted.add(k); });
905
+ if (from >= 0) {
906
+ const base = rows[from];
907
+ const bySeq = new Map();
908
+ rows.forEach((e, k) => { if (e.replicaId === base.replicaId && Number.isFinite(Number(e.seq)))
909
+ bySeq.set(Number(e.seq), k); });
910
+ for (let s = Number(base.seq) - 1; Number.isFinite(s); s--) {
911
+ const k = bySeq.get(s);
912
+ if (k === undefined || rows[k].kind !== 'principle7-window-blob')
913
+ break;
914
+ counted.add(k);
915
+ }
916
+ }
917
+ const blobs = new Map();
918
+ for (const k of counted) {
919
+ const e = rows[k];
920
+ if (!Array.isArray(e.inputs))
921
+ continue;
922
+ const i = e.inputs.map(String);
923
+ const b = i.find((x) => x.startsWith('blob:'));
924
+ if (!b)
925
+ continue;
926
+ const s = blobs.get(i[0]) ?? new Set();
927
+ s.add(b.slice(5));
928
+ blobs.set(i[0], s);
929
+ }
930
+ return blobs;
931
+ }
932
+ function ownChainRows(root) {
933
+ const out = { id: null, broken: false, baselines: [], windows: [] };
934
+ const dir = path.join(root, '.ax', 'ledger');
935
+ if (!fs.existsSync(dir))
936
+ return out;
937
+ try {
938
+ const { trustedLedgerEventsCached } = require('./recorded-pairs');
939
+ const { FileLedgerStore } = require('./ledger-store');
940
+ const own = new FileLedgerStore(dir).replicaId();
941
+ out.id = own;
942
+ // A-SPEC-794.114 — a chain this repository did not write (taken back, extended outside, never vouched for) is read
943
+ // as broken: the record writes nothing onto it
944
+ if (!ownChainWitness(root).ok) {
945
+ out.broken = true;
946
+ return out;
947
+ }
948
+ const read = trustedLedgerEventsCached(root);
949
+ out.broken = read.ignored.some((i) => i.seq === undefined && i.file.endsWith(`/provenance.${own}.jsonl`) && /does not verify|cannot be read/.test(i.why));
950
+ for (const e of read.events) {
951
+ if (e.replicaId !== own || !Array.isArray(e.inputs) || typeof e.ts !== 'string')
952
+ continue;
953
+ const i = e.inputs.map(String);
954
+ const seq = Number(e.seq);
955
+ if (e.kind === 'principle7-baseline' && e.actor === 'holmes-kit') {
956
+ const c = i.find((x) => /^commit:[0-9a-f]{40,64}$/.test(x));
957
+ if (c)
958
+ out.baselines.push({ seq, ts: e.ts, commit: c.slice(7), playbooks: i.filter((x) => x.startsWith('playbook:')).sort() });
959
+ }
960
+ else if (e.kind === 'principle7-window-blob' && e.actor === 'holmes-kit') {
961
+ const blob = i.find((x) => x.startsWith('blob:'));
962
+ if (blob)
963
+ out.windows.push({ seq, file: i[0], seal: (i.find((x) => x.startsWith('seal:')) ?? '').slice(5), blob: blob.slice(5), sha256: (i.find((x) => x.startsWith('sha256:')) ?? '').slice(7) || null });
964
+ }
965
+ }
966
+ out.baselines.sort((a, b) => a.seq - b.seq);
967
+ }
968
+ catch {
969
+ out.broken = true;
970
+ } // [no-substitution: unreadable chain → broken, and a broken chain records nothing]
971
+ return out;
972
+ }
973
+ /** The one choice of "the row before" (review A, L3): the highest sequence of this writer's chain. */
974
+ const latestOf = (rows) => (rows.length === 0 ? null : rows.reduce((a, b) => (b.seq > a.seq ? b : a)));
975
+ const latestWithDigests = (rows) => latestOf(rows.filter((r) => r.playbooks.length > 0));
976
+ /**
977
+ * @implements A-SPEC-794.97 — the content a window saw: one `principle7-window-blob` row per (file, spec, seal, blob) not
978
+ * yet recorded, written where a judgement passes because a window was open (Stop, commit, build).
979
+ */
980
+ function recordWindowBlobs(root, nowIso, v) {
981
+ if (v.byWindow.length === 0 && (v.playbooks ?? []).length === 0)
982
+ return;
983
+ inJudgement(() => {
984
+ try {
985
+ // A-SPEC-794.113 (review B, medium 1) — "already recorded" is asked of THIS WRITER'S rows since its latest
986
+ // baseline: a row another replica wrote, or one from before the baseline in force, anchors nothing here, so
987
+ // skipping on it left a change that came with a pull unrecorded on this machine for good
988
+ const own = ownChainRows(root);
989
+ if (own.broken)
990
+ return;
991
+ const since = latestOf(own.baselines)?.seq ?? -1;
992
+ const have = new Set(own.windows.filter((w) => w.seq > since).flatMap((w) => [`${w.file}\u0000${w.seal}\u0000blob:${w.blob}`, ...(w.sha256 ? [`${w.file}\u0000${w.seal}\u0000sha256:${w.sha256}`] : [])]));
993
+ const crypto = require('node:crypto');
994
+ const bytesOf = (file) => { try {
995
+ return fs.readFileSync(path.join(root, file));
996
+ }
997
+ catch {
998
+ return null;
999
+ } }; // [no-substitution: unreadable → the row carries no sha256 and anchors no reference]
1000
+ const idOf = (files) => {
1001
+ const present = files.filter((f) => fs.existsSync(path.join(root, f)));
1002
+ if (present.length === 0)
1003
+ return new Map();
1004
+ try {
1005
+ const ids = git(root, ['hash-object', '--', ...present]).trim().split('\n');
1006
+ return new Map(present.map((f, k) => [f, ids[k] ?? '']));
1007
+ }
1008
+ catch {
1009
+ return new Map();
1010
+ } // [no-substitution: unhashed → no sha256 on a row, and no playbook row]
1011
+ };
1012
+ const rows = [];
1013
+ const fresh = v.byWindow.filter((w) => !have.has(`${w.file}\u0000${w.ts}\u0000blob:${w.blob}`));
1014
+ // review A (L2) — the bytes' own digest rides with the row where the working tree holds that blob: two byte
1015
+ // contents can share a blob id (line-ending conversion), and the reference is a digest of bytes
1016
+ const working = idOf([...new Set([...fresh.map((w) => w.file), ...(v.playbooks ?? []).map((p) => p.file)])]);
1017
+ for (const w of fresh) {
1018
+ const b = working.get(w.file) === w.blob ? bytesOf(w.file) : null;
1019
+ rows.push({ ...w, sha256: b === null ? null : crypto.createHash('sha256').update(b).digest('hex') });
1020
+ }
1021
+ for (const p of v.playbooks ?? []) {
1022
+ if (have.has(`${p.file}\u0000${p.ts}\u0000sha256:${p.sha256}`) || rows.some((r) => r.file === p.file && r.ts === p.ts && r.sha256 === p.sha256))
1023
+ continue;
1024
+ const b = bytesOf(p.file);
1025
+ const blob = working.get(p.file) ?? '';
1026
+ if (b === null || blob === '' || crypto.createHash('sha256').update(b).digest('hex') !== p.sha256)
1027
+ continue; // the bytes moved since the judgement
1028
+ rows.push({ file: p.file, id: p.id, ts: p.ts, blob, sha256: p.sha256 });
1029
+ }
1030
+ if (rows.length === 0)
1031
+ return;
1032
+ const { FileLedgerStore } = require('./ledger-store');
1033
+ const store = new FileLedgerStore(path.join(root, '.ax', 'ledger'));
1034
+ for (const w of rows)
1035
+ store.append({ ts: nowIso, actor: 'holmes-kit', kind: 'principle7-window-blob',
1036
+ summary: `${w.file} at ${w.blob.slice(0, 12)} seen under ${w.id}'s window (sealed ${w.ts})`,
1037
+ inputs: [w.file, w.id, `seal:${w.ts}`, `blob:${w.blob}`, ...(w.sha256 ? [`sha256:${w.sha256}`] : [])], rationale: 'principle 7 seal window' });
1038
+ }
1039
+ catch { /* [no-substitution: the record is what reopens a committed file later; a failed write leaves it closed] */ }
1040
+ });
1041
+ }
1042
+ /**
1043
+ * @implements A-SPEC-794.97 — the one text for Stop, commit and build: the files, and two ways out — a person's seal, or
1044
+ * the file made equal to the live gate's baseline (restored from it, the commit reverted, a new untracked file removed);
1045
+ * before discarding anything, ask the person or stash it (L4: a restore loses work a seal would have kept).
1046
+ */
1047
+ const REFUSAL_LIST_MAX = 20;
1048
+ /**
1049
+ * @implements A-SPEC-794.97 r4b (M1, L2, L3, L4) — the warning comes before any restore (a restore from the baseline also
1050
+ * discards commits made after it: a pull, an owner's terminal commit, a branch switch); the exits are a person's seal,
1051
+ * undoing the branch switch or the pull, restoring from HEAD where a window saw HEAD's content, and making the file equal
1052
+ * to the baseline; at most 20 files are listed; a new clone and a lost baseline commit are told apart.
1053
+ */
1054
+ function principle7RefusalText(unopened, base, opts = {}) {
1055
+ // A-SPEC-794.113 — one line: what happened and what to do, by the failure it was (review B, medium 3: a timeout
1056
+ // under load is not a broken repository, and telling it to check the format version is no way out)
1057
+ // A-SPEC-794.113 (review A, H-B) — the latest baseline's commit is gone: no older baseline stands in
1058
+ // A-SPEC-794.114 — the chain is not the one this repository wrote: what happened, by kind, and the way out
1059
+ const witnessMarker = unopened.find((u) => u.startsWith(exports.PRINCIPLE7_WITNESS.slice(0, -1)));
1060
+ if (witnessMarker !== undefined) {
1061
+ const m = /: ([a-z-]+) — (.*)\)$/.exec(witnessMarker);
1062
+ const kind = m?.[1] ?? 'broken';
1063
+ const detail = m?.[2] ?? '';
1064
+ const vouchWay = 'a person vouches for the chain as it is: `holmes-kit ledger witness` files a request the person decides in the session\'s approval form (the form shows how this chain compares with the pushed one and the person rows to recognise), then run it again';
1065
+ const lead = `principle 7: ${detail}, so the live gate's baseline and the person-seal windows in it cannot be trusted, and the working tree is not judged against them (A-SPEC-794.114). `;
1066
+ if (kind === 'taken-back')
1067
+ return `${lead}If the tree moved (a branch switch, a stash, a reset), return it — the branch, \`git stash pop\` — and this opens again; otherwise ${vouchWay}.`;
1068
+ if (kind === 'extended')
1069
+ return `${lead}Rows came into the chain that this repository did not write — with a pull of this replica's own chain from another clone, or brought in by git. Do not vouch unless you recognise them; ${vouchWay}.`;
1070
+ if (kind === 'no-witness')
1071
+ return `${lead}This is a checkout's first moment under this gate (a new clone or worktree, or the upgrade from 0.40.x): ${vouchWay}.`;
1072
+ if (kind === 'replica-changed')
1073
+ return `${lead}This writer's replica id is not the one the witness names (a host rename, HOLMES_REPLICA_ID): ${vouchWay}, or restore the replica id.`;
1074
+ return `${lead}${vouchWay}; if the witness itself cannot be read, a person repairs it.`;
1075
+ }
1076
+ const lost = unopened.find((u) => u.startsWith(exports.PRINCIPLE7_BASELINE_LOST.slice(0, -1)));
1077
+ if (lost !== undefined) {
1078
+ const which = /: (.*)\)$/.exec(lost)?.[1] ?? '';
1079
+ return `principle 7: the live gate's baseline commit ${which} is not in this repository (history rewritten and collected, a shallow clone, or a commit that was never pushed), `
1080
+ + 'and no older baseline stands in for it, so the working tree cannot be judged. '
1081
+ + 'Ways out: bring the commit back (git fetch, or git fetch --unshallow); or a person seals an A-SPEC whose Files to Touch names the principle 7 paths as they are now '
1082
+ + '(src/holmes/**, bin/**, .claude/**, playbooks/**, .mcp.json and each tsconfig file) — the build inside that window records this tree as the new baseline.';
1083
+ }
1084
+ const marker = unopened.find((u) => u.startsWith(exports.PRINCIPLE7_GIT_UNREADABLE.slice(0, -1)));
1085
+ if (marker !== undefined) {
1086
+ const kind = /: (timeout|missing|refused|ledger)\b/.exec(marker)?.[1] ?? 'refused';
1087
+ const detail = / — (.*)\)$/.exec(marker)?.[1] ?? '';
1088
+ if (kind === 'ledger')
1089
+ return `principle 7: ${detail}, so neither the live gate's baseline nor an open window is known and the working tree cannot be judged. A person repairs the ledger; nothing stands in for it.`;
1090
+ // review B (low 5) — the judgement's git is not the shell's
1091
+ const head = 'principle 7: git cannot read this repository (principle 7 reads git without inherited GIT_* variables), so the working tree cannot be judged against the live gate\'s baseline';
1092
+ if (kind === 'timeout')
1093
+ return `${head} — git did not answer in time (${detail || 'a timeout'}). Nothing is wrong with the repository as far as this can tell: run this again when the machine is less busy.`;
1094
+ if (kind === 'missing')
1095
+ return `${head} — git was not found on PATH. Make git available to this session, then run this again.`;
1096
+ return `${head}${detail ? ` (${detail})` : ''}. `
1097
+ + 'Check that `git status` answers here — the repository format version, its extensions and its configuration, and that .git is in place — then run this again.';
1098
+ }
1099
+ const short = base.commit.slice(0, 12);
1100
+ const listed = unopened.length > REFUSAL_LIST_MAX ? `${unopened.slice(0, REFUSAL_LIST_MAX).join(', ')} and ${unopened.length - REFUSAL_LIST_MAX} more` : unopened.join(', ');
1101
+ const note = base.known ? ''
1102
+ : base.recorded > 0 ? ' (the recorded baseline commit is not in this repository — garbage-collected, or another clone: HEAD stands in)'
1103
+ : ' (this ledger holds no baseline row — a new clone or worktree: HEAD stands in)';
1104
+ const headSeen = (opts.headSeen ?? []).filter((f) => unopened.includes(f));
1105
+ const localOnly = (opts.localOnly ?? []).filter((f) => unopened.includes(f));
1106
+ // r6 (B-L4) — when every file is local-only, the seal is the one way out: no restore or stash lines
1107
+ if (localOnly.length === unopened.length && unopened.length > 0) {
1108
+ return `principle 7: ${listed} changed since the live gate's baseline ${short}${note} with no open person-seal window naming ${unopened.length === 1 ? 'it' : 'them'}. `
1109
+ + `${unopened.length === 1 ? 'It is' : 'They are'} local-only (skip-worktree or assume-unchanged): a stash or a restore does not reach ${unopened.length === 1 ? 'it' : 'them'}. `
1110
+ + 'Way out: a person seals an A-SPEC whose Files to Touch names the file (spec_approve asks in the session form).';
1111
+ }
1112
+ return `principle 7: ${listed} changed since the live gate's baseline ${short}${note} with no open person-seal window naming ${unopened.length === 1 ? 'it' : 'them'}. `
1113
+ + 'Before restoring anything, ask the person or stash it: a restore from the baseline also discards other people\'s commits made after it (a pull, an owner\'s terminal commit, a branch switch). '
1114
+ + 'Ways out: a person seals an A-SPEC whose Files to Touch names the file (spec_approve asks in the session form); '
1115
+ // r5 (B-M2) — a local-only file has the seal alone
1116
+ + (localOnly.length > 0 ? `${localOnly.join(', ')} ${localOnly.length === 1 ? 'is' : 'are'} local-only (skip-worktree or assume-unchanged): a stash or a restore does not reach ${localOnly.length === 1 ? 'it' : 'them'}, so only a person's seal frees ${localOnly.length === 1 ? 'it' : 'them'}; ` : '')
1117
+ // r5 (A-L3) — undoing a pull is the person's call: a reset discards uncommitted work
1118
+ + 'if the change came with a branch switch or a pull, return to the branch, or undo the pull — ask the person first (a reset discards uncommitted work); '
1119
+ + (headSeen.length > 0 ? `for ${headSeen.join(', ')}, whose committed content a window saw, git restore --source=HEAD --staged --worktree -- <file>; ` : '')
1120
+ + `or make the file equal to the baseline again (git restore --source=${short} --staged --worktree -- <file>, or revert the commit; a new untracked file is removed).`;
1121
+ }
1122
+ /**
1123
+ * @implements A-SPEC-794.97 — the live gate's baseline moves to HEAD; only the gate's allowed build records it.
1124
+ * @implements A-SPEC-794.110 — the same row carries the sha256 of every playbook in the working tree the gate has just
1125
+ * judged (playbooks/ is a principle 7 path, so an unopened playbook change refused the build before this): the recovery
1126
+ * skills' reference, as values in the ledger instead of git objects a ref move or a gc changes.
1127
+ */
1128
+ function recordBaseline(root, nowIso) {
1129
+ inJudgement(() => {
1130
+ try {
1131
+ const head = git(root, ['rev-parse', 'HEAD']).trim();
1132
+ const reference = require('../project/playbook-reference');
1133
+ // A-SPEC-794.113 — everything the record compares with is this writer's own chain, through the trusted read:
1134
+ // a chain that does not verify takes no new baseline (a row added by hand must not become the earlier digests a row
1135
+ // the gate writes then repeats)
1136
+ const own = ownChainRows(root);
1137
+ if (own.broken)
1138
+ return;
1139
+ const latest = latestOf(own.baselines);
1140
+ const earlier = latestWithDigests(own.baselines);
1141
+ const nowMs = Date.parse(nowIso);
1142
+ // the playbooks a person's window names as open, per the judgement that allowed this build (same root, same time)
1143
+ const open = openPlaybooksNow !== null && openPlaybooksNow.root === root && openPlaybooksNow.nowMs === nowMs ? openPlaybooksNow.files : new Set();
1144
+ openPlaybooksNow = null; // one use: a later record does not read what this judgement found
1145
+ const fileOf = (name) => `playbooks/${name}/PLAYBOOK.md`;
1146
+ const since = latest?.seq ?? -1;
1147
+ // review A (H1) — a window row anchors only when it was recorded after the baseline in force and its window is open
1148
+ // now: the reference moves forward only (an earlier version's row, or a draft a closed window once saw, anchors nothing)
1149
+ const seenNow = (name, digest) => open.has(fileOf(name))
1150
+ && own.windows.some((w) => w.seq > since && w.file === fileOf(name) && w.sha256 === digest);
1151
+ const now = reference.playbookDigestInputs(root);
1152
+ const nameAndDigest = (i) => i.split(':').slice(1);
1153
+ // A digest rides on the row by one of two ways, and no other (review A, the no-substitution contract): it is the
1154
+ // one this chain's latest digest-bearing row carried, or a person's window of this chain names the playbook now
1155
+ // and a window row after the baseline holds these bytes. There is no bootstrap from a commit and no rule that
1156
+ // "any person's seal" suffices: a chain's first digests are made by a window that names the playbooks. Git is not
1157
+ // read for any of it.
1158
+ const anchored = new Set(now.map(nameAndDigest).filter(([n, d]) => seenNow(n, d)).map(([n]) => n));
1159
+ // a playbook the earlier row carried and the tree no longer holds is carried on, unless a window names its removal
1160
+ const removed = new Set((earlier?.playbooks ?? []).map((i) => i.split(':')[1]).filter((n) => open.has(fileOf(n))));
1161
+ const playbooks = reference.anchoredPlaybookInputs(now, earlier?.playbooks ?? [], anchored, removed);
1162
+ // once a row carried digests every row carries them: with nothing to carry and nothing anchored (every earlier
1163
+ // playbook removed under a window, none anchored) no row is written. A chain that never had digests keeps its
1164
+ // commit-only row — principle 7's own baseline — and the reader says the reference is not made yet.
1165
+ if (earlier !== null && playbooks.length === 0)
1166
+ return; // [no-substitution: no digests to write → no row]
1167
+ // A-SPEC-794.97 r4b (L1) — HEAD is already the baseline (an older row stays the baseline, which only judges more);
1168
+ // A-SPEC-794.110 — and it carries these very digests
1169
+ if (latest !== null && latest.commit === head && latest.playbooks.join('\n') === playbooks.join('\n'))
1170
+ return;
1171
+ const { FileLedgerStore } = require('./ledger-store');
1172
+ new FileLedgerStore(path.join(root, '.ax', 'ledger')).append({ ts: nowIso, actor: 'holmes-kit', kind: 'principle7-baseline',
1173
+ summary: `the live gate is built from ${head.slice(0, 12)}`, inputs: [`commit:${head}`, ...playbooks], rationale: 'principle 7 baseline' });
1174
+ }
1175
+ catch { /* [no-substitution: the record failed → no row; the next judgement keeps the earlier baseline and reference] */ }
1176
+ });
1177
+ }
87
1178
  const TAINT_MARKERS = ['taint', 'dataflow-taint', 'flow-sensitive'];
88
1179
  // @implements A-SPEC-556.1 — the grader must judge a token by what it can ADMIT, to the same
89
1180
  // standard as the enforcer `matchesFtt` (globs expand, prose imposes nothing). Case is folded: a NEW
@@ -91,7 +1182,21 @@ const TAINT_MARKERS = ['taint', 'dataflow-taint', 'flow-sensitive'];
91
1182
  // case-insensitive FS. A glob is high-risk when its literal prefix OVERLAPS a risk root in either
92
1183
  // direction (`src/holmes/**` reaches the gate; `src/holmes/hooks/*` is inside it) — over-inclusive on
93
1184
  // purpose, because a glob spanning the gate surface must never self-approve.
94
- const GLOB_RISK_ROOTS = [...HIGH_RISK_PREFIXES, 'src/holmes/rtm/'];
1185
+ const GLOB_RISK_ROOTS = [...HIGH_RISK_PREFIXES, 'src/holmes/rtm/', 'dist/holmes/'];
1186
+ /** @implements A-SPEC-794.91 (M-a) — the built gate's root, compared both ways like the source roots (794.89). */
1187
+ const BUILT_GATE_ROOT = 'dist/holmes/';
1188
+ /**
1189
+ * @implements A-SPEC-794.91 (M-b) — a root-level token that is project-wide configuration: any root file but a Markdown
1190
+ * document, and of those the agent instruction files (AGENTS.md, CLAUDE.md, GEMINI.md) are configuration too.
1191
+ */
1192
+ function rootConfigToken(token) {
1193
+ const t = token.replace(/^["'`]|["'`]$/g, '').replace(/^(\.\/)+/, '');
1194
+ if (t.includes('/'))
1195
+ return false;
1196
+ if (!/\.md$/i.test(t))
1197
+ return true;
1198
+ return /^(?:agents|claude|gemini)\.md$/i.test(t);
1199
+ }
95
1200
  function isHighRiskPath(p) {
96
1201
  // @implements A-SPEC-569.4 — '.' segments fold BEFORE the verdict: `src/holmes/./governance/x`
97
1202
  // dodged every prefix check while naming the gate surface exactly (REQ-556's remaining edge).
@@ -112,13 +1217,22 @@ function isHighRiskPath(p) {
112
1217
  const s = raw.toLowerCase();
113
1218
  if (HIGH_RISK_PREFIXES.some((pre) => s.startsWith(pre)))
114
1219
  return true;
1220
+ // @implements A-SPEC-794.89 — a token naming a directory at or above a gate root admits the root's files too
1221
+ // (`src/holmes/hooks`, `src/holmes/`, `src`): the comparison runs both ways, as the enforcer's admission does
1222
+ const dir = s.replace(/\/+$/, '');
1223
+ if (dir !== '' && [...HIGH_RISK_PREFIXES, BUILT_GATE_ROOT].some((pre) => pre.startsWith(`${dir}/`) || pre.replace(/\/+$/, '') === dir))
1224
+ return true;
1225
+ // the built gate is the gate (A-SPEC-794.89)
1226
+ if (s.startsWith('dist/holmes/'))
1227
+ return true;
115
1228
  if (s === '.mcp.json' || s.endsWith('/.mcp.json'))
116
1229
  return true;
117
1230
  // A taint/security boundary file anywhere under rtm/ — the flow engine and its vocabulary.
118
1231
  if (s.startsWith('src/holmes/rtm/') && TAINT_MARKERS.some((m) => s.includes(m)))
119
1232
  return true;
120
- if (raw.includes('*')) {
121
- const litPrefix = s.split('*')[0];
1233
+ // A-SPEC-794.89 — a brace or bracket expansion is read like a glob: its literal prefix
1234
+ if (/[*{[?]/.test(raw)) {
1235
+ const litPrefix = s.split(/[*{[?]/)[0];
122
1236
  if (GLOB_RISK_ROOTS.some((pre) => litPrefix.startsWith(pre) || pre.startsWith(litPrefix)))
123
1237
  return true;
124
1238
  }
@@ -201,6 +1315,8 @@ function autonomyRuleMeaning(rule) {
201
1315
  case 'upstream-has-human-aspec': return 'an A-SPEC beneath it is the operator\'s to seal';
202
1316
  case 'architecture-document': return 'a C-SPEC or ADR is a decision';
203
1317
  case 'files-to-touch-empty': return 'Files to Touch names no path, so its scope is unbounded';
1318
+ // A-SPEC-794.91 (M-b) also returns this rule for a root configuration file mixed into a directory scope; the meaning's
1319
+ // text is pinned by tests outside 794.91's Files to Touch, so it stays (named in the commit as a wording limit)
204
1320
  case 'files-to-touch-root-only': return 'Files to Touch names only root-level files';
205
1321
  case 'requirement-without-intake': return 'the requirement was never admitted through requirement_triage';
206
1322
  default: return 'the spec kind is not one the grader knows';
@@ -265,7 +1381,9 @@ function specApprovalAutonomyReason(spec, resolveParent, descendants) {
265
1381
  if (paths.length === 0)
266
1382
  return 'files-to-touch-empty';
267
1383
  const gateFile = paths.find(isHighRiskPath);
268
- if (gateFile !== undefined && !directed)
1384
+ // @implements A-SPEC-794.88 — principle 7 (owner decision Q4(b), 11/10): a gate file goes to a person whatever
1385
+ // direction is declared; the declared grade may still pass the grade rule for a change outside the category
1386
+ if (gateFile !== undefined)
269
1387
  return `files-to-touch-gate-file: ${gateFile}`; // gate/governance/taint file
270
1388
  // @implements A-SPEC-654 — a ROOT-level file is project-wide configuration (the test runner, the
271
1389
  // manifest, the ignore policy): admitting it at the gate was the point of that slice, but grading
@@ -273,6 +1391,9 @@ function specApprovalAutonomyReason(spec, resolveParent, descendants) {
273
1391
  // a directory-scoped surface — the same doubt `paths.length === 0` already encodes.
274
1392
  if (!paths.some((p) => p.includes('/')))
275
1393
  return 'files-to-touch-root-only';
1394
+ // @implements A-SPEC-794.91 (M-b) — a root configuration file mixed into a directory scope is the same widening
1395
+ if (paths.some(rootConfigToken))
1396
+ return 'files-to-touch-root-only';
276
1397
  return null;
277
1398
  }
278
1399
  default: