@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
@@ -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) {
@@ -214,9 +225,12 @@ const USAGE = `holmes-kit — deterministic ASE governance for a project
214
225
  --dry-run print the diff, write nothing
215
226
  --remove remove holmes-kit wiring (holmes-owned entries only)
216
227
  --force re-wire an already-wired target (requires HOLMES_APPROVAL)
217
- --autonomy grant autonomous spec approval (low-risk only; governance-critical
218
- still ask you). Non-interactive: requires HOLMES_APPROVAL. At a TTY,
219
- init asks instead. Off is default; turn off with --no-autonomy.
228
+ --autonomy grant autonomous spec approval (low-risk only; high-risk, architecture
229
+ and gate specs still ask you). This explicit flag is the
230
+ non-interactive spelling: never prompted, even at a terminal; it needs
231
+ an out-of-band HOLMES_APPROVAL of kind "autonomy-grant". To be ASKED,
232
+ run init at a terminal WITHOUT --autonomy. Off is default;
233
+ --no-autonomy keeps it off.
220
234
  --no-autonomy keep every spec approval human (default)
221
235
 
222
236
  holmes-kit ledger rechain re-chain forked ledger files against the committed mainline
@@ -236,7 +250,12 @@ const USAGE = `holmes-kit — deterministic ASE governance for a project
236
250
  <ref> list index (1,2,…), full id, or a unique id prefix
237
251
  --target <dir> project root (default: cwd)
238
252
 
239
- 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)
240
259
  on [--for 2h] self-drive low-risk specs this session (governance-critical still
241
260
  ask you); at a TTY it just asks, non-interactive needs HOLMES_APPROVAL
242
261
  off end it now (always free)
