@holmes-lab/holmes-kit 0.35.16 → 0.35.18

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 (43) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +4 -2
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-watch.js +4 -0
  5. package/dist/holmes/cli/approve.d.ts +8 -1
  6. package/dist/holmes/cli/approve.js +27 -8
  7. package/dist/holmes/cli/doctor.js +14 -2
  8. package/dist/holmes/cli/index.js +9 -4
  9. package/dist/holmes/cli/init.js +3 -1
  10. package/dist/holmes/cli/interactive-prompt.d.ts +5 -0
  11. package/dist/holmes/cli/interactive-prompt.js +12 -4
  12. package/dist/holmes/cli/runtime-binding.d.ts +5 -0
  13. package/dist/holmes/cli/runtime-binding.js +42 -4
  14. package/dist/holmes/governance/approval-queue.d.ts +7 -1
  15. package/dist/holmes/governance/approval-queue.js +28 -3
  16. package/dist/holmes/governance/autonomy.js +13 -1
  17. package/dist/holmes/guardrail/write-target.d.ts +18 -0
  18. package/dist/holmes/guardrail/write-target.js +136 -35
  19. package/dist/holmes/hooks/pre-tool-use.js +15 -10
  20. package/dist/holmes/hooks/rtm-refresh-child.d.ts +12 -2
  21. package/dist/holmes/hooks/rtm-refresh-child.js +26 -4
  22. package/dist/holmes/hooks/stop-timing.d.ts +12 -0
  23. package/dist/holmes/hooks/stop-timing.js +22 -0
  24. package/dist/holmes/hooks/stop.js +28 -0
  25. package/dist/holmes/mcp/handlers/graph-operations.d.ts +1 -0
  26. package/dist/holmes/mcp/handlers/graph-operations.js +4 -4
  27. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +25 -0
  28. package/dist/holmes/mcp/handlers/operator-inspection.js +60 -1
  29. package/dist/holmes/mcp/handlers/test-execution.d.ts +7 -0
  30. package/dist/holmes/mcp/handlers/test-execution.js +9 -2
  31. package/dist/holmes/mcp/handlers.d.ts +9 -0
  32. package/dist/holmes/mcp/operator-recovery.js +5 -2
  33. package/dist/holmes/refresh/freshness-coordinator.d.ts +9 -0
  34. package/dist/holmes/refresh/freshness-coordinator.js +14 -4
  35. package/dist/holmes/rtm/anchor-ids.d.ts +15 -0
  36. package/dist/holmes/rtm/anchor-ids.js +45 -0
  37. package/dist/holmes/rtm/test-scope.d.ts +12 -0
  38. package/dist/holmes/rtm/test-scope.js +29 -4
  39. package/dist/holmes/runtime/dispatch.js +28 -3
  40. package/package.json +1 -1
  41. package/playbooks/publish/PLAYBOOK.md +29 -6
  42. package/dist/holmes/guardrail/write-verb-word.d.ts +0 -13
  43. package/dist/holmes/guardrail/write-verb-word.js +0 -55
@@ -43,6 +43,7 @@ exports.patchAmbiguous = patchAmbiguous;
43
43
  exports.canonicalPatch = canonicalPatch;
44
44
  exports.patchTargetsOf = patchTargetsOf;
45
45
  exports.applyPatchUpdate = applyPatchUpdate;
46
+ exports.applyPatchUpdateDetailed = applyPatchUpdateDetailed;
46
47
  exports.pathFlavorFor = pathFlavorFor;
47
48
  exports.resolveTarget = resolveTarget;
48
49
  exports.isProtectedTarget = isProtectedTarget;
@@ -66,7 +67,7 @@ exports.joinShellText = joinShellText;
66
67
  exports.commandBases = commandBases;
67
68
  exports.shellSegments = shellSegments;
68
69
  exports.resolvesInside = resolvesInside;
69
- // @implements A-SPEC-728, A-SPEC-733, A-SPEC-163, A-SPEC-627
70
+ // @implements A-SPEC-728, A-SPEC-733, A-SPEC-163, A-SPEC-627, A-SPEC-768.2, A-SPEC-768.3
70
71
  const fs = __importStar(require("node:fs"));
71
72
  const path = __importStar(require("node:path"));
72
73
  const os = __importStar(require("node:os"));
