@holmes-lab/holmes-kit 0.35.24 → 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 (136) hide show
  1. package/CHANGELOG.md +363 -0
  2. package/README.md +4 -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 +34 -4
  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 +31 -1
  13. package/dist/holmes/cli/doctor.js +204 -7
  14. package/dist/holmes/cli/index.js +115 -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-approval.js +3 -2
  27. package/dist/holmes/cli/runtime-binding.d.ts +30 -0
  28. package/dist/holmes/cli/runtime-binding.js +116 -11
  29. package/dist/holmes/cli/scratch.d.ts +12 -0
  30. package/dist/holmes/cli/scratch.js +20 -0
  31. package/dist/holmes/cli/test-platform.d.ts +16 -0
  32. package/dist/holmes/cli/test-platform.js +31 -1
  33. package/dist/holmes/config/config.d.ts +49 -0
  34. package/dist/holmes/config/config.js +146 -3
  35. package/dist/holmes/config/project-caps.d.ts +21 -0
  36. package/dist/holmes/config/project-caps.js +114 -0
  37. package/dist/holmes/governance/approval-queue.d.ts +17 -3
  38. package/dist/holmes/governance/approval-queue.js +51 -8
  39. package/dist/holmes/governance/autonomy.d.ts +6 -0
  40. package/dist/holmes/governance/autonomy.js +21 -0
  41. package/dist/holmes/governance/push-gate-runner.d.ts +8 -0
  42. package/dist/holmes/governance/push-gate-runner.js +49 -1
  43. package/dist/holmes/governance/replica-id.d.ts +9 -0
  44. package/dist/holmes/governance/replica-id.js +44 -7
  45. package/dist/holmes/governance/role-policy.d.ts +41 -1
  46. package/dist/holmes/governance/role-policy.js +137 -20
  47. package/dist/holmes/governance/run-mode.d.ts +14 -0
  48. package/dist/holmes/governance/run-mode.js +120 -0
  49. package/dist/holmes/governance/tool-actions.d.ts +30 -0
  50. package/dist/holmes/governance/tool-actions.js +121 -0
  51. package/dist/holmes/guardrail/agent-launch-policy.d.ts +15 -0
  52. package/dist/holmes/guardrail/agent-launch-policy.js +177 -0
  53. package/dist/holmes/guardrail/classification-mode.d.ts +17 -0
  54. package/dist/holmes/guardrail/classification-mode.js +135 -0
  55. package/dist/holmes/guardrail/dynamic-write.d.ts +43 -0
  56. package/dist/holmes/guardrail/dynamic-write.js +304 -0
  57. package/dist/holmes/guardrail/impact-gate.d.ts +2 -0
  58. package/dist/holmes/guardrail/impact-gate.js +34 -11
  59. package/dist/holmes/guardrail/phase.d.ts +2 -1
  60. package/dist/holmes/guardrail/phase.js +22 -8
  61. package/dist/holmes/guardrail/powershell-shell.d.ts +21 -0
  62. package/dist/holmes/guardrail/powershell-shell.js +801 -0
  63. package/dist/holmes/guardrail/refusal-codes.d.ts +24 -0
  64. package/dist/holmes/guardrail/refusal-codes.js +140 -0
  65. package/dist/holmes/guardrail/risk-classifier.d.ts +17 -0
  66. package/dist/holmes/guardrail/risk-classifier.js +255 -27
  67. package/dist/holmes/guardrail/risk-types.d.ts +16 -0
  68. package/dist/holmes/guardrail/run-plan-scope.d.ts +23 -0
  69. package/dist/holmes/guardrail/run-plan-scope.js +155 -0
  70. package/dist/holmes/guardrail/run-refusals.d.ts +116 -0
  71. package/dist/holmes/guardrail/run-refusals.js +348 -0
  72. package/dist/holmes/guardrail/run-stages.d.ts +67 -0
  73. package/dist/holmes/guardrail/run-stages.js +188 -0
  74. package/dist/holmes/guardrail/scope-judgment.d.ts +5 -1
  75. package/dist/holmes/guardrail/scope-judgment.js +8 -10
  76. package/dist/holmes/guardrail/scope-refusal-memory.d.ts +3 -0
  77. package/dist/holmes/guardrail/scope-refusal-memory.js +85 -0
  78. package/dist/holmes/guardrail/shell-words.js +7 -7
  79. package/dist/holmes/guardrail/write-target.d.ts +31 -2
  80. package/dist/holmes/guardrail/write-target.js +118 -16
  81. package/dist/holmes/hooks/pre-tool-use.d.ts +36 -2
  82. package/dist/holmes/hooks/pre-tool-use.js +740 -81
  83. package/dist/holmes/hooks/session-start.js +5 -3
  84. package/dist/holmes/hooks/stop.d.ts +35 -1
  85. package/dist/holmes/hooks/stop.js +142 -7
  86. package/dist/holmes/mcp/elicit-approval.js +4 -4
  87. package/dist/holmes/mcp/handlers/graph-operations.js +5 -5
  88. package/dist/holmes/mcp/handlers/maintenance-analysis.js +2 -2
  89. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -1
  90. package/dist/holmes/mcp/handlers/operator-inspection.js +3 -1
  91. package/dist/holmes/mcp/handlers/phase-queries.js +16 -1
  92. package/dist/holmes/mcp/handlers/requirement-triage.js +2 -2
  93. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -3
  94. package/dist/holmes/mcp/handlers/spec-approval.js +56 -9
  95. package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +1 -0
  96. package/dist/holmes/mcp/handlers/spec-lifecycle.js +3 -3
  97. package/dist/holmes/mcp/handlers/spec-queries.d.ts +7 -0
  98. package/dist/holmes/mcp/handlers/spec-queries.js +5 -0
  99. package/dist/holmes/mcp/handlers/workspace-queries.js +2 -2
  100. package/dist/holmes/mcp/handlers.d.ts +2 -3
  101. package/dist/holmes/mcp/handlers.js +22 -2
  102. package/dist/holmes/mcp/harness-attestation.d.ts +2 -0
  103. package/dist/holmes/mcp/harness-attestation.js +3 -1
  104. package/dist/holmes/mcp/operator-recovery.d.ts +2 -0
  105. package/dist/holmes/mcp/operator-recovery.js +4 -3
  106. package/dist/holmes/mcp/server.js +9 -0
  107. package/dist/holmes/mcp/tool-schemas.js +6 -3
  108. package/dist/holmes/project/npx-bin.d.ts +26 -0
  109. package/dist/holmes/project/npx-bin.js +272 -2
  110. package/dist/holmes/project/root.js +6 -1
  111. package/dist/holmes/project/run-records.d.ts +17 -0
  112. package/dist/holmes/project/run-records.js +126 -0
  113. package/dist/holmes/project/scratch-root.d.ts +12 -0
  114. package/dist/holmes/project/scratch-root.js +132 -0
  115. package/dist/holmes/review/mrp.d.ts +35 -0
  116. package/dist/holmes/review/mrp.js +119 -0
  117. package/dist/holmes/review/verdicts.d.ts +117 -0
  118. package/dist/holmes/review/verdicts.js +345 -0
  119. package/dist/holmes/runtime/dispatch.js +6 -3
  120. package/dist/holmes/semantic/cloud-usage.d.ts +20 -0
  121. package/dist/holmes/semantic/cloud-usage.js +106 -0
  122. package/dist/holmes/semantic/embedder.d.ts +15 -6
  123. package/dist/holmes/semantic/embedder.js +84 -3
  124. package/dist/holmes/semantic/local-model.d.ts +21 -2
  125. package/dist/holmes/semantic/local-model.js +14 -3
  126. package/dist/holmes/semantic/tier.d.ts +25 -0
  127. package/dist/holmes/semantic/tier.js +86 -1
  128. package/dist/holmes/semantic/vector-cache.d.ts +1 -0
  129. package/dist/holmes/semantic/vector-cache.js +4 -1
  130. package/dist/holmes/spec/approval-blockers.d.ts +11 -1
  131. package/dist/holmes/spec/approval-blockers.js +70 -2
  132. package/dist/holmes/spec/renumber.d.ts +1 -1
  133. package/dist/holmes/spec/renumber.js +5 -2
  134. package/dist/holmes/spec/transition-policy.d.ts +5 -7
  135. package/dist/holmes/spec/transition-policy.js +17 -2
  136. package/package.json +1 -1
