@holmes-lab/holmes-kit 0.35.18 → 0.35.20

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 (48) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +3 -2
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/agents.js +13 -7
  5. package/dist/holmes/cli/approve-status.d.ts +4 -1
  6. package/dist/holmes/cli/approve-status.js +10 -0
  7. package/dist/holmes/cli/approve-watch.js +1 -1
  8. package/dist/holmes/cli/approve.d.ts +3 -3
  9. package/dist/holmes/cli/approve.js +12 -7
  10. package/dist/holmes/cli/autonomy.d.ts +13 -6
  11. package/dist/holmes/cli/autonomy.js +105 -16
  12. package/dist/holmes/cli/codex-hooks.js +3 -1
  13. package/dist/holmes/cli/doctor.js +7 -1
  14. package/dist/holmes/cli/index.js +25 -6
  15. package/dist/holmes/cli/init.js +2 -1
  16. package/dist/holmes/cli/runtime-binding.d.ts +18 -1
  17. package/dist/holmes/cli/runtime-binding.js +80 -5
  18. package/dist/holmes/cpg/scan-cache.d.ts +11 -1
  19. package/dist/holmes/cpg/scan-cache.js +72 -2
  20. package/dist/holmes/governance/approval-queue.d.ts +1 -1
  21. package/dist/holmes/governance/approval-queue.js +10 -4
  22. package/dist/holmes/governance/autonomy.d.ts +0 -2
  23. package/dist/holmes/governance/autonomy.js +14 -4
  24. package/dist/holmes/governance/delegation.d.ts +40 -0
  25. package/dist/holmes/governance/delegation.js +151 -0
  26. package/dist/holmes/guardrail/write-target.d.ts +10 -0
  27. package/dist/holmes/guardrail/write-target.js +82 -0
  28. package/dist/holmes/hooks/adapters/antigravity.d.ts +2 -0
  29. package/dist/holmes/hooks/adapters/antigravity.js +8 -1
  30. package/dist/holmes/hooks/pre-tool-use.d.ts +3 -1
  31. package/dist/holmes/hooks/pre-tool-use.js +22 -4
  32. package/dist/holmes/hooks/rtm-refresh-child.d.ts +27 -0
  33. package/dist/holmes/hooks/rtm-refresh-child.js +69 -3
  34. package/dist/holmes/hooks/rtm-refresh.d.ts +1 -0
  35. package/dist/holmes/hooks/rtm-refresh.js +8 -0
  36. package/dist/holmes/hooks/stop.d.ts +8 -0
  37. package/dist/holmes/hooks/stop.js +20 -5
  38. package/dist/holmes/mcp/handlers/spec-approval.d.ts +1 -1
  39. package/dist/holmes/mcp/handlers/spec-approval.js +21 -2
  40. package/dist/holmes/mcp/handlers.d.ts +5 -5
  41. package/dist/holmes/refresh/freshness-coordinator.d.ts +13 -0
  42. package/dist/holmes/refresh/freshness-coordinator.js +42 -2
  43. package/dist/holmes/runtime/dispatch.js +5 -3
  44. package/dist/holmes/runtime/hook-process.d.ts +8 -0
  45. package/dist/holmes/runtime/hook-process.js +13 -1
  46. package/dist/holmes/semantic/embedder.d.ts +6 -0
  47. package/dist/holmes/semantic/embedder.js +10 -0
  48. package/package.json +1 -1
