@holmes-lab/holmes-kit 0.30.0 → 0.31.1

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 (139) hide show
  1. package/CHANGELOG.md +505 -0
  2. package/README.md +10 -1
  3. package/bin/holmes-hook-antigravity.js +4 -0
  4. package/bin/holmes-kit.js +4 -0
  5. package/bin/holmes-pre-push.js +3 -0
  6. package/bin/holmes-stop-antigravity.js +4 -0
  7. package/dist/.build-id +1 -1
  8. package/dist/holmes/cli/agents.d.ts +41 -0
  9. package/dist/holmes/cli/agents.js +382 -2
  10. package/dist/holmes/cli/attest.d.ts +2 -0
  11. package/dist/holmes/cli/attest.js +66 -15
  12. package/dist/holmes/cli/ci-gate.js +16 -1
  13. package/dist/holmes/cli/claude-switches.d.ts +95 -0
  14. package/dist/holmes/cli/claude-switches.js +967 -0
  15. package/dist/holmes/cli/codex-hooks.d.ts +77 -0
  16. package/dist/holmes/cli/codex-hooks.js +802 -0
  17. package/dist/holmes/cli/codex-oracle.d.ts +194 -0
  18. package/dist/holmes/cli/codex-oracle.js +1245 -0
  19. package/dist/holmes/cli/codex-toml.d.ts +35 -0
  20. package/dist/holmes/cli/codex-toml.js +321 -52
  21. package/dist/holmes/cli/doctor.d.ts +98 -8
  22. package/dist/holmes/cli/doctor.js +1328 -94
  23. package/dist/holmes/cli/index.js +26 -11
  24. package/dist/holmes/cli/init.d.ts +11 -0
  25. package/dist/holmes/cli/init.js +736 -44
  26. package/dist/holmes/cli/mcp-launcher.d.ts +64 -6
  27. package/dist/holmes/cli/mcp-launcher.js +189 -6
  28. package/dist/holmes/cli/mcp-version.js +13 -2
  29. package/dist/holmes/cli/settings-merge.js +8 -2
  30. package/dist/holmes/cli/upgrade.d.ts +18 -0
  31. package/dist/holmes/cli/upgrade.js +129 -24
  32. package/dist/holmes/cli/workspace-scope.d.ts +22 -0
  33. package/dist/holmes/cli/workspace-scope.js +375 -0
  34. package/dist/holmes/cpg/cpg-scanner.d.ts +29 -0
  35. package/dist/holmes/cpg/cpg-scanner.js +403 -3
  36. package/dist/holmes/cpg/cycle-detect.js +2 -1
  37. package/dist/holmes/cpg/forbidden-edges.js +9 -2
  38. package/dist/holmes/cpg/required-calls.js +8 -1
  39. package/dist/holmes/governance/constitution-debt.js +3 -2
  40. package/dist/holmes/governance/constitution.js +15 -3
  41. package/dist/holmes/governance/provenance-chain.js +3 -2
  42. package/dist/holmes/governance/push-gate-runner.js +4 -3
  43. package/dist/holmes/guardrail/dependency-delta.js +4 -3
  44. package/dist/holmes/guardrail/linear-match.d.ts +57 -0
  45. package/dist/holmes/guardrail/linear-match.js +256 -0
  46. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -7
  47. package/dist/holmes/guardrail/risk-classifier.js +931 -44
  48. package/dist/holmes/guardrail/risk-types.d.ts +6 -0
  49. package/dist/holmes/guardrail/scope-judgment.d.ts +4 -24
  50. package/dist/holmes/guardrail/scope-judgment.js +100 -23
  51. package/dist/holmes/guardrail/shell-words.d.ts +42 -0
  52. package/dist/holmes/guardrail/shell-words.js +1720 -0
  53. package/dist/holmes/guardrail/write-target.d.ts +168 -3
  54. package/dist/holmes/guardrail/write-target.js +2379 -87
  55. package/dist/holmes/hooks/adapters/antigravity.d.ts +3 -1
  56. package/dist/holmes/hooks/adapters/antigravity.js +115 -11
  57. package/dist/holmes/hooks/pre-tool-use.d.ts +32 -6
  58. package/dist/holmes/hooks/pre-tool-use.js +923 -87
  59. package/dist/holmes/hooks/rtm-refresh-child.js +3 -1
  60. package/dist/holmes/hooks/rtm-refresh.js +8 -4
  61. package/dist/holmes/hooks/session-start.d.ts +10 -0
  62. package/dist/holmes/hooks/session-start.js +31 -7
  63. package/dist/holmes/hooks/stop.d.ts +2 -1
  64. package/dist/holmes/hooks/stop.js +197 -91
  65. package/dist/holmes/mcp/approval-commit.d.ts +5 -6
  66. package/dist/holmes/mcp/approval-commit.js +18 -2
  67. package/dist/holmes/mcp/elicit-approval.js +4 -2
  68. package/dist/holmes/mcp/handlers/graph-operations.js +3 -2
  69. package/dist/holmes/mcp/handlers/maintenance-analysis.js +11 -5
  70. package/dist/holmes/mcp/handlers/maintenance-evidence.js +3 -2
  71. package/dist/holmes/mcp/handlers/phase-queries.d.ts +22 -7
  72. package/dist/holmes/mcp/handlers/phase-queries.js +81 -2
  73. package/dist/holmes/mcp/handlers/requirement-triage.js +5 -3
  74. package/dist/holmes/mcp/handlers/review-evidence.js +8 -2
  75. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +11 -0
  76. package/dist/holmes/mcp/handlers/slice-orchestration.js +115 -16
  77. package/dist/holmes/mcp/handlers/spec-approval.d.ts +9 -0
  78. package/dist/holmes/mcp/handlers/spec-approval.js +110 -17
  79. package/dist/holmes/mcp/handlers/spec-authoring.js +17 -2
  80. package/dist/holmes/mcp/handlers/spec-queries.d.ts +39 -3
  81. package/dist/holmes/mcp/handlers/spec-queries.js +114 -7
  82. package/dist/holmes/mcp/handlers/test-execution.js +9 -3
  83. package/dist/holmes/mcp/handlers.d.ts +81 -9
  84. package/dist/holmes/mcp/handlers.js +70 -23
  85. package/dist/holmes/mcp/harness-attestation.d.ts +20 -0
  86. package/dist/holmes/mcp/harness-attestation.js +179 -0
  87. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +36 -0
  88. package/dist/holmes/mcp/requirement-triage-evidence.js +160 -4
  89. package/dist/holmes/mcp/server.js +20 -1
  90. package/dist/holmes/mcp/tool-schemas.js +26 -9
  91. package/dist/holmes/mcp/validate-args.js +12 -0
  92. package/dist/holmes/project/bounded-io.d.ts +102 -0
  93. package/dist/holmes/project/bounded-io.js +212 -0
  94. package/dist/holmes/project/change-source.js +3 -1
  95. package/dist/holmes/project/ci-runs.js +3 -2
  96. package/dist/holmes/project/ignore.d.ts +31 -2
  97. package/dist/holmes/project/ignore.js +409 -50
  98. package/dist/holmes/project/regular-file-guard.d.ts +13 -0
  99. package/dist/holmes/project/regular-file-guard.js +149 -0
  100. package/dist/holmes/project/root.js +12 -3
  101. package/dist/holmes/reverse/anchor.js +4 -3
  102. package/dist/holmes/reverse/scan.js +6 -2
  103. package/dist/holmes/review/commit-text.js +3 -2
  104. package/dist/holmes/review/condition-hunk-replay.js +3 -2
  105. package/dist/holmes/review/failed-test-names.js +13 -10
  106. package/dist/holmes/review/findings.js +3 -1
  107. package/dist/holmes/review/kills-check.js +6 -1
  108. package/dist/holmes/review/point-in-time-replay.js +5 -4
  109. package/dist/holmes/review/replay-corpus.js +5 -4
  110. package/dist/holmes/review/run-replay.js +3 -2
  111. package/dist/holmes/review/temporal-prior.js +3 -2
  112. package/dist/holmes/review/test-evidence.js +3 -2
  113. package/dist/holmes/review/test-outcomes.js +3 -2
  114. package/dist/holmes/review/test-runner.d.ts +6 -0
  115. package/dist/holmes/review/test-runner.js +36 -15
  116. package/dist/holmes/rtm/advisory-outcomes.js +3 -2
  117. package/dist/holmes/rtm/anchor-ids.js +42 -2
  118. package/dist/holmes/rtm/file-anchors.js +4 -1
  119. package/dist/holmes/rtm/ftt-fulfilment.js +8 -3
  120. package/dist/holmes/rtm/git-changes.js +3 -1
  121. package/dist/holmes/rtm/graph-store.js +3 -2
  122. package/dist/holmes/rtm/test-scope.js +9 -4
  123. package/dist/holmes/spec/compat-impact.d.ts +25 -4
  124. package/dist/holmes/spec/compat-impact.js +682 -11
  125. package/dist/holmes/spec/entity-git-snapshot.js +3 -2
  126. package/dist/holmes/spec/entity-integration.js +3 -2
  127. package/dist/holmes/spec/entity-renumber-transaction.d.ts +19 -0
  128. package/dist/holmes/spec/entity-renumber-transaction.js +79 -6
  129. package/dist/holmes/spec/remote-spec-refs.js +3 -2
  130. package/dist/holmes/spec/renumber.js +25 -10
  131. package/dist/holmes/spec/spec-parser.js +9 -3
  132. package/dist/holmes/spec/yaml-scalar.js +2 -2
  133. package/dist/holmes/update/refresh.d.ts +5 -0
  134. package/dist/holmes/update/refresh.js +26 -1
  135. package/dist/holmes/update/update-notice.d.ts +6 -0
  136. package/dist/holmes/update/update-notice.js +18 -1
  137. package/dist/holmes/update/upgrade-plan.d.ts +28 -0
  138. package/dist/holmes/update/upgrade-plan.js +31 -2
  139. package/package.json +11 -4