@@ -40,6 +40,7 @@ exports.specApprovalAutonomy = specApprovalAutonomy;
40
40
  exports.declaredGateDirection = declaredGateDirection;
41
41
  exports.autonomyRuleMeaning = autonomyRuleMeaning;
42
42
  exports.specApprovalAutonomyReason = specApprovalAutonomyReason;
43
+ exports.ceilingRefusal = ceilingRefusal;
43
44
  exports.requiresAutonomousApprovalPrompt = requiresAutonomousApprovalPrompt;
44
45
  exports.sessionAutonomyActive = sessionAutonomyActive;
45
46
  exports.projectDefaultAutonomy = projectDefaultAutonomy;
@@ -256,6 +257,26 @@ function specApprovalAutonomyReason(spec, resolveParent, descendants) {
256
257
  return 'unknown-kind'; // unknown kind: fail-safe to human
257
258
  }
258
259
  }
260
+ /**
261
+ * @implements A-SPEC-532.6 — the owner's ceiling (ax.config.json `autonomy.ceiling`) over every automatic seal, autonomous
262
+ * or delegated. It only narrows: `default` refuses nothing, and a spec it lets through still faces the grader. The
263
+ * returned text is why the seal stays with the operator, or null.
264
+ */
265
+ function ceilingRefusal(ceiling, spec, descendants) {
266
+ if (ceiling === 'default')
267
+ return null;
268
+ if (ceiling === 'off')
269
+ return 'no seal is automatic here';
270
+ if (spec.type === 'T-SPEC')
271
+ return null;
272
+ if (ceiling === 'tests')
273
+ return 'only T-SPECs seal automatically here';
274
+ // no-gate: a gate-behavior A-SPEC, or a REQ/H-SPEC above one, is the operator's whatever direction it declares.
275
+ const gate = (s) => s.type === 'A-SPEC' && breakingGrade(s) === 'gate-behavior';
276
+ if (gate(spec) || (descendants ?? []).some(gate))
277
+ return 'a gate-behavior change is never automatic here';
278
+ return null;
279
+ }
259
280
  /**
260
281
  * Whether an otherwise HITL-classed approval is one of the exceptional cases that must still be
261
282
  * presented in-session while autonomous mode is enabled. This is intentionally narrower than
@@ -10,6 +10,14 @@ export interface PrePushIo {
10
10
  stdinText: string;
11
11
  /** Refusals and notices land here (stderr in the shipped hook). */
12
12
  write: (s: string) => void;
13
+ /** @implements A-SPEC-102.4 — the environment run mode is read from; `process.env` when absent. */
14
+ env?: NodeJS.ProcessEnv;
13
15
  }
