@holmes-lab/holmes-kit 0.35.17 → 0.35.19

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 (35) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +4 -2
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-status.d.ts +4 -1
  5. package/dist/holmes/cli/approve-status.js +10 -0
  6. package/dist/holmes/cli/approve-watch.js +4 -0
  7. package/dist/holmes/cli/approve.d.ts +9 -2
  8. package/dist/holmes/cli/approve.js +33 -9
  9. package/dist/holmes/cli/autonomy.d.ts +13 -6
  10. package/dist/holmes/cli/autonomy.js +105 -16
  11. package/dist/holmes/cli/doctor.js +21 -3
  12. package/dist/holmes/cli/index.js +33 -9
  13. package/dist/holmes/cli/init.js +3 -1
  14. package/dist/holmes/cli/interactive-prompt.d.ts +5 -0
  15. package/dist/holmes/cli/interactive-prompt.js +12 -4
  16. package/dist/holmes/cli/runtime-binding.d.ts +23 -1
  17. package/dist/holmes/cli/runtime-binding.js +117 -5
  18. package/dist/holmes/governance/approval-queue.d.ts +7 -1
  19. package/dist/holmes/governance/approval-queue.js +34 -3
  20. package/dist/holmes/governance/autonomy.d.ts +0 -2
  21. package/dist/holmes/governance/autonomy.js +27 -5
  22. package/dist/holmes/governance/delegation.d.ts +40 -0
  23. package/dist/holmes/governance/delegation.js +151 -0
  24. package/dist/holmes/guardrail/write-target.d.ts +10 -0
  25. package/dist/holmes/guardrail/write-target.js +82 -0
  26. package/dist/holmes/hooks/pre-tool-use.d.ts +3 -1
  27. package/dist/holmes/hooks/pre-tool-use.js +22 -4
  28. package/dist/holmes/hooks/stop-timing.d.ts +12 -0
  29. package/dist/holmes/hooks/stop-timing.js +22 -0
  30. package/dist/holmes/hooks/stop.js +28 -0
  31. package/dist/holmes/mcp/handlers/spec-approval.d.ts +1 -1
  32. package/dist/holmes/mcp/handlers/spec-approval.js +21 -2
  33. package/dist/holmes/mcp/handlers.d.ts +5 -5
  34. package/dist/holmes/runtime/dispatch.js +28 -3
  35. package/package.json +1 -1
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.RUN_ID_RE = exports.NEVER_DELEGABLE = exports.DELEGABLE_RULES = exports.DELEGATION_SCHEMA = exports.DELEGATION_MARKER = void 0;
37
+ exports.baseRule = baseRule;
38
+ exports.readDelegation = readDelegation;
39
+ exports.delegationCovers = delegationCovers;
40
+ exports.delegationNote = delegationNote;
41
+ exports.writeDelegation = writeDelegation;
42
+ exports.removeDelegation = removeDelegation;
43
+ // @implements A-SPEC-771
44
+ // The run delegation — the third autonomy envelope. Measured need (X1, 2026-10-12): a benchmark fixture the operator
45
+ // had approved as a whole still stopped on `upstream-has-human-aspec: … — files-to-touch-root-only`, because neither
46
+ // the project default (A-SPEC-552.1) nor the session marker (A-SPEC-553.1) can name a run, a workspace boundary or a
47
+ // grader rule. This document can. It is written only by the operator CLI under operator proof, lives under the
48
+ // protected state directory an agent cannot write, binds to the workspace by realpath, expires, and covers a CLOSED
49
+ // set of grader rules — never the NEVER set. The grader itself is untouched: this module only answers "does the
50
+ // operator's delegation cover the rule the grader named?".
51
+ const fs = __importStar(require("node:fs"));
52
+ const path = __importStar(require("node:path"));
53
+ exports.DELEGATION_MARKER = ['.ax', 'state', 'delegation.json'];
54
+ exports.DELEGATION_SCHEMA = 'run-delegation/1';
55
+ /** Grader rules an operator may delegate for a run (bare names; a suffixed rule is matched by its bare name). */
56
+ exports.DELEGABLE_RULES = [
57
+ 'files-to-touch-root-only', 'files-to-touch-gate-file', 'breaking-change-gate-behavior', 'upstream-without-aspec',
58
+ ];
59
+ /** Never delegable, whatever the document says: a decision, an un-admitted requirement, an undeclared or unknown grade. */
60
+ exports.NEVER_DELEGABLE = [
61
+ 'architecture-document', 'requirement-without-intake', 'breaking-change-undeclared', 'unknown-kind',
62
+ ];
63
+ exports.RUN_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
64
+ /** The bare rule name a grader reason resolves to: the child rule of an upstream reason, with any `: <argument>` dropped. */
65
+ function baseRule(rule) {
66
+ const upstream = /^upstream-has-human-aspec: \S+ — (.+)$/.exec(rule);
67
+ const inner = upstream ? upstream[1] : rule;
68
+ return inner.split(':')[0].trim();
69
+ }
70
+ function realpathOrNull(p) {
71
+ try {
72
+ return fs.realpathSync.native(p);
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ /** Read the document for `root` as it stands at `now`. Fail-closed: anything unreadable or malformed grants nothing. */
79
+ function readDelegation(root, now) {
80
+ const file = path.join(root, ...exports.DELEGATION_MARKER);
81
+ let raw;
82
+ try {
83
+ raw = fs.readFileSync(file, 'utf8');
84
+ }
85
+ catch (e) {
86
+ return e.code === 'ENOENT' ? { active: false, why: 'none' } : { active: false, why: 'unreadable' };
87
+ }
88
+ let doc;
89
+ try {
90
+ doc = JSON.parse(raw);
91
+ }
92
+ catch {
93
+ return { active: false, why: 'unreadable' };
94
+ }
95
+ if (!doc || typeof doc !== 'object')
96
+ return { active: false, why: 'invalid' };
97
+ const d = doc;
98
+ const str = (v) => typeof v === 'string' && v.trim() !== '';
99
+ if (d.schema !== exports.DELEGATION_SCHEMA || !str(d.run) || !exports.RUN_ID_RE.test(d.run) || !str(d.workspace) || !str(d.expires) || !str(d.issuedBy) || !Array.isArray(d.allow)) {
100
+ return { active: false, why: 'invalid' };
101
+ }
102
+ const allow = d.allow.filter((a) => typeof a === 'string');
103
+ if (allow.length !== d.allow.length || allow.length === 0)
104
+ return { active: false, why: 'invalid' };
105
+ // A NEVER rule anywhere in `allow` voids the document: the CLI never writes one, so its presence is a forgery or a
106
+ // hand edit, and a forged document must not cover even the rules it names correctly.
107
+ if (allow.some((a) => !exports.DELEGABLE_RULES.includes(a)))
108
+ return { active: false, why: 'invalid' };
109
+ const exp = Date.parse(d.expires);
110
+ const nowMs = Date.parse(now);
111
+ if (!Number.isFinite(exp) || !Number.isFinite(nowMs) || nowMs >= exp)
112
+ return { active: false, why: 'expired', expires: d.expires, run: d.run };
113
+ const here = realpathOrNull(root);
114
+ const there = realpathOrNull(d.workspace);
115
+ if (here === null || there === null || here !== there)
116
+ return { active: false, why: 'workspace-mismatch', workspace: d.workspace, run: d.run };
117
+ return { active: true, delegation: { schema: exports.DELEGATION_SCHEMA, run: d.run, workspace: d.workspace, allow, issuedAt: str(d.issuedAt) ? d.issuedAt : '', expires: d.expires, issuedBy: d.issuedBy,
118
+ ...(d.limits && typeof d.limits === 'object' ? { limits: d.limits } : {}), ...(str(d.rationale) ? { rationale: d.rationale } : {}) } };
119
+ }
120
+ /** Whether an active delegation covers the grader reason `rule` (its bare name must be delegable and in `allow`). */
121
+ function delegationCovers(d, rule) {
122
+ const bare = baseRule(rule);
123
+ if (exports.NEVER_DELEGABLE.includes(bare) || !exports.DELEGABLE_RULES.includes(bare))
124
+ return false;
125
+ return d.allow.includes(bare);
126
+ }
127
+ /** The one refusal line that names which limit of the delegation applied (empty when there is no document). */
128
+ function delegationNote(state, rule) {
129
+ if (state.active)
130
+ return delegationCovers(state.delegation, rule) ? '' : `\n[delegation: run ${state.delegation.run} does not cover ${rule}]`;
131
+ switch (state.why) {
132
+ case 'none': return '';
133
+ case 'expired': return `\n[delegation: expired ${state.expires ?? '?'}]`;
134
+ case 'workspace-mismatch': return `\n[delegation: for ${state.workspace ?? '?'}, not this root]`;
135
+ case 'unreadable': return '\n[delegation: unreadable document — covers nothing]';
136
+ case 'invalid': return '\n[delegation: invalid document (schema, run id, expiry or a rule outside the delegable set) — covers nothing]';
137
+ }
138
+ }
139
+ /** Write the document for the CLI (operator proof is the caller's job). Returns the written document. */
140
+ function writeDelegation(root, d) {
141
+ const file = path.join(root, ...exports.DELEGATION_MARKER);
142
+ fs.mkdirSync(path.dirname(file), { recursive: true });
143
+ fs.writeFileSync(file, JSON.stringify(d, null, 2) + '\n');
144
+ }
145
+ /** Remove the document; true when one was there. Never throws on absence. */
146
+ function removeDelegation(root) {
147
+ const file = path.join(root, ...exports.DELEGATION_MARKER);
148
+ const existed = fs.existsSync(file);
149
+ fs.rmSync(file, { force: true });
150
+ return existed;
151
+ }
@@ -94,6 +94,16 @@ export declare function patchAmbiguous(text: string): boolean;
94
94
  * pattern over the whole text, nothing to back-track on.
95
95
  */
96
96
  export declare function canonicalPatch(text: string): boolean;
97
+ /**
98
+ * @implements A-SPEC-769.7 — WHY a text is not canonical, for the refusal that names it. `null` when `canonicalPatch`
99
+ * is true; `'no-op'` when every grammar rule holds and the only fault is an update block with no `+`/`-` line (the
100
+ * X1 HB negative control, 2026-10-13: a context-only `apply_patch` was refused as "file_path missing" although its
101
+ * header named the file); `'grammar'` for every other shape. Invariant pinned by its test: `canonicalPatch(t) ===
102
+ * (canonicalPatchReason(t) === null)`. The walk is the same walk as `canonicalPatch`, with one difference: an update
103
+ * block that closes with zero content lines is counted instead of refused, and an add block that adds nothing stays a
104
+ * grammar fault (an add must add). This function changes no gate decision — only the reason text a caller prints.
105
+ */
106
+ export declare function canonicalPatchReason(text: string): null | 'no-op' | 'grammar';
97
107
  /** Every header is a target, in order; nothing is merged or dropped by path (A-SPEC-163.2 rule 2). */
98
108
  export declare function patchTargetsOf(text: string): PatchTarget[];
99
109
  /**
@@ -41,6 +41,7 @@ exports.hasPatchEnvelope = hasPatchEnvelope;
41
41
  exports.isWholePatch = isWholePatch;
42
42
  exports.patchAmbiguous = patchAmbiguous;
43
43
  exports.canonicalPatch = canonicalPatch;
44
+ exports.canonicalPatchReason = canonicalPatchReason;
44
45
  exports.patchTargetsOf = patchTargetsOf;
45
46
  exports.applyPatchUpdate = applyPatchUpdate;
46
47
  exports.applyPatchUpdateDetailed = applyPatchUpdateDetailed;
@@ -315,6 +316,87 @@ function canonicalPatch(text) {
315
316
  }
316
317
  return block !== null && closes();
317
318
  }
319
+ /**
320
+ * @implements A-SPEC-769.7 — WHY a text is not canonical, for the refusal that names it. `null` when `canonicalPatch`
321
+ * is true; `'no-op'` when every grammar rule holds and the only fault is an update block with no `+`/`-` line (the
322
+ * X1 HB negative control, 2026-10-13: a context-only `apply_patch` was refused as "file_path missing" although its
323
+ * header named the file); `'grammar'` for every other shape. Invariant pinned by its test: `canonicalPatch(t) ===
324
+ * (canonicalPatchReason(t) === null)`. The walk is the same walk as `canonicalPatch`, with one difference: an update
325
+ * block that closes with zero content lines is counted instead of refused, and an add block that adds nothing stays a
326
+ * grammar fault (an add must add). This function changes no gate decision — only the reason text a caller prints.
327
+ */
328
+ function canonicalPatchReason(text) {
329
+ const lines = text.split('\n').map(unCR);
330
+ let start = 0;
331
+ let end = lines.length;
332
+ while (start < end && lines[start].trim() === '')
333
+ start++;
334
+ while (end > start && lines[end - 1].trim() === '')
335
+ end--;
336
+ if (end - start < 3 || lines[start] !== PATCH_BEGIN || lines[end - 1] !== PATCH_END)
337
+ return 'grammar';
338
+ let block = null;
339
+ let content = 0;
340
+ let sinceHeader = 0;
341
+ let moved = false;
342
+ let emptyUpdates = 0;
343
+ const closes = () => {
344
+ if (block === 'update' && content === 0) {
345
+ emptyUpdates++;
346
+ return true;
347
+ }
348
+ return block === null || block === 'delete' || content > 0;
349
+ };
350
+ for (let i = start + 1; i < end - 1; i++) {
351
+ const line = lines[i];
352
+ if (PATCH_LINE_BREAK.test(line))
353
+ return 'grammar';
354
+ if (line === PATCH_BEGIN || line === PATCH_END)
355
+ return 'grammar';
356
+ if (line.startsWith('*** ')) {
357
+ if (line === PATCH_EOF) {
358
+ if (block !== 'update')
359
+ return 'grammar';
360
+ sinceHeader++;
361
+ continue;
362
+ }
363
+ if (line.startsWith(PATCH_MOVE)) {
364
+ if (block !== 'update' || sinceHeader !== 0 || moved || !canonicalPath(line.slice(PATCH_MOVE.length)))
365
+ return 'grammar';
366
+ moved = true;
367
+ sinceHeader++;
368
+ continue;
369
+ }
370
+ const header = PATCH_FILE_HEADERS.find(([prefix]) => line.startsWith(prefix));
371
+ if (header === undefined || !canonicalPath(line.slice(header[0].length)) || !closes())
372
+ return 'grammar';
373
+ block = header[1];
374
+ content = 0;
375
+ sinceHeader = 0;
376
+ moved = false;
377
+ continue;
378
+ }
379
+ if (block === 'add') {
380
+ if (!line.startsWith('+'))
381
+ return 'grammar';
382
+ content++;
383
+ continue;
384
+ }
385
+ if (block !== 'update')
386
+ return 'grammar';
387
+ sinceHeader++;
388
+ if (line === '@@' || line.startsWith('@@ '))
389
+ continue;
390
+ const head = line.charAt(0);
391
+ if (head === '+' || head === '-')
392
+ content++;
393
+ else if (head !== ' ')
394
+ return 'grammar';
395
+ }
396
+ if (block === null || !closes())
397
+ return 'grammar';
398
+ return emptyUpdates > 0 ? 'no-op' : null;
399
+ }
318
400
  /** Every header is a target, in order; nothing is merged or dropped by path (A-SPEC-163.2 rule 2). */
319
401
  function patchTargetsOf(text) {
320
402
  if (!text.includes('*** '))
@@ -94,7 +94,9 @@ export interface HookInput {
94
94
  /** @implements A-SPEC-163.2 — the payload carries a patch whose targets cannot be read one way; denied whichever tool sent it. */
95
95
  patchUnreadable?: boolean;
96
96
  /** @implements A-SPEC-163.7 — set only when the one cause is a marked shell command (A-SPEC-163.6 rule 3). */
97
- patchUnreadableCause?: 'shell-marker';
97
+ /** @implements A-SPEC-769.7 — `'no-op'`: the one cause is an update block with no `+`/`-` line; the paths are named. */
98
+ patchUnreadableCause?: 'shell-marker' | 'no-op';
99
+ patchNoopPaths?: string[];
98
100
  }
99
101
  /**
100
102
  * @implements A-SPEC-753.2 — what a denial leaves in the provenance ledger: the reason up to the operator command.
@@ -955,6 +955,9 @@ const PATCH_UNREADABLE_REASON = '[Holmes-Kit] cannot read the edit target path,
955
955
  // @implements A-SPEC-768.2 — a patch the tool could not apply is told so, by file and chunk; measured 2026-10-11 (H0 arm)
956
956
  // the path-missing sentence above was returned for a readable file whose patch simply did not apply.
957
957
  const patchNotAppliedReason = (file, why) => `[Holmes-Kit] the patch does not apply to ${file} as it stands (${why}), so the result cannot be judged`;
958
+ // @implements A-SPEC-769.7 — a context-only update is refused by its own name (measured 2026-10-13, X1 HB control: the
959
+ // path-missing sentence was printed for a patch whose header named the file). The deny is unchanged; the reason is not.
960
+ const patchNoopReason = (files) => `[Holmes-Kit] the patch to ${files.join(', ')} adds or removes no line (a context-only update is a no-op), so there is nothing to judge — include at least one + or - line`;
958
961
  // @implements A-SPEC-163.7 — the refusal of A-SPEC-163.6 rule 3 in its own words (each refusal names its channel, A-SPEC-737).
959
962
  const SHELL_MARKED_REASON = '[Holmes-Kit] this shell command mentions the patch tool or a patch marker and is not one plain read, so it is not judged — '
960
963
  + 'search with the harness\'s own search tool, or run one plain grep, egrep, fgrep, rg, cat, head, tail, wc or ls with literal words (no pipe, redirect or substitution)';
@@ -1032,6 +1035,7 @@ function normalizeHookInput(raw) {
1032
1035
  // A patch that cannot be read one way (no target, an empty path, too many, an indented header) is unreadable.
1033
1036
  const toolName = (str(r.tool_name) ?? '').toLowerCase();
1034
1037
  let patchUnreadable = false;
1038
+ let noopPaths = null; // @implements A-SPEC-769.7
1035
1039
  // @implements A-SPEC-163.7 — why: a shell command refused for a patch marker is told so (it has no file path to miss).
1036
1040
  let shellMarked = false;
1037
1041
  let otherUnreadable = false;
@@ -1078,13 +1082,22 @@ function normalizeHookInput(raw) {
1078
1082
  if (targets.length === 0 || targets.length > write_target_1.PATCH_TARGETS_MAX || patches.some((text) => !(0, write_target_1.canonicalPatch)(text))) {
1079
1083
  patchUnreadable = true;
1080
1084
  otherUnreadable = true;
1085
+ // @implements A-SPEC-769.7 — when the targets are readable and the only fault is a context-only update block,
1086
+ // the refusal names that condition and those paths instead of a missing path.
1087
+ if (targets.length > 0 && targets.length <= write_target_1.PATCH_TARGETS_MAX) {
1088
+ const reasons = patches.map(write_target_1.canonicalPatchReason);
1089
+ if (reasons.every((why) => why === null || why === 'no-op') && reasons.includes('no-op')) {
1090
+ noopPaths = targets.filter((t) => t.kind === 'update' && !/^[+-]/m.test(t.hunk ?? '')).map((t) => t.path);
1091
+ }
1092
+ }
1081
1093
  }
1082
1094
  else
1083
1095
  out.patch_targets = targets;
1084
1096
  }
1085
1097
  }
1086
1098
  return { tool_name: str(r.tool_name) ?? '', tool_input: out, ...(cwd === undefined ? {} : { cwd }), ...(malformed ? { malformed: true } : {}),
1087
- ...(patchUnreadable ? { patchUnreadable: true } : {}), ...(shellMarked && !otherUnreadable ? { patchUnreadableCause: 'shell-marker' } : {}) };
1099
+ ...(patchUnreadable ? { patchUnreadable: true } : {}), ...(shellMarked && !otherUnreadable ? { patchUnreadableCause: 'shell-marker' } : {}),
1100
+ ...(noopPaths !== null && !shellMarked ? { patchUnreadableCause: 'no-op', patchNoopPaths: noopPaths } : {}) };
1088
1101
  }
1089
1102
  /**
1090
1103
  * Which way to fail when the gate itself throws.
@@ -1236,8 +1249,11 @@ function evaluateHook(input, specsDir, opts) {
1236
1249
  // a patch that cannot be read or applied is denied. When no target is denied, a payload with a path field or a
1237
1250
  // shell command is then judged as before.
1238
1251
  if (input.patchUnreadable) {
1239
- return { permissionDecision: 'deny', permissionDecisionReason: input.patchUnreadableCause === 'shell-marker'
1240
- ? SHELL_MARKED_REASON : PATCH_UNREADABLE_REASON };
1252
+ const cause = input;
1253
+ // @implements A-SPEC-769.7 — four conditions, four sentences: shell marker, no-op update, and (below) the
1254
+ // path-missing sentence for a payload whose targets cannot be read; non-application has its own site.
1255
+ return { permissionDecision: 'deny', permissionDecisionReason: cause.patchUnreadableCause === 'shell-marker'
1256
+ ? SHELL_MARKED_REASON : cause.patchUnreadableCause === 'no-op' ? patchNoopReason(cause.patchNoopPaths ?? []) : PATCH_UNREADABLE_REASON };
1241
1257
  }
1242
1258
  const patchTargets = input.tool_input.patch_targets;
1243
1259
  if (patchTargets !== undefined && !input.malformed) {
@@ -2598,7 +2614,9 @@ function evaluateHook(input, specsDir, opts) {
2598
2614
  if (!hint) {
2599
2615
  const id = (0, approval_queue_1.approvalRequestId)('code-write', relPath);
2600
2616
  if ((0, approval_queue_1.readQueue)(projectRoot).pending.some((request) => request.id === id)) {
2601
- hint = (0, approval_queue_1.pendingRequestLine)(id);
2617
+ // @implements A-SPEC-770.2 — the already-pending line names the same kind and workspace the filing line
2618
+ // did, so the two refusals of one request read the same (gate-isolation pins their equality).
2619
+ hint = (0, approval_queue_1.pendingRequestLine)(id, 'code-write', projectRoot);
2602
2620
  }
2603
2621
  }
2604
2622
  return {
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The Stop hook's stage clock. Measured 2026-10-12 (X1): the Stop hook took 11.3 s at load 5 against the
3
+ * dispatcher's 18 s budget (A-SPEC-751.1), and a deadline refusal said nothing about which stage took the time.
4
+ * `mark(name)` closes the stage that ran since the previous mark; `line(budget)` names every stage with its
5
+ * milliseconds when the stages together used at least `threshold` (default half) of the budget, else `null`.
6
+ * Pure: no I/O, no clock of its own beyond the injected `now`. It never touches the verdict.
7
+ */
8
+ export interface StageClock {
9
+ mark(name: string): void;
10
+ line(budgetMs: number, threshold?: number): string | null;
11
+ }
12
+ export declare function createStageClock(now?: () => number): StageClock;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createStageClock = createStageClock;
4
+ function createStageClock(now = () => performance.now()) {
5
+ const stages = [];
6
+ let last = now();
7
+ return {
8
+ mark(name) {
9
+ const t = now();
10
+ stages.push({ name, ms: Math.max(0, t - last) });
11
+ last = t;
12
+ },
13
+ line(budgetMs, threshold = 0.5) {
14
+ if (stages.length === 0)
15
+ return null;
16
+ const total = stages.reduce((sum, s) => sum + s.ms, 0);
17
+ if (total < budgetMs * threshold)
18
+ return null;
19
+ return `[Holmes-Kit] Stop hook used ${Math.round(total)} ms of its ${budgetMs} ms hook budget — ${stages.map((s) => `${s.name} ${Math.round(s.ms)} ms`).join(', ')}`;
20
+ },
21
+ };
22
+ }
@@ -74,6 +74,9 @@ const autonomy_1 = require("../governance/autonomy");
74
74
  const risk_gate_1 = require("../guardrail/risk-gate");
75
75
  const json_state_1 = require("../project/json-state");
76
76
  const node_child_process_1 = require("node:child_process");
77
+ // @implements A-SPEC-769.2 — the stage clock and the budget it is measured against.
78
+ const stop_timing_1 = require("./stop-timing");
79
+ const hook_process_1 = require("../runtime/hook-process");
77
80
  /**
78
81
  * @implements A-SPEC-734 (round 11) — every git child of the Stop hook runs under a timeout, and a timeout or
79
82
  * failure is "no signal": a FIFO `.gitignore` (or a FIFO in place of a tracked file) kept `git status` blocked
@@ -1340,6 +1343,9 @@ if (require.main === module) {
1340
1343
  process.stdin.on('end', () => {
1341
1344
  try {
1342
1345
  const input = JSON.parse(buf || '{}');
1346
+ // @implements A-SPEC-769.2 — stage marks sit OUTSIDE every try block below, so a stage that throws is still closed
1347
+ // by the next mark; the line is printed once the verdict is decided and never touches it.
1348
+ const clock = (0, stop_timing_1.createStageClock)();
1343
1349
  const sessionId = typeof input.session_id === 'string' ? input.session_id : 'unknown-session';
1344
1350
  // @implements A-SPEC-190 (round 8) — same wiring channel as the PreToolUse hook.
1345
1351
  const { wiredSpecsDir } = require('./pre-tool-use');
@@ -1402,6 +1408,7 @@ if (require.main === module) {
1402
1408
  catch {
1403
1409
  testCasesByAspec = undefined;
1404
1410
  }
1411
+ clock.mark('specs');
1405
1412
  // EXECUTION evidence (ART-4 upgrade): usable only when produced at the CURRENT git HEAD, so a
1406
1413
  // stale record can never vouch for changed code. Absent/stale -> syntactic fallback.
1407
1414
  let executedByAspec;
@@ -1437,6 +1444,7 @@ if (require.main === module) {
1437
1444
  changedAspecs = undefined;
1438
1445
  outcomesByAspec = undefined;
1439
1446
  }
1447
+ clock.mark('evidence');
1440
1448
  // @implements A-SPEC-574.4 — the code graph's acyclicity, judged where the code exists. The
1441
1449
  // scan is the same one every other layer uses; the classification reads only the files an
1442
1450
  // import edge starts from. Fail-open in every direction: any error leaves the article silent,
@@ -1452,6 +1460,7 @@ if (require.main === module) {
1452
1460
  catch {
1453
1461
  sharedScan = undefined;
1454
1462
  }
1463
+ clock.mark('scan');
1455
1464
  // Its OWN try, like the observation below: a fault in the architecture judgement must not
1456
1465
  // discard the cycle evidence, nor the other way round.
1457
1466
  let forbiddenEdges;
@@ -1493,6 +1502,7 @@ if (require.main === module) {
1493
1502
  catch {
1494
1503
  cycles = undefined;
1495
1504
  }
1505
+ clock.mark('cycles');
1496
1506
  // Provenance-chain verification (fail-open: a verify error skips the check, never crashes).
1497
1507
  let provenance;
1498
1508
  // @implements A-SPEC-148
@@ -1509,6 +1519,7 @@ if (require.main === module) {
1509
1519
  catch {
1510
1520
  provenance = undefined;
1511
1521
  }
1522
+ clock.mark('provenance');
1512
1523
  // @implements A-SPEC-160 — supply the findings ledger so ART-6 can see judgements sealed on a
1513
1524
  // diverged server. An article nobody feeds is a dead article; ADR-014's discipline applies to
1514
1525
  // the constitution too.
@@ -1527,6 +1538,7 @@ if (require.main === module) {
1527
1538
  const unrecorded = unrecordedApprovals(stopProjectRoot());
1528
1539
  // @implements A-SPEC-455
1529
1540
  const rolledBack = rolledBackLedgers(stopProjectRoot());
1541
+ clock.mark('ledgers');
1530
1542
  // @implements A-SPEC-564.2 — the Claude usage enrichment: numbers out of transcript_path into
1531
1543
  // the session-context ledger, once per session. Capability-declared: Codex/AGY pass no
1532
1544
  // transcript_path and skip silently. Fail-open around EVERYTHING — observation never touches
@@ -1556,6 +1568,7 @@ if (require.main === module) {
1556
1568
  }
1557
1569
  }
1558
1570
  catch { /* silent skip — the other harnesses' path, and any read failure, land here */ }
1571
+ clock.mark('usage');
1559
1572
  // @implements A-SPEC-566.4 — graph freshness rides the same turn boundary, detached and
1560
1573
  // TTL-gated (A-SPEC-547.2's idiom): staleness was MEASURED to be the advisory's quality
1561
1574
  // factor (7 findings on an 8-day graph, 17 after a 1s reindex). Never waits, never judges.
@@ -1569,8 +1582,10 @@ if (require.main === module) {
1569
1582
  });
1570
1583
  }