@@ -1,14 +1,13 @@
1
1
  import { ApprovalIntent, IntentBinding } from './approval-intent';
2
2
  import { Approval } from '../guardrail/risk-gate';
3
- /**
4
- * Memory-only continuations deliberately die with the MCP session. A rejected or malformed
5
- * commit never burns a valid pending intent; only an exact, live host-gated commit can be consumed
6
- * by the original action, exactly once.
7
- */
8
3
  export declare class ApprovalContinuationStore {
9
4
  private readonly pending;
10
5
  private readonly committed;
11
- prepare(intent: ApprovalIntent): void;
6
+ prepare(intent: ApprovalIntent, now?: Date): void;
7
+ size(): {
8
+ pending: number;
9
+ committed: number;
10
+ };
12
11
  commit(candidate: ApprovalIntent, now?: Date): {
13
12
  ok: true;
14
13
  } | {
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ApprovalContinuationStore = void 0;
37
- // @implements A-SPEC-718
37
+ // @implements A-SPEC-718, A-SPEC-732
38
38
  const crypto = __importStar(require("node:crypto"));
39
39
  const approval_intent_1 = require("./approval-intent");
40
40
  /**
@@ -42,12 +42,28 @@ const approval_intent_1 = require("./approval-intent");
42
42
  * commit never burns a valid pending intent; only an exact, live host-gated commit can be consumed
43
43
  * by the original action, exactly once.
44
44
  */
45
+ /** Live pending intents kept per session; the oldest leaves first. */
46
+ const MAX_PENDING = 256;
45
47
  class ApprovalContinuationStore {
46
48
  pending = new Map();
47
49
  committed = new Map();
48
- prepare(intent) {
50
+ prepare(intent, now = new Date()) {
51
+ // @implements A-SPEC-732 (round 3) — refused host-gated calls left ~800 bytes each, forever:
52
+ // the only deletion was a successful commit. Expired intents can never commit or be consumed.
53
+ const expired = (i) => Date.parse(i.expiresAt) <= now.getTime();
54
+ for (const [id, i] of this.pending)
55
+ if (expired(i))
56
+ this.pending.delete(id);
57
+ for (const [id, i] of this.committed)
58
+ if (expired(i))
59
+ this.committed.delete(id);
60
+ while (this.pending.size >= MAX_PENDING)
61
+ this.pending.delete(this.pending.keys().next().value);
49
62
  this.pending.set(intent.id, intent);
50
63
  }
64
+ size() {
65
+ return { pending: this.pending.size, committed: this.committed.size };
66
+ }
51
67
  commit(candidate, now = new Date()) {
52
68
  const pending = this.pending.get(candidate.id);
53
69
  if (!pending)
@@ -9,7 +9,7 @@ exports.buildDecisionForm = buildDecisionForm;
9
9
  exports.buildReasonForm = buildReasonForm;
10
10
  exports.runElicitFlow = runElicitFlow;
11
11
  exports.interpretElicitResult = interpretElicitResult;
12
- // @implements A-SPEC-718, A-SPEC-263.1
12
+ // @implements A-SPEC-718, A-SPEC-263.1, A-SPEC-732
13
13
  const npx_bin_1 = require("../project/npx-bin");
14
14
  /**
15
15
  * The decision comes INTO the session (REQ-263): an approval-shaped refusal (spec_approve without a
@@ -214,8 +214,10 @@ async function collectReason(raw, decision) {
214
214
  function interpretElicitResult(r) {
215
215
  if (!r || typeof r !== 'object')
216
216
  return null;
217
+ // @implements A-SPEC-732 — the protocol cannot tell a person's decline from a client that declines
218
+ // forms automatically (codex exec, measured 2026-09-24), so the reason names both and the fallback.
217
219
  if (r.action === 'decline')
218
- return { granted: false, reason: '사람이 세션에서 거절했습니다(decline)' };
220
+ return { granted: false, reason: 'the session client declined the approval form (decline) — a person declined, or a client that cannot show forms (e.g. codex exec) declined automatically. If nobody saw the form, set HOLMES_ELICIT=off in the holmes-kit MCP server environment and decide with holmes-kit approve' };
219
221
  if (r.action !== 'accept')
220
222
  return null; // cancel, absent, anything else: no decision
221
223
  const content = r.content;
@@ -39,7 +39,7 @@ exports.warmRequirementSemanticCache = warmRequirementSemanticCache;
39
39
  exports.headOf = headOf;
40
40
  exports.refreshSemanticVectors = refreshSemanticVectors;
41
41
  exports.createGraphOperationsHandlers = createGraphOperationsHandlers;
42
- // @implements A-SPEC-719
42
+ // @implements A-SPEC-719, A-SPEC-734
43
43
  // @implements A-SPEC-614, A-SPEC-613, A-SPEC-100.2, A-SPEC-121.2, A-SPEC-128, A-SPEC-139, A-SPEC-189, A-SPEC-280, A-SPEC-282, A-SPEC-283, A-SPEC-419, A-SPEC-433, A-SPEC-469, A-SPEC-478, A-SPEC-568.1, A-SPEC-568.2, A-SPEC-569.1, A-SPEC-569.2, A-SPEC-569.3, A-SPEC-589
44
44
  // @implements A-SPEC-632
45
45
  const fs = __importStar(require("node:fs"));
@@ -54,6 +54,7 @@ const trace_gaps_1 = require("../../rtm/trace-gaps");
54
54
  const tier_1 = require("../../semantic/tier");
55
55
  const vector_cache_1 = require("../../semantic/vector-cache");
56
56
  const embedder_1 = require("../../semantic/embedder");
57
+ const bounded_io_1 = require("../../project/bounded-io");
57
58
  const vector_coverage_1 = require("../../semantic/vector-coverage");
58
59
  // @implements A-SPEC-283 — bumped whenever the graph's node/edge shape changes, so a store written
59
60
  // by an older build is rebuilt rather than read with new assumptions.
@@ -128,7 +129,7 @@ async function warmRequirementSemanticCache(root, specs) {
128
129
  function headOf(root) {
129
130
  try {
130
131
  const { execFileSync } = require('node:child_process');
131
- return execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
132
+ return execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
132
133
  }
133
134
  catch {
134
135
  return null;
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createMaintenanceAnalysisHandlers = createMaintenanceAnalysisHandlers;
37
- // @implements A-SPEC-612, A-SPEC-100.2, A-SPEC-128, A-SPEC-189, A-SPEC-267, A-SPEC-268, A-SPEC-269, A-SPEC-277, A-SPEC-283, A-SPEC-290, A-SPEC-292, A-SPEC-293, A-SPEC-378, A-SPEC-388, A-SPEC-418, A-SPEC-478, A-SPEC-571.2, A-SPEC-573.4, A-SPEC-578.5
37
+ // @implements A-SPEC-612, A-SPEC-100.2, A-SPEC-128, A-SPEC-189, A-SPEC-267, A-SPEC-268, A-SPEC-269, A-SPEC-277, A-SPEC-283, A-SPEC-290, A-SPEC-292, A-SPEC-293, A-SPEC-378, A-SPEC-388, A-SPEC-418, A-SPEC-478, A-SPEC-571.2, A-SPEC-573.4, A-SPEC-578.5, A-SPEC-734
38
38
  const fs = __importStar(require("node:fs"));
39
39
  const path = __importStar(require("node:path"));
40
40
  const node_child_process_1 = require("node:child_process");
@@ -54,6 +54,7 @@ const embedder_1 = require("../../semantic/embedder");
54
54
  const maintenance_analyze_1 = require("../maintenance-analyze");
55
55
  const maintenance_evidence_1 = require("../maintenance-evidence");
56
56
  const defuse_bound_1 = require("../defuse-bound");
57
+ const bounded_io_1 = require("../../project/bounded-io");
57
58
  function createMaintenanceAnalysisHandlers(context) {
58
59
  return {
59
60
  async maintenance_analyze(a) {
@@ -71,21 +72,26 @@ function createMaintenanceAnalysisHandlers(context) {
71
72
  const detail = context.basisFor(root, true);
72
73
  let head = '';
73
74
  try {
74
- head = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), stdio: ['ignore', 'pipe', 'pipe'] }).trim();
75
+ head = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { maxBuffer: bounded_io_1.GIT_MAX_BUFFER, timeout: 5000, encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), stdio: ['ignore', 'pipe', 'pipe'] }).trim();
75
76
  }
76
77
  catch { /* non-git */ }
77
78
  const supportedExtensions = new Set(cpg_scanner_1.SCANNABLE_EXTENSIONS);
78
79
  const knownCodeExtensions = new Set(['.rb', '.php', '.kt', '.kts', '.swift', '.scala', '.sh', '.ex', '.exs', '.lua', '.r']);
79
80
  const unsupportedLanguages = new Set();
80
81
  try {
81
- const files = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), maxBuffer: 8 * 1024 * 1024 }).split('\0');
82
+ // A-SPEC-734 (round 12): a root whose git timed out is not asked again (the shared memory).
83
+ if ((0, bounded_io_1.gitRootBlocked)(root))
84
+ throw new Error('git blocked on this root');
85
+ // A-SPEC-734 (round 15): with the fsmonitor hook off.
86
+ const files = (0, node_child_process_1.execFileSync)('git', ['-c', 'core.fsmonitor=false', '-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { timeout: 5000, encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), maxBuffer: bounded_io_1.GIT_MAX_BUFFER }).split('\0'); // round 16: the shared bound
82
87
  for (const file of files) {
83
88
  const ext = path.extname(file).toLowerCase();
84
89
  if (knownCodeExtensions.has(ext) && !supportedExtensions.has(ext))
85
90
  unsupportedLanguages.add(ext);
86
91
  }
87
92
  }
88
- catch {
93
+ catch (e) {
94
+ (0, bounded_io_1.noteGitFailure)(root, e);
89
95
  // A non-git tree cannot be enumerated cheaply without reimplementing the scanner's ignore
90
96
  // rules. Surface the missing axis rather than claiming every language was covered.
91
97
  unsupportedLanguages.add('not-enumerated(non-git)');
@@ -141,7 +147,7 @@ function createMaintenanceAnalysisHandlers(context) {
141
147
  let historyStatus = limit === 0 || candidateFiles.length === 0 ? 'not-requested' : 'unavailable';
142
148
  if (limit > 0 && candidateFiles.length > 0) {
143
149
  try {
144
- const raw = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'log', `-${limit}`, '--date=short', '--format=%H%x00%ad%x00%s', '--name-only', '--', ...candidateFiles], { encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), maxBuffer: 2 * 1024 * 1024 });
150
+ const raw = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'log', `-${limit}`, '--date=short', '--format=%H%x00%ad%x00%s', '--name-only', '--', ...candidateFiles], { timeout: 5000, encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), maxBuffer: 2 * 1024 * 1024 });
145
151
  let current = null;
146
152
  for (const line of raw.split('\n')) {
147
153
  if (line.includes('\0')) {
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createMaintenanceEvidenceHandlers = createMaintenanceEvidenceHandlers;
37
- // @implements A-SPEC-724.1, A-SPEC-603
37
+ // @implements A-SPEC-724.1, A-SPEC-603, A-SPEC-734
38
38
  const fs = __importStar(require("node:fs"));
39
39
  const path = __importStar(require("node:path"));
40
40
  const node_child_process_1 = require("node:child_process");
@@ -42,6 +42,7 @@ const maintenance_evidence_1 = require("../maintenance-evidence");
42
42
  const impact_gate_1 = require("../../guardrail/impact-gate");
43
43
  const root_1 = require("../../project/root");
44
44
  const trace_gaps_1 = require("../../rtm/trace-gaps");
45
+ const bounded_io_1 = require("../../project/bounded-io");
45
46
  /** Raw handlers: the public facade attaches basis exactly once. */
46
47
  function createMaintenanceEvidenceHandlers(context) {
47
48
  return {
@@ -66,7 +67,7 @@ function createMaintenanceEvidenceHandlers(context) {
66
67
  const root = context.projectRootOf(a.root);
67
68
  let head = '';
68
69
  try {
69
- head = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), stdio: ['ignore', 'pipe', 'pipe'] }).trim();
70
+ head = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), stdio: ['ignore', 'pipe', 'pipe'] }).trim();
70
71
  }
71
72
  catch { /* non-git */ }
72
73
  let artifact = null;
@@ -5,21 +5,35 @@ export interface PhaseQueryContext {
5
5
  boundSpecsRoot(): string | undefined;
6
6
  projectRootOf(root: string): string;
7
7
  }
8
+ type PhaseRow = {
9
+ id: string;
10
+ type: string;
11
+ status: string;
12
+ };
8
13
  export declare function createPhaseQueryHandlers(context: PhaseQueryContext): {
9
14
  phase_status(a: {
10
15
  root?: string;
16
+ ids?: string[];
17
+ type?: string;
18
+ status?: string;
19
+ limit?: number;
20
+ cursor?: string;
11
21
  }): Promise<{
12
22
  ok: boolean;
13
23
  reason: string;
14
- specs?: undefined;
15
- note?: undefined;
16
24
  } | {
17
- specs: {
18
- id: string;
19
- type: import("../../spec/spec-types").SpecType;
20
- status: "draft" | "review" | "approved" | "outdated";
21
- }[];
22
25
  note: string;
26
+ unknownIds?: string[] | undefined;
27
+ unknownIdsTotal?: number | undefined;
28
+ nextCursor?: string | undefined;
29
+ summary: {
30
+ total: number;
31
+ counts: Record<string, Record<string, number>>;
32
+ notApproved: PhaseRow[];
33
+ notApprovedTotal: number;
34
+ };
35
+ specs: PhaseRow[];
36
+ matched: number;
23
37
  ok?: undefined;
24
38
  reason?: undefined;
25
39
  }>;
@@ -32,3 +46,4 @@ export declare function createPhaseQueryHandlers(context: PhaseQueryContext): {
32
46
  note: string;
33
47
  }>;
34
48
  };
49
+ export {};
@@ -34,11 +34,87 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createPhaseQueryHandlers = createPhaseQueryHandlers;
37
- // @implements A-SPEC-606, A-SPEC-100.2
37
+ // @implements A-SPEC-606, A-SPEC-100.2, A-SPEC-735
38
38
  const fs = __importStar(require("node:fs"));
39
39
  const path = __importStar(require("node:path"));
40
40
  const phase_1 = require("../../guardrail/phase");
41
41
  const write_target_1 = require("../../guardrail/write-target");
42
+ // @implements A-SPEC-735 — the whole corpus in one answer was 153,888 characters here, past what a
43
+ // client accepts, so the overview could not be read. A bounded summary plus a stateless page.
44
+ const PAGE_DEFAULT = 100;
45
+ const PAGE_MAX = 500;
46
+ const NOT_APPROVED_SHOWN = 50;
47
+ // @implements A-SPEC-735 (round 2) — a TOTAL order: numeric-aware alone ties REQ-1/REQ-01/REQ-001
48
+ // (and NFC/NFD), and a strictly-after cursor then dropped the tied rows across pages (measured).
49
+ const codepoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
50
+ const byId = (a, b) => a.id.localeCompare(b.id, 'en', { numeric: true })
51
+ || codepoint(a.id, b.id) || codepoint(a.type, b.type) || codepoint(a.status, b.status);
52
+ const CURSOR_SEP = '\u0001';
53
+ const UNKNOWN_SHOWN = 50;
54
+ function limitProblem(limit) {
55
+ if (limit === undefined || limit === null)
56
+ return undefined;
57
+ if (typeof limit === 'number' && Number.isInteger(limit) && limit >= 1 && limit <= PAGE_MAX)
58
+ return undefined;
59
+ return `limit은 1..${PAGE_MAX} 범위의 정수여야 합니다 (받은 값: ${JSON.stringify(limit)}).`;
60
+ }
61
+ function phasePage(all, a) {
62
+ const rows = [...all].sort(byId);
63
+ // @implements A-SPEC-735 (round 2) — Maps, never assignment into a plain object: `type: __proto__`
64
+ // set ({}).approved = 1 for the whole process (measured).
65
+ const byType = new Map();
66
+ for (const r of rows) {
67
+ const t = byType.get(r.type) ?? new Map();
68
+ t.set(r.status, (t.get(r.status) ?? 0) + 1);
69
+ byType.set(r.type, t);
70
+ }
71
+ const counts = Object.fromEntries([...byType].map(([t, m]) => [t, Object.fromEntries(m)]));
72
+ const pending = rows.filter((r) => r.status !== 'approved');
73
+ const wanted = Array.isArray(a.ids) ? new Set(a.ids.filter((x) => typeof x === 'string')) : undefined;
74
+ const known = new Set(rows.map((r) => r.id));
75
+ const unknownIds = wanted ? [...wanted].filter((id) => !known.has(id)) : [];
76
+ const selected = rows.filter((r) => (!wanted || wanted.has(r.id))
77
+ && (typeof a.type !== 'string' || r.type === a.type)
78
+ && (typeof a.status !== 'string' || r.status === a.status));
79
+ // Cursor = the last row's key, plus how many rows EQUAL to that key were already returned (so
80
+ // identical rows — duplicate files — are neither lost nor repeated).
81
+ const key = (r) => `${r.id}${CURSOR_SEP}${r.type}${CURSOR_SEP}${r.status}`;
82
+ let start = 0;
83
+ if (typeof a.cursor === 'string' && a.cursor !== '') {
84
+ const parts = a.cursor.split(CURSOR_SEP);
85
+ const probe = { id: parts[0], type: parts[1] ?? '', status: parts[2] ?? '' };
86
+ const seenEqual = Number.parseInt(parts[3] ?? '0', 10) || 0;
87
+ const exact = parts.length >= 3;
88
+ start = selected.findIndex((r) => byId(r, probe) > 0 || (exact && byId(r, probe) === 0));
89
+ if (start < 0)
90
+ start = selected.length;
91
+ if (exact) {
92
+ let k = 0;
93
+ while (start < selected.length && byId(selected[start], probe) === 0 && k < seenEqual) {
94
+ start++;
95
+ k++;
96
+ }
97
+ }
98
+ else {
99
+ while (start < selected.length && byId(selected[start], { id: probe.id, type: '', status: '' }) <= 0 && selected[start].id === probe.id)
100
+ start++;
101
+ }
102
+ }
103
+ const limit = typeof a.limit === 'number' ? a.limit : PAGE_DEFAULT;
104
+ const specs = selected.slice(start, start + limit);
105
+ const last = specs[specs.length - 1];
106
+ let equalTaken = 0;
107
+ if (last)
108
+ for (let i = start + specs.length - 1; i >= 0 && byId(selected[i], last) === 0; i--)
109
+ equalTaken++;
110
+ return {
111
+ summary: { total: rows.length, counts, notApproved: pending.slice(0, NOT_APPROVED_SHOWN), notApprovedTotal: pending.length },
112
+ specs,
113
+ matched: selected.length,
114
+ ...(start + limit < selected.length ? { nextCursor: `${key(last)}${CURSOR_SEP}${equalTaken}` } : {}),
115
+ ...(unknownIds.length > 0 ? { unknownIds: unknownIds.slice(0, UNKNOWN_SHOWN), unknownIdsTotal: unknownIds.length } : {}),
116
+ };
117
+ }
42
118
  function createPhaseQueryHandlers(context) {
43
119
  return {
44
120
  async phase_status(a) {
@@ -72,8 +148,11 @@ function createPhaseQueryHandlers(context) {
72
148
  };
73
149
  }
74
150
  }
151
+ const badLimit = limitProblem(a?.limit);
152
+ if (badLimit)
153
+ return { ok: false, reason: badLimit };
75
154
  const specs = await context.listSpecs();
76
- return { specs: specs.map((s) => ({ id: s.id, type: s.type, status: s.status })), note: 'derive phase via phase_check' };
155
+ return { ...phasePage(specs.map((s) => ({ id: s.id, type: s.type, status: s.status })), a ?? {}), note: 'derive phase via phase_check' };
77
156
  },
78
157
  async phase_check(a) {
79
158
  const specs = await context.listSpecs();
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createRequirementTriageHandlers = createRequirementTriageHandlers;
37
- // @implements A-SPEC-723, A-SPEC-719
37
+ // @implements A-SPEC-729, A-SPEC-723, A-SPEC-719, A-SPEC-734
38
38
  // @implements A-SPEC-713
39
39
  /** Read-only MCP projection of the pure requirement lifecycle triage model. */
40
40
  const node_child_process_1 = require("node:child_process");
@@ -49,6 +49,7 @@ const requirement_triage_evidence_1 = require("../requirement-triage-evidence");
49
49
  const model_cache_1 = require("../../semantic/model-cache");
50
50
  const graph_store_1 = require("../../rtm/graph-store");
51
51
  const freshness_coordinator_1 = require("../../refresh/freshness-coordinator");
52
+ const bounded_io_1 = require("../../project/bounded-io");
52
53
  const requirementKinds = new Set(['REQ', 'H-SPEC', 'A-SPEC', 'T-SPEC']);
53
54
  const cosine = (a, b) => {
54
55
  if (a.length === 0 || a.length !== b.length)
@@ -76,7 +77,7 @@ function lineageOf(id, byId) {
76
77
  }
77
78
  function headOf(root) {
78
79
  try {
79
- return (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
80
+ return (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
80
81
  }
81
82
  catch {
82
83
  return '';
@@ -212,7 +213,8 @@ function createRequirementTriageHandlers(context) {
212
213
  refresh: refresh ?? { status: freshnessCurrent ? 'not-needed' : 'unavailable' } };
213
214
  if (!a.persist || !freshnessCurrent || freshness === null)
214
215
  return answer;
215
- const artifact = (0, requirement_triage_evidence_1.writeRequirementTriageEvidence)(root, { schema: 'requirement-triage-evidence/2', promptDigest,
216
+ // @implements A-SPEC-729 — persisted AND issued on the ledger; intake accepts nothing else.
217
+ const artifact = (0, requirement_triage_evidence_1.issueRequirementTriageEvidence)(root, { schema: 'requirement-triage-evidence/2', promptDigest,
216
218
  workspaceId: freshness.workspaceId, head: freshness.head, freshnessGeneration: freshness.generation, result: answer });
217
219
  return { ...answer, evidenceDigest: artifact.digest, persistedTo: artifact.path, artifact };
218
220
  },
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createReviewEvidenceHandlers = createReviewEvidenceHandlers;
37
- // @implements A-SPEC-718, A-SPEC-617, A-SPEC-100.2, A-SPEC-102.1, A-SPEC-133, A-SPEC-135, A-SPEC-141, A-SPEC-157, A-SPEC-160, A-SPEC-189, A-SPEC-191, A-SPEC-244, A-SPEC-245, A-SPEC-263.1, A-SPEC-497.1
37
+ // @implements A-SPEC-718, A-SPEC-617, A-SPEC-100.2, A-SPEC-102.1, A-SPEC-133, A-SPEC-135, A-SPEC-141, A-SPEC-157, A-SPEC-160, A-SPEC-189, A-SPEC-191, A-SPEC-244, A-SPEC-245, A-SPEC-263.1, A-SPEC-497.1, A-SPEC-732
38
38
  const path = __importStar(require("node:path"));
39
39
  const findings_1 = require("../../review/findings");
40
40
  const review_targets_1 = require("../../review/review-targets");
@@ -105,7 +105,13 @@ function createReviewEvidenceHandlers(context) {
105
105
  const elicitExpiries = new Map();
106
106
  if (context.hasElicitor()) {
107
107
  try {
108
- const autonomyOn = (0, autonomy_1.autonomousApprovalEnabled)(process.env, a.root, new Date().toISOString());
108
+ // @implements A-SPEC-732 (round 2) — autonomy is read at the project root, never a raw root.
109
+ const autonomyOn = (0, autonomy_1.autonomousApprovalEnabled)(process.env, (() => { try {
110
+ return context.projectRootOf(a.root);
111
+ }
112
+ catch {
113
+ return undefined;
114
+ } })(), new Date().toISOString());
109
115
  const snapshot = new Map();
110
116
  for (const f of new findings_1.FindingsLedger(findingsFile).list())
111
117
  snapshot.set(f.id, f);
@@ -15,6 +15,16 @@ export interface SliceOrchestrationContext {
15
15
  sliceName: string;
16
16
  }): Promise<unknown>;
17
17
  };
18
+ /**
19
+ * @implements A-SPEC-732 (round 4) — the store and project root a slice acts on. A `root` naming
20
+ * another project is refused; a rootless call uses the BOUND store's project, never the cwd.
21
+ */
22
+ sliceStore(root: string | undefined): {
23
+ store: SpecStore;
24
+ root: string;
25
+ } | {
26
+ refusal: string;
27
+ };
18
28
  }
19
29
  /**
20
30
  * @implements A-SPEC-652.1 — the T-SPEC that belongs to an A-SPEC, by the mirror rule the
@@ -56,6 +66,7 @@ export declare function createSliceOrchestrationHandlers(context: SliceOrchestra
56
66
  root?: string;
57
67
  sliceName: string;
58
68
  }): Promise<{
69
+ approvalIntent?: {} | null | undefined;
59
70
  ok: boolean;
60
71
  approvedSpecs: string[];
61
72
  alreadySealed: string[];
@@ -35,7 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.tspecFor = tspecFor;
37
37
  exports.createSliceOrchestrationHandlers = createSliceOrchestrationHandlers;
38
- // @implements A-SPEC-724, A-SPEC-609, A-SPEC-100.2, A-SPEC-156, A-SPEC-203, A-SPEC-204, A-SPEC-298, A-SPEC-299, A-SPEC-536.1, A-SPEC-546.1, A-SPEC-565.2, A-SPEC-587.2, A-SPEC-501.1
38
+ // @implements A-SPEC-733, A-SPEC-732, A-SPEC-729, A-SPEC-724, A-SPEC-609, A-SPEC-100.2, A-SPEC-156, A-SPEC-203, A-SPEC-204, A-SPEC-298, A-SPEC-299, A-SPEC-536.1, A-SPEC-546.1, A-SPEC-565.2, A-SPEC-587.2, A-SPEC-501.1
39
39
  const fs = __importStar(require("node:fs"));
40
40
  const path = __importStar(require("node:path"));
41
41
  const spec_store_1 = require("../../spec/spec-store");
@@ -43,7 +43,10 @@ const root_1 = require("../../project/root");
43
43
  const yaml_scalar_1 = require("../../spec/yaml-scalar");
44
44
  const draft_1 = require("../../reverse/draft");
45
45
  const anchor_comment_1 = require("../../rtm/anchor-comment");
46
+ /** The only text `spec_remediate` writes into a file besides the comment syntax (A-SPEC-732 round 5). */
47
+ const REMEDIATE_ASPEC_ID = /^A-SPEC-\d{3,}(?:\.\d+)*$/;
46
48
  const requirement_triage_evidence_1 = require("../requirement-triage-evidence");
49
+ const linear_match_1 = require("../../guardrail/linear-match");
47
50
  /**
48
51
  * @implements A-SPEC-652.1 — the T-SPEC that belongs to an A-SPEC, by the mirror rule the
49
52
  * author-slice playbook states (the chain inherits the parent's number, dot included): the
@@ -71,6 +74,8 @@ function tspecFor(aspec, specs) {
71
74
  function createSliceOrchestrationHandlers(context) {
72
75
  return {
73
76
  async spec_slice_init(a) {
77
+ // A-SPEC-651.5 (sealed) scaffolds drafts into the REQUESTED root, which may differ from the bound
78
+ // store; drafts seal nothing, and sealing them goes through spec_slice_approve's bound store.
74
79
  const root = a.root ? (0, root_1.resolveProjectRoot)(a.root).root : process.cwd();
75
80
  const specsDir = path.join(root, '.ax', 'specs');
76
81
  const existing = await context.listSpecs();
@@ -240,14 +245,42 @@ depends_on:
240
245
  const intake = (0, requirement_triage_evidence_1.validateRequirementIntake)(root, a.triage_evidence);
241
246
  if (!intake.ok)
242
247
  return { ok: false, reason: intake.reason, specsCreated: [], unreadable: [] };
243
- fs.mkdirSync(path.join(specsDir, '01_req'), { recursive: true });
244
- fs.mkdirSync(path.join(specsDir, '02_h-spec', 'functional'), { recursive: true });
245
- fs.mkdirSync(path.join(specsDir, '03_a-spec'), { recursive: true });
246
- fs.mkdirSync(path.join(specsDir, '05_t-spec'), { recursive: true });
247
- fs.writeFileSync(path.join(specsDir, '01_req', `${reqId}.md`), reqContent);
248
- fs.writeFileSync(path.join(specsDir, '02_h-spec', 'functional', `${hspecId}.md`), hspecContent);
249
- fs.writeFileSync(path.join(specsDir, '03_a-spec', `${aspecId}.md`), aspecContent);
250
- fs.writeFileSync(path.join(specsDir, '05_t-spec', `${tspecId}.md`), tspecContent);
248
+ // @implements A-SPEC-729 — spend the evidence on this REQ atomically, then record it on the REQ.
249
+ const triageDigest = a.triage_evidence.digest;
250
+ const spent = (0, requirement_triage_evidence_1.consumeRequirementTriageEvidence)(root, triageDigest, reqId);
251
+ if (!spent.ok)
252
+ return { ok: false, reason: spent.reason, specsCreated: [], unreadable: [] };
253
+ const reqWithEvidence = reqContent.replace(/^depends_on: \[\]$/m, `depends_on: []\ntriage_evidence: ${triageDigest}`);
254
+ const written = [];
255
+ try {
256
+ const plan = [
257
+ [reqId, path.join(specsDir, '01_req'), reqWithEvidence],
258
+ [hspecId, path.join(specsDir, '02_h-spec', 'functional'), hspecContent],
259
+ [aspecId, path.join(specsDir, '03_a-spec'), aspecContent],
260
+ [tspecId, path.join(specsDir, '05_t-spec'), tspecContent],
261
+ ];
262
+ for (const [id, dir, content] of plan) {
263
+ fs.mkdirSync(dir, { recursive: true });
264
+ // @implements A-SPEC-729 (round 4) — exclusive create: a file a concurrent call created after
265
+ // the existence check above is never overwritten (measured: 16/16 races lost one slice).
266
+ try {
267
+ fs.writeFileSync(path.join(dir, `${id}.md`), content, { flag: 'wx' });
268
+ }
269
+ catch (e) {
270
+ if (e.code === 'EEXIST')
271
+ throw new Error(`${id}.md was created by another call meanwhile and was left untouched`);
272
+ throw e;
273
+ }
274
+ written.push(id);
275
+ }
276
+ }
277
+ catch (e) {
278
+ // @implements A-SPEC-729 — the evidence is already spent; the files written so far stay
279
+ // (A-SPEC-299) and are NAMED, so a half-slice is never left behind silently.
280
+ return { ok: false, reason: `spec_slice_init: writing the chain failed (${e instanceof Error ? e.message : String(e)})`
281
+ + `${written.length > 0 ? ` after writing ${written.join(', ')}, which remain on disk` : ''}. 이 triage evidence는 이미 소비되었습니다 — requirement_triage(persist:true)를 다시 실행해 새 증거를 받으십시오.`,
282
+ specsCreated: written, unreadable: [] };
283
+ }
251
284
  // @implements A-SPEC-299
252
285
  // Read back what was just written. S-298 fixed one cause of unparseable frontmatter; this
253
286
  // closes the class. `list()` silently skips documents it cannot parse, so "created" and
@@ -260,8 +293,14 @@ depends_on:
260
293
  return { ok: unreadable.length === 0, specsCreated, unreadable };
261
294
  },
262
295
  async spec_slice_approve(a) {
263
- const root = a.root ? (0, root_1.resolveProjectRoot)(a.root).root : process.cwd();
264
- const rawStore = new spec_store_1.LocalMarkdownRepository(path.join(root, '.ax', 'specs'));
296
+ // @implements A-SPEC-732 (round 5) — an empty name matched every spec in the store.
297
+ if (typeof a.sliceName !== 'string' || a.sliceName.trim() === '') {
298
+ return { ok: false, approvedSpecs: [], alreadySealed: [], refused: [{ id: String(a.sliceName ?? ''), reason: 'sliceName is empty — name a slice or a spec id' }] };
299
+ }
300
+ const bound = context.sliceStore(a.root);
301
+ if ('refusal' in bound)
302
+ return { ok: false, approvedSpecs: [], alreadySealed: [], refused: [{ id: a.sliceName, reason: bound.refusal }] };
303
+ const { root, store: rawStore } = bound;
265
304
  const specs = await rawStore.list();
266
305
  const inSlice = specs.filter((s) => {
267
306
  if (s.frontmatter?.slice === a.sliceName)
@@ -295,10 +334,17 @@ depends_on:
295
334
  const matches = specs.filter((s) => s.id.includes(a.sliceName));
296
335
  idsToApprove.push(...matches.map((s) => s.id));
297
336
  }
337
+ // @implements A-SPEC-732 (round 3) — a slice named by a REQ id listed it twice (the slice spec
338
+ // and its own REQ): a form client was asked twice and the spec sealed twice.
339
+ const unique = [...new Set(idsToApprove)];
340
+ idsToApprove.splice(0, idsToApprove.length, ...unique);
298
341
  const rawHandlers = context.rawHandlersForStore(rawStore);
299
342
  const approvedSpecs = [];
300
343
  const alreadySealed = [];
301
344
  const refused = [];
345
+ // @implements A-SPEC-732 (round 3) — the host-gated continuation the inner spec_approve offered;
346
+ // dropping it left the caller nothing to commit.
347
+ let approvalIntent;
302
348
  if (idsToApprove.length === 0) {
303
349
  // Reporting this as a success is how a caller ends up believing an unapproved slice was
304
350
  // approved. Measured 2026-08-28: a broken-frontmatter REQ made the whole slice invisible
@@ -318,13 +364,17 @@ depends_on:
318
364
  continue;
319
365
  }
320
366
  const res = (await rawHandlers.spec_approve({ root, id }));
321
- if (res.approved || res.ok) {
367
+ // @implements A-SPEC-732 (round 4) — only the result's OWN string `approved` means sealed: an
368
+ // inherited `approved` (a polluted prototype) reported a draft as sealed.
369
+ if (Object.prototype.hasOwnProperty.call(res, 'approved') && typeof res.approved === 'string') {
322
370
  approvedSpecs.push(id);
323
371
  continue;
324
372
  }
325
373
  const findings = Array.isArray(res.findings)
326
374
  ? res.findings.map((f) => f.message).filter(Boolean).join('; ')
327
375
  : '';
376
+ if (res.approvalIntent !== undefined)
377
+ approvalIntent = res.approvalIntent;
328
378
  refused.push({ id, reason: findings ? `${res.reason ?? 'refused'}: ${findings}` : (res.reason ?? 'refused') });
329
379
  // The chain is topological: approving a child whose parent was refused would either fail
330
380
  // again or, worse, succeed against an unsealed parent. Stop and say what is left.
@@ -338,14 +388,64 @@ depends_on:
338
388
  refused.push({ id: missingTspec, reason: `no T-SPEC mirrors ${aspecId} or depends on it — write ${missingTspec} first` });
339
389
  }
340
390
  // `ok` means the slice is approved — freshly or already. Anything less is not a success.
341
- return { ok: refused.length === 0 && approvedSpecs.length + alreadySealed.length > 0, approvedSpecs, alreadySealed, refused };
391
+ return { ok: refused.length === 0 && approvedSpecs.length + alreadySealed.length > 0, approvedSpecs, alreadySealed, refused,
392
+ ...(approvalIntent !== undefined ? { approvalIntent } : {}) };
342
393
  },
343
394
  async spec_remediate(a) {
344
- const root = a.root ? (0, root_1.resolveProjectRoot)(a.root).root : process.cwd();
395
+ const bound = context.sliceStore(a.root);
396
+ if ('refusal' in bound)
397
+ return { ok: false, actionsTaken: [], refused: [{ id: a.aspecId ?? 'slice', reason: bound.refusal }] };
398
+ const { root, store: rawStore } = bound;
345
399
  const actionsTaken = [];
400
+ // @implements A-SPEC-732 (round 5) — the id is written into the file: a newline in it injected
401
+ // code and YAML keys into any in-project file (measured). Only a spec id is ever written.
402
+ if (a.aspecId !== undefined && !REMEDIATE_ASPEC_ID.test(a.aspecId)) {
403
+ return { ok: false, actionsTaken, refused: [{ id: String(a.aspecId).slice(0, 80), reason: 'aspecId must be an A-SPEC id (A-SPEC-<digits>[.<digits>]); nothing was written' }] };
404
+ }
346
405
  if (a.targetFile && a.aspecId) {
347
406
  const fullPath = path.isAbsolute(a.targetFile) ? a.targetFile : path.join(root, a.targetFile);
348
- if (fs.existsSync(fullPath)) {
407
+ // @implements A-SPEC-732 (round 4) — an anchor is written only inside the bound project.
408
+ const real = (p) => { try {
409
+ return fs.realpathSync(p);
410
+ }
411
+ catch {
412
+ return path.resolve(p);
413
+ } };
414
+ const rel = path.relative(real(root), path.join(real(path.dirname(path.resolve(fullPath))), path.basename(fullPath)));
415
+ const inside = rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
416
+ // Confirmation round (measured): a FILE symlink passed the directory-level check and the write
417
+ // followed it out of the project — or, named `.ts`, prepended `//` to the ledger. A link is
418
+ // never written through.
419
+ const isLink = (() => { try {
420
+ return fs.lstatSync(fullPath).isSymbolicLink();
421
+ }
422
+ catch {
423
+ return false;
424
+ } })();
425
+ // Round 5 (measured): a hard link carried the anchor out of the project and into a ledger, and
426
+ // `.ax/` is governance state no anchor belongs in.
427
+ const hardLinked = (() => { try {
428
+ return fs.lstatSync(fullPath).nlink > 1;
429
+ }
430
+ catch {
431
+ return false;
432
+ } })();
433
+ // Round 6: folded — `.AX/…` reached `.ax/` on a case-insensitive disk (measured); Windows also
434
+ // drops trailing dots and spaces from a segment.
435
+ const governed = (0, linear_match_1.trimTrailing)(rel.split(/[\\/]/)[0].toLowerCase(), '. ') === '.ax';
436
+ if (!inside) {
437
+ actionsTaken.push(`앵커 주입 거부: ${a.targetFile} 은(는) 이 프로젝트(${root}) 밖입니다`);
438
+ }
439
+ else if (governed) {
440
+ actionsTaken.push(`앵커 주입 거부: ${a.targetFile} 은(는) .ax/ 거버넌스 상태입니다 — 앵커는 소스 파일에만 씁니다`);
441
+ }
442
+ else if (hardLinked) {
443
+ actionsTaken.push(`앵커 주입 거부: ${a.targetFile} 은(는) 하드 링크가 둘 이상입니다 — 다른 경로의 같은 파일에 쓰게 됩니다`);
444
+ }
445
+ else if (isLink) {
446
+ actionsTaken.push(`앵커 주입 거부: ${a.targetFile} 은(는) 심볼릭 링크입니다 — 실제 파일에 직접 1행 앵커를 추가하십시오`);
447
+ }
448
+ else if (fs.existsSync(fullPath)) {
349
449
  // @implements A-SPEC-501.1 — BUG-4 (dogfooded twice): the old unconditional
350
450
  // `// @implements` broke Python/YAML targets outright AND produced anchors the scanner
351
451
  // could not read. The syntax comes from the one map the scanner is aligned with, an
@@ -362,7 +462,6 @@ depends_on:
362
462
  }
363
463
  }
364
464
  }
365
- const rawStore = new spec_store_1.LocalMarkdownRepository(path.join(root, '.ax', 'specs'));
366
465
  const rawHandlers = context.rawHandlersForStore(rawStore);
367
466
  const approveRes = await rawHandlers.spec_slice_approve({ root, sliceName: a.aspecId ?? 'slice' });
368
467
  if (approveRes.approvedSpecs?.length > 0) {