16
+ /**
17
+ * @implements A-SPEC-102.4 — in a run whose record carries `base`, a push of `sha` needs an independent passing review
18
+ * of base..sha. Null outside a run, without a base, for the base itself, on a passing gate, or on any error (the push
19
+ * gate stays fail-open on collection errors, H-SPEC-509).
20
+ */
21
+ export declare function runPushReviewRefusal(cwd: string, env: NodeJS.ProcessEnv, sha: string): string | null;
14
22
  /** Exit code of the hook: 0 = push proceeds, 1 = refused. */
15
23
  export declare function runPrePush(io: PrePushIo): 0 | 1;
@@ -34,8 +34,9 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.effectiveHooksDir = effectiveHooksDir;
37
+ exports.runPushReviewRefusal = runPushReviewRefusal;
37
38
  exports.runPrePush = runPrePush;
38
- // @implements A-SPEC-509.1, A-SPEC-734
39
+ // @implements A-SPEC-509.1, A-SPEC-734, A-SPEC-102.4, A-SPEC-774.21
39
40
  /**
40
41
  * The push gate's IMPURE half: collect (stdin lines, git facts, the evidence ledger) and hand
41
42
  * everything to the pure judgePush. Any collection failure ALLOWS — this gate safens the default
@@ -62,6 +63,47 @@ function effectiveHooksDir(repoRoot) {
62
63
  catch { /* unset config exits 1 — the default location applies */ }
63
64
  return path.join(repoRoot, '.git', 'hooks');
64
65
  }
66
+ /**
67
+ * @implements A-SPEC-102.4 — in a run whose record carries `base`, a push of `sha` needs an independent passing review
68
+ * of base..sha. Null outside a run, without a base, for the base itself, on a passing gate, or on any error (the push
69
+ * gate stays fail-open on collection errors, H-SPEC-509).
70
+ */
71
+ function runPushReviewRefusal(cwd, env, sha) {
72
+ let mode;
73
+ try {
74
+ const { runMode } = require('./run-mode');
75
+ mode = runMode(env, cwd, cwd);
76
+ }
77
+ catch {
78
+ return null;
79
+ } // whether this is a run cannot be read: as an interactive push
80
+ if (!mode.run)
81
+ return null;
82
+ // @implements A-SPEC-774.21 — in a run, a push gate that cannot judge refuses, naming what it could not read.
83
+ const cannot = (what) => `[Holmes-Kit push gate] the run's review gate could not judge this push: ${what} — `
84
+ + 'repair the run record or end the run with holmes-kit run stop';
85
+ try {
86
+ if (!mode.id)
87
+ return cannot('the run has no id');
88
+ const { listRuns, mainCheckoutOf } = require('../project/run-records');
89
+ const rec = listRuns(mainCheckoutOf(cwd)).find((r) => r.run_id === mode.id);
90
+ if (!rec)
91
+ return cannot(`no run record for ${mode.id}`);
92
+ if (typeof rec.base !== 'string' || rec.base === '')
93
+ return cannot('run record carries no base');
94
+ if (rec.base === sha)
95
+ return null;
96
+ const { gateRange } = require('../review/verdicts');
97
+ const g = gateRange(rec.worktree, rec.base, sha, {});
98
+ if (g.ok)
99
+ return null;
100
+ return `[Holmes-Kit push gate] the run's commits ${rec.base}..${sha} are not reviewed (${g.reasons.join('; ')}) — an independent reviewer records a verdict with `
101
+ + `holmes-kit review record --base ${rec.base} --head ${sha} --verdict pass`;
102
+ }
103
+ catch (e) {
104
+ return cannot(e instanceof Error ? e.message : String(e));
105
+ }
106
+ }
65
107
  /** Exit code of the hook: 0 = push proceeds, 1 = refused. */
66
108
  function runPrePush(io) {
67
109
  try {
@@ -93,6 +135,12 @@ function runPrePush(io) {
93
135
  io.write((v.reason ?? '[Holmes-Kit push 게이트] 거부') + '\n');
94
136
  refused = true;
95
137
  }
138
+ // @implements A-SPEC-102.4 — a run's push also needs its range reviewed.
139
+ const review = runPushReviewRefusal(io.cwd, io.env ?? process.env, line.localSha);
140
+ if (review) {
141
+ io.write(review + '\n');
142
+ refused = true;
143
+ }
96
144
  }
97
145
  return refused ? 1 : 0;
98
146
  }
@@ -8,8 +8,16 @@
8
8
  * file is worse than either rule being wrong.
9
9
  */
10
10
  export declare function sanitizeReplicaId(raw: string): string;
11
+ /**
12
+ * @implements A-SPEC-643.1 — `<host>-<tag>-<value>` while it fits the 32-character limit. When it does not (a macOS
13
+ * host is often 25 characters already), the host is shortened and the value becomes an 8-hex digest of itself, so two
14
+ * worktrees or two runs never collapse into one id by truncation.
15
+ */
16
+ export declare function composeReplicaId(host: string, tag: 'wt' | 'run', value: string): string;
11
17
  /**
12
18
  * Resolve this machine's replica id: explicit env, then the stored value, then the hostname.
19
+ * @implements A-SPEC-643.1 — between the env override and the stored value, a run id gives `<host>-run-<id>`
20
+ * (never persisted: a run ends); between the stored value and the host, a linked worktree gives `<host>-wt-<name>`.
13
21
  *
14
22
  * The env override exists for CI and for tests, where the hostname is neither stable nor meaningful.
15
23
  * Writing the generated value down is what makes the identity stable — an id derived fresh each run
@@ -17,4 +25,5 @@ export declare function sanitizeReplicaId(raw: string): string;
17
25
  */
18
26
  export declare function resolveReplicaId(root: string, env?: NodeJS.ProcessEnv, opts?: {
19
27
  persist?: boolean;
28
+ host?: string;
20
29
  }): string;