@@ -81,7 +81,7 @@ const KNOWN_FLAGS = {
81
81
  'runtime-binding': ['help', 'workspace', 'package', 'release-package', 'registry', 'dry-run', 'activate-hooks'],
82
82
  guidance: ['help', 'target', 'dry-run'],
83
83
  init: ['help', 'target', 'mode', 'specs-dir', 'settings', 'matcher', 'dry-run', 'no-mcp', 'remove', 'force', 'agent', 'mcp-launcher', 'autonomy', 'no-autonomy'],
84
- autonomy: ['help', 'target', 'for'],
84
+ autonomy: ['help', 'target', 'for', 'run', 'allow', 'limit', 'rationale'], // @implements A-SPEC-771.1 — the run delegation's flags
85
85
  doctor: ['help', 'target', 'json', 'agent', 'registry'],
86
86
  // @implements A-SPEC-702 — a statement, not a gate: how many source files trace to an approved spec.
87
87
  attest: ['help', 'target', 'exclude', 'json', 'badge', 'readme'],
@@ -129,6 +129,8 @@ class UnknownFlagError extends Error {
129
129
  // A-SPEC-251.1 (round 26): `yes` — `upgrade --yes` was refused as "--yes requires a value", so the non-interactive
130
130
  // upgrade its own guidance names could not run (measured).
131
131
  const BOOLEAN_FLAGS = new Set(['badge', 'readme', 'help', 'dry-run', 'no-mcp', 'remove', 'force', 'json', 'list', 'status', 'watch', 'autonomy', 'no-autonomy', 'yes']); // A-SPEC-650: --status
132
+ /** @implements A-SPEC-771.1 — value flags that may be given more than once. */
133
+ const REPEATABLE_FLAGS = new Set(['limit']);
132
134
  function parseFlags(argv, known) {
133
135
  const flags = {};
134
136
  const positionals = [];
@@ -164,6 +166,15 @@ function parseFlags(argv, known) {
164
166
  // `--target A --target B` acted on B while the operator was looking at A. 'Cannot decide is not
165
167
  // permission' applies to the operator's own contradiction too.
166
168
  if (Object.prototype.hasOwnProperty.call(flags, key)) {
169
+ // @implements A-SPEC-771.1 — `--limit k=v` is the one flag that repeats by design (one limit per flag); the
170
+ // values are joined with a newline, which no argv value carries, and split again by the autonomy command.
171
+ if (REPEATABLE_FLAGS.has(key) && typeof flags[key] === 'string') {
172
+ const more = inline !== undefined ? inline : (argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : undefined);
173
+ if (more === undefined)
174
+ throw new UnknownFlagError(`--${key} requires a value`);
175
+ flags[key] = `${flags[key]}\n${more}`;
176
+ continue;
177
+ }
167
178
  throw new UnknownFlagError(`--${key} was given more than once — say it once, or the run acts on a directory you did not read`);
168
179
  }
169
180
  if (inline !== undefined) {
@@ -239,7 +250,12 @@ const USAGE = `holmes-kit — deterministic ASE governance for a project
239
250
  <ref> list index (1,2,…), full id, or a unique id prefix
240
251
  --target <dir> project root (default: cwd)
241
252
 
242
- holmes-kit autonomy status|on|off grant/end per-session autonomous spec approval
253
+ holmes-kit autonomy status|on|off|delegate|revoke-delegation grant/end autonomous spec approval
254
+ delegate --run <id> --allow <rule[,rule]> [--for 2h] [--limit k=v]… [--rationale <text>]
255
+ run delegation for THIS workspace: hitl specs whose only reason is a
256
+ listed grader rule seal on their own (never architecture-document,
257
+ requirement-without-intake); same human proof as 'on'
258
+ revoke-delegation end the run delegation now (always free; 'off' ends it too)
243
259
  on [--for 2h] self-drive low-risk specs this session (governance-critical still
244
260
  ask you); at a TTY it just asks, non-interactive needs HOLMES_APPROVAL
245
261
  off end it now (always free)
@@ -315,7 +331,7 @@ async function main(argv) {
315
331
  // silently wrote into CWD while the named target stayed stale (round-3 HIGH).
316
332
  const expected = cmd === 'runtime-binding' ? ['setup', 'status', 'remove'] : cmd === 'guidance' ? ['check', 'refresh'] : cmd === 'skills' ? ['refresh'] : cmd === 'ledger' ? ['rechain']
317
333
  : cmd === 'semantic-key' ? ['set', 'unset', 'status']
318
- : cmd === 'autonomy' ? ['status', 'on', 'off'] : [];
334
+ : cmd === 'autonomy' ? ['status', 'on', 'off', 'delegate', 'revoke-delegation'] : []; // @implements A-SPEC-771.1
319
335
  const unexpected = positionals.filter((p) => !expected.includes(p));
320
336
  if (unexpected.length > 0) {
321
337
  const hint = fs.existsSync(unexpected[0]) ? ` — did you mean --target ${unexpected[0]}?` : '';
@@ -407,12 +423,15 @@ async function main(argv) {
407
423
  const { runAutonomy } = await Promise.resolve().then(() => __importStar(require('./autonomy')));
408
424
  const root = path.resolve(typeof flags.target === 'string' ? flags.target : process.cwd());
409
425
  const forStr = typeof flags.for === 'string' ? flags.for : undefined;
426
+ // @implements A-SPEC-771.1 — the delegation's own inputs ride through to the core; `--limit` may repeat.
427
+ const str = (k) => (typeof flags[k] === 'string' ? flags[k] : undefined);
428
+ const extra = { run: str('run'), allow: str('allow'), limits: str('limit')?.split('\n'), rationale: str('rationale') };
410
429
  return (0, cli_execution_1.runOperatorExecution)(root, () => {
411
430
  const r = runAutonomy(root, positionals[0], forStr, {
412
431
  now: new Date().toISOString(),
413
432
  isTTY: !!process.stdin.isTTY && !!process.stdout.isTTY,
414
433
  approval: readApproval(),
415
- });
434
+ }, extra);
416
435
  process[r.ok ? 'stdout' : 'stderr'].write(`${r.message}\n`);
417
436
  return r.exitCode;
418
437
  });
@@ -1004,7 +1023,7 @@ async function main(argv) {
1004
1023
  if (flags.list) {
1005
1024
  // @implements A-SPEC-770 — the list ends with the count of refusals outside it.
1006
1025
  const { refusalsOutsideInbox } = require('../governance/approval-queue');
1007
- process.stdout.write(renderPending(readQueue(root, queueOpts), listView, refusalsOutsideInbox(root)) + '\n');
1026
+ process.stdout.write(renderPending(readQueue(root, queueOpts), listView, refusalsOutsideInbox(root), root) + '\n'); // @implements A-SPEC-770.2
1008
1027
  return 0;
1009
1028
  }
1010
1029
  // @implements A-SPEC-650 — the whole picture, read-only; the list above stays script-clean.
@@ -1022,7 +1041,7 @@ async function main(argv) {
1022
1041
  process.stderr.write(`✗ --refusals expects a positive integer count — received: ${flags.refusals}\n`);
1023
1042
  return 1;
1024
1043
  }
1025
- process.stdout.write(renderRefusals(readRefusals(root), limit) + '\n');
1044
+ process.stdout.write(renderRefusals(readRefusals(root), limit, root) + '\n'); // @implements A-SPEC-770.2
1026
1045
  return 0;
1027
1046
  }
1028
1047
  // @implements A-SPEC-262.2 — the RESIDENT surface. Validate --poll-ms first (so a bad value is
@@ -38,6 +38,7 @@ exports.buildHookPlan = buildHookPlan;
38
38
  exports.runInit = runInit;
39
39
  // @implements A-SPEC-727, A-SPEC-724, A-SPEC-721, A-SPEC-738, A-SPEC-752.8
40
40
  // @implements A-SPEC-709
41
+ // @implements A-SPEC-769.11
41
42
  // @implements A-SPEC-340
42
43
  // @implements A-SPEC-100.2
43
44
  const fs = __importStar(require("node:fs"));
@@ -557,7 +558,7 @@ function runInitUnguarded(opts) {
557
558
  opts.remove
558
559
  ? 'Stripping governance wiring is also changing the wiring — an out-of-band approval is required (self-disarm prevention).'
559
560
  : codexHooksRepoint && !opts.force
560
- ? `Re-wiring the Codex user hooks would change hooks Codex already trusts (another holmes-kit install, a changed matcher, or a moved group); Codex would treat them as new, untrusted hooks — off in every workspace until trusted again with /hooks — so an out-of-band approval is required.`
561
+ ? `Re-wiring the Codex user hooks would change hooks Codex already trusts (another holmes-kit install, a changed matcher, a changed Stop timeout (75 s since A-SPEC-769.10), or a moved group); Codex would treat them as new, untrusted hooks — off in every workspace until trusted again with /hooks — so an out-of-band approval is required.`
561
562
  : '--force changes existing governance wiring and requires an out-of-band approval that covers it.',
562
563
  `Set HOLMES_APPROVAL='{"actor":"<you>","token":"<any>","rationale":"<why>"}' (scoped approvals need kind "governance-wiring") and re-run.`,
563
564
  ] };
@@ -33,13 +33,30 @@ export declare function registryWiringOwnership(file: string, registryPath?: str
33
33
  matches: boolean;
34
34
  };
35
35
  export declare function registryOwnedWiring(file: string, registryPath?: string): boolean;
36
- export declare function runtimeBindingStatus(registryPath: string, workspace: string): {
36
+ /**
37
+ * @implements A-SPEC-769.8 — a Codex lifecycle routed to Holmes from BOTH the user-level `hooks.json` and the
38
+ * workspace's `.codex/hooks.json`, while the user-level entry is not switched off in `config.toml` `[hooks.state]`
39
+ * (a missing table or a missing `enabled` key counts as on). Measured 2026-10-12/13: the X1 fixtures' Stop hook wrote
40
+ * two identical cycle rows 1 ms apart because `~/.codex/hooks.json:stop:0:0` carried no `enabled = false` while
41
+ * `pre_tool_use` did. Reads files only; unreadable or absent files contribute nothing (a diagnostic fails open).
42
+ */
43
+ export interface DuplicateRoute {
44
+ harness: 'codex';
45
+ event: 'pre_tool_use' | 'stop' | 'session_start';
46
+ files: string[];
47
+ fix: string;
48
+ }
49
+ export declare function codexDuplicateRoutes(codexHome: string, workspace: string): DuplicateRoute[];
50
+ export declare function runtimeBindingStatus(registryPath: string, workspace: string, opts?: {
51
+ codexHome?: string;
52
+ }): {
37
53
  selection: import("../runtime/binding").RuntimeSelection;
38
54
  conflicts: string[];
39
55
  drift: {
40
56
  path: string;
41
57
  kind: "operator-config" | "stale-workspace";
42
58
  }[];
59
+ duplicateRoutes: DuplicateRoute[];
43
60
  router: "changed" | "intact";
44
61
  activation: "unverified";
45
62
  };
@@ -38,10 +38,11 @@ exports.runtimeHookCommand = runtimeHookCommand;
38
38
  exports.wiringViewOf = wiringViewOf;
39
39
  exports.registryWiringOwnership = registryWiringOwnership;
40
40
  exports.registryOwnedWiring = registryOwnedWiring;
41
+ exports.codexDuplicateRoutes = codexDuplicateRoutes;
41
42
  exports.runtimeBindingStatus = runtimeBindingStatus;
42
43
  exports.runRuntimeBinding = runRuntimeBinding;
43
44
  exports.trackedWorkspacePaths = trackedWorkspacePaths;
44
- // @implements A-SPEC-752.10, A-SPEC-752.9, A-SPEC-751.5, A-SPEC-751.6, A-SPEC-751, A-SPEC-752, A-SPEC-752.7, A-SPEC-752.8
45
+ // @implements A-SPEC-769.10, A-SPEC-752.10, A-SPEC-752.9, A-SPEC-751.5, A-SPEC-751.6, A-SPEC-751, A-SPEC-752, A-SPEC-752.7, A-SPEC-752.8
45
46
  const fs = __importStar(require("node:fs"));
46
47
  const os = __importStar(require("node:os"));
47
48
  const path = __importStar(require("node:path"));
@@ -49,6 +50,7 @@ const node_crypto_1 = require("node:crypto");
49
50
  const bounded_io_1 = require("../project/bounded-io");
50
51
  const smol_toml_1 = require("smol-toml");
51
52
  const binding_1 = require("../runtime/binding");
53
+ const hook_process_1 = require("../runtime/hook-process");
52
54
  const runtime_binding_approval_1 = require("./runtime-binding-approval");
53
55
  const codex_toml_1 = require("./codex-toml");
54
56
  const codex_hooks_1 = require("./codex-hooks");
@@ -161,7 +163,78 @@ function registryWiringOwnership(file, registryPath = (0, exports.defaultRuntime
161
163
  function registryOwnedWiring(file, registryPath) {
162
164
  return registryWiringOwnership(file, registryPath).owned;
163
165
  }
164
- function runtimeBindingStatus(registryPath, workspace) {
166
+ const CODEX_LIFECYCLES = [
167
+ ['PreToolUse', 'pre_tool_use', 'pre-tool-use'], ['Stop', 'stop', 'stop'], ['SessionStart', 'session_start', 'session-start'],
168
+ ];
169
+ /** For each lifecycle the file routes to a Holmes router: the `<group>:<hook>` index of that entry. */
170
+ function holmesRoutesIn(file) {
171
+ let doc;
172
+ try {
173
+ const raw = readOptional(file); // a strict decode may throw on bytes Codex itself refuses: nothing to report
174
+ if (raw === null)
175
+ return null;
176
+ doc = JSON.parse(raw);
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ const hooks = doc?.hooks;
182
+ if (!object(hooks))
183
+ return null;
184
+ const out = new Map();
185
+ for (const [jsonKey, stateKey, router] of CODEX_LIFECYCLES) {
186
+ const groups = hooks[jsonKey];
187
+ if (!Array.isArray(groups))
188
+ continue;
189
+ groups.forEach((group, g) => {
190
+ const entries = group?.hooks;
191
+ if (!Array.isArray(entries))
192
+ return;
193
+ entries.forEach((entry, h) => {
194
+ const command = entry?.command;
195
+ if (typeof command !== 'string' || out.has(stateKey))
196
+ return;
197
+ if (/holmes/i.test(command) && command.includes(`${router}.js`))
198
+ out.set(stateKey, `${g}:${h}`);
199
+ });
200
+ });
201
+ }
202
+ return out;
203
+ }
204
+ function codexDuplicateRoutes(codexHome, workspace) {
205
+ const userHooks = path.join(codexHome, 'hooks.json');
206
+ const wsHooks = path.join(workspace, '.codex', 'hooks.json');
207
+ const user = holmesRoutesIn(userHooks);
208
+ const ws = holmesRoutesIn(wsHooks);
209
+ if (user === null || ws === null)
210
+ return [];
211
+ const configPath = path.join(codexHome, 'config.toml');
212
+ let state = {};
213
+ try {
214
+ const rawConfig = readOptional(configPath);
215
+ if (rawConfig !== null) {
216
+ const parsed = (0, codex_toml_1.parseCodexConfig)(rawConfig);
217
+ const table = parsed.ok ? parsed.doc.hooks?.state : undefined;
218
+ if (object(table))
219
+ state = table;
220
+ }
221
+ }
222
+ catch { /* an unreadable config: every entry counts as on, which is what Codex does with a file it cannot load */ }
223
+ const out = [];
224
+ for (const [, stateKey] of CODEX_LIFECYCLES) {
225
+ const index = user.get(stateKey);
226
+ if (index === undefined || !ws.has(stateKey))
227
+ continue;
228
+ const key = `${userHooks}:${stateKey}:${index}`;
229
+ const entry = state[key];
230
+ if (object(entry) && entry.enabled === false)
231
+ continue;
232
+ out.push({ harness: 'codex', event: stateKey, files: [userHooks, wsHooks],
233
+ fix: `set enabled = false under [hooks.state."${key}"] in ${configPath} (or remove the ${stateKey} entry from one file) — Holmes runs once per lifecycle` });
234
+ }
235
+ return out;
236
+ }
237
+ function runtimeBindingStatus(registryPath, workspace, opts) {
165
238
  const registry = (0, binding_1.readRuntimeRegistry)(registryPath);
166
239
  const selection = (0, binding_1.selectRuntime)(registry, { cwd: workspace });
167
240
  const manifest = readOptional(path.join(path.dirname(registryPath), 'installation.json'));
@@ -218,7 +291,9 @@ function runtimeBindingStatus(registryPath, workspace) {
218
291
  conflicts.push(`Wiring changed or incomplete: ${row.path}`);
219
292
  }
220
293
  }
221
- return { selection, conflicts, drift, router: routerChanged ? 'changed' : 'intact', activation: 'unverified' };
294
+ // @implements A-SPEC-769.8 — reported beside the receipt verdicts; it changes neither `conflicts` nor `router`.
295
+ const duplicateRoutes = codexDuplicateRoutes(opts?.codexHome ?? path.join(os.homedir(), '.codex'), workspace);
296
+ return { selection, conflicts, drift, duplicateRoutes, router: routerChanged ? 'changed' : 'intact', activation: 'unverified' };
222
297
  }
223
298
  function runRuntimeBinding(opts) {
224
299
  if (opts.activateHooks !== undefined && (!Array.isArray(opts.activateHooks)
@@ -377,7 +452,7 @@ function runRuntimeBinding(opts) {
377
452
  }
378
453
  const explicitlyEmpty = Array.isArray(hooks[event]) && hooks[event].length === 0;
379
454
  if ((!explicitlyEmpty || activate.has(harness)) && (typeof primary === 'boolean' ? primary : primary.has(event)))
380
- groups.push({ ...(event === 'PreToolUse' ? { matcher: '.*' } : {}), hooks: [{ type: 'command', command: command(harness, event === 'PreToolUse' ? 'pre-tool-use' : 'stop'), timeout: 30 }] });
455
+ groups.push({ ...(event === 'PreToolUse' ? { matcher: '.*' } : {}), hooks: [{ type: 'command', command: command(harness, event === 'PreToolUse' ? 'pre-tool-use' : 'stop'), timeout: event === 'Stop' ? hook_process_1.STOP_HOOK_TIMEOUT_SECONDS : 30 }] }); // A-SPEC-769.10
381
456
  if (groups.length || hooks[event] !== undefined)
382
457
  hooks[event] = groups;
383
458
  }
@@ -477,7 +552,7 @@ function runRuntimeBinding(opts) {
477
552
  else if (!(Array.isArray(old?.PreToolUse) && old.PreToolUse.length === 0))
478
553
  delete ours.PreToolUse;
479
554
  if (primary.has('Stop'))
480
- ours.Stop = !activate.has('antigravity') && Array.isArray(old?.Stop) && old.Stop.length === 0 ? [] : [{ command: command('antigravity', 'stop') }];
555
+ ours.Stop = !activate.has('antigravity') && Array.isArray(old?.Stop) && old.Stop.length === 0 ? [] : [{ command: command('antigravity', 'stop'), timeout: hook_process_1.STOP_HOOK_TIMEOUT_SECONDS }]; // A-SPEC-769.10
481
556
  else if (!(Array.isArray(old?.Stop) && old.Stop.length === 0))
482
557
  delete ours.Stop;
483
558
  add(file, json({ ...doc, 'holmes-kit': ours }));
@@ -1,14 +1,22 @@
1
1
  import type { ScannedFile } from './scanned-file';
2
2
  export declare const SCAN_CACHE_VERSION = 4;
3
+ /**
4
+ * @implements A-SPEC-769.9 — the one cache directory per workspace root, shared by the refresh child and the Stop
5
+ * hook. Measured 2026-10-15: the Stop hook's uncached scan took 23.0 s of its budget; served from here, 0.48 s.
6
+ */
7
+ export declare function scanCacheDirFor(root: string, tmp?: string): string;
3
8
  export declare class ScanFileCache {
4
9
  private readonly dir;
5
10
  private readonly file;
11
+ private readonly tempSuffix;
6
12
  private entries;
7
13
  private seen;
8
14
  private dirty;
9
15
  hits: number;
10
16
  misses: number;
11
- constructor(dir: string);
17
+ constructor(dir: string, opts?: {
18
+ tempSuffix?: () => string;
19
+ });
12
20
  static hashOf(content: string): string;
13
21
  /** Cached scan result iff the stored hash matches this content. Marks the path as seen. */
14
22
  get(sourcePath: string, contentHash: string): Omit<ScannedFile, 'path'> | undefined;
@@ -18,4 +26,6 @@ export declare class ScanFileCache {
18
26
  * deleted/renamed files — pruned so the cache cannot grow unboundedly. No-op when nothing changed.
19
27
  */
20
28
  save(scannedScopeDir?: string): void;
29
+ /** @implements A-SPEC-769.11 — removes temporary files of this cache's shape older than ten minutes. */
30
+ private sweepTemporaries;
21
31
  }
@@ -34,9 +34,13 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ScanFileCache = exports.SCAN_CACHE_VERSION = void 0;
37
+ exports.scanCacheDirFor = scanCacheDirFor;
37
38
  // @implements A-SPEC-208
38
39
  // @implements A-SPEC-113.1
40
+ // @implements A-SPEC-769.9
41
+ // @implements A-SPEC-769.11
39
42
  const fs = __importStar(require("node:fs"));
43
+ const os = __importStar(require("node:os"));
40
44
  const path = __importStar(require("node:path"));
41
45
  const node_crypto_1 = require("node:crypto");
42
46
  function cloneExpr(e) {
@@ -62,16 +66,36 @@ function cloneDataFlow(df) {
62
66
  // version-3 entry has none, and serving it would put every anchor back on the file for as long as
63
67
  // the file's content did not change.
64
68
  exports.SCAN_CACHE_VERSION = 4;
69
+ /**
70
+ * @implements A-SPEC-769.9 — the one cache directory per workspace root, shared by the refresh child and the Stop
71
+ * hook. Measured 2026-10-15: the Stop hook's uncached scan took 23.0 s of its budget; served from here, 0.48 s.
72
+ */
73
+ function scanCacheDirFor(root, tmp = os.tmpdir()) {
74
+ // @implements A-SPEC-769.11 — a governed workspace keeps the cache in its own .ax (the directory the MCP server
75
+ // uses): the Stop GATE reads it, and a name anyone can compute in the shared /tmp let another local user plant it.
76
+ try {
77
+ if (fs.statSync(path.join(root, '.ax')).isDirectory())
78
+ return path.join(root, '.ax', 'cpg_cache');
79
+ }
80
+ catch { /* not governed */ }
81
+ return path.join(tmp, 'holmes-cpg-cache-' + (0, node_crypto_1.createHash)('sha256').update(root).digest('hex').slice(0, 16));
82
+ }
83
+ // @implements A-SPEC-769.11 — temporary files are `scan-cache.json.<suffix>.tmp`; one older than this is left over
84
+ // from a writer that died between create and rename.
85
+ const TEMP_SWEEP_MS = 10 * 60_000;
86
+ const TEMP_NAME = /^scan-cache\.json\.[0-9a-z.]+\.tmp$/; // the dots admit the former `<pid>.<ms>` names
65
87
  class ScanFileCache {
66
88
  dir;
67
89
  file;
90
+ tempSuffix;
68
91
  entries;
69
92
  seen = new Set();
70
93
  dirty = false;
71
94
  hits = 0;
72
95
  misses = 0;
73
- constructor(dir) {
96
+ constructor(dir, opts = {}) {
74
97
  this.dir = dir;
98
+ this.tempSuffix = opts.tempSuffix ?? (() => (0, node_crypto_1.randomBytes)(6).toString('hex'));
75
99
  this.file = path.join(dir, 'scan-cache.json');
76
100
  try {
77
101
  const raw = JSON.parse(fs.readFileSync(this.file, 'utf8'));
@@ -134,12 +158,58 @@ class ScanFileCache {
134
158
  try {
135
159
  if (this.dirty) {
136
160
  fs.mkdirSync(this.dir, { recursive: true });
137
- fs.writeFileSync(this.file, JSON.stringify({ v: exports.SCAN_CACHE_VERSION, entries: this.entries }), 'utf8');
161
+ // @implements A-SPEC-769.9 — the Stop hook and the refresh child share this file: a reader in the other
162
+ // process sees the old or the new content, never a partly written one.
163
+ // @implements A-SPEC-769.11 — an unpredictable name created exclusively: a file or link already at that name
164
+ // fails the create (another name is tried) and is never written through.
165
+ const body = JSON.stringify({ v: exports.SCAN_CACHE_VERSION, entries: this.entries });
166
+ let tmp;
167
+ for (let attempt = 0; attempt < 3 && tmp === undefined; attempt++) {
168
+ const candidate = `${this.file}.${this.tempSuffix()}.tmp`;
169
+ try {
170
+ fs.writeFileSync(candidate, body, { encoding: 'utf8', flag: 'wx' });
171
+ tmp = candidate;
172
+ }
173
+ catch (error) {
174
+ if (error.code !== 'EEXIST')
175
+ throw error;
176
+ }
177
+ }
178
+ if (tmp === undefined)
179
+ throw new Error('no free temporary name');
180
+ try {
181
+ fs.renameSync(tmp, this.file);
182
+ }
183
+ catch (error) {
184
+ try {
185
+ fs.rmSync(tmp, { force: true });
186
+ }
187
+ catch { /* nothing more to undo */ }
188
+ throw error;
189
+ }
138
190
  this.dirty = false;
191
+ this.sweepTemporaries();
139
192
  }
140
193
  }
141
194
  catch { /* cache persistence is best-effort — next scan just runs colder */ }
142
195
  this.seen.clear();
143
196
  }
197
+ /** @implements A-SPEC-769.11 — removes temporary files of this cache's shape older than ten minutes. */
198
+ sweepTemporaries() {
199
+ try {
200
+ const cutoff = Date.now() - TEMP_SWEEP_MS;
201
+ for (const name of fs.readdirSync(this.dir)) {
202
+ if (!TEMP_NAME.test(name))
203
+ continue;
204
+ const p = path.join(this.dir, name);
205
+ try {
206
+ if (fs.lstatSync(p).mtimeMs < cutoff)
207
+ fs.rmSync(p, { force: true });
208
+ }
209
+ catch { /* raced with its writer */ }
210
+ }
211
+ }
212
+ catch { /* best-effort */ }
213
+ }
144
214
  }
145
215
  exports.ScanFileCache = ScanFileCache;
@@ -24,7 +24,7 @@ export declare const DECISION_KINDS: ReadonlySet<string>;
24
24
  * The line a refusal ends with to name its pending request and the operator command.
25
25
  * @implements A-SPEC-134.2 — one wording for a request just filed and for one that was already pending.
26
26
  */
27
- export declare function pendingRequestLine(id: string, kind?: string): string;
27
+ export declare function pendingRequestLine(id: string, kind?: string, root?: string): string;
28
28
  export interface RefusalRecord {
29
29
  event: 'requested';
30
30
  id: string;
@@ -97,8 +97,14 @@ exports.DECISION_KINDS = new Set([
97
97
  * The line a refusal ends with to name its pending request and the operator command.
98
98
  * @implements A-SPEC-134.2 — one wording for a request just filed and for one that was already pending.
99
99
  */
100
- function pendingRequestLine(id, kind) {
100
+ function pendingRequestLine(id, kind, root) {
101
101
  const command = `${(0, npx_bin_1.npxBin)()} holmes-kit approve`;
102
+ // @implements A-SPEC-770.2 — the request lives in the refusal log / queue of the workspace whose hook refused, not in
103
+ // the shell's cwd (measured 2026-10-12: a command run under a worktree filed its request in the development root;
104
+ // 2026-10-13, Codex X1: the hint carried no `--target` at all). With a root, every command names it; a root with
105
+ // white space is double-quoted once; a root is never folded or relativised. Without a root the A-SPEC-770.1 lines
106
+ // are produced byte for byte.
107
+ const target = root === undefined ? '' : ` --target ${/\s/.test(root) ? `"${root}"` : root}`;
102
108
  // @implements A-SPEC-770 — a request outside the decision inbox (A-SPEC-563.1 routes gate refusals to the local
103
109
  // refusal log) names the id-bearing command, because the bare command opens a screen that by design does not list
104
110
  // it. Field report (jarvis, 2026-10-11): the operator ran the bare command, saw six old inbox requests, and the
@@ -106,9 +112,9 @@ function pendingRequestLine(id, kind) {
106
112
  // @implements A-SPEC-770.1 — the id rides the `--grant` flag: the CLI refuses a positional id (`unexpected
107
113
  // argument: req-…`, measured by the operator on 0.35.17 with the command this line used to name).
108
114
  if (kind !== undefined && !exports.DECISION_KINDS.has(kind)) {
109
- return `\n[승인 대기 ${id}] 운영자: ${command} --grant ${id} — 인박스 화면에는 뜨지 않는 거부입니다(${command} --refusals 로 조회)`;
115
+ return `\n[승인 대기 ${id}] 운영자: ${command} --grant ${id}${target} — 인박스 화면에는 뜨지 않는 거부입니다(${command} --refusals${target} 로 조회)`;
110
116
  }
111
- return `\n[승인 대기 ${id}] 운영자: ${command}`;
117
+ return root === undefined ? `\n[승인 대기 ${id}] 운영자: ${command}` : `\n[승인 대기 ${id}] 운영자: ${command} --grant ${id}${target}`;
112
118
  }
113
119
  const REFUSALS_FILE_RE = /^refusals\.([^.]+)\.jsonl$/;
114
120
  function refusalsFilename(replica) {
@@ -530,7 +536,7 @@ function queueHint(root, req, opts) {
530
536
  // @implements A-SPEC-564.2 — the hint is composed BEFORE the enqueue so the refusal record can
531
537
  // carry its own feedback cost: reasonBytes = the caller's base reason + this hint, i.e. the text
532
538
  // that actually re-enters the conversation. Observation only — nothing reads it on a gate path.
533
- const hint = denialLine + (opts?.pendingHint ? opts.pendingHint(id) : pendingRequestLine(id, req.kind)); // @implements A-SPEC-770
539
+ const hint = denialLine + (opts?.pendingHint ? opts.pendingHint(id) : pendingRequestLine(id, req.kind, root)); // @implements A-SPEC-770, A-SPEC-770.2
534
540
  return enqueueApprovalRequest(root, { ...req, reasonBytes: (opts?.baseReasonBytes ?? 0) + hint.length })
535
541
  ? hint
536
542
  : denialLine;
@@ -1,6 +1,4 @@
1
1
  import { Spec } from '../spec/spec-parser';
2
- /** The out-of-band switch. An agent cannot read or set it — the pre-tool-use gate blocks that
3
- * (A-SPEC-532.2), the same self-disarm protection HOLMES_APPROVAL and HOLMES_GATE_BYPASS have. */
4
2
  export declare const AUTONOMY_ENV = "HOLMES_AUTONOMOUS_APPROVAL";
5
3
  export type ApprovalAutonomy = 'auto' | 'hitl';
6
4
  export declare function isHighRiskPath(p: string): boolean;
@@ -64,6 +64,7 @@ const path = __importStar(require("node:path"));
64
64
  const scope_judgment_1 = require("../guardrail/scope-judgment");
65
65
  /** The out-of-band switch. An agent cannot read or set it — the pre-tool-use gate blocks that
66
66
  * (A-SPEC-532.2), the same self-disarm protection HOLMES_APPROVAL and HOLMES_GATE_BYPASS have. */
67
+ const delegation_1 = require("./delegation"); // @implements A-SPEC-771 — the run delegation, the third envelope
67
68
  exports.AUTONOMY_ENV = 'HOLMES_AUTONOMOUS_APPROVAL';
68
69
  /**
69
70
  * Path prefixes whose files govern the gate, the ledger, taint boundaries, or this session's own
@@ -330,16 +331,25 @@ function autonomousApprovalEnabled(env, root, now) {
330
331
  return true;
331
332
  if (root !== undefined && projectDefaultAutonomy(root))
332
333
  return true; // @implements A-SPEC-560.2
333
- return root !== undefined && now !== undefined && sessionAutonomyActive(root, now);
334
+ if (root !== undefined && now !== undefined && sessionAutonomyActive(root, now))
335
+ return true;
336
+ // @implements A-SPEC-771 — an active run delegation is the third envelope: ON for its workspace while it is valid.
337
+ return root !== undefined && now !== undefined && (0, delegation_1.readDelegation)(root, now).active;
334
338
  }
335
339
  // @implements A-SPEC-554.1 — the session-start REMINDER (the headless hook surfaces, it never decides).
336
340
  // Only ON postures get a line; OFF is silent (a permanent line is one nobody reads). Wired below.
337
341
  function autonomyBanner(env, root, now) {
338
342
  const v = env[exports.AUTONOMY_ENV];
343
+ // @implements A-SPEC-771 — one added line names an active run delegation, beside whichever posture line applies.
344
+ const delegation = (0, delegation_1.readDelegation)(root, now);
345
+ const runLine = delegation.active
346
+ ? `[Holmes-Kit] run delegation: ${delegation.delegation.run} until ${delegation.delegation.expires} — covers ${delegation.delegation.allow.join(', ')}`
347
+ : '';
348
+ const withRun = (line) => (runLine === '' ? line : line === '' ? runLine : `${line}\n${runLine}`);
339
349
  // @implements A-SPEC-560.2 — the project default is visible via env (server-side) OR .mcp.json
340
350
  // (hook-side); either way the banner names the same posture.
341
351
  if ((typeof v === 'string' && v !== '') || projectDefaultAutonomy(root)) {
342
- return '[Holmes-Kit] autonomous spec approval: ON (project default) — governance-critical, high-risk and irreversible specs still ask you.';
352
+ return withRun('[Holmes-Kit] autonomous spec approval: ON (project default) — governance-critical, high-risk and irreversible specs still ask you.');
343
353
  }
344
354
  if (sessionAutonomyActive(root, now)) {
345
355
  let expires = '';
@@ -347,9 +357,9 @@ function autonomyBanner(env, root, now) {
347
357
  expires = String(JSON.parse(fs.readFileSync(path.join(root, ...exports.SESSION_AUTONOMY_MARKER), 'utf8')).expires);
348
358
  }
349
359
  catch { /* the marker parsed inside sessionAutonomyActive; a stray read failure just omits the time */ }
350
- return `[Holmes-Kit] autonomous spec approval: ON (this session, until ${expires}) — governance-critical still ask you. End early: holmes-kit autonomy off.`;
360
+ return withRun(`[Holmes-Kit] autonomous spec approval: ON (this session, until ${expires}) — governance-critical still ask you. End early: holmes-kit autonomy off.`);
351
361
  }
352
- return '';
362
+ return withRun('');
353
363
  }
354
364
  // @implements A-SPEC-554.1 — true when a marker file exists but is NOT active (expired / disabled /
355
365
  // malformed): housekeeping the headless hook may do. A LIVE envelope is never prunable.
@@ -0,0 +1,40 @@
1
+ export declare const DELEGATION_MARKER: readonly [".ax", "state", "delegation.json"];
2
+ export declare const DELEGATION_SCHEMA = "run-delegation/1";
3
+ /** Grader rules an operator may delegate for a run (bare names; a suffixed rule is matched by its bare name). */
4
+ export declare const DELEGABLE_RULES: readonly string[];
5
+ /** Never delegable, whatever the document says: a decision, an un-admitted requirement, an undeclared or unknown grade. */
6
+ export declare const NEVER_DELEGABLE: readonly string[];
7
+ export interface RunDelegation {
8
+ schema: typeof DELEGATION_SCHEMA;
9
+ run: string;
10
+ workspace: string;
11
+ allow: string[];
12
+ issuedAt: string;
13
+ expires: string;
14
+ issuedBy: string;
15
+ limits?: Record<string, string>;
16
+ rationale?: string;
17
+ }
18
+ export type DelegationState = {
19
+ active: true;
20
+ delegation: RunDelegation;
21
+ } | {
22
+ active: false;
23
+ why: 'none' | 'expired' | 'workspace-mismatch' | 'unreadable' | 'invalid';
24
+ expires?: string;
25
+ workspace?: string;
26
+ run?: string;
27
+ };
28
+ export declare const RUN_ID_RE: RegExp;
29
+ /** The bare rule name a grader reason resolves to: the child rule of an upstream reason, with any `: <argument>` dropped. */
30
+ export declare function baseRule(rule: string): string;
31
+ /** Read the document for `root` as it stands at `now`. Fail-closed: anything unreadable or malformed grants nothing. */
32
+ export declare function readDelegation(root: string, now: string): DelegationState;
33
+ /** Whether an active delegation covers the grader reason `rule` (its bare name must be delegable and in `allow`). */
34
+ export declare function delegationCovers(d: RunDelegation, rule: string): boolean;
35
+ /** The one refusal line that names which limit of the delegation applied (empty when there is no document). */
36
+ export declare function delegationNote(state: DelegationState, rule: string): string;
37
+ /** Write the document for the CLI (operator proof is the caller's job). Returns the written document. */
38
+ export declare function writeDelegation(root: string, d: RunDelegation): void;
39
+ /** Remove the document; true when one was there. Never throws on absence. */
40
+ export declare function removeDelegation(root: string): boolean;