@@ -367,6 +368,23 @@ function patchTargetsOf(text) {
367
368
  * rule (below): its one place in the file, or no result.
368
369
  */
369
370
  function applyPatchUpdate(original, hunk) {
371
+ const r = applyPatchUpdateDetailed(original, hunk);
372
+ return 'result' in r ? r.result : null;
373
+ }
374
+ /**
375
+ * @implements A-SPEC-768.2
376
+ * The same application, with the reason when there is no result. Measured 2026-10-11 (SWE-bench Sphinx 11510, H0
377
+ * arm): a four-chunk Codex patch — two chunks context-only, one context line (`def run(self) -> list[Node]:`) occurring
378
+ * eight times earlier in the file — got no result under rule 4's "exactly once in the whole file", and the refusal
379
+ * said a file path was missing. The tool applies each chunk from where the previous one ended; so does this now:
380
+ * exact first, then white-space-loose, the FIRST match at or after the previous chunk. A `@@ ctx` header first seeks
381
+ * `ctx` the same way; an add-only chunk under such a header inserts directly after it. A kept line stays as the file
382
+ * has it. Supersedes A-SPEC-163.3 rule 4.
383
+ *
384
+ * @implements A-SPEC-163.3 (rules 1-3, 5-7: chunk grammar, ops, end-of-file, size), A-SPEC-163.4 — their rule 4 (one
385
+ * place in the whole file) is the part A-SPEC-768.2 replaces; everything else they pin still holds here.
386
+ */
387
+ function applyPatchUpdateDetailed(original, hunk) {
370
388
  const endsWithNewline = original.endsWith('\n');
371
389
  const lines = original.split('\n');
372
390
  if (endsWithNewline)
@@ -396,17 +414,38 @@ function applyPatchUpdate(original, hunk) {
396
414
  else if (head === ' ' || head === '-' || head === '+')
397
415
  current.ops.push({ kind: head, text: line.slice(1) });
398
416
  else
399
- return null;
417
+ return { failure: `chunk ${chunks.length}: a line is not a patch line` };
400
418
  }
401
- // @implements A-SPEC-163.3 (rule 4) — a chunk is applied only where its old text is found exactly once in the whole
402
- // file, compared with surrounding white space ignored (the loosest comparison any parser uses), and in file order.
403
- // Then exact-first, `@@` seeking and end-of-file anchoring all choose the same place, so the result does not depend
404
- // on which parser applies it. No old text (an add-only chunk), none found, or two found: no one result.
405
419
  // The loose reading of each file line is computed once and spliced beside `lines`: per chunk it would be
406
420
  // chunks x lines regex passes inside a hook with a deadline.
407
421
  const loose = lines.map(patchLoose);
422
+ // The first index at or after `from` where `exact` matches the file, else where `looseOld` matches, else -1.
423
+ const seekFrom = (from, exact, looseOld) => {
424
+ for (const [source, want] of [[lines, exact], [loose, looseOld]]) {
425
+ for (let i = from; i + want.length <= source.length; i++) {
426
+ let ok = true;
427
+ for (let j = 0; j < want.length; j++)
428
+ if (source[i + j] !== want[j]) {
429
+ ok = false;
430
+ break;
431
+ }
432
+ if (ok)
433
+ return i;
434
+ }
435
+ }
436
+ return -1;
437
+ };
408
438
  let pos = 0;
409
- for (const chunk of chunks) {
439
+ for (const [index, chunk] of chunks.entries()) {
440
+ const n = index + 1;
441
+ let from = pos;
442
+ if (chunk.seek !== null) {
443
+ const at = seekFrom(pos, [chunk.seek], [patchLoose(chunk.seek)]);
444
+ if (at === -1)
445
+ return { failure: `chunk ${n}: the @@ context line was not found at or after the previous chunk` };
446
+ from = at + 1;
447
+ pos = from;
448
+ }
410
449
  const blank = (o) => o.empty === true;
411
450
  const ops = chunk.ops.slice();
412
451
  while (ops.length > 0 && blank(ops[0]))
@@ -416,30 +455,18 @@ function applyPatchUpdate(original, hunk) {
416
455
  if (ops.length === 0)
417
456
  continue;
418
457
  const oldExact = ops.filter((o) => o.kind !== '+').map((o) => o.text);
419
- if (oldExact.length === 0)
420
- return null;
421
- const old = oldExact.map(patchLoose);
422
- let at = -1;
423
- for (let i = 0; i + old.length <= lines.length; i++) {
424
- let ok = true;
425
- for (let j = 0; j < old.length; j++)
426
- if (loose[i + j] !== old[j]) {
427
- ok = false;
428
- break;
429
- }
430
- if (!ok)
431
- continue;
432
- if (at !== -1)
433
- return null;
434
- at = i;
435
- }
436
- if (at === -1 || at < pos)
437
- return null;
438
- // @implements A-SPEC-163.4 (rule 4) — the one loose place must also be an exact one: then the lines the patch
439
- // keeps are the same text in the file and in the patch, whichever of the two a tool writes back.
440
- for (let j = 0; j < oldExact.length; j++)
441
- if (lines[at + j] !== oldExact[j])
442
- return null;
458
+ if (oldExact.length === 0) {
459
+ if (chunk.seek === null)
460
+ return { failure: `chunk ${n}: adds lines with no place to add them` };
461
+ const added = ops.map((o) => o.text);
462
+ lines.splice(from, 0, ...added);
463
+ loose.splice(from, 0, ...added.map(patchLoose));
464
+ pos = from + added.length;
465
+ continue;
466
+ }
467
+ const at = seekFrom(from, oldExact, oldExact.map(patchLoose));
468
+ if (at === -1)
469
+ return { failure: `chunk ${n}: its old lines were not found at or after the previous chunk` };
443
470
  const replacement = [];
444
471
  let k = at;
445
472
  for (const op of ops) {
@@ -450,11 +477,11 @@ function applyPatchUpdate(original, hunk) {
450
477
  else
451
478
  replacement.push(op.text);
452
479
  }
453
- lines.splice(at, old.length, ...replacement);
454
- loose.splice(at, old.length, ...replacement.map(patchLoose));
480
+ lines.splice(at, oldExact.length, ...replacement);
481
+ loose.splice(at, oldExact.length, ...replacement.map(patchLoose));
455
482
  pos = at + replacement.length;
456
483
  }
457
- return lines.join('\n') + (endsWithNewline ? '\n' : '');
484
+ return { result: lines.join('\n') + (endsWithNewline ? '\n' : '') };
458
485
  }
459
486
  /**
460
487
  * The file a raw path actually names.
@@ -2105,8 +2132,82 @@ function mentionsAxSpelling(command) {
2105
2132
  axSpellingMemo = { command, answer };
2106
2133
  return answer;
2107
2134
  }
2135
+ /**
2136
+ * @implements A-SPEC-768.3
2137
+ * The command with every glob character the shell would NOT expand replaced by a literal placeholder: inside single
2138
+ * quotes (`$'…'` included), inside double quotes outside any `$(…)`/backtick substitution, or directly after an
2139
+ * unescaped backslash. Measured 2026-10-11 (SWE-bench Sphinx 11510, HG arm): the `.*` of a quoted regex was read as a
2140
+ * glob that could spell `.ax`, and with an uncertain base every segment of a read-only command was judged under the
2141
+ * store. A shell never globs a quoted or escaped character, so such a character cannot spell the store. An unterminated
2142
+ * quote leaves the text as written (conservative: the glob still counts).
2143
+ */
2144
+ function literalGlobsNeutralized(command) {
2145
+ const GLOB = /[*?[]/;
2146
+ let out = '';
2147
+ let quote = null;
2148
+ let subDepth = 0;
2149
+ let tick = false;
2150
+ for (let i = 0; i < command.length; i++) {
2151
+ const c = command[i];
2152
+ if (quote === "'") {
2153
+ out += c === "'" ? c : GLOB.test(c) ? '_' : c;
2154
+ if (c === "'")
2155
+ quote = null;
2156
+ continue;
2157
+ }
2158
+ if (c === '\\' && i + 1 < command.length) {
2159
+ const n = command[i + 1];
2160
+ out += quote === null && GLOB.test(n) ? '\\_' : c + n;
2161
+ i++;
2162
+ continue;
2163
+ }
2164
+ if (quote === '"') {
2165
+ if (c === '"' && subDepth === 0 && !tick) {
2166
+ quote = null;
2167
+ out += c;
2168
+ continue;
2169
+ }
2170
+ if (c === '$' && command[i + 1] === '(') {
2171
+ subDepth++;
2172
+ out += '$(';
2173
+ i++;
2174
+ continue;
2175
+ }
2176
+ if (c === ')' && subDepth > 0) {
2177
+ subDepth--;
2178
+ out += c;
2179
+ continue;
2180
+ }
2181
+ if (c === '`') {
2182
+ tick = !tick;
2183
+ out += c;
2184
+ continue;
2185
+ }
2186
+ out += subDepth === 0 && !tick && GLOB.test(c) ? '_' : c;
2187
+ continue;
2188
+ }
2189
+ if (c === "'") {
2190
+ quote = "'";
2191
+ out += c;
2192
+ continue;
2193
+ }
2194
+ if (c === '$' && command[i + 1] === "'") {
2195
+ quote = "'";
2196
+ out += "$'";
2197
+ i++;
2198
+ continue;
2199
+ }
2200
+ if (c === '"') {
2201
+ quote = '"';
2202
+ out += c;
2203
+ continue;
2204
+ }
2205
+ out += c;
2206
+ }
2207
+ return quote === null ? out : command;
2208
+ }
2108
2209
  function mentionsAxSpellingUncached(command) {
2109
- const decoded = command
2210
+ const decoded = literalGlobsNeutralized(command)
2110
2211
  .replace(/\\\n/g, '')
2111
2212
  .replace(/\\(?:x([0-9A-Fa-f]{1,2})|u([0-9A-Fa-f]{1,4})|U([0-9A-Fa-f]{1,8})|([0-7]{1,3}))/g, (_w, x, u, U, o) => {
2112
2213
  const cp = x !== undefined ? parseInt(x, 16) : u !== undefined ? parseInt(u, 16) : U !== undefined ? parseInt(U, 16) : parseInt(o ?? '0', 8);
@@ -48,7 +48,7 @@ exports.gateErrorDecision = gateErrorDecision;
48
48
  exports.wiredSpecsDir = wiredSpecsDir;
49
49
  exports.evaluateHook = evaluateHook;
50
50
  exports.readSpecsSync = readSpecsSync;
51
- // @implements A-SPEC-753.3, A-SPEC-134.2, A-SPEC-278, A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7
51
+ // @implements A-SPEC-753.3, A-SPEC-134.2, A-SPEC-278, A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2
52
52
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
53
53
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
54
54
  // evaluateHook in this file to prove it.
@@ -952,6 +952,9 @@ const PATCH_STRINGS_MAX = 256;
952
952
  /** A file an update hunk is applied to; a larger one is not judged by its result. */
953
953
  const PATCH_UPDATE_BYTES_MAX = 8 * 1024 * 1024;
954
954
  const PATCH_UNREADABLE_REASON = '[Holmes-Kit] cannot read the edit target path, so it cannot be judged (file_path missing or not a string)';
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
+ // the path-missing sentence above was returned for a readable file whose patch simply did not apply.
957
+ const patchNotAppliedReason = (file, why) => `[Holmes-Kit] the patch does not apply to ${file} as it stands (${why}), so the result cannot be judged`;
955
958
  // @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).
956
959
  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 — '
957
960
  + '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)';
@@ -1244,18 +1247,20 @@ function evaluateHook(input, specsDir, opts) {
1244
1247
  const workdir = isShell ? input.tool_input.workdir : undefined;
1245
1248
  const base = workdir === undefined ? outer : (path.isAbsolute(workdir) ? workdir : outer.replace(/\/+$/, '') + '/' + workdir);
1246
1249
  const at = (p) => (path.isAbsolute(p) ? p : base.replace(/\/+$/, '') + '/' + p);
1250
+ // @implements A-SPEC-768.2 — null: the file cannot be read (unreadable target); `failure`: readable, patch not applicable.
1247
1251
  const resultOf = (source, hunk) => {
1248
1252
  try {
1249
1253
  // @implements A-SPEC-163.3 (rule 7) — only a regular file is read: a FIFO or a device would hold the hook.
1250
1254
  const stat = fs.statSync(source);
1251
1255
  if (!stat.isFile() || stat.size > PATCH_UPDATE_BYTES_MAX)
1252
1256
  return null;
1253
- return (0, write_target_1.applyPatchUpdate)(fs.readFileSync(source, 'utf8'), hunk);
1257
+ return (0, write_target_1.applyPatchUpdateDetailed)(fs.readFileSync(source, 'utf8'), hunk);
1254
1258
  }
1255
1259
  catch {
1256
1260
  return null;
1257
1261
  }
1258
1262
  };
1263
+ const judged = (file, r) => r === null ? { deny: PATCH_UNREADABLE_REASON } : 'failure' in r ? { deny: patchNotAppliedReason(file, r.failure) } : { content: r.result };
1259
1264
  // @implements A-SPEC-163.3 (rule 1), A-SPEC-163.4 (rule 5) — two targets on one file have no one result: the tool
1260
1265
  // applies them in sequence, the gate reads the disk once. One file is one key whatever link or letter case names it.
1261
1266
  // (What a shell could rewrite is settled before this point: only the one quoted-heredoc form reaches here.)
@@ -1271,16 +1276,16 @@ function evaluateHook(input, specsDir, opts) {
1271
1276
  if (t.kind === 'add')
1272
1277
  content = t.content;
1273
1278
  else if (t.kind === 'update' && t.movedTo === undefined) {
1274
- const result = resultOf(at(t.path), t.hunk ?? '');
1275
- if (result === null)
1276
- return { permissionDecision: 'deny', permissionDecisionReason: PATCH_UNREADABLE_REASON };
1277
- content = result;
1279
+ const j = judged(at(t.path), resultOf(at(t.path), t.hunk ?? ''));
1280
+ if ('deny' in j)
1281
+ return { permissionDecision: 'deny', permissionDecisionReason: j.deny };
1282
+ content = j.content;
1278
1283
  }
1279
1284
  else if (t.kind === 'move') {
1280
- const result = t.from === undefined ? null : resultOf(at(t.from), t.hunk ?? '');
1281
- if (result === null)
1282
- return { permissionDecision: 'deny', permissionDecisionReason: PATCH_UNREADABLE_REASON };
1283
- content = result;
1285
+ const j = judged(at(t.from ?? t.path), t.from === undefined ? null : resultOf(at(t.from), t.hunk ?? ''));
1286
+ if ('deny' in j)
1287
+ return { permissionDecision: 'deny', permissionDecisionReason: j.deny };
1288
+ content = j.content;
1284
1289
  }
1285
1290
  // Judged as a patch tool's write whichever tool carried the patch, so the shell branch below is not re-entered.
1286
1291
  const verdict = evaluateHook({ tool_name: 'apply_patch', tool_input: { file_path: at(t.path), ...(content === undefined ? {} : { content }) },
@@ -1,11 +1,16 @@
1
- import { FreshnessLane, FreshnessReceipt } from '../refresh/freshness-coordinator';
1
+ import { FreshnessLane, FreshnessReceipt, RefreshFailure } from '../refresh/freshness-coordinator';
2
+ /** The error as a bounded reason: its message (never a stack), at most REFRESH_FAILURE_REASON_MAX characters. */
3
+ export declare function failureReason(error: unknown): string;
2
4
  /** The detached worker must publish its own failure; the parent is intentionally non-blocking. */
3
- export declare function recordRefreshFailure(root: string, generation: string, head: string | null, now: Date): FreshnessReceipt | null;
5
+ export declare function recordRefreshFailure(root: string, generation: string, head: string | null, now: Date, failure?: RefreshFailure): FreshnessReceipt | null;
4
6
  export interface RefreshChildDeps {
5
7
  head: (root: string) => string | null;
6
8
  refreshGraph: (root: string) => Promise<unknown>;
9
+ /** @implements A-SPEC-768.4 — a failed lane may carry `detail` (the embedder's message) beside its reason. */
7
10
  refreshSource: (root: string) => Promise<{
8
11
  lane: FreshnessLane;
12
+ reason?: string;
13
+ detail?: string;
9
14
  }>;
10
15
  refreshRequirement: (root: string) => Promise<{
11
16
  status: string;
@@ -16,6 +21,11 @@ export interface RefreshChildDeps {
16
21
  * so a superseded worker, or one whose root was removed, stops without writing (A-SPEC-724). Any
17
22
  * failure — synchronous module load included — is published as bounded retry for this generation
18
23
  * rather than left as a `refreshing` lease that only expiry can clear (A-SPEC-719).
24
+ *
25
+ * @implements A-SPEC-768.4 — and the receipt says WHY. Measured 2026-10-11 (SWE-bench Sphinx 11510, HG arm):
26
+ * generation 77968db7 recorded both semantic lanes `failed` while direct probes of the same endpoint returned HTTP
27
+ * 200; every error was swallowed here, so the cause was unknowable. The stage that threw and the error's message
28
+ * now ride the receipt; a source lane that returns `failed` carries the embedder's detail.
19
29
  */
20
30
  export declare function runRefreshChild(root: string, generation: string, deps: RefreshChildDeps): Promise<void>;
21
31
  /** The production phases: the scan/build machinery, loaded only inside the detached child. */
@@ -33,11 +33,13 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.failureReason = failureReason;
36
37
  exports.recordRefreshFailure = recordRefreshFailure;
37
38
  exports.runRefreshChild = runRefreshChild;
38
39
  exports.defaultRefreshChildDeps = defaultRefreshChildDeps;
39
40
  // @implements A-SPEC-719, A-SPEC-734
40
41
  // @implements A-SPEC-566.4
42
+ // @implements A-SPEC-768.4
41
43
  /**
42
44
  * The detached refresh child — the ONLY place this slice touches the scan/build machinery. Spawned
43
45
  * by `maybeSpawnRtmRefresh` (rtm-refresh.ts) outside any turn; nothing in the hook path imports
@@ -56,10 +58,17 @@ const currentHead = (root) => {
56
58
  return null;
57
59
  }
58
60
  };
61
+ // @implements A-SPEC-768.4
62
+ /** The error as a bounded reason: its message (never a stack), at most REFRESH_FAILURE_REASON_MAX characters. */
63
+ function failureReason(error) {
64
+ const message = error instanceof Error ? error.message : String(error);
65
+ return message.slice(0, freshness_coordinator_1.REFRESH_FAILURE_REASON_MAX);
66
+ }
59
67
  /** The detached worker must publish its own failure; the parent is intentionally non-blocking. */
60
- function recordRefreshFailure(root, generation, head, now) {
68
+ function recordRefreshFailure(root, generation, head, now, failure) {
61
69
  return (0, freshness_coordinator_1.completeRefresh)(root, generation, {
62
70
  graph: 'failed', sourceSemantic: 'failed', requirementSemantic: 'failed', head,
71
+ ...(failure ? { failure } : {}), // A-SPEC-768.4
63
72
  }, now);
64
73
  }
65
74
  /**
@@ -67,12 +76,18 @@ function recordRefreshFailure(root, generation, head, now) {
67
76
  * so a superseded worker, or one whose root was removed, stops without writing (A-SPEC-724). Any
68
77
  * failure — synchronous module load included — is published as bounded retry for this generation
69
78
  * rather than left as a `refreshing` lease that only expiry can clear (A-SPEC-719).
79
+ *
80
+ * @implements A-SPEC-768.4 — and the receipt says WHY. Measured 2026-10-11 (SWE-bench Sphinx 11510, HG arm):
81
+ * generation 77968db7 recorded both semantic lanes `failed` while direct probes of the same endpoint returned HTTP
82
+ * 200; every error was swallowed here, so the cause was unknowable. The stage that threw and the error's message
83
+ * now ride the receipt; a source lane that returns `failed` carries the embedder's detail.
70
84
  */
71
85
  async function runRefreshChild(root, generation, deps) {
72
86
  if (!fs.existsSync(path.join(root, '.ax')))
73
87
  return;
74
88
  if (!(0, freshness_coordinator_1.ownsLease)(root, generation))
75
89
  return; // spawned late behind a newer lease: not even the graph
90
+ let stage = 'graph';
76
91
  try {
77
92
  await deps.refreshGraph(root);
78
93
  // @implements A-SPEC-683 — the vectors ride the channel that already refreshes the graph.
@@ -80,15 +95,21 @@ async function runRefreshChild(root, generation, deps) {
80
95
  // stayed current.
81
96
  if (!(0, freshness_coordinator_1.ownsLease)(root, generation))
82
97
  return;
98
+ stage = 'source';
83
99
  const source = await deps.refreshSource(root);
84
100
  if (!(0, freshness_coordinator_1.ownsLease)(root, generation))
85
101
  return;
102
+ let failure;
103
+ if (source.lane === 'failed')
104
+ failure = { stage: 'source', reason: (source.detail ?? source.reason ?? 'failed').slice(0, freshness_coordinator_1.REFRESH_FAILURE_REASON_MAX) };
105
+ stage = 'requirement';
86
106
  let requirement;
87
107
  try {
88
108
  requirement = await deps.refreshRequirement(root);
89
109
  }
90
- catch {
110
+ catch (error) {
91
111
  requirement = { status: 'unavailable' };
112
+ failure ??= { stage: 'requirement', reason: failureReason(error) };
92
113
  }
93
114
  (0, freshness_coordinator_1.completeRefresh)(root, generation, {
94
115
  graph: 'current',
@@ -97,11 +118,12 @@ async function runRefreshChild(root, generation, deps) {
97
118
  : requirement.status === 'not-applicable' ? 'not-adopted'
98
119
  : requirement.status === 'suppressed' ? 'suppressed' : 'failed',
99
120
  head: deps.head(root),
121
+ ...(failure ? { failure } : {}),
100
122
  }, new Date());
101
123
  }
102
- catch {
124
+ catch (error) {
103
125
  try {
104
- recordRefreshFailure(root, generation, deps.head(root), new Date());
126
+ recordRefreshFailure(root, generation, deps.head(root), new Date(), { stage, reason: failureReason(error) });
105
127
  }
106
128
  catch { /* fail-soft */ }
107
129
  }
@@ -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.
@@ -55,6 +55,7 @@ export type SourceSemanticRefreshOutcome = {
55
55
  } | {
56
56
  lane: 'failed';
57
57
  reason: 'unavailable' | 'failed';
58
+ detail?: string;
58
59
  };
59
60
  /**
60
61
  * @implements A-SPEC-478 — the semantic cache WARMING lives in explicit heavy operations, so the
@@ -184,11 +184,11 @@ async function refreshSemanticVectors(root, env = process.env, warm = warmSemant
184
184
  try {
185
185
  outcome = await warm(root, scanned);
186
186
  }
187
- catch {
188
- return { lane: 'failed', reason: 'failed' };
189
- }
187
+ catch (error) {
188
+ return { lane: 'failed', reason: 'failed', detail: error instanceof Error ? error.message : String(error) };
189
+ } // A-SPEC-768.4
190
190
  if (outcome.status !== 'discharged')
191
- return { lane: 'failed', reason: 'unavailable' };
191
+ return { lane: 'failed', reason: 'unavailable', detail: `warm status: ${outcome.status}` };
192
192
  // What LANDED, not what was attempted. Measured 2026-09-19 the warm answered `computed: 603`
193
193
  // while 26 vectors were never stored; a count of attempts reported as a success is the same
194
194
  // class of dishonesty as a tier that says PASS while covering nothing.
@@ -1,6 +1,29 @@
1
1
  import { Spec } from '../../spec/spec-parser';
2
2
  import { SpecStore } from '../../spec/spec-store';
3
3
  import type { Approval } from '../../guardrail/risk-gate';
4
+ import type { ApprovalStatus } from '../../spec/approval-status';
5
+ /** The spec-approve request for one spec as the queue holds it now: its state and, when held, the operator's LATEST question. */
6
+ export interface ApprovalRequestState {
7
+ id: string;
8
+ state: 'pending' | 'held' | 'granted' | 'consumed' | 'denied' | 'revoked';
9
+ question?: string;
10
+ reason?: string;
11
+ ts?: string;
12
+ }
13
+ /**
14
+ * @implements A-SPEC-768
15
+ * Measured 2026-10-11 (SWE-bench Sphinx 11510, H0 arm): the operator held one request twice with two different
16
+ * questions; the worker polled `approval_status` eleven times and never saw the second, because the response reported
17
+ * the spec's seal only. The queue fold already keeps the latest `held` question (`pending[].question`, `holds[id]`);
18
+ * this reads it. Read-only; an unreadable queue is no request.
19
+ */
20
+ export declare function approvalRequestOf(root: string, specId: string): ApprovalRequestState | undefined;
21
+ /**
22
+ * @implements A-SPEC-768
23
+ * One sentence an agent can act on. Measured 2026-10-11 (HG arm): 58 `sealed: true` answers were read as "pending"
24
+ * because nothing in the response said what to do once the seal was there.
25
+ */
26
+ export declare function nextActionOf(described: Pick<ApprovalStatus, 'sealed' | 'blockers'>, request: ApprovalRequestState | undefined): string;
4
27
  export interface OperatorInspectionContext {
5
28
  listSpecs(): Promise<Spec[]>;
6
29
  readSpec: SpecStore['read'];
@@ -71,6 +94,8 @@ export declare function createOperatorInspectionHandlers(context: OperatorInspec
71
94
  };
72
95
  unavailable?: "empty" | "unreadable";
73
96
  } | undefined;
97
+ nextAction: string;
98
+ request?: ApprovalRequestState | undefined;
74
99
  id: string;
75
100
  type?: string;
76
101
  status: string;