@@ -34,8 +34,10 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.sanitizeReplicaId = sanitizeReplicaId;
37
+ exports.composeReplicaId = composeReplicaId;
37
38
  exports.resolveReplicaId = resolveReplicaId;
38
- // @implements A-SPEC-148
39
+ // @implements A-SPEC-148, A-SPEC-643.1
40
+ const node_crypto_1 = require("node:crypto");
39
41
  const fs = __importStar(require("node:fs"));
40
42
  const os = __importStar(require("node:os"));
41
43
  const path = __importStar(require("node:path"));
@@ -63,8 +65,39 @@ function sanitizeReplicaId(raw) {
63
65
  // Everything stripped (an all-punctuation name, or an empty one) still needs a usable filename.
64
66
  return cleaned === '' ? 'local' : cleaned;
65
67
  }
68
+ /**
69
+ * @implements A-SPEC-643.1 — `<host>-<tag>-<value>` while it fits the 32-character limit. When it does not (a macOS
70
+ * host is often 25 characters already), the host is shortened and the value becomes an 8-hex digest of itself, so two
71
+ * worktrees or two runs never collapse into one id by truncation.
72
+ */
73
+ function composeReplicaId(host, tag, value) {
74
+ const h = sanitizeReplicaId(host);
75
+ const v = (value || '').replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'x';
76
+ const plain = `${h}-${tag}-${v}`;
77
+ if (plain.length <= MAX)
78
+ return plain;
79
+ const digest = (0, node_crypto_1.createHash)('sha256').update(value).digest('hex').slice(0, 8);
80
+ const room = MAX - tag.length - digest.length - 2;
81
+ return `${h.slice(0, room).replace(/-+$/, '') || 'h'}-${tag}-${digest}`;
82
+ }
83
+ /** @implements A-SPEC-643.1 — a linked worktree's name: its `.git` is a file with `gitdir:`. */
84
+ function linkedWorktreeName(root) {
85
+ try {
86
+ const pointer = path.join(root, '.git');
87
+ if (!fs.lstatSync(pointer).isFile())
88
+ return null;
89
+ if (!/^gitdir:\s*\S/m.test(fs.readFileSync(pointer, 'utf8')))
90
+ return null;
91
+ return path.basename(path.resolve(root));
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
66
97
  /**
67
98
  * Resolve this machine's replica id: explicit env, then the stored value, then the hostname.
99
+ * @implements A-SPEC-643.1 — between the env override and the stored value, a run id gives `<host>-run-<id>`
100
+ * (never persisted: a run ends); between the stored value and the host, a linked worktree gives `<host>-wt-<name>`.
68
101
  *
69
102
  * The env override exists for CI and for tests, where the hostname is neither stable nor meaningful.
70
103
  * Writing the generated value down is what makes the identity stable — an id derived fresh each run
@@ -75,6 +108,14 @@ function resolveReplicaId(root, env = process.env, opts = {}) {
75
108
  const fromEnv = env.HOLMES_REPLICA_ID;
76
109
  if (typeof fromEnv === 'string' && fromEnv.trim() !== '')
77
110
  return sanitizeReplicaId(fromEnv);
111
+ let host = 'local';
112
+ try {
113
+ host = opts.host ?? os.hostname();
114
+ }
115
+ catch { /* keep the fallback */ }
116
+ const run = env.HOLMES_RUN_ID;
117
+ if (typeof run === 'string' && run.trim() !== '')
118
+ return composeReplicaId(host, 'run', run.trim());
78
119
  const file = path.join(root, STORE);
79
120
  try {
80
121
  const stored = fs.readFileSync(file, 'utf8').trim();
@@ -82,12 +123,8 @@ function resolveReplicaId(root, env = process.env, opts = {}) {
82
123
  return sanitizeReplicaId(stored);
83
124
  }
84
125
  catch { /* not yet written */ }
85
- let host = 'local';
86
- try {
87
- host = os.hostname();
88
- }
89
- catch { /* keep the fallback */ }
90
- const id = sanitizeReplicaId(host);
126
+ const worktree = linkedWorktreeName(root);
127
+ const id = worktree !== null ? composeReplicaId(host, 'wt', worktree) : sanitizeReplicaId(host);
91
128
  // Best-effort persistence: failing to record the id must not stop the caller from writing to the
92
129
  // ledger, it only means the next run re-derives the same value from the same hostname.
93
130
  // @implements A-SPEC-150
@@ -15,8 +15,12 @@ import { Identity } from './identity';
15
15
  * would simply change what that role is allowed to do.
16
16
  */
17
17
  export interface RolePolicy {
18
+ /** @implements A-SPEC-774.19 — `stages`: the run stages the role may act in; absent means every stage. */
19
+ /** @implements A-SPEC-774.22 — `stagesMalformed`: a `stages` key that is not a list of strings (refused in a run). */
18
20
  roles: Record<string, {
19
21
  allow: string[];
22
+ stages?: string[];
23
+ stagesMalformed?: true;
20
24
  }>;
21
25
  /**
22
26
  * Which role an UNSPECIFIED agent is treated as. Declared by the project, never assumed by code.
@@ -29,14 +33,41 @@ export interface RolePolicy {
29
33
  * Omitting it keeps the fail-closed behaviour: unspecified is refused.
30
34
  */
31
35
  default?: string;
36
+ /** @implements A-SPEC-774.10 — 2 when the policy is written in the REQ-774 vocabulary and read strictly. */
37
+ vocabulary?: number;
38
+ /** @implements A-SPEC-774.15 — the roles directory exists but cannot be listed: the policy grants nothing. */
39
+ loadIssue?: string;
40
+ /** @implements A-SPEC-774.15 — role names declared in more than one file (the later still loads; a run refuses them). */
41
+ duplicates?: string[];
32
42
  }
33
43
  /** `null` when the project has not opted in. A PRESENT-but-broken policy is never null — see below. */
34
44
  export declare function loadRolePolicy(root: string): RolePolicy | null;
45
+ /** A policy from one document's text, as the loader would read it. */
46
+ export declare function parseRolePolicyText(text: string): RolePolicy;
47
+ /**
48
+ * @implements A-SPEC-774.10 — the actions REQ-774 added that 0.35.25 never role-checked. A policy written for
49
+ * 0.35.25 names none of them; outside a run it keeps allowing them, so no person has to migrate by hand. `AUTHOR_*`,
50
+ * `WRITE_CODE` and `WRITE_TEST` are not here: they kept their meaning, and their checks are the Fixed set (C1, C2).
51
+ */
52
+ export declare const LEGACY_UNCHECKED: ReadonlySet<string>;
53
+ /**
54
+ * @implements A-SPEC-774.10 §4 — the same policy written in the new vocabulary: `vocabulary: 2`, and every role
55
+ * granted the actions the legacy reading allowed implicitly, so verdicts outside a run are unchanged.
56
+ */
57
+ export declare function migrateRolePolicyText(text: string): string;
35
58
  /** What `doctor` reports. Three states, because "no policy" and "guidance present but off" differ. */
36
59
  export interface RolePolicyStatus {
37
60
  state: 'absent' | 'inactive' | 'active';
38
61
  roles: string[];
62
+ /** @implements A-SPEC-774.22 — roles whose `stages` cannot be read. */
63
+ malformedStages?: string[];
39
64
  default?: string;
65
+ /** @implements A-SPEC-774.8 — a default broader than every role: refused in a run, a doctor warning interactively. */
66
+ defaultIssue?: string;
67
+ /** @implements A-SPEC-774.15 — the roles directory could not be read; every action is refused. */
68
+ loadIssue?: string;
69
+ /** @implements A-SPEC-774.15 — roles declared in more than one file. */
70
+ duplicates?: string[];
40
71
  }
41
72
  /**
42
73
  * Describes the project's role configuration WITHOUT judging it. Not having roles on is not a
@@ -49,4 +80,13 @@ export declare function rolePolicyStatus(root: string): RolePolicyStatus;
49
80
  * Fail-closed once a policy exists: an absent role, an unregistered role, and a role without the
50
81
  * action are all refusals. Before a policy exists there is no opinion at all.
51
82
  */
52
- export declare function roleCheck(action: string, identity: Identity, policy: RolePolicy | null): string | null;
83
+ /**
84
+ * @implements A-SPEC-774.8 — a session reaches the default by LOSING its role (unset, or a harness that does not pass it
85
+ * to the MCP server). A default broader than what every role allows turns that loss into an escalation. Null when the
86
+ * default is a subset of the intersection of every role's allow list (an empty intersection makes `allow: []` valid).
87
+ */
88
+ export declare function defaultBreadthIssue(policy: RolePolicy): string | null;
89
+ export declare function roleCheck(action: string, identity: Identity, policy: RolePolicy | null, opts?: {
90
+ run?: boolean;
91
+ stage?: string;
92
+ }): string | null;
@@ -33,10 +33,14 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.LEGACY_UNCHECKED = void 0;
36
37
  exports.loadRolePolicy = loadRolePolicy;
38
+ exports.parseRolePolicyText = parseRolePolicyText;
39
+ exports.migrateRolePolicyText = migrateRolePolicyText;
37
40
  exports.rolePolicyStatus = rolePolicyStatus;
41
+ exports.defaultBreadthIssue = defaultBreadthIssue;
38
42
  exports.roleCheck = roleCheck;
39
- // @implements A-SPEC-152
43
+ // @implements A-SPEC-152, A-SPEC-774.19, A-SPEC-774.22
40
44
  const fs = __importStar(require("node:fs"));
41
45
  const path = __importStar(require("node:path"));
42
46
  const yaml = __importStar(require("js-yaml"));
@@ -46,30 +50,33 @@ function loadRolePolicy(root) {
46
50
  const dir = path.join(root, ROLES_DIR);
47
51
  let files;
48
52
  try {
49
- files = fs.readdirSync(dir).filter((f) => f.endsWith('.yaml') || f.endsWith('.yml')).sort();
53
+ // @implements A-SPEC-774.15 — a `.json` policy is read (the YAML parser reads JSON), never silently ignored.
54
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.yaml') || f.endsWith('.yml') || f.endsWith('.json')).sort();
50
55
  }
51
- catch {
52
- return null; // no directory: not opted in
56
+ catch (e) {
57
+ // @implements A-SPEC-774.15 — only a missing directory means "not opted in". Any other error (a file in its place,
58
+ // no permission) used to switch roles off; it now grants nothing, the direction REQ-144 set.
59
+ if (e.code === 'ENOENT')
60
+ return null;
61
+ return { roles: {}, loadIssue: `the role policy directory .ax/roles could not be read (${e.code ?? 'error'})` };
53
62
  }
54
63
  if (files.length === 0)
55
64
  return null; // empty directory: not opted in either
56
- const roles = {};
57
- let dflt;
65
+ const acc = { roles: {} };
66
+ const seen = new Set();
67
+ const dup = new Set();
58
68
  for (const f of files) {
59
69
  try {
60
70
  const doc = yaml.load(fs.readFileSync(path.join(dir, f), 'utf8'));
61
- // FIRST declaration wins, by filename order. If the last one won, dropping in a new file would
62
- // silently reverse a decision another file already made — and nothing would report the change.
63
- if (dflt === undefined && typeof doc?.default === 'string' && doc.default.trim() !== '') {
64
- dflt = doc.default.trim();
65
- }
66
- const declared = doc && typeof doc === 'object' ? doc.roles : undefined;
67
- if (!declared || typeof declared !== 'object')
68
- continue;
69
- for (const [name, def] of Object.entries(declared)) {
70
- const allow = def?.allow;
71
- roles[name] = { allow: Array.isArray(allow) ? allow.filter((a) => typeof a === 'string') : [] };
71
+ // @implements A-SPEC-774.15 — a role declared again in another file is recorded; the later still loads, as before.
72
+ if (doc && typeof doc === 'object' && doc.roles && typeof doc.roles === 'object') {
73
+ for (const name of Object.keys(doc.roles)) {
74
+ if (seen.has(name))
75
+ dup.add(name);
76
+ seen.add(name);
77
+ }
72
78
  }
79
+ mergePolicyDoc(acc, doc);
73
80
  }
74
81
  catch {
75
82
  // A corrupt file contributes NO roles — deliberately not `null`. Returning "no policy" would
@@ -78,7 +85,67 @@ function loadRolePolicy(root) {
78
85
  continue;
79
86
  }
80
87
  }
81
- return dflt === undefined ? { roles } : { roles, default: dflt };
88
+ if (dup.size > 0)
89
+ acc.duplicates = [...dup].sort();
90
+ return acc;
91
+ }
92
+ /** One policy document folded into the accumulated policy (shared by the loader and `parseRolePolicyText`). */
93
+ function mergePolicyDoc(acc, raw) {
94
+ const doc = raw;
95
+ // FIRST declaration wins, by filename order. If the last one won, dropping in a new file would
96
+ // silently reverse a decision another file already made — and nothing would report the change.
97
+ if (acc.default === undefined && typeof doc?.default === 'string' && doc.default.trim() !== '') {
98
+ acc.default = doc.default.trim();
99
+ }
100
+ // @implements A-SPEC-774.10 — any file declaring the new vocabulary opts the whole policy into strict reading.
101
+ if (doc && typeof doc === 'object' && doc.vocabulary === 2)
102
+ acc.vocabulary = 2;
103
+ const declared = doc && typeof doc === 'object' ? doc.roles : undefined;
104
+ if (!declared || typeof declared !== 'object')
105
+ return;
106
+ for (const [name, def] of Object.entries(declared)) {
107
+ const allow = def?.allow;
108
+ // @implements A-SPEC-774.19 — `stages` is kept only as a list of strings; anything else declares no stages.
109
+ const stages = def?.stages;
110
+ const readable = Array.isArray(stages) && stages.every((s) => typeof s === 'string');
111
+ acc.roles[name] = {
112
+ allow: Array.isArray(allow) ? allow.filter((a) => typeof a === 'string') : [],
113
+ ...(readable ? { stages: stages } : {}),
114
+ // @implements A-SPEC-774.22 — present but unreadable is kept as a flag, not dropped: a run refuses it.
115
+ ...(!readable && stages !== undefined ? { stagesMalformed: true } : {}),
116
+ };
117
+ }
118
+ }
119
+ /** A policy from one document's text, as the loader would read it. */
120
+ function parseRolePolicyText(text) {
121
+ const acc = { roles: {} };
122
+ mergePolicyDoc(acc, yaml.load(text));
123
+ return acc;
124
+ }
125
+ /**
126
+ * @implements A-SPEC-774.10 — the actions REQ-774 added that 0.35.25 never role-checked. A policy written for
127
+ * 0.35.25 names none of them; outside a run it keeps allowing them, so no person has to migrate by hand. `AUTHOR_*`,
128
+ * `WRITE_CODE` and `WRITE_TEST` are not here: they kept their meaning, and their checks are the Fixed set (C1, C2).
129
+ */
130
+ exports.LEGACY_UNCHECKED = new Set(['WRITE_OTHER', 'APPROVE_SPEC', 'RECORD_REVIEW', 'RECORD_EVIDENCE', 'MAINTAIN_GOVERNANCE']);
131
+ /**
132
+ * @implements A-SPEC-774.10 §4 — the same policy written in the new vocabulary: `vocabulary: 2`, and every role
133
+ * granted the actions the legacy reading allowed implicitly, so verdicts outside a run are unchanged.
134
+ */
135
+ function migrateRolePolicyText(text) {
136
+ const doc = (yaml.load(text) ?? {});
137
+ if (doc.vocabulary === 2)
138
+ return text;
139
+ const roles = doc.roles && typeof doc.roles === 'object' ? doc.roles : {};
140
+ const migratedRoles = {};
141
+ for (const [name, def] of Object.entries(roles)) {
142
+ const allow = Array.isArray(def?.allow) ? def.allow.filter((a) => typeof a === 'string') : [];
143
+ migratedRoles[name] = { ...(def ?? {}), allow: [...allow, ...[...exports.LEGACY_UNCHECKED].filter((a) => !allow.includes(a))] };
144
+ }
145
+ const { vocabulary: _v, roles: _r, ...rest } = doc;
146
+ void _v;
147
+ void _r;
148
+ return yaml.dump({ vocabulary: 2, ...rest, roles: migratedRoles });
82
149
  }
83
150
  /**
84
151
  * Describes the project's role configuration WITHOUT judging it. Not having roles on is not a
@@ -91,7 +158,12 @@ function rolePolicyStatus(root) {
91
158
  const policy = loadRolePolicy(root);
92
159
  if (policy === null)
93
160
  return { state: 'inactive', roles: [] };
94
- return { state: 'active', roles: Object.keys(policy.roles).sort(), default: policy.default };
161
+ const defaultIssue = defaultBreadthIssue(policy);
162
+ // @implements A-SPEC-774.22 — the roles whose stages cannot be read, for doctor.
163
+ const malformedStages = Object.entries(policy.roles).filter(([, d]) => d.stagesMalformed).map(([n]) => n).sort();
164
+ return { state: 'active', roles: Object.keys(policy.roles).sort(), default: policy.default, ...(defaultIssue ? { defaultIssue } : {}),
165
+ ...(policy.loadIssue ? { loadIssue: policy.loadIssue } : {}), ...(policy.duplicates ? { duplicates: policy.duplicates } : {}),
166
+ ...(malformedStages.length > 0 ? { malformedStages } : {}) };
95
167
  }
96
168
  /**
97
169
  * Whether this identity may perform this action. Returns the refusal reason, or `null` to allow.
@@ -99,9 +171,40 @@ function rolePolicyStatus(root) {
99
171
  * Fail-closed once a policy exists: an absent role, an unregistered role, and a role without the
100
172
  * action are all refusals. Before a policy exists there is no opinion at all.
101
173
  */
102
- function roleCheck(action, identity, policy) {
174
+ /**
175
+ * @implements A-SPEC-774.8 — a session reaches the default by LOSING its role (unset, or a harness that does not pass it
176
+ * to the MCP server). A default broader than what every role allows turns that loss into an escalation. Null when the
177
+ * default is a subset of the intersection of every role's allow list (an empty intersection makes `allow: []` valid).
178
+ */
179
+ function defaultBreadthIssue(policy) {
180
+ if (policy.default === undefined)
181
+ return null;
182
+ const dflt = policy.roles[policy.default];
183
+ if (!dflt)
184
+ return null; // an undefined default is refused by roleCheck already
185
+ const all = Object.values(policy.roles).map((r) => new Set(r.allow));
186
+ const extra = dflt.allow.filter((a) => !all.every((s) => s.has(a)));
187
+ if (extra.length === 0)
188
+ return null;
189
+ return `the default role "${policy.default}" allows ${extra.join(', ')}, which not every role allows — a session that loses `
190
+ + 'its role would gain them. Make the default a role that allows only what every role allows, for example '
191
+ + '`readonly: { allow: [] }` with `default: readonly` (A-SPEC-774.8)';
192
+ }
193
+ function roleCheck(action, identity, policy, opts) {
103
194
  if (policy === null)
104
195
  return null;
196
+ // @implements A-SPEC-774.15 — a policy that could not be read grants nothing, in every mode.
197
+ if (policy.loadIssue)
198
+ return `[Holmes-Kit] ${policy.loadIssue} — ${action} cannot be allowed until the policy can be read`;
199
+ // @implements A-SPEC-774.8 — in a run a broad default invalidates the policy: it grants nothing.
200
+ if (opts?.run) {
201
+ const breadth = defaultBreadthIssue(policy);
202
+ if (breadth)
203
+ return `[Holmes-Kit] this role policy is refused in a run: ${breadth}`;
204
+ }
205
+ // @implements A-SPEC-774.10 — a legacy policy, outside a run, keeps allowing what 0.35.25 never checked.
206
+ if (!opts?.run && policy.vocabulary !== 2 && exports.LEGACY_UNCHECKED.has(action))
207
+ return null;
105
208
  const known = Object.keys(policy.roles);
106
209
  // The default is resolved HERE, not in the identity provider. Identity is observed fact — what the
107
210
  // operator actually claimed — while a default is the policy's interpretation of silence. Folding
@@ -124,11 +227,25 @@ function roleCheck(action, identity, policy) {
124
227
  }
125
228
  // Exact match on purpose: a silent case-fold would make `Developer` and `developer` the same
126
229
  // principal by accident, which is not a decision a policy file ever expressed.
230
+ // @implements A-SPEC-774.15 — in a run, a role defined in more than one file grants nothing: which definition holds
231
+ // is a decision no file expressed. Interactively the later definition still decides (0.35.25).
232
+ if (opts?.run && policy.duplicates?.includes(effective)) {
233
+ return `[Holmes-Kit] role "${effective}" is defined in more than one file under .ax/roles — ${action} cannot be allowed in a run until it is defined once`;
234
+ }
127
235
  const def = policy.roles[effective];
128
236
  if (!def) {
129
237
  return `[Holmes-Kit] 역할 "${effective}"이(가) 역할 정책에 없습니다 — ${action}을(를) 허용할 수 없습니다.`
130
238
  + ` 등록된 역할: ${known.join(', ') || '(없음)'}`;
131
239
  }
240
+ // @implements A-SPEC-774.22 — in a run, a stages declaration that cannot be read limits the role to no stage at all.
241
+ if (opts?.run && def.stagesMalformed) {
242
+ return `[Holmes-Kit] role ${effective} may not act in stage ${opts.stage ?? 'any'} of a run: its stages declaration cannot be read`
243
+ + ' (a list of stage names is expected)';
244
+ }
245
+ // @implements A-SPEC-774.19 — action, role and stage together: a role that declares stages acts only in them.
246
+ if (opts?.stage !== undefined && def.stages !== undefined && !def.stages.includes(opts.stage)) {
247
+ return `[Holmes-Kit] role ${effective} may not act in stage ${opts.stage} (its stages: ${def.stages.join(', ') || 'none'})`;
248
+ }
132
249
  if (!def.allow.includes(action)) {
133
250
  return `[Holmes-Kit] 역할 "${effective}"은(는) ${action}을(를) 수행할 수 없습니다.`
134
251
  + ` 허용된 동작: ${def.allow.join(', ') || '(없음)'}`;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Whether this SESSION is an orchestrated run. Owner principle (2026-10-18): new controls bind runs; a person working
3
+ * interactively keeps what 0.35.25 allowed. Until the G2.4 run token exists, a run is known by either of two marks the
4
+ * session cannot remove:
5
+ * - `HOLMES_RUN_ID` in the environment the orchestrator launched the harness with (an authority name, A-SPEC-774.2);
6
+ * - a run record under `.ax/state/runs/` (a protected path) binding the session's cwd or its harness session id.
7
+ * Judged by the session, never by the target a command names: `cd <other repo> && …` stays in the run.
8
+ * A runs directory that cannot be read, or a record of the wrong shape, answers "run" — the stricter side.
9
+ */
10
+ export declare function runMode(env: NodeJS.ProcessEnv, projectRoot: string, cwd?: string, sessionId?: string): {
11
+ run: boolean;
12
+ why: string;
13
+ id?: string;
14
+ };
@@ -0,0 +1,120 @@
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.runMode = runMode;
37
+ // @implements A-SPEC-774.9
38
+ const fs = __importStar(require("node:fs"));
39
+ const path = __importStar(require("node:path"));
40
+ /**
41
+ * Whether this SESSION is an orchestrated run. Owner principle (2026-10-18): new controls bind runs; a person working
42
+ * interactively keeps what 0.35.25 allowed. Until the G2.4 run token exists, a run is known by either of two marks the
43
+ * session cannot remove:
44
+ * - `HOLMES_RUN_ID` in the environment the orchestrator launched the harness with (an authority name, A-SPEC-774.2);
45
+ * - a run record under `.ax/state/runs/` (a protected path) binding the session's cwd or its harness session id.
46
+ * Judged by the session, never by the target a command names: `cd <other repo> && …` stays in the run.
47
+ * A runs directory that cannot be read, or a record of the wrong shape, answers "run" — the stricter side.
48
+ */
49
+ // @implements A-SPEC-778 — `id` names the run that binds the session (the marker's value or the record's run_id), so
50
+ // the run's refusal log can be found; a run known only by an unreadable store has no id.
51
+ function runMode(env, projectRoot, cwd, sessionId) {
52
+ const marker = env.HOLMES_RUN_ID;
53
+ if (typeof marker === 'string' && marker.trim() !== '')
54
+ return { run: true, why: 'HOLMES_RUN_ID is set', id: marker.trim() };
55
+ // @implements A-SPEC-774.11 §1 — a `git worktree add` worktree checks out its own spec store, so it IS the project
56
+ // root, while the run record lives in the main checkout's gitignored state (supervisor probe7749). Both are read.
57
+ const roots = [projectRoot];
58
+ const pointer = path.join(projectRoot, '.git');
59
+ try {
60
+ if (fs.existsSync(pointer) && fs.lstatSync(pointer).isFile()) {
61
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(fs.readFileSync(pointer, 'utf8'));
62
+ if (!m)
63
+ return { run: true, why: 'worktree pointer unreadable — treated as a run' };
64
+ const gitdir = path.resolve(projectRoot, m[1]);
65
+ const commondir = path.join(gitdir, 'commondir');
66
+ if (fs.existsSync(commondir)) {
67
+ const common = path.resolve(gitdir, fs.readFileSync(commondir, 'utf8').trim());
68
+ if (path.basename(common) === '.git')
69
+ roots.push(path.dirname(common));
70
+ }
71
+ }
72
+ }
73
+ catch {
74
+ return { run: true, why: 'worktree pointer unreadable — treated as a run' };
75
+ }
76
+ const real = (p) => { try {
77
+ return fs.realpathSync(p);
78
+ }
79
+ catch {
80
+ return path.resolve(p);
81
+ } };
82
+ const here = cwd ? real(cwd) : undefined;
83
+ for (const root of roots) {
84
+ const found = recordsIn(path.join(root, '.ax', 'state', 'runs'), here, sessionId, real);
85
+ if (found)
86
+ return found;
87
+ }
88
+ return { run: false, why: 'no run marker or record binds this session' };
89
+ }
90
+ function recordsIn(dir, here, sessionId, real) {
91
+ let names;
92
+ try {
93
+ names = fs.readdirSync(dir);
94
+ }
95
+ catch (e) {
96
+ if (e.code === 'ENOENT')
97
+ return null;
98
+ return { run: true, why: `run records unreadable (${e.code ?? 'error'}) — treated as a run` };
99
+ }
100
+ for (const n of names.filter((f) => f.endsWith('.json'))) {
101
+ let rec;
102
+ try {
103
+ rec = JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8'));
104
+ }
105
+ catch {
106
+ return { run: true, why: `run record ${n} unreadable — treated as a run` };
107
+ }
108
+ const r = rec;
109
+ if (!r || typeof r !== 'object' || typeof r.run_id !== 'string' || typeof r.worktree !== 'string'
110
+ || (r.sessions !== undefined && !(Array.isArray(r.sessions) && r.sessions.every((s) => typeof s === 'string')))) {
111
+ return { run: true, why: `run record ${n} malformed — treated as a run` };
112
+ }
113
+ const wt = real(r.worktree);
114
+ if (here && (here === wt || here.startsWith(wt + path.sep)))
115
+ return { run: true, why: `cwd is run ${r.run_id}'s worktree`, id: r.run_id };
116
+ if (sessionId && Array.isArray(r.sessions) && r.sessions.includes(sessionId))
117
+ return { run: true, why: `session bound to run ${r.run_id}`, id: r.run_id };
118
+ }
119
+ return null;
120
+ }