@holmes-lab/holmes-kit 0.35.25 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +3 -2
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-status.js +4 -1
  5. package/dist/holmes/cli/approve-watch.js +3 -1
  6. package/dist/holmes/cli/approve.d.ts +10 -0
  7. package/dist/holmes/cli/approve.js +31 -1
  8. package/dist/holmes/cli/claude-switches.d.ts +7 -1
  9. package/dist/holmes/cli/claude-switches.js +11 -7
  10. package/dist/holmes/cli/codex-toml.d.ts +3 -0
  11. package/dist/holmes/cli/codex-toml.js +2 -1
  12. package/dist/holmes/cli/doctor.d.ts +25 -1
  13. package/dist/holmes/cli/doctor.js +153 -7
  14. package/dist/holmes/cli/index.js +99 -4
  15. package/dist/holmes/cli/init.js +4 -3
  16. package/dist/holmes/cli/os-notify.d.ts +3 -1
  17. package/dist/holmes/cli/os-notify.js +10 -4
  18. package/dist/holmes/cli/review.d.ts +25 -0
  19. package/dist/holmes/cli/review.js +111 -0
  20. package/dist/holmes/cli/roles-readme.d.ts +11 -0
  21. package/dist/holmes/cli/roles-readme.js +38 -16
  22. package/dist/holmes/cli/roles.d.ts +12 -0
  23. package/dist/holmes/cli/roles.js +86 -0
  24. package/dist/holmes/cli/run.d.ts +65 -0
  25. package/dist/holmes/cli/run.js +308 -0
  26. package/dist/holmes/cli/runtime-binding.d.ts +30 -0
  27. package/dist/holmes/cli/runtime-binding.js +96 -7
  28. package/dist/holmes/cli/test-platform.d.ts +16 -0
  29. package/dist/holmes/cli/test-platform.js +31 -1
  30. package/dist/holmes/config/config.d.ts +49 -0
  31. package/dist/holmes/config/config.js +146 -3
  32. package/dist/holmes/config/project-caps.d.ts +21 -0
  33. package/dist/holmes/config/project-caps.js +114 -0
  34. package/dist/holmes/governance/approval-queue.d.ts +17 -3
  35. package/dist/holmes/governance/approval-queue.js +48 -6
  36. package/dist/holmes/governance/autonomy.d.ts +6 -0
  37. package/dist/holmes/governance/autonomy.js +21 -0
  38. package/dist/holmes/governance/push-gate-runner.d.ts +8 -0
  39. package/dist/holmes/governance/push-gate-runner.js +49 -1
  40. package/dist/holmes/governance/replica-id.d.ts +9 -0
  41. package/dist/holmes/governance/replica-id.js +44 -7
  42. package/dist/holmes/governance/role-policy.d.ts +41 -1
  43. package/dist/holmes/governance/role-policy.js +137 -20
  44. package/dist/holmes/governance/run-mode.d.ts +14 -0
  45. package/dist/holmes/governance/run-mode.js +120 -0
  46. package/dist/holmes/governance/tool-actions.d.ts +30 -0
  47. package/dist/holmes/governance/tool-actions.js +121 -0
  48. package/dist/holmes/guardrail/agent-launch-policy.d.ts +15 -0
  49. package/dist/holmes/guardrail/agent-launch-policy.js +177 -0
  50. package/dist/holmes/guardrail/classification-mode.d.ts +17 -0
  51. package/dist/holmes/guardrail/classification-mode.js +135 -0
  52. package/dist/holmes/guardrail/dynamic-write.d.ts +43 -0
  53. package/dist/holmes/guardrail/dynamic-write.js +304 -0
  54. package/dist/holmes/guardrail/phase.d.ts +2 -1
  55. package/dist/holmes/guardrail/phase.js +22 -8
  56. package/dist/holmes/guardrail/powershell-shell.d.ts +21 -0
  57. package/dist/holmes/guardrail/powershell-shell.js +801 -0
  58. package/dist/holmes/guardrail/refusal-codes.d.ts +24 -0
  59. package/dist/holmes/guardrail/refusal-codes.js +140 -0
  60. package/dist/holmes/guardrail/risk-classifier.d.ts +17 -0
  61. package/dist/holmes/guardrail/risk-classifier.js +242 -26
  62. package/dist/holmes/guardrail/risk-types.d.ts +15 -0
  63. package/dist/holmes/guardrail/run-plan-scope.d.ts +23 -0
  64. package/dist/holmes/guardrail/run-plan-scope.js +155 -0
  65. package/dist/holmes/guardrail/run-refusals.d.ts +116 -0
  66. package/dist/holmes/guardrail/run-refusals.js +348 -0
  67. package/dist/holmes/guardrail/run-stages.d.ts +67 -0
  68. package/dist/holmes/guardrail/run-stages.js +188 -0
  69. package/dist/holmes/guardrail/scope-judgment.d.ts +5 -1
  70. package/dist/holmes/guardrail/scope-judgment.js +8 -10
  71. package/dist/holmes/guardrail/scope-refusal-memory.d.ts +3 -0
  72. package/dist/holmes/guardrail/scope-refusal-memory.js +85 -0
  73. package/dist/holmes/guardrail/shell-words.js +7 -7
  74. package/dist/holmes/guardrail/write-target.d.ts +31 -2
  75. package/dist/holmes/guardrail/write-target.js +118 -16
  76. package/dist/holmes/hooks/pre-tool-use.d.ts +35 -1
  77. package/dist/holmes/hooks/pre-tool-use.js +702 -81
  78. package/dist/holmes/hooks/session-start.js +5 -3
  79. package/dist/holmes/hooks/stop.d.ts +32 -0
  80. package/dist/holmes/hooks/stop.js +129 -4
  81. package/dist/holmes/mcp/handlers/graph-operations.js +5 -5
  82. package/dist/holmes/mcp/handlers/maintenance-analysis.js +2 -2
  83. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -1
  84. package/dist/holmes/mcp/handlers/operator-inspection.js +3 -1
  85. package/dist/holmes/mcp/handlers/phase-queries.js +16 -1
  86. package/dist/holmes/mcp/handlers/requirement-triage.js +2 -2
  87. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -3
  88. package/dist/holmes/mcp/handlers/spec-approval.js +54 -8
  89. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +1 -0
  90. package/dist/holmes/mcp/handlers/spec-lifecycle.js +3 -3
  91. package/dist/holmes/mcp/handlers/spec-queries.d.ts +7 -0
  92. package/dist/holmes/mcp/handlers/spec-queries.js +5 -0
  93. package/dist/holmes/mcp/handlers/workspace-queries.js +2 -2
  94. package/dist/holmes/mcp/handlers.d.ts +2 -3
  95. package/dist/holmes/mcp/handlers.js +22 -2
  96. package/dist/holmes/mcp/harness-attestation.d.ts +2 -0
  97. package/dist/holmes/mcp/harness-attestation.js +3 -1
  98. package/dist/holmes/mcp/operator-recovery.d.ts +2 -0
  99. package/dist/holmes/mcp/operator-recovery.js +4 -3
  100. package/dist/holmes/mcp/server.js +9 -0
  101. package/dist/holmes/mcp/tool-schemas.js +6 -3
  102. package/dist/holmes/project/root.js +6 -1
  103. package/dist/holmes/project/run-records.d.ts +17 -0
  104. package/dist/holmes/project/run-records.js +126 -0
  105. package/dist/holmes/review/mrp.d.ts +35 -0
  106. package/dist/holmes/review/mrp.js +119 -0
  107. package/dist/holmes/review/verdicts.d.ts +117 -0
  108. package/dist/holmes/review/verdicts.js +345 -0
  109. package/dist/holmes/semantic/cloud-usage.d.ts +20 -0
  110. package/dist/holmes/semantic/cloud-usage.js +106 -0
  111. package/dist/holmes/semantic/embedder.d.ts +15 -6
  112. package/dist/holmes/semantic/embedder.js +84 -3
  113. package/dist/holmes/semantic/local-model.d.ts +21 -2
  114. package/dist/holmes/semantic/local-model.js +14 -3
  115. package/dist/holmes/semantic/tier.d.ts +25 -0
  116. package/dist/holmes/semantic/tier.js +86 -1
  117. package/dist/holmes/semantic/vector-cache.d.ts +1 -0
  118. package/dist/holmes/semantic/vector-cache.js +4 -1
  119. package/dist/holmes/spec/approval-blockers.d.ts +11 -1
  120. package/dist/holmes/spec/approval-blockers.js +70 -2
  121. package/dist/holmes/spec/renumber.d.ts +1 -1
  122. package/dist/holmes/spec/renumber.js +5 -2
  123. package/dist/holmes/spec/transition-policy.d.ts +5 -7
  124. package/dist/holmes/spec/transition-policy.js +17 -2
  125. package/package.json +1 -1
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.planTargets = planTargets;
37
+ exports.applyPlanScope = applyPlanScope;
38
+ exports.planScopeRefusal = planScopeRefusal;
39
+ // @implements A-SPEC-102.5, A-SPEC-774.23
40
+ /**
41
+ * @implements A-SPEC-102.5 — plan-then-execute for a remediation run. The operator fixes the plan as A-SPEC ids at
42
+ * `run start --scope`; the run then writes files only inside those specs' Files to Touch. Review findings, PR text and
43
+ * tool output are untrusted input, so a line in them asking for "one more file" cannot widen what the run changes.
44
+ */
45
+ const fs = __importStar(require("node:fs"));
46
+ const path = __importStar(require("node:path"));
47
+ const run_mode_1 = require("../governance/run-mode");
48
+ const run_records_1 = require("../project/run-records");
49
+ const compat_impact_1 = require("../spec/compat-impact");
50
+ const spec_parser_1 = require("../spec/spec-parser");
51
+ const write_target_1 = require("./write-target");
52
+ const FILE_TOOLS = new Set(['write', 'edit', 'multiedit', 'notebookedit']);
53
+ /** The paths a file tool writes; for apply_patch, every target the patch names. */
54
+ function planTargets(tool, input) {
55
+ const name = tool.toLowerCase();
56
+ if (FILE_TOOLS.has(name)) {
57
+ return ['file_path', 'notebook_path', 'path'].map((k) => input[k]).filter((v) => typeof v === 'string' && v !== '');
58
+ }
59
+ if (name === 'apply_patch') {
60
+ const text = [input.input, input.command, input.patch].find((v) => typeof v === 'string') ?? '';
61
+ return (0, write_target_1.patchTargetsOf)(text).flatMap((t) => [t.path, ...(t.movedTo ? [t.movedTo] : [])]);
62
+ }
63
+ return [];
64
+ }
65
+ function findSpec(dir, id, depth = 0) {
66
+ if (depth > 6)
67
+ return null;
68
+ let entries;
69
+ try {
70
+ entries = fs.readdirSync(dir, { withFileTypes: true });
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ for (const e of entries)
76
+ if (e.isFile() && e.name === `${id}.md`)
77
+ return path.join(dir, e.name);
78
+ for (const e of entries) {
79
+ if (!e.isDirectory())
80
+ continue;
81
+ const hit = findSpec(path.join(dir, e.name), id, depth + 1);
82
+ if (hit)
83
+ return hit;
84
+ }
85
+ return null;
86
+ }
87
+ const globRe = (entry) => new RegExp(`^${entry.split('**').map((part) => part.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')).join('.*')}$`);
88
+ function inPlan(rel, entries) {
89
+ return entries.some((e) => rel === e || (e.endsWith('/') && rel.startsWith(e)) || (e.includes('*') && globRe(e).test(rel)));
90
+ }
91
+ function applyPlanScope(out, ctx) {
92
+ if (out.permissionDecision === 'deny')
93
+ return out;
94
+ const targets = planTargets(ctx.tool, ctx.toolInput);
95
+ if (targets.length === 0)
96
+ return out;
97
+ const refusal = planScopeRefusal(ctx, targets);
98
+ return refusal ? { permissionDecision: 'deny', permissionDecisionReason: refusal } : out;
99
+ }
100
+ /**
101
+ * @implements A-SPEC-774.23 — the plan-scope judgement for any writer (file tools, apply_patch, the shell): null when
102
+ * the run is unscoped or every target lies in the plan, otherwise the refusal. A plan that cannot be read refuses,
103
+ * naming what could not be read — a malformed scope, a spec not found or unparseable, an unreadable or empty FtT.
104
+ */
105
+ function planScopeRefusal(ctx, targets) {
106
+ if (targets.length === 0)
107
+ return null;
108
+ const mode = (0, run_mode_1.runMode)(ctx.env, ctx.projectRoot, ctx.cwd, ctx.sessionId);
109
+ if (!mode.run || !mode.id)
110
+ return null;
111
+ const rec = (0, run_records_1.listRuns)((0, run_records_1.mainCheckoutOf)(ctx.projectRoot)).find((r) => r.run_id === mode.id);
112
+ if (!rec || rec.scope === undefined)
113
+ return null; // an unscoped run
114
+ const cannot = (what) => `[Holmes-Kit] the run's plan cannot be read (${what}) — a scoped run writes nothing until its plan reads`;
115
+ if (!Array.isArray(rec.scope) || rec.scope.length === 0 || !rec.scope.every((s) => typeof s === 'string' && s !== '')) {
116
+ return cannot('scope is not a list of A-SPEC ids');
117
+ }
118
+ const scope = rec.scope;
119
+ const entries = [];
120
+ for (const id of scope) {
121
+ const file = findSpec(ctx.specsDir, id);
122
+ if (!file)
123
+ return `[Holmes-Kit] the run's plan spec ${id} cannot be found under ${ctx.specsDir} — a scoped run writes nothing until its plan reads`;
124
+ let spec;
125
+ try {
126
+ spec = (0, spec_parser_1.parseSpec)(fs.readFileSync(file, 'utf8'));
127
+ }
128
+ catch (e) {
129
+ return `[Holmes-Kit] the run's plan spec ${id} cannot be read (${e instanceof Error ? e.message : String(e)}) — a scoped run writes nothing until its plan reads`;
130
+ }
131
+ const sealed = spec.status === 'approved' && typeof spec.frontmatter?.approved_digest === 'string';
132
+ if (!sealed)
133
+ return `[Holmes-Kit] the run's plan spec ${id} is not approved — a scoped run writes nothing until its plan is sealed`;
134
+ let ftt;
135
+ try {
136
+ ftt = (0, compat_impact_1.filesToTouch)(spec);
137
+ }
138
+ catch (e) {
139
+ return `[Holmes-Kit] the Files to Touch of ${id} cannot be read (${e instanceof Error ? e.message : String(e)})`;
140
+ }
141
+ if (ftt.length === 0)
142
+ return `[Holmes-Kit] the Files to Touch of ${id} is empty — a scoped run writes nothing outside an empty plan`;
143
+ entries.push(...ftt);
144
+ }
145
+ const base = path.resolve(ctx.cwd ?? ctx.projectRoot);
146
+ for (const t of targets) {
147
+ const abs = path.isAbsolute(t) ? t : path.resolve(base, t);
148
+ const rel = path.relative(ctx.projectRoot, abs).replace(/\\/g, '/');
149
+ if (!inPlan(rel, entries)) {
150
+ return `[Holmes-Kit] ${rel} is outside the run's plan — it is in no Files to Touch of ${scope.join(', ')} `
151
+ + '(a review or tool text cannot widen the plan; the operator re-plans with a new run)';
152
+ }
153
+ }
154
+ return null;
155
+ }
@@ -0,0 +1,116 @@
1
+ type Install = {
2
+ version: string | null;
3
+ build: string | null;
4
+ };
5
+ export interface RunRefusalEvent {
6
+ ts: string;
7
+ event: 'refusal' | 'awaiting_approval' | 'approval_resolved' | 'approval_expired' | 'install_changed' | 'stage' | 'versions_accepted' | 'stages_interpreted' | 'stop_blocked' | 'stalled';
8
+ /** @implements A-SPEC-778.1 — the constitution articles a blocked Stop named. */
9
+ articles?: string[];
10
+ /** @implements A-SPEC-778.1 — on `stalled`: how many Stops in a row were blocked. */
11
+ count?: number;
12
+ /** @implements A-SPEC-781 — a stage transition: from, to, who moved it and why. */
13
+ from?: string;
14
+ to?: string;
15
+ by?: string;
16
+ why?: string;
17
+ pinned?: Install;
18
+ current?: Install;
19
+ code?: string;
20
+ class?: string;
21
+ tool?: string;
22
+ request?: string;
23
+ queue_root?: string;
24
+ decision?: string;
25
+ /** @implements A-SPEC-774.20 — the version fields run start accepted unread. */
26
+ fields?: string[];
27
+ /** @implements A-SPEC-781.2 — the stage machine's notes, on a `stages_interpreted` event. */
28
+ notes?: string[];
29
+ /** @implements A-SPEC-781.2 — on a `stage` event: transition conditions whose checker is still a slot. */
30
+ unchecked?: string[];
31
+ }
32
+ /** @implements A-SPEC-770.12 — the request id a refusal names, or null. */
33
+ export declare function pendingRequestId(reason: string): string | null;
34
+ export declare const runRefusalsDir: (main: string) => string;
35
+ export declare function runRefusalsFile(main: string, id: string): string;
36
+ /** The run's events; `[]` when the log does not exist yet, `'unreadable'` on any other read error. */
37
+ export declare function readRunRefusals(file: string): RunRefusalEvent[] | 'unreadable';
38
+ type Stop = {
39
+ code: string;
40
+ count: number;
41
+ expired?: string;
42
+ install?: {
43
+ pinned: Install;
44
+ current: Install;
45
+ };
46
+ articles?: string[];
47
+ };
48
+ /** The first code refused `limit` times or more, with its count, the expired approval wait, or an install change; else null. */
49
+ export declare function stoppedBy(events: readonly RunRefusalEvent[], limit: number): Stop | null;
50
+ /** The last approval wait no later event closed, or null. */
51
+ export declare function openWait(events: readonly RunRefusalEvent[]): RunRefusalEvent | null;
52
+ type Decision = {
53
+ permissionDecision: string;
54
+ permissionDecisionReason?: string;
55
+ } & Record<string, unknown>;
56
+ export interface RunRefusalContext {
57
+ projectRoot: string;
58
+ env: NodeJS.ProcessEnv;
59
+ cwd?: string;
60
+ sessionId?: string;
61
+ tool: string;
62
+ now?: () => Date;
63
+ /** @implements A-SPEC-780 — injected in tests; otherwise the package this module runs from. */
64
+ ownInstall?: Install;
65
+ }
66
+ /** @implements A-SPEC-780 — the holmes-kit package above `file`: its directory and version. */
67
+ export declare function holmesPackageAbove(file: string): {
68
+ root: string;
69
+ version: string;
70
+ } | null;
71
+ /** @implements A-SPEC-781 — the run log writer, shared with the stage machine. */
72
+ export declare function appendRunEvent(main: string, runId: string, ev: RunRefusalEvent): boolean;
73
+ export declare function applyRunRefusalStop(out: Decision, ctx: RunRefusalContext): Decision;
74
+ /**
75
+ * @implements A-SPEC-778.1 — the Stop hook's record of a blocked turn in a run. Every block appends `stop_blocked`; the
76
+ * guard's cap yield also appends `stalled` and returns the line that says so. Outside a run, or when the log cannot be
77
+ * written, nothing is recorded and null is returned: the block itself never depends on this.
78
+ */
79
+ export declare function recordRunStopBlock(ctx: {
80
+ projectRoot: string;
81
+ env: NodeJS.ProcessEnv;
82
+ cwd?: string;
83
+ sessionId?: string;
84
+ now?: () => Date;
85
+ }, articles: readonly string[], yielded: boolean): string | null;
86
+ /** @implements A-SPEC-779 — the run's state, from its log alone. */
87
+ export declare function runState(main: string, runId: string, opts: {
88
+ limit: number;
89
+ waitMinutes: number;
90
+ now?: () => Date;
91
+ }): {
92
+ state: 'running' | 'awaiting_approval' | 'stopped' | 'stalled';
93
+ awaiting?: {
94
+ request: string;
95
+ code: string;
96
+ since: string;
97
+ };
98
+ stopped?: {
99
+ code: string;
100
+ count: number;
101
+ expired?: string;
102
+ articles?: string[];
103
+ } | {
104
+ unreadable: true;
105
+ };
106
+ };
107
+ /**
108
+ * @implements A-SPEC-779 — a grant is the operator's, from their own terminal (owner decision 2026-10-18): a process
109
+ * carrying a run marker never grants, and a run's awaited request is not granted from a non-terminal. A deny is never
110
+ * asked here.
111
+ */
112
+ export declare function grantGuard(root: string, id: string, opts: {
113
+ env: NodeJS.ProcessEnv;
114
+ interactive: boolean;
115
+ }): string | null;
116
+ export {};
@@ -0,0 +1,348 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.runRefusalsDir = void 0;
37
+ exports.pendingRequestId = pendingRequestId;
38
+ exports.runRefusalsFile = runRefusalsFile;
39
+ exports.readRunRefusals = readRunRefusals;
40
+ exports.stoppedBy = stoppedBy;
41
+ exports.openWait = openWait;
42
+ exports.holmesPackageAbove = holmesPackageAbove;
43
+ exports.appendRunEvent = appendRunEvent;
44
+ exports.applyRunRefusalStop = applyRunRefusalStop;
45
+ exports.recordRunStopBlock = recordRunStopBlock;
46
+ exports.runState = runState;
47
+ exports.grantGuard = grantGuard;
48
+ // @implements A-SPEC-778, A-SPEC-779, A-SPEC-780, A-SPEC-781, A-SPEC-780.1, A-SPEC-774.20, A-SPEC-781.2, A-SPEC-770.12, A-SPEC-778.1, A-SPEC-779.2
49
+ /**
50
+ * @implements A-SPEC-778 — a refusal loop in a run ends in a stop the orchestrator can read, not in a used-up budget.
51
+ * Every PreToolUse refusal of a run is appended to `<main>/.ax/state/run-refusals/<run>.jsonl` (a protected path the
52
+ * session cannot reset). Once one code has been refused `run.refusalRepeatLimit` times, every later tool call of that
53
+ * run is refused with `run.stopped` until the operator ends the run. A session outside a run is never touched.
54
+ *
55
+ * @implements A-SPEC-779 — a refusal that files an approval request pauses the run: until the operator decides the
56
+ * request in a terminal, every call is refused as `run.awaiting-approval` and nothing is counted; a decision resumes
57
+ * the run, a wait past `run.approvalWaitMinutes` stops it, and a grant of an awaited request needs a terminal.
58
+ */
59
+ const crypto = __importStar(require("node:crypto"));
60
+ const fs = __importStar(require("node:fs"));
61
+ const path = __importStar(require("node:path"));
62
+ const config_1 = require("../config/config");
63
+ const approval_queue_1 = require("../governance/approval-queue");
64
+ const run_mode_1 = require("../governance/run-mode");
65
+ const dist_freshness_1 = require("../project/dist-freshness");
66
+ const run_records_1 = require("../project/run-records");
67
+ const refusal_codes_1 = require("./refusal-codes");
68
+ const SAFE_ID = /^[A-Za-z0-9._-]{1,128}$/;
69
+ // @implements A-SPEC-770.12 — the bracket may carry ` · <kind> <target> 「<title>」` after the id.
70
+ const REQUEST_RE = /\[승인 대기 (req-[0-9a-f]{12})(?: · [^\]\n]*)?\]/;
71
+ /** @implements A-SPEC-770.12 — the request id a refusal names, or null. */
72
+ function pendingRequestId(reason) {
73
+ return REQUEST_RE.exec(reason)?.[1] ?? null;
74
+ }
75
+ const runRefusalsDir = (main) => path.join(main, '.ax', 'state', 'run-refusals');
76
+ exports.runRefusalsDir = runRefusalsDir;
77
+ function runRefusalsFile(main, id) {
78
+ const name = SAFE_ID.test(id) && id !== '.' && id !== '..'
79
+ ? id
80
+ : `id-${crypto.createHash('sha256').update(id).digest('hex').slice(0, 16)}`;
81
+ return path.join((0, exports.runRefusalsDir)(main), `${name}.jsonl`);
82
+ }
83
+ /** The run's events; `[]` when the log does not exist yet, `'unreadable'` on any other read error. */
84
+ function readRunRefusals(file) {
85
+ let text;
86
+ try {
87
+ text = fs.readFileSync(file, 'utf8');
88
+ }
89
+ catch (e) {
90
+ return e.code === 'ENOENT' ? [] : 'unreadable';
91
+ }
92
+ const events = [];
93
+ for (const line of text.split('\n')) {
94
+ if (line.trim() === '')
95
+ continue;
96
+ try {
97
+ const ev = JSON.parse(line);
98
+ if (ev && typeof ev.event === 'string' && typeof ev.ts === 'string')
99
+ events.push(ev);
100
+ }
101
+ catch { /* a torn line is skipped */ }
102
+ }
103
+ return events;
104
+ }
105
+ /** The first code refused `limit` times or more, with its count, the expired approval wait, or an install change; else null. */
106
+ function stoppedBy(events, limit) {
107
+ // @implements A-SPEC-780 — an install change stops the run for good, even if the install is changed back.
108
+ const changed = events.find((e) => e.event === 'install_changed');
109
+ if (changed)
110
+ return { code: 'install.changed', count: 1, install: { pinned: changed.pinned ?? { version: null, build: null }, current: changed.current ?? { version: null, build: null } } };
111
+ // @implements A-SPEC-778.1 — a Stop the gate kept blocking until it yielded: the run made no progress and stops.
112
+ const stalled = events.find((e) => e.event === 'stalled');
113
+ if (stalled)
114
+ return { code: 'run.stalled', count: stalled.count ?? 0, articles: stalled.articles ?? [] };
115
+ const expired = events.find((e) => e.event === 'approval_expired');
116
+ if (expired)
117
+ return { code: 'approval.expired', count: 1, expired: expired.request ?? '' };
118
+ const counts = new Map();
119
+ for (const ev of events)
120
+ if (ev.event === 'refusal' && typeof ev.code === 'string')
121
+ counts.set(ev.code, (counts.get(ev.code) ?? 0) + 1);
122
+ for (const [code, count] of counts)
123
+ if (count >= limit)
124
+ return { code, count };
125
+ return null;
126
+ }
127
+ /** The last approval wait no later event closed, or null. */
128
+ function openWait(events) {
129
+ for (let i = events.length - 1; i >= 0; i--) {
130
+ const e = events[i];
131
+ if (e.event === 'approval_resolved' || e.event === 'approval_expired')
132
+ return null;
133
+ if (e.event === 'awaiting_approval')
134
+ return e;
135
+ }
136
+ return null;
137
+ }
138
+ /** @implements A-SPEC-780 — the holmes-kit package above `file`: its directory and version. */
139
+ function holmesPackageAbove(file) {
140
+ let dir = path.dirname(file);
141
+ for (let i = 0; i < 64; i++) {
142
+ try {
143
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
144
+ if (pkg.name === '@holmes-lab/holmes-kit' && typeof pkg.version === 'string')
145
+ return { root: dir, version: pkg.version };
146
+ }
147
+ catch { /* keep walking */ }
148
+ const up = path.dirname(dir);
149
+ if (up === dir)
150
+ return null;
151
+ dir = up;
152
+ }
153
+ return null;
154
+ }
155
+ function ownInstall() {
156
+ const pkg = holmesPackageAbove(__filename);
157
+ return { version: pkg?.version ?? null, build: pkg ? (0, dist_freshness_1.distBuildId)(pkg.root) : null };
158
+ }
159
+ /** @implements A-SPEC-780 — what run start pinned for the hook, from the run's record; null without one. */
160
+ function pinnedInstall(main, runId) {
161
+ const rec = (0, run_records_1.listRuns)(main).find((r) => r.run_id === runId);
162
+ const v = rec?.versions;
163
+ if (!v || typeof v !== 'object')
164
+ return null;
165
+ const str = (x) => (typeof x === 'string' && x !== '' ? x : null);
166
+ return { version: str(v.hook) ?? str(v.cli), build: str(v.hook_build) };
167
+ }
168
+ /**
169
+ * A pinned value differs from a current one that is not equal — including one the hook can no longer read
170
+ * (@implements A-SPEC-780.1: unreadable is not "unchanged"). A null pin (accepted unread at start) is not compared.
171
+ */
172
+ const installDiffers = (pinned, current) => (pinned.version !== null && pinned.version !== current.version)
173
+ || (pinned.build !== null && pinned.build !== current.build);
174
+ const END = 'the operator ends it with holmes-kit run stop and starts a new run';
175
+ const append = (file, ev) => {
176
+ try {
177
+ fs.mkdirSync(path.dirname(file), { recursive: true });
178
+ fs.appendFileSync(file, `${JSON.stringify(ev)}\n`);
179
+ return true;
180
+ }
181
+ catch {
182
+ return false;
183
+ }
184
+ };
185
+ /** @implements A-SPEC-781 — the run log writer, shared with the stage machine. */
186
+ function appendRunEvent(main, runId, ev) {
187
+ return append(runRefusalsFile(main, runId), ev);
188
+ }
189
+ const stallLine = (count, articles) => `[Holmes-Kit] this run stalled: its Stop was blocked ${count} times in a row (${articles.join(', ') || 'no article named'}) — the turn ends blocked; ${END}`;
190
+ const stopReason = (stop, limit, waitMinutes) => stop.code === 'run.stalled'
191
+ ? stallLine(stop.count, stop.articles ?? [])
192
+ : stop.install !== undefined
193
+ ? `[Holmes-Kit] this run stopped: the Holmes install changed since run start (pinned ${stop.install.pinned.version ?? '?'} build ${stop.install.pinned.build ?? '?'}, `
194
+ + `now ${stop.install.current.version ?? 'unreadable'} build ${stop.install.current.build ?? 'unreadable'}) — one build governs a run; ${END}`
195
+ : stop.expired !== undefined
196
+ ? `[Holmes-Kit] this run stopped: approval ${stop.expired} was not decided within ${waitMinutes} minutes — ${END}`
197
+ : `[Holmes-Kit] this run stopped: refusal ${stop.code} repeated ${stop.count} times (limit ${limit}) — ${END}`;
198
+ /** The decision recorded for `request` at or after `since`, read from the queue it was filed in; null when undecided. */
199
+ function decisionAfter(queueRoot, request, since) {
200
+ try {
201
+ const d = (0, approval_queue_1.readQueue)(queueRoot).decisions[request];
202
+ // @implements A-SPEC-779.2 — a request the run withdrew is no longer awaited.
203
+ if (d && (d.event === 'granted' || d.event === 'denied' || d.event === 'withdrawn') && Date.parse(d.ts) >= Date.parse(since))
204
+ return d.event;
205
+ }
206
+ catch { /* an unreadable queue decides nothing: the run keeps waiting, then expires */ }
207
+ return null;
208
+ }
209
+ function applyRunRefusalStop(out, ctx) {
210
+ const mode = (0, run_mode_1.runMode)(ctx.env, ctx.projectRoot, ctx.cwd, ctx.sessionId);
211
+ if (!mode.run)
212
+ return out;
213
+ const cfg = (0, config_1.loadConfig)(ctx.projectRoot).run;
214
+ const limit = cfg.refusalRepeatLimit;
215
+ const now = ctx.now ? ctx.now() : new Date();
216
+ const file = runRefusalsFile((0, run_records_1.mainCheckoutOf)(ctx.projectRoot), mode.id ?? 'unidentified-run');
217
+ const events = readRunRefusals(file);
218
+ if (events === 'unreadable') {
219
+ return { permissionDecision: 'deny', permissionDecisionReason: `[Holmes-Kit] this run stopped: its refusal log cannot be read (${file}) — ${END}` };
220
+ }
221
+ // @implements A-SPEC-780 — compared with what run start pinned; logged once, then the stop below holds.
222
+ if (mode.id && !events.some((e) => e.event === 'install_changed')) {
223
+ const pinned = pinnedInstall((0, run_records_1.mainCheckoutOf)(ctx.projectRoot), mode.id);
224
+ const current = ctx.ownInstall ?? ownInstall();
225
+ if (pinned && installDiffers(pinned, current)) {
226
+ const ev = { ts: now.toISOString(), event: 'install_changed', pinned, current };
227
+ append(file, ev);
228
+ events.push(ev);
229
+ }
230
+ }
231
+ const stop = stoppedBy(events, limit);
232
+ if (stop)
233
+ return { permissionDecision: 'deny', permissionDecisionReason: stopReason(stop, limit, cfg.approvalWaitMinutes) };
234
+ // @implements A-SPEC-779 — an open wait: resolved by a decision, expired by the clock, or still waiting.
235
+ const wait = openWait(events);
236
+ if (wait && wait.request) {
237
+ const queueRoot = wait.queue_root ?? ctx.projectRoot;
238
+ const decided = decisionAfter(queueRoot, wait.request, wait.ts);
239
+ if (decided) {
240
+ append(file, { ts: now.toISOString(), event: 'approval_resolved', request: wait.request, decision: decided });
241
+ }
242
+ else if (now.getTime() - Date.parse(wait.ts) > cfg.approvalWaitMinutes * 60_000) {
243
+ append(file, { ts: now.toISOString(), event: 'approval_expired', request: wait.request });
244
+ return { permissionDecision: 'deny', permissionDecisionReason: stopReason({ code: 'approval.expired', count: 1, expired: wait.request }, limit, cfg.approvalWaitMinutes) };
245
+ }
246
+ else {
247
+ return {
248
+ permissionDecision: 'deny',
249
+ permissionDecisionReason: `[Holmes-Kit] this run is awaiting approval ${wait.request} (${wait.code ?? 'approval'}) since ${wait.ts} — `
250
+ + `the operator decides it in a terminal: holmes-kit approve --grant ${wait.request} --target ${queueRoot}; `
251
+ + `until then every tool call of this run is refused (the wait stops the run after ${cfg.approvalWaitMinutes} minutes)`,
252
+ };
253
+ }
254
+ }
255
+ if (out.permissionDecision !== 'deny')
256
+ return out;
257
+ const reason = out.permissionDecisionReason ?? '';
258
+ const rc = (0, refusal_codes_1.refusalCode)(reason);
259
+ if (!append(file, { ts: now.toISOString(), event: 'refusal', code: rc.code, class: rc.class, tool: ctx.tool }))
260
+ return out;
261
+ let next = reason;
262
+ const request = REQUEST_RE.exec(reason)?.[1];
263
+ if (request && rc.class === 'needs_hitl'
264
+ && append(file, { ts: now.toISOString(), event: 'awaiting_approval', request, code: rc.code, queue_root: ctx.projectRoot })) {
265
+ next += `\n[Holmes-Kit] this run now awaits approval ${request}: until the operator decides it in a terminal, every tool call of this run is refused`;
266
+ }
267
+ const count = events.filter((e) => e.event === 'refusal' && e.code === rc.code).length + 1;
268
+ if (count >= limit)
269
+ next += `\n[Holmes-Kit] this run is now stopped: refusal ${rc.code} repeated ${count} times (limit ${limit}) — ${END}`;
270
+ return next === reason ? out : { ...out, permissionDecisionReason: next };
271
+ }
272
+ /**
273
+ * @implements A-SPEC-778.1 — the Stop hook's record of a blocked turn in a run. Every block appends `stop_blocked`; the
274
+ * guard's cap yield also appends `stalled` and returns the line that says so. Outside a run, or when the log cannot be
275
+ * written, nothing is recorded and null is returned: the block itself never depends on this.
276
+ */
277
+ function recordRunStopBlock(ctx, articles, yielded) {
278
+ try {
279
+ const mode = (0, run_mode_1.runMode)(ctx.env, ctx.projectRoot, ctx.cwd, ctx.sessionId);
280
+ if (!mode.run)
281
+ return null;
282
+ const file = runRefusalsFile((0, run_records_1.mainCheckoutOf)(ctx.projectRoot), mode.id ?? 'unidentified-run');
283
+ const ts = (ctx.now ? ctx.now() : new Date()).toISOString();
284
+ if (!append(file, { ts, event: 'stop_blocked', articles: [...articles] }))
285
+ return null;
286
+ if (!yielded)
287
+ return null;
288
+ const events = readRunRefusals(file);
289
+ if (events === 'unreadable')
290
+ return null;
291
+ let count = 0;
292
+ for (let i = events.length - 1; i >= 0 && events[i].event === 'stop_blocked'; i--)
293
+ count++;
294
+ if (!append(file, { ts, event: 'stalled', articles: [...articles], count }))
295
+ return null;
296
+ return stallLine(count, articles);
297
+ }
298
+ catch {
299
+ return null;
300
+ }
301
+ }
302
+ /** @implements A-SPEC-779 — the run's state, from its log alone. */
303
+ function runState(main, runId, opts) {
304
+ const events = readRunRefusals(runRefusalsFile(main, runId));
305
+ if (events === 'unreadable')
306
+ return { state: 'stopped', stopped: { unreadable: true } };
307
+ const stop = stoppedBy(events, opts.limit);
308
+ // @implements A-SPEC-778.1 — a stalled run is a stop the orchestrator can tell apart from a refusal loop.
309
+ if (stop)
310
+ return { state: stop.code === 'run.stalled' ? 'stalled' : 'stopped', stopped: stop };
311
+ const wait = openWait(events);
312
+ if (wait && wait.request)
313
+ return { state: 'awaiting_approval', awaiting: { request: wait.request, code: wait.code ?? '', since: wait.ts } };
314
+ return { state: 'running' };
315
+ }
316
+ /**
317
+ * @implements A-SPEC-779 — a grant is the operator's, from their own terminal (owner decision 2026-10-18): a process
318
+ * carrying a run marker never grants, and a run's awaited request is not granted from a non-terminal. A deny is never
319
+ * asked here.
320
+ */
321
+ function grantGuard(root, id, opts) {
322
+ const marker = opts.env.HOLMES_RUN_ID;
323
+ if (typeof marker === 'string' && marker.trim() !== '') {
324
+ return 'a grant is the operator\'s, from their own terminal — not from inside a run (HOLMES_RUN_ID is set in this process)';
325
+ }
326
+ if (opts.interactive)
327
+ return null;
328
+ const dir = (0, exports.runRefusalsDir)((0, run_records_1.mainCheckoutOf)(root));
329
+ // @implements A-SPEC-779.1 — a log that cannot be read cannot say no run awaits the request: refuse, naming it.
330
+ const unknown = (what) => `cannot tell whether a run awaits ${id}: the run logs cannot be read (${what}) — the operator grants it from a terminal`;
331
+ let names;
332
+ try {
333
+ names = fs.readdirSync(dir).filter((n) => n.endsWith('.jsonl'));
334
+ }
335
+ catch (e) {
336
+ return e.code === 'ENOENT' ? null : unknown(dir);
337
+ }
338
+ for (const n of names) {
339
+ const events = readRunRefusals(path.join(dir, n));
340
+ if (events === 'unreadable')
341
+ return unknown(path.join(dir, n));
342
+ const wait = openWait(events);
343
+ if (wait && wait.request === id) {
344
+ return `${id} is awaited by run ${n.slice(0, -'.jsonl'.length)}; the operator grants it in a terminal (this CLI is not attached to one)`;
345
+ }
346
+ }
347
+ return null;
348
+ }