@@ -312,7 +331,7 @@ async function main(argv) {
312
331
  // silently wrote into CWD while the named target stayed stale (round-3 HIGH).
313
332
  const expected = cmd === 'runtime-binding' ? ['setup', 'status', 'remove'] : cmd === 'guidance' ? ['check', 'refresh'] : cmd === 'skills' ? ['refresh'] : cmd === 'ledger' ? ['rechain']
314
333
  : cmd === 'semantic-key' ? ['set', 'unset', 'status']
315
- : cmd === 'autonomy' ? ['status', 'on', 'off'] : [];
334
+ : cmd === 'autonomy' ? ['status', 'on', 'off', 'delegate', 'revoke-delegation'] : []; // @implements A-SPEC-771.1
316
335
  const unexpected = positionals.filter((p) => !expected.includes(p));
317
336
  if (unexpected.length > 0) {
318
337
  const hint = fs.existsSync(unexpected[0]) ? ` — did you mean --target ${unexpected[0]}?` : '';
@@ -404,12 +423,15 @@ async function main(argv) {
404
423
  const { runAutonomy } = await Promise.resolve().then(() => __importStar(require('./autonomy')));
405
424
  const root = path.resolve(typeof flags.target === 'string' ? flags.target : process.cwd());
406
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') };
407
429
  return (0, cli_execution_1.runOperatorExecution)(root, () => {
408
430
  const r = runAutonomy(root, positionals[0], forStr, {
409
431
  now: new Date().toISOString(),
410
432
  isTTY: !!process.stdin.isTTY && !!process.stdout.isTTY,
411
433
  approval: readApproval(),
412
- });
434
+ }, extra);
413
435
  process[r.ok ? 'stdout' : 'stderr'].write(`${r.message}\n`);
414
436
  return r.exitCode;
415
437
  });
@@ -999,7 +1021,9 @@ async function main(argv) {
999
1021
  const queueOpts = stale ? { now: Date.now(), ttlMs: stale.ttlMs } : undefined;
1000
1022
  const listView = stale ? { staleHours: stale.ttlMs / 3_600_000, showAll: stale.showAll } : undefined;
1001
1023
  if (flags.list) {
1002
- process.stdout.write(renderPending(readQueue(root, queueOpts), listView) + '\n');
1024
+ // @implements A-SPEC-770 — the list ends with the count of refusals outside it.
1025
+ const { refusalsOutsideInbox } = require('../governance/approval-queue');
1026
+ process.stdout.write(renderPending(readQueue(root, queueOpts), listView, refusalsOutsideInbox(root), root) + '\n'); // @implements A-SPEC-770.2
1003
1027
  return 0;
1004
1028
  }
1005
1029
  // @implements A-SPEC-650 — the whole picture, read-only; the list above stays script-clean.
@@ -1017,7 +1041,7 @@ async function main(argv) {
1017
1041
  process.stderr.write(`✗ --refusals expects a positive integer count — received: ${flags.refusals}\n`);
1018
1042
  return 1;
1019
1043
  }
1020
- process.stdout.write(renderRefusals(readRefusals(root), limit) + '\n');
1044
+ process.stdout.write(renderRefusals(readRefusals(root), limit, root) + '\n'); // @implements A-SPEC-770.2
1021
1045
  return 0;
1022
1046
  }
1023
1047
  // @implements A-SPEC-262.2 — the RESIDENT surface. Validate --poll-ms first (so a bad value is
@@ -570,7 +570,9 @@ function runInitUnguarded(opts) {
570
570
  if (opts.autonomy === true && !opts.autonomyInteractive
571
571
  && !(0, risk_gate_1.approvalCovers)(opts.approval, { kind: 'autonomy-grant', target: opts.target }, new Date().toISOString())) {
572
572
  return { ok: false, exitCode: 2, changes, messages: [
573
- 'Enabling autonomous spec approval needs a human: answer the interactive prompt at a terminal, or supply an out-of-band approval.',
573
+ // @implements A-SPEC-769.1 — the flag is never prompted (X1, 2026-10-12: the old line sent the operator to a prompt
574
+ // that does not open with the flag).
575
+ 'Enabling autonomous spec approval needs a human: --autonomy is the non-interactive spelling and is never prompted, even at a terminal. Run init at a terminal WITHOUT --autonomy to be asked, or supply an out-of-band approval.',
574
576
  `Set HOLMES_APPROVAL='{"actor":"<you>","token":"<any>","rationale":"<why>"}' (scoped approvals need kind "autonomy-grant") and re-run with --autonomy.`,
575
577
  ] };
576
578
  }
@@ -14,4 +14,9 @@ export declare function promptAgentSelection(availableAgents?: readonly Agent[],
14
14
  * Non-TTY returns false (leave HITL); the caller does not treat that as an interactive answer.
15
15
  * Default is NO — autonomy is opt-in.
16
16
  */
17
+ /**
18
+ * @implements A-SPEC-769.1 — what the prompt says matches the grader (X1, 2026-10-12: the old text said REQ/H-SPEC
19
+ * "ALWAYS ask", while A-SPEC-587 seals an upstream autonomously when every A-SPEC beneath it is low-risk).
20
+ */
21
+ export declare const AUTONOMY_PROMPT_TEXT: string;
17
22
  export declare function promptAutonomy(): Promise<boolean>;
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.AUTONOMY_PROMPT_TEXT = void 0;
36
37
  exports.parseAgentList = parseAgentList;
37
38
  exports.promptAgentSelection = promptAgentSelection;
38
39
  exports.promptAutonomy = promptAutonomy;
@@ -157,15 +158,22 @@ async function promptAgentSelection(availableAgents = agents_1.AGENTS, currentWi
157
158
  * Non-TTY returns false (leave HITL); the caller does not treat that as an interactive answer.
158
159
  * Default is NO — autonomy is opt-in.
159
160
  */
161
+ /**
162
+ * @implements A-SPEC-769.1 — what the prompt says matches the grader (X1, 2026-10-12: the old text said REQ/H-SPEC
163
+ * "ALWAYS ask", while A-SPEC-587 seals an upstream autonomously when every A-SPEC beneath it is low-risk).
164
+ */
165
+ exports.AUTONOMY_PROMPT_TEXT = '\n 🔑 Autonomous spec approval\n'
166
+ + ' The agent may self-approve LOW-RISK specs (tests, benign changes). High-risk and irreversible\n'
167
+ + ' specs (C-SPEC/ADR, gate/security/architecture files, root-only or unbounded Files to Touch)\n'
168
+ + ' still ask you; a REQ or H-SPEC seals on its own only when every A-SPEC beneath it is low-risk,\n'
169
+ + ' and a REQ never admitted through requirement_triage always asks. You can turn this off\n'
170
+ + ' anytime: holmes-kit autonomy off.\n';
160
171
  async function promptAutonomy() {
161
172
  if (!process.stdin.isTTY || !process.stdout.isTTY)
162
173
  return false;
163
174
  return new Promise((resolve) => {
164
175
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
165
- process.stdout.write('\n 🔑 Autonomous spec approval\n'
166
- + ' The agent may self-approve LOW-RISK specs (tests, benign changes). Governance-critical,\n'
167
- + ' high-risk and irreversible specs (REQ/H-SPEC/C-SPEC, gate/security/architecture) ALWAYS\n'
168
- + ' ask you. You can turn this off anytime: holmes-kit autonomy off.\n');
176
+ process.stdout.write(exports.AUTONOMY_PROMPT_TEXT);
169
177
  rl.question(' Grant autonomous spec approval for this project? [y/N] ', (ans) => {
170
178
  rl.close();
171
179
  resolve(/^\s*y(es)?\s*$/i.test(ans));
@@ -33,9 +33,31 @@ 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[];
55
+ drift: {
56
+ path: string;
57
+ kind: "operator-config" | "stale-workspace";
58
+ }[];
59
+ duplicateRoutes: DuplicateRoute[];
60
+ router: "changed" | "intact";
39
61
  activation: "unverified";
40
62
  };
41
63
  export declare function runRuntimeBinding(opts: RuntimeBindingOptions): unknown;
@@ -38,6 +38,7 @@ 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;
@@ -161,12 +162,102 @@ function registryWiringOwnership(file, registryPath = (0, exports.defaultRuntime
161
162
  function registryOwnedWiring(file, registryPath) {
162
163
  return registryWiringOwnership(file, registryPath).owned;
163
164
  }
164
- function runtimeBindingStatus(registryPath, workspace) {
165
- const selection = (0, binding_1.selectRuntime)((0, binding_1.readRuntimeRegistry)(registryPath), { cwd: workspace });
165
+ const CODEX_LIFECYCLES = [
166
+ ['PreToolUse', 'pre_tool_use', 'pre-tool-use'], ['Stop', 'stop', 'stop'], ['SessionStart', 'session_start', 'session-start'],
167
+ ];
168
+ /** For each lifecycle the file routes to a Holmes router: the `<group>:<hook>` index of that entry. */
169
+ function holmesRoutesIn(file) {
170
+ let doc;
171
+ try {
172
+ const raw = readOptional(file); // a strict decode may throw on bytes Codex itself refuses: nothing to report
173
+ if (raw === null)
174
+ return null;
175
+ doc = JSON.parse(raw);
176
+ }
177
+ catch {
178
+ return null;
179
+ }
180
+ const hooks = doc?.hooks;
181
+ if (!object(hooks))
182
+ return null;
183
+ const out = new Map();
184
+ for (const [jsonKey, stateKey, router] of CODEX_LIFECYCLES) {
185
+ const groups = hooks[jsonKey];
186
+ if (!Array.isArray(groups))
187
+ continue;
188
+ groups.forEach((group, g) => {
189
+ const entries = group?.hooks;
190
+ if (!Array.isArray(entries))
191
+ return;
192
+ entries.forEach((entry, h) => {
193
+ const command = entry?.command;
194
+ if (typeof command !== 'string' || out.has(stateKey))
195
+ return;
196
+ if (/holmes/i.test(command) && command.includes(`${router}.js`))
197
+ out.set(stateKey, `${g}:${h}`);
198
+ });
199
+ });
200
+ }
201
+ return out;
202
+ }
203
+ function codexDuplicateRoutes(codexHome, workspace) {
204
+ const userHooks = path.join(codexHome, 'hooks.json');
205
+ const wsHooks = path.join(workspace, '.codex', 'hooks.json');
206
+ const user = holmesRoutesIn(userHooks);
207
+ const ws = holmesRoutesIn(wsHooks);
208
+ if (user === null || ws === null)
209
+ return [];
210
+ const configPath = path.join(codexHome, 'config.toml');
211
+ let state = {};
212
+ try {
213
+ const rawConfig = readOptional(configPath);
214
+ if (rawConfig !== null) {
215
+ const parsed = (0, codex_toml_1.parseCodexConfig)(rawConfig);
216
+ const table = parsed.ok ? parsed.doc.hooks?.state : undefined;
217
+ if (object(table))
218
+ state = table;
219
+ }
220
+ }
221
+ catch { /* an unreadable config: every entry counts as on, which is what Codex does with a file it cannot load */ }
222
+ const out = [];
223
+ for (const [, stateKey] of CODEX_LIFECYCLES) {
224
+ const index = user.get(stateKey);
225
+ if (index === undefined || !ws.has(stateKey))
226
+ continue;
227
+ const key = `${userHooks}:${stateKey}:${index}`;
228
+ const entry = state[key];
229
+ if (object(entry) && entry.enabled === false)
230
+ continue;
231
+ out.push({ harness: 'codex', event: stateKey, files: [userHooks, wsHooks],
232
+ fix: `set enabled = false under [hooks.state."${key}"] in ${configPath} (or remove the ${stateKey} entry from one file) — Holmes runs once per lifecycle` });
233
+ }
234
+ return out;
235
+ }
236
+ function runtimeBindingStatus(registryPath, workspace, opts) {
237
+ const registry = (0, binding_1.readRuntimeRegistry)(registryPath);
238
+ const selection = (0, binding_1.selectRuntime)(registry, { cwd: workspace });
166
239
  const manifest = readOptional(path.join(path.dirname(registryPath), 'installation.json'));
167
240
  const conflicts = [];
168
- if (manifest === null)
241
+ // @implements A-SPEC-769.3 — a row that differs from the receipt is classified, not only counted. Measured 2026-10-12
242
+ // (X1): every router file under the registry directory matched, and the "conflicts" were operator-owned configuration
243
+ // that changes by design (hook trust state, Claude settings) plus six rows of a removed temporary workspace — on which
244
+ // doctor refused the routed identity and called the intact router "not this install's server".
245
+ // @implements A-SPEC-769.5 / A-SPEC-769.6 — what counts as operator drift is only what was MEASURED to change by
246
+ // design: the registry file (a dead binding is deleted by hand; the dispatcher reads the registry live) and the Codex
247
+ // USER config (Codex rewrites its `[projects.*]`, `[hooks.state.*]`, plugin and marketplace tables itself). Every
248
+ // other wiring file — Claude settings (A-SPEC-752.5/752.6: a digest cannot say which key changed, and some keys
249
+ // switch Holmes off), `.mcp.json`, the Codex hooks files, a project Codex config, the Antigravity files — keeps the
250
+ // receipt conflict. The ROUTER verdict is the receipt rows under the registry directory alone.
251
+ const drift = [];
252
+ const registryDir = path.dirname(registryPath);
253
+ const under = (dir, file) => { const rel = path.relative(dir, file); return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); };
254
+ const workspaceRoots = registry.bindings.map((b) => b.workspaceRoot);
255
+ const codexUserConfig = (file) => path.basename(file) === 'config.toml' && path.basename(path.dirname(file)) === '.codex' && !workspaceRoots.some((w) => under(w, file));
256
+ let routerChanged = false;
257
+ if (manifest === null) {
169
258
  conflicts.push('No installation receipt; registry selection alone does not establish wiring');
259
+ routerChanged = true;
260
+ }
170
261
  else {
171
262
  const rows = document(manifest, 'installation.json').files;
172
263
  if (!Array.isArray(rows))
@@ -176,11 +267,32 @@ function runtimeBindingStatus(registryPath, workspace) {
176
267
  throw new Error('Invalid installation file record');
177
268
  const current = readOptional(row.path);
178
269
  // A-SPEC-752.5: the view's digest, or the whole file's for a row written before the view existed.
179
- if (current === null || (digest(wiringViewOf(row.path, current)) !== row.digest && digest(current) !== row.digest))
270
+ if (current !== null && (digest(wiringViewOf(row.path, current)) === row.digest || digest(current) === row.digest))
271
+ continue;
272
+ const registryFile = current !== null && path.resolve(row.path) === path.resolve(registryPath);
273
+ // 1. a router program (or the receipt's neighbours) under the registry directory: a conflict, and the router is changed.
274
+ if (under(registryDir, row.path) && !registryFile) {
180
275
  conflicts.push(`Wiring changed or incomplete: ${row.path}`);
276
+ routerChanged = true;
277
+ continue;
278
+ }
279
+ // 2./3. the registry file, or the Codex user config, present but changed: operator drift.
280
+ if (registryFile || (current !== null && codexUserConfig(row.path))) {
281
+ drift.push({ path: row.path, kind: 'operator-config' });
282
+ continue;
283
+ }
284
+ // 4. a missing file whose directory is gone: a stale row of a workspace that no longer exists.
285
+ if (current === null && !fs.existsSync(path.dirname(row.path))) {
286
+ drift.push({ path: row.path, kind: 'stale-workspace' });
287
+ continue;
288
+ }
289
+ // 5. everything else — a changed wiring file, or a living workspace that lost one: the receipt conflict as before.
290
+ conflicts.push(`Wiring changed or incomplete: ${row.path}`);
181
291
  }
182
292
  }
183
- return { selection, conflicts, activation: 'unverified' };
293
+ // @implements A-SPEC-769.8 — reported beside the receipt verdicts; it changes neither `conflicts` nor `router`.
294
+ const duplicateRoutes = codexDuplicateRoutes(opts?.codexHome ?? path.join(os.homedir(), '.codex'), workspace);
295
+ return { selection, conflicts, drift, duplicateRoutes, router: routerChanged ? 'changed' : 'intact', activation: 'unverified' };
184
296
  }
185
297
  function runRuntimeBinding(opts) {
186
298
  if (opts.activateHooks !== undefined && (!Array.isArray(opts.activateHooks)
@@ -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): 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;
@@ -222,6 +222,12 @@ export declare function queueHint(root: string, req: {
222
222
  *
223
223
  * Measured 2026-09-19: `readRefusals` found req-9e92e52bd233 while `approve --grant` refused it.
224
224
  */
225
+ /**
226
+ * @implements A-SPEC-770 — how many open requests this machine's refusal log (and any pre-split queue row of a
227
+ * non-decision kind) holds that the inbox screen does not list. Information for a footer, never a lever: an
228
+ * unreadable store counts 0 (the list itself still renders as today).
229
+ */
230
+ export declare function refusalsOutsideInbox(root: string): number;
225
231
  export declare function grantableRequests(root: string): PendingRequest[];
226
232
  /**
227
233
  * @implements A-SPEC-690
@@ -45,6 +45,7 @@ exports.enqueueApprovalRequestDetailed = enqueueApprovalRequestDetailed;
45
45
  exports.appendQueueEvent = appendQueueEvent;
46
46
  exports.readQueue = readQueue;
47
47
  exports.queueHint = queueHint;
48
+ exports.refusalsOutsideInbox = refusalsOutsideInbox;
48
49
  exports.grantableRequests = grantableRequests;
49
50
  exports.openOccurrences = openOccurrences;
50
51
  exports.asPendingRequest = asPendingRequest;
@@ -96,8 +97,24 @@ exports.DECISION_KINDS = new Set([
96
97
  * The line a refusal ends with to name its pending request and the operator command.
97
98
  * @implements A-SPEC-134.2 — one wording for a request just filed and for one that was already pending.
98
99
  */
99
- function pendingRequestLine(id) {
100
- return `\n[승인 대기 ${id}] 운영자: ${(0, npx_bin_1.npxBin)()} holmes-kit approve`;
100
+ function pendingRequestLine(id, kind, root) {
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}`;
108
+ // @implements A-SPEC-770 — a request outside the decision inbox (A-SPEC-563.1 routes gate refusals to the local
109
+ // refusal log) names the id-bearing command, because the bare command opens a screen that by design does not list
110
+ // it. Field report (jarvis, 2026-10-11): the operator ran the bare command, saw six old inbox requests, and the
111
+ // agent's shell command was refused again with the same id. A decision kind keeps the short line: it IS listed.
112
+ // @implements A-SPEC-770.1 — the id rides the `--grant` flag: the CLI refuses a positional id (`unexpected
113
+ // argument: req-…`, measured by the operator on 0.35.17 with the command this line used to name).
114
+ if (kind !== undefined && !exports.DECISION_KINDS.has(kind)) {
115
+ return `\n[승인 대기 ${id}] 운영자: ${command} --grant ${id}${target} — 인박스 화면에는 뜨지 않는 거부입니다(${command} --refusals${target} 로 조회)`;
116
+ }
117
+ return root === undefined ? `\n[승인 대기 ${id}] 운영자: ${command}` : `\n[승인 대기 ${id}] 운영자: ${command} --grant ${id}${target}`;
101
118
  }
102
119
  const REFUSALS_FILE_RE = /^refusals\.([^.]+)\.jsonl$/;
103
120
  function refusalsFilename(replica) {
@@ -519,7 +536,7 @@ function queueHint(root, req, opts) {
519
536
  // @implements A-SPEC-564.2 — the hint is composed BEFORE the enqueue so the refusal record can
520
537
  // carry its own feedback cost: reasonBytes = the caller's base reason + this hint, i.e. the text
521
538
  // that actually re-enters the conversation. Observation only — nothing reads it on a gate path.
522
- const hint = denialLine + (opts?.pendingHint ? opts.pendingHint(id) : pendingRequestLine(id));
539
+ const hint = denialLine + (opts?.pendingHint ? opts.pendingHint(id) : pendingRequestLine(id, req.kind, root)); // @implements A-SPEC-770, A-SPEC-770.2
523
540
  return enqueueApprovalRequest(root, { ...req, reasonBytes: (opts?.baseReasonBytes ?? 0) + hint.length })
524
541
  ? hint
525
542
  : denialLine;
@@ -537,6 +554,20 @@ function queueHint(root, req, opts) {
537
554
  *
538
555
  * Measured 2026-09-19: `readRefusals` found req-9e92e52bd233 while `approve --grant` refused it.
539
556
  */
557
+ /**
558
+ * @implements A-SPEC-770 — how many open requests this machine's refusal log (and any pre-split queue row of a
559
+ * non-decision kind) holds that the inbox screen does not list. Information for a footer, never a lever: an
560
+ * unreadable store counts 0 (the list itself still renders as today).
561
+ */
562
+ function refusalsOutsideInbox(root) {
563
+ try {
564
+ const inbox = new Set(readQueue(root).pending.map((p) => p.id));
565
+ return grantableRequests(root).filter((p) => !inbox.has(p.id)).length;
566
+ }
567
+ catch {
568
+ return 0;
569
+ }
570
+ }
540
571
  function grantableRequests(root) {
541
572
  const state = readQueue(root, { includeAllKinds: true });
542
573
  const seen = new Set(state.pending.map((p) => p.id));
@@ -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
@@ -185,6 +186,10 @@ function autonomyRuleMeaning(rule) {
185
186
  return 'the gate change does not declare its direction as tightens or wording';
186
187
  if (rule.startsWith('breaking-change-'))
187
188
  return rule === 'breaking-change-undeclared' ? 'breaking_change is not declared' : 'the breaking_change grade is not one the grader knows';
189
+ // @implements A-SPEC-769 — `upstream-has-human-aspec: <child id> — <child rule>` composes the child's own meaning.
190
+ const upstream = /^upstream-has-human-aspec: (\S+) — (.+)$/.exec(rule);
191
+ if (upstream)
192
+ return `an A-SPEC beneath it (${upstream[1]}) is the operator's to seal — ${autonomyRuleMeaning(upstream[2])}`;
188
193
  switch (rule) {
189
194
  case 'upstream-without-aspec': return 'no A-SPEC exists beneath it yet, so its scope is unknown';
190
195
  case 'upstream-has-human-aspec': return 'an A-SPEC beneath it is the operator\'s to seal';
@@ -209,7 +214,15 @@ function specApprovalAutonomyReason(spec, resolveParent, descendants) {
209
214
  const below = (descendants ?? []).filter((s) => s.type === 'A-SPEC');
210
215
  if (below.length === 0)
211
216
  return 'upstream-without-aspec'; // unknown scope stays human
212
- return below.every((a) => specApprovalAutonomyReason(a, resolveParent) === null) ? null : 'upstream-has-human-aspec';
217
+ // @implements A-SPEC-769 — the FIRST child that is the operator's, with its own rule: X1 (2026-10-12) handed a
218
+ // REQ and an H-SPEC to the operator over one A-SPEC's root-only Files to Touch, and the note said only that
219
+ // "an A-SPEC beneath it" was the operator's — neither the agent nor the operator could tell which, or why.
220
+ for (const a of below) {
221
+ const childRule = specApprovalAutonomyReason(a, resolveParent);
222
+ if (childRule !== null)
223
+ return `upstream-has-human-aspec: ${a.id} — ${childRule}`;
224
+ }
225
+ return null;
213
226
  }
214
227
  case 'C-SPEC':
215
228
  case 'ADR': // @implements A-SPEC-571.1 — a decision is the human's to seal
@@ -318,16 +331,25 @@ function autonomousApprovalEnabled(env, root, now) {
318
331
  return true;
319
332
  if (root !== undefined && projectDefaultAutonomy(root))
320
333
  return true; // @implements A-SPEC-560.2
321
- 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;
322
338
  }
323
339
  // @implements A-SPEC-554.1 — the session-start REMINDER (the headless hook surfaces, it never decides).
324
340
  // Only ON postures get a line; OFF is silent (a permanent line is one nobody reads). Wired below.
325
341
  function autonomyBanner(env, root, now) {
326
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}`);
327
349
  // @implements A-SPEC-560.2 — the project default is visible via env (server-side) OR .mcp.json
328
350
  // (hook-side); either way the banner names the same posture.
329
351
  if ((typeof v === 'string' && v !== '') || projectDefaultAutonomy(root)) {
330
- 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.');
331
353
  }
332
354
  if (sessionAutonomyActive(root, now)) {
333
355
  let expires = '';
@@ -335,9 +357,9 @@ function autonomyBanner(env, root, now) {
335
357
  expires = String(JSON.parse(fs.readFileSync(path.join(root, ...exports.SESSION_AUTONOMY_MARKER), 'utf8')).expires);
336
358
  }
337
359
  catch { /* the marker parsed inside sessionAutonomyActive; a stray read failure just omits the time */ }
338
- 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.`);
339
361
  }
340
- return '';
362
+ return withRun('');
341
363
  }
342
364
  // @implements A-SPEC-554.1 — true when a marker file exists but is NOT active (expired / disabled /
343
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;