1571
1584
  catch { /* maintenance, never a hook failure */ }
1585
+ clock.mark('refresh');
1572
1586
  // @implements A-SPEC-660 — the marker walk: no signal when it cannot run (never a clean verdict).
1573
1587
  const knownDefects = collectKnownDefects(stopProjectRoot(), new Date());
1588
+ clock.mark('defects');
1574
1589
  // @implements A-SPEC-664 — the CI matrix line rides beside the constitution's verdict.
1575
1590
  let ci;
1576
1591
  try {
@@ -1579,6 +1594,7 @@ if (require.main === module) {
1579
1594
  catch {
1580
1595
  ci = undefined;
1581
1596
  }
1597
+ clock.mark('ci');
1582
1598
  // @implements A-SPEC-673 — the build-freshness line rides the same non-blocking channel.
1583
1599
  let dist;
1584
1600
  try {
@@ -1587,6 +1603,7 @@ if (require.main === module) {
1587
1603
  catch {
1588
1604
  dist = undefined;
1589
1605
  }
1606
+ clock.mark('dist');
1590
1607
  // @implements A-SPEC-681 — the analysis line rides the same non-blocking channel.
1591
1608
  let analysis;
1592
1609
  try {
@@ -1595,6 +1612,7 @@ if (require.main === module) {
1595
1612
  catch {
1596
1613
  analysis = undefined;
1597
1614
  }
1615
+ clock.mark('analysis');
1598
1616
  // @implements A-SPEC-683 — read-only: the refresh child computed this, the hook only reports.
1599
1617
  let semantic;
1600
1618
  try {
@@ -1604,6 +1622,7 @@ if (require.main === module) {
1604
1622
  catch {
1605
1623
  semantic = undefined;
1606
1624
  }
1625
+ clock.mark('semantic');
1607
1626
  // @implements A-SPEC-694 — `cycles` rides in the evidence below. It was computed and written
1608
1627
  // to the observation ledger from the founding commit on (071bbf0c) and never handed over, so
1609
1628
  // the ART-2 track branch and the constitution's strict branch were dead code in the product:
@@ -1673,6 +1692,15 @@ if (require.main === module) {
1673
1692
  }
1674
1693
  const guard = decideStopGuard(out.block, guardCountOrZero(sessionId));
1675
1694
  const persisted = writeGuardCount(sessionId, guard.nextCount);
1695
+ // @implements A-SPEC-769.2 — the stage line, only when the stages used at least half of the hook budget; a
1696
+ // clock fault is swallowed, because an observation never touches the verdict.
1697
+ clock.mark('evaluate');
1698
+ try {
1699
+ const timing = clock.line(hook_process_1.HOOK_BUDGET_MS);
1700
+ if (timing !== null)
1701
+ process.stderr.write(`${timing}\n`);
1702
+ }
1703
+ catch { /* never a lever */ }
1676
1704
  // @implements A-SPEC-134 — the cap-yield is no longer silent: a clean turn clears any debt, a
1677
1705
  // give-up records the unresolved articles so WRITE_CODE is blocked until the constitution is
1678
1706
  // clean again. Fail-open: a debt-state write error never changes the stop verdict.
@@ -97,7 +97,7 @@ export declare function createSpecApprovalHandlers(context: SpecApprovalContext)
97
97
  advisoryIds?: Partial<Record<string, string>> | undefined;
98
98
  killsAdvisory?: import("../../review/kills-check").KillsAdvisory | undefined;
99
99
  fttFulfilment?: import("../../rtm/ftt-fulfilment").FttFulfilment | undefined;
100
- impactAdvisoryUnavailable?: "empty" | "unreadable" | undefined;
100
+ impactAdvisoryUnavailable?: "unreadable" | "empty" | undefined;
101
101
  impactGraph?: {
102
102
  status: "current" | "stale" | "unverified";
103
103
  sourceCommit: string | null;
@@ -46,6 +46,7 @@ const validator_1 = require("../../spec/validator");
46
46
  const elicit_approval_1 = require("../elicit-approval");
47
47
  const autonomy_1 = require("../../governance/autonomy");
48
48
  const write_target_1 = require("../../guardrail/write-target");
49
+ const delegation_1 = require("../../governance/delegation"); // @implements A-SPEC-771
49
50
  const approval_grants_1 = require("../../governance/approval-grants");
50
51
  const spec_digest_1 = require("../../spec/spec-digest");
51
52
  const version_conflict_1 = require("../../spec/version-conflict");
@@ -189,10 +190,28 @@ function createSpecApprovalHandlers(context) {
189
190
  risk = 'hitl';
190
191
  if (autonomyOn && risk === 'hitl') {
191
192
  const rule = noIntake ? 'requirement-without-intake' : (0, autonomy_1.specApprovalAutonomyReason)(target.spec, resolver([target.spec]), below);
192
- if (rule !== null)
193
+ if (rule !== null) {
193
194
  autonomyNote = `\n[autonomy: this seal is the operator's — ${rule} (${(0, autonomy_1.autonomyRuleMeaning)(rule)})]`;
195
+ // @implements A-SPEC-771 — the operator's run delegation may cover this very rule: then the seal proceeds
196
+ // as a DELEGATED grant (actor `delegated:<client>`, the run and the rule in the ledger) and no person is
197
+ // asked; otherwise the refusal names which limit of the delegation applied. The grader's verdict above
198
+ // is unchanged — only its consumer learned a third envelope (A-SPEC-552.1 project default, A-SPEC-553.1
199
+ // session marker, and this).
200
+ const delegation = autonomyRoot === undefined ? { active: false, why: 'none' } : (0, delegation_1.readDelegation)(autonomyRoot, new Date().toISOString());
201
+ if (delegation.active && (0, delegation_1.delegationCovers)(delegation.delegation, rule)) {
202
+ const base = autonomousApproval(below?.map((s) => s.id));
203
+ approveResolved = { approval: { ...base, actor: base.actor.replace(/^autonomous:/, 'delegated:'), rationale: `delegated grant (run ${delegation.delegation.run}, rule ${rule})` }, source: 'delegated' };
204
+ decidedSubject = targetSubject;
205
+ }
206
+ else {
207
+ autonomyNote += (0, delegation_1.delegationNote)(delegation, rule);
208
+ }
209
+ }
210
+ }
211
+ if (approveResolved !== undefined) {
212
+ // @implements A-SPEC-771 — delegated above: the existing seal path owns validation and audit from here.
194
213
  }
195
- if (autonomyOn && risk === 'auto') {
214
+ else if (autonomyOn && risk === 'auto') {
196
215
  approveResolved = { approval: autonomousApproval(below?.map((s) => s.id)), source: 'autonomous' };
197
216
  decidedSubject = targetSubject;
198
217
  const direction = (0, autonomy_1.declaredGateDirection)(target.spec);
@@ -735,7 +735,7 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
735
735
  };
736
736
  }[];
737
737
  graph: {
738
- status: "current" | "empty" | "absent" | "unreadable" | "stale" | "unverified";
738
+ status: "current" | "unreadable" | "empty" | "absent" | "stale" | "unverified";
739
739
  sourceCommit: string | null;
740
740
  graphAsOf: string | null;
741
741
  resolutionLimits: string[];
@@ -795,7 +795,7 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
795
795
  };
796
796
  }[];
797
797
  graph: {
798
- status: "current" | "empty" | "absent" | "unreadable" | "stale" | "unverified";
798
+ status: "current" | "unreadable" | "empty" | "absent" | "stale" | "unverified";
799
799
  sourceCommit: string | null;
800
800
  graphAsOf: string | null;
801
801
  resolutionLimits: string[];
@@ -877,7 +877,7 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
877
877
  };
878
878
  }[];
879
879
  graph: {
880
- status: "current" | "empty" | "absent" | "unreadable" | "stale" | "unverified";
880
+ status: "current" | "unreadable" | "empty" | "absent" | "stale" | "unverified";
881
881
  sourceCommit: string | null;
882
882
  graphAsOf: string | null;
883
883
  resolutionLimits: string[];
@@ -943,7 +943,7 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
943
943
  };
944
944
  }[];
945
945
  graph: {
946
- status: "current" | "empty" | "absent" | "unreadable" | "stale" | "unverified";
946
+ status: "current" | "unreadable" | "empty" | "absent" | "stale" | "unverified";
947
947
  sourceCommit: string | null;
948
948
  graphAsOf: string | null;
949
949
  resolutionLimits: string[];
@@ -1307,7 +1307,7 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
1307
1307
  advisoryIds?: Partial<Record<string, string>> | undefined;
1308
1308
  killsAdvisory?: import("../review/kills-check").KillsAdvisory | undefined;
1309
1309
  fttFulfilment?: import("../rtm/ftt-fulfilment").FttFulfilment | undefined;
1310
- impactAdvisoryUnavailable?: "empty" | "unreadable" | undefined;
1310
+ impactAdvisoryUnavailable?: "unreadable" | "empty" | undefined;
1311
1311
  impactGraph?: {
1312
1312
  status: "current" | "stale" | "unverified";
1313
1313
  sourceCommit: string | null;