@holmes-lab/holmes-kit 0.35.9 → 0.35.11

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 (41) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -0
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cpg/cpg-scanner.d.ts +10 -0
  5. package/dist/holmes/cpg/cpg-scanner.js +37 -3
  6. package/dist/holmes/cpg/scan-cache.d.ts +1 -1
  7. package/dist/holmes/cpg/scan-cache.js +6 -1
  8. package/dist/holmes/cpg/scanned-file.d.ts +42 -0
  9. package/dist/holmes/cpg/ts-call-resolution.d.ts +46 -0
  10. package/dist/holmes/cpg/ts-call-resolution.js +252 -0
  11. package/dist/holmes/governance/constitution.d.ts +5 -0
  12. package/dist/holmes/governance/constitution.js +1 -1
  13. package/dist/holmes/hooks/stop.d.ts +28 -0
  14. package/dist/holmes/hooks/stop.js +69 -6
  15. package/dist/holmes/mcp/handlers/graph-operations.js +9 -3
  16. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +29 -4
  17. package/dist/holmes/mcp/handlers/requirement-triage.js +51 -4
  18. package/dist/holmes/mcp/handlers.d.ts +14 -4
  19. package/dist/holmes/mcp/handlers.js +9 -2
  20. package/dist/holmes/mcp/maintenance-analyze.d.ts +8 -0
  21. package/dist/holmes/mcp/maintenance-analyze.js +69 -4
  22. package/dist/holmes/review/graph-resolution.d.ts +61 -0
  23. package/dist/holmes/review/graph-resolution.js +158 -0
  24. package/dist/holmes/review/requirement-triage.js +3 -2
  25. package/dist/holmes/review/run-replay.d.ts +49 -0
  26. package/dist/holmes/review/run-replay.js +132 -13
  27. package/dist/holmes/review/semantic-retrieval.d.ts +2 -0
  28. package/dist/holmes/review/semantic-retrieval.js +4 -1
  29. package/dist/holmes/rtm/anchor-binding.d.ts +34 -0
  30. package/dist/holmes/rtm/anchor-binding.js +43 -0
  31. package/dist/holmes/rtm/anchor-history.d.ts +39 -0
  32. package/dist/holmes/rtm/anchor-history.js +97 -0
  33. package/dist/holmes/rtm/anchor-ids.d.ts +21 -0
  34. package/dist/holmes/rtm/anchor-ids.js +51 -5
  35. package/dist/holmes/rtm/localize.d.ts +7 -0
  36. package/dist/holmes/rtm/localize.js +11 -2
  37. package/dist/holmes/rtm/rtm-builder.d.ts +12 -0
  38. package/dist/holmes/rtm/rtm-builder.js +64 -2
  39. package/dist/holmes/rtm/rtm-graph.d.ts +11 -0
  40. package/dist/holmes/rtm/rtm-graph.js +20 -0
  41. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,95 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  <!-- @implements A-SPEC-209 -->
8
+ ## [0.35.11] - 2026-10-07
9
+
10
+ ### Fixed
11
+
12
+ - **`requirement_triage` reads the whole text of a requirement lineage** (A-SPEC-757). Its BM25 tokenised each
13
+ lineage with the tokeniser written for a request, which drops repeated words and stops at 64. Every lineage was
14
+ therefore ranked on the first 64 distinct words of its text — out of a median of 831 in this repository — with
15
+ every word counted once, and which 64 were read depended on the order the store listed the documents in. Lineage
16
+ text is now tokenised in full with word frequency; the request keeps its 64-term bound. Measured by replay
17
+ through the product function (request = a commit subject without spec ids, truth = the lineage that commit
18
+ cites): the right lineage is in the top five in 0.664 of 342 cases instead of 0.281 on this repository (paired
19
+ difference +0.383, minimum detectable 0.075) and in 0.850 of 613 instead of 0.760 on a second, Python repository
20
+ (+0.090, minimum detectable 0.038). One call takes about 0.3 s instead of 0.25 s on a store of 2,900 documents.
21
+ Verdict rules are unchanged: a confident verdict still needs two channels to agree, so this changes which
22
+ candidates you are shown, not how often the answer is `ambiguous`.
23
+
24
+ - **A TypeScript call is linked to the function the compiler says it reaches** (A-SPEC-758, 758.1). The graph
25
+ linked a call by name: the same file first, else the only symbol in the scan with that name or last name
26
+ segment, without knowing the receiver. Measured against the TypeScript compiler on this repository's 380 source
27
+ files, 952 of 4,543 `calls` edges (21%; a third of the cross-file ones) linked a standard-library call to an
28
+ unrelated symbol — every `xs.map(...)` on an array pointed at the one class that defines a method `map`. The
29
+ scanner now runs one compiler pass over the TypeScript files of a scan and the graph uses its answer: a call
30
+ bound to a scanned function, method or constructor becomes a `calls` edge to it (edge derivation
31
+ `compiler-symbol`), a call bound to the standard library gets no edge, and a call the compiler cannot decide
32
+ keeps what the name rule gave. Here: 437 callers of that `map` → 14, ambiguous candidate edges 2,898 → 325.
33
+ The compiler is given only the text of the files the scan already read plus TypeScript's bundled library — no
34
+ `tsconfig.json`, no `node_modules`, no other path — so a call on a type that comes from a dependency stays
35
+ decided by name. A scan takes about 1.3 s longer on this repository (6.5 s → 7.8 s); above 5,000 TypeScript
36
+ files the pass is not run and the scan says so. Other languages are unchanged. The extractor is `holmes-rtm/4`,
37
+ so an existing graph is rebuilt once. **Measured and not claimed:** through the product path on 120 replayed
38
+ changes, what `maintenance_analyze` returns for a request moved by +0.0021 recall and +0.0006 precision
39
+ against minimum detectable 0.0131 and 0.0028 — no measurable effect. **A measured cost:** the ungraded impact
40
+ closure (`impacts.impactedFiles`, the list the pre-edit gate reads) gained real callers and, on one of the two
41
+ windows measured, its precision against files that actually changed together fell by 0.012 (minimum
42
+ detectable 0.009); on the other it rose by 0.001. This is a correction of what the graph states.
43
+
44
+ - **The second `rtm_dashboard` call no longer fails with `read ECONNRESET`** (A-SPEC-545.6). The handler read its
45
+ census from the dashboard server it had started over a kept-alive connection and did seconds of synchronous work
46
+ between reads; on a slow or busy machine the server had closed the idle socket by then and the next read was
47
+ written to it. Each read now uses its own connection.
48
+
49
+ ### Changed
50
+
51
+ - **A `requirement_triage` call that asks for intake evidence waits for the refresh it requested** (A-SPEC-723.1).
52
+ After a commit the evidence is stale; the call started a background refresh and returned `ambiguous` at once,
53
+ so the same call had to be repeated until the refresh had finished — measured here, every one of four intakes
54
+ took two or three calls, and a consumer workspace reported "triage is always ambiguous". A call with
55
+ `persist: true` now re-reads the freshness receipt every 250 ms for up to 20 seconds and answers from the
56
+ refreshed evidence in the same call; `refresh.waitedMs` and `refresh.outcome` (`current`, `timeout`, `ended`)
57
+ say what happened. On a timeout or a failed refresh the answer is what it was before. The refresh still runs in
58
+ the detached process and the receipt is still the only authority for currency. `HOLMES_TRIAGE_WAIT_MS` sets the
59
+ bound in milliseconds (0 turns the wait off; the ceiling is 60000) — lower it if your harness's tool timeout
60
+ is short. Calls without `persist` do not wait.
61
+ - **`maintenance_analyze` lists the relevant tests in relevance order** (A-SPEC-745.1). `relevantTests` was emitted
62
+ in path order and the response keeps ten, so the ten you saw were the alphabetically first test files whatever
63
+ you asked. The same set is now ordered: tests named after a changed file (or, with a request alone, after a
64
+ ranked candidate) first — `widget.ts` → `widget.test.ts`, `widget-render.test.ts`, `test_widget.py`,
65
+ `widget_test.go`, `WidgetTests.java` — then tests anchoring a spec that file anchors, then the rest. Which tests
66
+ a scope selects is unchanged (`impacts.test` and `testScope` still carry the path-ordered set). Measured on
67
+ replayed changes with the changed files given: a test the change also touched is among the first ten with
68
+ recall 0.48 instead of 0.21 on this repository (minimum detectable 0.10). A separate "what verifies this file"
69
+ graph query was measured against that name convention first and lost to it, so none was added.
70
+ - **An anchor written inside or directly above a function links the spec to that function** (A-SPEC-756, 756.2,
71
+ 756.3). Until now every `@implements` id found anywhere in a file was linked to every function of that file: in
72
+ all 330 multi-function files of this repository each function carried the same set of specs. An anchor inside a
73
+ function, or in the comment block directly above it, now links to that function only; an anchor that belongs to
74
+ no function (the file header) still links to every function of the file, so nothing that walks from a function
75
+ to its specs loses a link. Share of multi-function files whose functions all carry one identical spec set: 1.00
76
+ → 0.469 here; 0.992 on a repository that writes its anchors in the header, where this changes almost nothing.
77
+ The graph schema is `rtm-graph/4` and the extractor `holmes-rtm/3`: an existing graph is rebuilt once on the
78
+ next `rtm_reindex` or session refresh. **Measured and not claimed:** on a fixed replay of 120 changes per
79
+ repository the function-level recall of `maintenance_analyze` moved by +0.0056 against a minimum detectable
80
+ 0.0157 — no measurable effect on what the analysis finds. This is a correction of what the graph states, not
81
+ an improvement in analysis results.
82
+
83
+ ## [0.35.10] - 2026-10-06
84
+
85
+ ### Changed
86
+
87
+ - **A Stop block says who acts next** (A-SPEC-247.1). Measured in a live session: the Stop gate repeated the same
88
+ violations on more than eight stops while every exit needed the operator, and the text named neither the pending
89
+ request nor who had to act. The block now lists each violation under one of two headings. *Waiting on the
90
+ operator* — an ART-4 whose document, or an open critical finding whose id, already has a pending request in the
91
+ approval queue; the line carries the request id and says the operator decides it, in the session's approval
92
+ dialog or with `holmes-kit approve`. *The session acts* — everything else, with the act that clears it (for ART-4:
93
+ anchor real covering tests, or retire a withdrawn design with `spec_retire`; for an open critical: fix, re-review,
94
+ then record `resolved`). Only the text changed: which violations block, the block cap and constitution debt are
95
+ as before, and a violation that waits on the operator still blocks. The first line of the block is unchanged.
96
+
8
97
  ## [0.35.9] - 2026-10-06
9
98
 
10
99
  ### Security
package/README.md CHANGED
@@ -23,6 +23,7 @@ Measured at `173b99650442` (specs `sha256:215f84d4e9f4`) — reproduce with `hol
23
23
 
24
24
  ### 🛡️ Currently Supported Features (Production Features)
25
25
 
26
+ - **The graph states what the code does, and intake answers in one call** *(new in 0.35.11)*: three corrections to what the traceability graph and `requirement_triage` say, each measured before it was built. `requirement_triage` ranked every requirement lineage on the first 64 distinct words of its text; it now reads the whole text (right lineage in the top five: 0.28 → 0.66 on this repository, 0.76 → 0.85 on a second one, both beyond the minimum detectable difference). A call with `persist: true` waits up to 20 seconds for the refresh it requested instead of returning `ambiguous` and asking to be repeated (`HOLMES_TRIAGE_WAIT_MS` sets the bound, 0 turns it off). `maintenance_analyze` lists `relevantTests` in relevance order — tests named after the changed file first — so the ten a bounded response shows are no longer the alphabetically first ten (a test the change also touched is among them with recall 0.48 instead of 0.21 here). TypeScript `calls` edges are bound by the compiler's symbol resolution — 21% of the name-bound edges linked a standard-library call such as `xs.map()` to an unrelated symbol — using only the files the scan already read plus TypeScript's bundled library; and an `@implements` anchor written in or directly above a function links the spec to that function instead of to every function of the file. **What is not claimed:** on replayed changes neither graph correction moved what `maintenance_analyze` returns beyond the minimum detectable difference; they change what the graph states, and the CHANGELOG records one measured cost.
26
27
  - **The protected store is recognised however a shell command spells it** *(new in 0.35.2 — security fix, upgrade recommended)*: through 0.35.1 a path into `.ax/specs`, `.ax/ledger`, `.ax/approvals` or `.ax/state` written directly after a shell expansion, a variable, or a character the shell removes at run time was not seen as protected, so a removal, move or overwrite of governance state could pass the gate. The store spelling now counts wherever it appears in a command, and an output redirect to a computed target is not a read. Reads still pass. A directory that merely ends in `.ax` and has a child named like the store's is judged as the store. Limit: a path assembled so the spelling never appears in the command text is outside this rule.
27
28
  - **The session-start banner in Codex** *(new in 0.35.8)*: with a runtime registry, `runtime-binding setup --activate-hooks codex` (or the `runtime_binding` tool) adds a SessionStart entry to the workspace's `.codex/hooks.json`, so a Codex session starts by being told which Holmes build governs it and whether autonomous approval is on — as Claude Code sessions are. It runs after you trust it in Codex's `/hooks`. Antigravity passes no hook output to the model, so nothing is wired there.
28
29
  - **The Stop hook leaves other repositories alone** *(new in 0.35.7 — upgrade recommended for Codex users)*: Codex wires the Holmes Stop hook at user level, so it is called in every repository on the machine. Through 0.35.6 it blocked the end of a turn in a repository that is not a Holmes project (`[ART-1] … no @implements anchor`). It now answers nothing where no project can be found; inside a project nothing changes.
package/dist/.build-id CHANGED
@@ -1 +1 @@
1
- f3d900b3-muvjdy3u
1
+ e768a6ae-muxcf7lv
@@ -82,6 +82,8 @@ export declare class CpgScanner {
82
82
  private readonly opts;
83
83
  constructor(parser?: LanguageParser, cache?: import("./scan-cache").ScanFileCache | undefined, opts?: {
84
84
  dataflow?: boolean;
85
+ compilerCalls?: boolean;
86
+ compilerMaxFiles?: number;
85
87
  });
86
88
  private skipped;
87
89
  /** `{file, reason}` for every file the LAST scan claimed but could not ingest. Empty on a clean tree. */
@@ -110,4 +112,12 @@ export declare class CpgScanner {
110
112
  */
111
113
  scanTests(rootDir: string, repoRoot?: string): ScannedFile[];
112
114
  private walkScan;
115
+ /**
116
+ * @implements A-SPEC-758
117
+ * One compiler program over the TypeScript files of this scan. Runs after the cache is saved: the
118
+ * record depends on every other file, so it is attached to the returned objects only. A pass that
119
+ * cannot run leaves the field absent on every file and says why in the skip channel — the edge
120
+ * builder then decides those files by name, as before.
121
+ */
122
+ private attachCompilerCalls;
113
123
  }
@@ -41,12 +41,13 @@ exports.forgetUnverifiedUnder = forgetUnverifiedUnder;
41
41
  exports.underUnverifiedNesting = underUnverifiedNesting;
42
42
  exports.isRegularSource = isRegularSource;
43
43
  exports.langForPath = langForPath;
44
- // @implements A-SPEC-208, A-SPEC-734
44
+ // @implements A-SPEC-208, A-SPEC-734, A-SPEC-758
45
45
  const fs = __importStar(require("node:fs"));
46
46
  const path = __importStar(require("node:path"));
47
47
  const node_child_process_1 = require("node:child_process");
48
48
  const language_parser_1 = require("./language-parser");
49
49
  const source_path_1 = require("./source-path");
50
+ const ts_call_resolution_1 = require("./ts-call-resolution");
50
51
  const bounded_io_1 = require("../project/bounded-io");
51
52
  /**
52
53
  * Directories that never contain hand-written source for the project under analysis.
@@ -538,6 +539,7 @@ const test_files_2 = require("./test-files");
538
539
  // @implements A-SPEC-574.3 — a plain import now: the cycle that forced a lazy require is gone.
539
540
  const scan_cache_1 = require("./scan-cache");
540
541
  const anchor_ids_1 = require("../rtm/anchor-ids");
542
+ const anchor_binding_1 = require("../rtm/anchor-binding");
541
543
  // .ts/.mts/.cts can contain TS type-assertion syntax (`<T>x`, arrow-generics)
542
544
  // that the 'tsx' grammar misreads as JSX, so they must stay on 'typescript'.
543
545
  // Everything else in SCANNABLE_EXTENSIONS (.tsx/.jsx/.js/.mjs/.cjs) never uses
@@ -555,6 +557,8 @@ class CpgScanner {
555
557
  // tree-sitter parse entirely and reuse their cached symbols — file-key incremental scanning.
556
558
  constructor(parser = new language_parser_1.TreeSitterTsParser(), cache,
557
559
  // @implements A-SPEC-140.1 — see ScannedFile.dataflow for why this is opt-in.
560
+ // @implements A-SPEC-758 — `compilerCalls` (default on): bind TypeScript calls with the compiler after
561
+ // the walk. `compilerMaxFiles` overrides the file bound above which the pass is not run.
558
562
  opts = {}) {
559
563
  this.parser = parser;
560
564
  this.cache = cache;
@@ -597,6 +601,9 @@ class CpgScanner {
597
601
  walkScan(rootDir, repoRoot, include) {
598
602
  this.skipped = [];
599
603
  const out = [];
604
+ // @implements A-SPEC-758 — the text of each TypeScript file this walk read, for the compiler pass
605
+ // below: the pass is handed what the scan accepted and reads nothing from disk itself.
606
+ const tsTexts = new Map();
600
607
  const walk = (d) => {
601
608
  let entries;
602
609
  try {
@@ -627,6 +634,8 @@ class CpgScanner {
627
634
  // disk is not mistaken for one big test tree.
628
635
  try {
629
636
  const code = fs.readFileSync(p, 'utf8');
637
+ if (this.opts.compilerCalls !== false && /\.tsx?$/i.test(e.name))
638
+ tsTexts.set(p, code);
630
639
  // @implements A-SPEC-121.5
631
640
  // @implements A-SPEC-121.6
632
641
  // .h is routed to the C++ grammar (not a separate C parser): the
@@ -639,6 +648,9 @@ class CpgScanner {
639
648
  // invisible to the warning. Both consumers now ride the shared list parser.
640
649
  const implementsSpecs = (0, anchor_ids_1.anchorSpecIds)(code);
641
650
  const unanchoredImplements = (0, anchor_ids_1.wrongKindAnchorIds)(code);
651
+ // @implements A-SPEC-756 — WHERE each anchor sits, bound to the function it is written in
652
+ // or directly above. No extra parse: the symbol ranges are the ones this scan extracts.
653
+ const anchorSites = (symbols) => (0, anchor_binding_1.bindAnchorSites)(code.split('\n'), symbols, (0, anchor_ids_1.anchorSpecSites)(code));
642
654
  const sourcePath = (0, source_path_1.toSourcePath)(repoRoot, path.resolve(p));
643
655
  // @implements A-SPEC-140.1
644
656
  // The third parse happens only when asked for. `undefined` from the parser (a language
@@ -658,12 +670,14 @@ class CpgScanner {
658
670
  out.push({ path: p, ...hit });
659
671
  continue;
660
672
  }
661
- const fresh = { sourcePath, symbols: this.parser.extractSymbols(code, lang), edges: this.parser.extractEdges(code, lang), dataflow: dataflow(), implementsSpecs, unanchoredImplements };
673
+ const freshSymbols = this.parser.extractSymbols(code, lang);
674
+ const fresh = { sourcePath, symbols: freshSymbols, edges: this.parser.extractEdges(code, lang), dataflow: dataflow(), implementsSpecs, unanchoredImplements, anchorSites: anchorSites(freshSymbols) };
662
675
  this.cache.put(sourcePath, h, fresh);
663
676
  out.push({ path: p, ...fresh });
664
677
  continue;
665
678
  }
666
- out.push({ path: p, sourcePath, symbols: this.parser.extractSymbols(code, lang), edges: this.parser.extractEdges(code, lang), dataflow: dataflow(), implementsSpecs, unanchoredImplements });
679
+ const symbols = this.parser.extractSymbols(code, lang);
680
+ out.push({ path: p, sourcePath, symbols, edges: this.parser.extractEdges(code, lang), dataflow: dataflow(), implementsSpecs, unanchoredImplements, anchorSites: anchorSites(symbols) });
667
681
  }
668
682
  catch (err) {
669
683
  // A single unreadable/unparseable file must not abort a whole-tree scan — but it must
@@ -685,7 +699,27 @@ class CpgScanner {
685
699
  walk(rootDir);
686
700
  const scopeRel = (0, source_path_1.toSourcePath)(repoRoot, rootDir);
687
701
  this.cache?.save(scopeRel === '.' ? undefined : scopeRel); // batched persist + scoped mark-and-sweep prune
702
+ this.attachCompilerCalls(out, tsTexts);
688
703
  return out;
689
704
  }
705
+ /**
706
+ * @implements A-SPEC-758
707
+ * One compiler program over the TypeScript files of this scan. Runs after the cache is saved: the
708
+ * record depends on every other file, so it is attached to the returned objects only. A pass that
709
+ * cannot run leaves the field absent on every file and says why in the skip channel — the edge
710
+ * builder then decides those files by name, as before.
711
+ */
712
+ attachCompilerCalls(out, tsTexts) {
713
+ const covered = out.filter((f) => tsTexts.has(f.path));
714
+ if (covered.length === 0)
715
+ return;
716
+ const resolved = (0, ts_call_resolution_1.resolveTsCalls)(covered.map((f) => ({ path: f.path, sourcePath: f.sourcePath, text: tsTexts.get(f.path), symbols: f.symbols })), { maxFiles: this.opts.compilerMaxFiles });
717
+ if (!resolved.ok) {
718
+ this.skipped.push({ file: '<typescript-compiler>', reason: `call resolution not applied: ${resolved.skipped}` });
719
+ return;
720
+ }
721
+ for (const f of covered)
722
+ f.resolvedCalls = resolved.calls.get(f.sourcePath) ?? [];
723
+ }
690
724
  }
691
725
  exports.CpgScanner = CpgScanner;
@@ -1,5 +1,5 @@
1
1
  import type { ScannedFile } from './scanned-file';
2
- export declare const SCAN_CACHE_VERSION = 3;
2
+ export declare const SCAN_CACHE_VERSION = 4;
3
3
  export declare class ScanFileCache {
4
4
  private readonly dir;
5
5
  private readonly file;
@@ -58,7 +58,10 @@ function cloneDataFlow(df) {
58
58
  // without a version stamp, cached entries kept serving OLD-parser symbols indefinitely after an
59
59
  // upgrade — content hashes match, so nothing else invalidates them). A mismatch drops the whole
60
60
  // cache (one cold scan), which is exactly the correct cost of a parser upgrade.
61
- exports.SCAN_CACHE_VERSION = 3;
61
+ // @implements A-SPEC-756 — 4: a scanned file records where each anchor sits (`anchorSites`). A
62
+ // version-3 entry has none, and serving it would put every anchor back on the file for as long as
63
+ // the file's content did not change.
64
+ exports.SCAN_CACHE_VERSION = 4;
62
65
  class ScanFileCache {
63
66
  dir;
64
67
  file;
@@ -98,6 +101,8 @@ class ScanFileCache {
98
101
  unanchoredImplements: [...(e.file.unanchoredImplements ?? [])],
99
102
  edges: e.file.edges ? e.file.edges.map((edge) => ({ ...edge })) : undefined,
100
103
  dataflow: cloneDataFlow(e.file.dataflow),
104
+ // @implements A-SPEC-756 — copied like every other array, so a caller cannot edit the cache.
105
+ ...(e.file.anchorSites ? { anchorSites: e.file.anchorSites.map((site) => ({ ...site })) } : {}),
101
106
  };
102
107
  }
103
108
  this.misses++;
@@ -26,6 +26,48 @@ export interface ScannedFile {
26
26
  */
27
27
  dataflow?: DataFlowFacts;
28
28
  implementsSpecs: string[];
29
+ /**
30
+ * @implements A-SPEC-756
31
+ * Every A-SPEC anchor mention with its line and the function it binds to BY PLACE — written inside
32
+ * the function, or in the comment block directly above it — or `null` when it binds to none (a
33
+ * header anchor, which is a statement about the file). `implementsSpecs` stays the file-wide union
34
+ * the gates read; this is the finer record the graph builds function-level links from.
35
+ *
36
+ * Optional so a cache entry written by an older scanner still loads: such an entry reads as "every
37
+ * anchor is file-level", which is what the graph said before this field existed.
38
+ */
39
+ anchorSites?: Array<{
40
+ spec: string;
41
+ line: number;
42
+ symbol: string | null;
43
+ /**
44
+ * @implements A-SPEC-756.1 — HOW the site was bound: by the place it is written (absent means
45
+ * this), or by the commit that introduced it, which the scanner never sets — `bindAnchorsByHistory`
46
+ * adds it, once per function that commit last touched.
47
+ */
48
+ by?: 'site' | 'commit';
49
+ }>;
50
+ /**
51
+ * @implements A-SPEC-758
52
+ * What the TypeScript compiler bound for the calls in this file, per (calling function, callee name):
53
+ * the scanned symbols it reaches, or `library` when every such call binds to TypeScript's bundled
54
+ * library. A pair the compiler could not decide is not listed, and the edge builder falls back to
55
+ * the name rule for it.
56
+ *
57
+ * ABSENT means the pass did not cover this file (another language, the option off, more files than
58
+ * the bound, a compiler failure, a single-file scan); an EMPTY list means it was covered and nothing
59
+ * was recorded. Computed over the whole scan after the walk, so it is never written to the per-file
60
+ * scan cache — it depends on every other file.
61
+ */
62
+ resolvedCalls?: Array<{
63
+ from: string;
64
+ name: string;
65
+ targets: Array<{
66
+ qualifiedName: string;
67
+ sourcePath: string;
68
+ }>;
69
+ library: boolean;
70
+ }>;
29
71
  /**
30
72
  * `@implements` tags shaped like a well-formed governed spec id (REQ/H-SPEC/
31
73
  * C-SPEC/T-SPEC-NNN) instead of an A-SPEC anchor — a wrong-kind anchor that
@@ -0,0 +1,46 @@
1
+ import * as ts from 'typescript';
2
+ import type { CodeSymbol } from './language-parser';
3
+ export interface TsCallFile {
4
+ /** Absolute path; only used as the compiler's file name. */
5
+ path: string;
6
+ /** Repo-root-relative POSIX path, the key the graph uses. */
7
+ sourcePath: string;
8
+ text: string;
9
+ symbols: readonly CodeSymbol[];
10
+ }
11
+ /** What the compiler bound for one callee name inside one calling function. */
12
+ export interface ResolvedCall {
13
+ /** Qualified name of the calling symbol, defined in the file that carries this record. */
14
+ from: string;
15
+ /** The callee as written: an identifier, or the property name of a property access. */
16
+ name: string;
17
+ /** Scanned symbols bound at any such call, the caller itself excluded. */
18
+ targets: Array<{
19
+ qualifiedName: string;
20
+ sourcePath: string;
21
+ }>;
22
+ /** No target, and every such call binds to TypeScript's bundled library. */
23
+ library: boolean;
24
+ }
25
+ export type TsCallResolution = {
26
+ ok: true;
27
+ calls: Map<string, ResolvedCall[]>;
28
+ } | {
29
+ ok: false;
30
+ skipped: string;
31
+ };
32
+ /** Above this many TypeScript files in one scan the pass is not run (and says so). */
33
+ export declare const MAX_COMPILER_FILES = 5000;
34
+ /**
35
+ * A compiler host that serves exactly `files` and the files directly inside TypeScript's own library
36
+ * directory. Every other path does not exist, no directory is listed, and no real path is resolved.
37
+ */
38
+ export declare function restrictedCompilerHost(files: readonly TsCallFile[], options: ts.CompilerOptions): ts.CompilerHost;
39
+ /**
40
+ * Bind every call and `new` expression of the given files with the compiler. Never throws: a failure,
41
+ * or more files than the bound, comes back as `skipped` and the caller keeps the name rule.
42
+ */
43
+ export declare function resolveTsCalls(files: readonly TsCallFile[], opts?: {
44
+ maxFiles?: number;
45
+ createProgram?: typeof ts.createProgram;
46
+ }): TsCallResolution;
@@ -0,0 +1,252 @@
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.MAX_COMPILER_FILES = void 0;
37
+ exports.restrictedCompilerHost = restrictedCompilerHost;
38
+ exports.resolveTsCalls = resolveTsCalls;
39
+ // @implements A-SPEC-758
40
+ // Which function does a TypeScript call reach? The edge builder used to answer by NAME: same file,
41
+ // else the one symbol in the scan carrying that name or last name segment. It never knew the receiver,
42
+ // so `xs.map(...)` on an array was linked to the only scanned class with a `map` method. Measured on this
43
+ // repository (2026-10-07): 952 of 4,543 `calls` edges were library calls linked to an unrelated symbol.
44
+ // The compiler knows the receiver. This module asks it, and gives it nothing but what the scan already
45
+ // read: no project configuration, no dependency directory, no other path on disk.
46
+ const crypto = __importStar(require("node:crypto"));
47
+ const path = __importStar(require("node:path"));
48
+ const ts = __importStar(require("typescript"));
49
+ /** Above this many TypeScript files in one scan the pass is not run (and says so). */
50
+ exports.MAX_COMPILER_FILES = 5000;
51
+ const OPTIONS = {
52
+ noEmit: true, skipLibCheck: true, allowJs: false, types: [],
53
+ target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.CommonJS,
54
+ moduleResolution: ts.ModuleResolutionKind.Node10, esModuleInterop: true,
55
+ };
56
+ // Parsed library files, kept for the life of the process. Measured: a one-file pass costs about
57
+ // 100 ms when the library is parsed each time and about 12 ms when it is shared, and many callers
58
+ // scan small trees. Keyed by file name and language version, which is all a library parse depends on.
59
+ const libraryFiles = new Map();
60
+ /**
61
+ * A compiler host that serves exactly `files` and the files directly inside TypeScript's own library
62
+ * directory. Every other path does not exist, no directory is listed, and no real path is resolved.
63
+ */
64
+ function restrictedCompilerHost(files, options) {
65
+ const base = ts.createCompilerHost(options, true);
66
+ const canonical = (f) => base.getCanonicalFileName(path.resolve(f));
67
+ const texts = new Map();
68
+ const directories = new Set();
69
+ for (const f of files) {
70
+ texts.set(canonical(f.path), f.text);
71
+ for (let dir = path.dirname(path.resolve(f.path));; dir = path.dirname(dir)) {
72
+ const key = base.getCanonicalFileName(dir);
73
+ if (directories.has(key))
74
+ break;
75
+ directories.add(key);
76
+ if (path.dirname(dir) === dir)
77
+ break;
78
+ }
79
+ }
80
+ const libraryDir = canonical(path.dirname(ts.getDefaultLibFilePath(options)));
81
+ const inLibrary = (f) => canonical(path.dirname(path.resolve(f))) === libraryDir;
82
+ const baseExists = base.fileExists.bind(base);
83
+ const baseRead = base.readFile.bind(base);
84
+ return {
85
+ ...base,
86
+ fileExists: (f) => texts.has(canonical(f)) || (inLibrary(f) && baseExists(f)),
87
+ readFile: (f) => texts.get(canonical(f)) ?? (inLibrary(f) ? baseRead(f) : undefined),
88
+ directoryExists: (d) => directories.has(canonical(d)) || canonical(d) === libraryDir,
89
+ getDirectories: () => [],
90
+ realpath: (f) => f,
91
+ getSourceFile: (fileName, languageVersionOrOptions) => {
92
+ const given = texts.get(canonical(fileName));
93
+ if (given !== undefined)
94
+ return ts.createSourceFile(fileName, given, languageVersionOrOptions, true);
95
+ if (!inLibrary(fileName))
96
+ return undefined;
97
+ const version = typeof languageVersionOrOptions === 'object' ? languageVersionOrOptions.languageVersion : languageVersionOrOptions;
98
+ const key = `${canonical(fileName)}\u0000${version}`;
99
+ if (!libraryFiles.has(key)) {
100
+ const text = baseRead(fileName);
101
+ libraryFiles.set(key, text === undefined ? undefined : ts.createSourceFile(fileName, text, languageVersionOrOptions, true));
102
+ }
103
+ return libraryFiles.get(key);
104
+ },
105
+ };
106
+ }
107
+ /**
108
+ * Bind every call and `new` expression of the given files with the compiler. Never throws: a failure,
109
+ * or more files than the bound, comes back as `skipped` and the caller keeps the name rule.
110
+ */
111
+ function resolveTsCalls(files, opts = {}) {
112
+ const maxFiles = opts.maxFiles ?? exports.MAX_COMPILER_FILES;
113
+ if (files.length > maxFiles)
114
+ return { ok: false, skipped: `more than ${maxFiles} TypeScript files in one scan (${files.length})` };
115
+ // The last answer, kept for the life of the process. An analysis tool scans on every call and the
116
+ // tree rarely changes between two calls: measured, a warm scan of this repository costs about 0.1 s
117
+ // and the compiler pass on top of it about 1.0 s. The key covers everything the answer depends on.
118
+ const key = inputDigest(files);
119
+ if (lastAnswer !== null && lastAnswer.key === key)
120
+ return { ok: true, calls: copyOf(lastAnswer.calls) };
121
+ const answer = compile(files, opts.createProgram ?? ts.createProgram);
122
+ if (answer.ok)
123
+ lastAnswer = { key, calls: copyOf(answer.calls) };
124
+ return answer;
125
+ }
126
+ let lastAnswer = null;
127
+ function inputDigest(files) {
128
+ const hash = crypto.createHash('sha256');
129
+ for (const f of files) {
130
+ hash.update(`${f.path}\u0000${f.sourcePath}\u0000${f.text.length}\u0000`);
131
+ hash.update(f.text);
132
+ for (const s of f.symbols)
133
+ hash.update(`\u0000${s.qualifiedName}\u0000${s.name}\u0000${s.startLine}\u0000${s.endLine}`);
134
+ hash.update('\u0001');
135
+ }
136
+ return hash.digest('hex');
137
+ }
138
+ /** A copy a caller may keep and edit: the scanner attaches these lists to the files it returns. */
139
+ function copyOf(calls) {
140
+ const out = new Map();
141
+ for (const [sourcePath, records] of calls) {
142
+ out.set(sourcePath, records.map((r) => ({ from: r.from, name: r.name, targets: r.targets.map((t) => ({ ...t })), library: r.library })));
143
+ }
144
+ return out;
145
+ }
146
+ function compile(files, createProgram) {
147
+ try {
148
+ const host = restrictedCompilerHost(files, OPTIONS);
149
+ const canonical = (f) => host.getCanonicalFileName(path.resolve(f));
150
+ const byPath = new Map(files.map((f) => [canonical(f.path), f]));
151
+ const libraryDir = canonical(path.dirname(ts.getDefaultLibFilePath(OPTIONS)));
152
+ const program = createProgram(files.map((f) => f.path), OPTIONS, host);
153
+ const checker = program.getTypeChecker();
154
+ const lineOf = (sf, pos) => sf.getLineAndCharacterOfPosition(pos).line + 1;
155
+ const innermost = (file, line) => {
156
+ let best = null;
157
+ for (const s of file.symbols) {
158
+ if (s.startLine > line || line > s.endLine)
159
+ continue;
160
+ if (best === null || s.endLine - s.startLine < best.endLine - best.startLine)
161
+ best = s;
162
+ }
163
+ return best;
164
+ };
165
+ /** The scanned symbol named `name` that starts on the declaration's own lines, nearest first. */
166
+ const symbolAt = (file, name, startLine, endLine) => {
167
+ let best = null;
168
+ for (const s of file.symbols) {
169
+ if (s.name !== name || s.startLine < startLine || s.startLine > endLine)
170
+ continue;
171
+ if (best === null || s.startLine - startLine < best.startLine - startLine)
172
+ best = s;
173
+ }
174
+ return best;
175
+ };
176
+ const bindDeclaration = (decl, isNew) => {
177
+ const sf = decl.getSourceFile();
178
+ if (canonical(path.dirname(sf.fileName)) === libraryDir)
179
+ return { kind: 'library' };
180
+ const file = byPath.get(canonical(sf.fileName));
181
+ if (file === undefined)
182
+ return { kind: 'unknown' };
183
+ const startLine = lineOf(sf, decl.getStart(sf));
184
+ const endLine = lineOf(sf, decl.getEnd());
185
+ if (isNew && ts.isClassLike(decl)) {
186
+ const ctor = decl.members.find((m) => ts.isConstructorDeclaration(m));
187
+ const hit = ctor ? symbolAt(file, 'constructor', lineOf(sf, ctor.getStart(sf)), lineOf(sf, ctor.getEnd())) : null;
188
+ if (hit)
189
+ return { kind: 'target', qualifiedName: hit.qualifiedName, sourcePath: file.sourcePath };
190
+ }
191
+ const named = decl.name;
192
+ const name = ts.isConstructorDeclaration(decl) ? 'constructor' : named && (ts.isIdentifier(named) || ts.isPrivateIdentifier(named)) ? named.text : null;
193
+ const hit = name === null ? null : symbolAt(file, name, startLine, endLine);
194
+ return hit ? { kind: 'target', qualifiedName: hit.qualifiedName, sourcePath: file.sourcePath } : { kind: 'unknown' };
195
+ };
196
+ const calls = new Map();
197
+ for (const file of files) {
198
+ const sf = program.getSourceFile(file.path);
199
+ const order = [];
200
+ const seen = new Map();
201
+ const visit = (node) => {
202
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
203
+ const callee = ts.isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression;
204
+ const caller = innermost(file, lineOf(sf, node.getStart(sf)));
205
+ if (caller !== null && (ts.isIdentifier(callee) || ts.isPrivateIdentifier(callee))) {
206
+ const key = `${caller.qualifiedName}\u0000${callee.text}`;
207
+ let entry = seen.get(key);
208
+ if (!entry) {
209
+ entry = { from: caller.qualifiedName, name: callee.text, targets: new Map(), library: 0, other: 0 };
210
+ seen.set(key, entry);
211
+ order.push(key);
212
+ }
213
+ let symbol = checker.getSymbolAtLocation(callee);
214
+ if (symbol && (symbol.flags & ts.SymbolFlags.Alias) !== 0)
215
+ symbol = checker.getAliasedSymbol(symbol);
216
+ const bound = (symbol?.declarations ?? []).map((d) => bindDeclaration(d, ts.isNewExpression(node)));
217
+ const targets = bound.filter((b) => b.kind === 'target');
218
+ if (targets.length > 0) {
219
+ for (const t of targets) {
220
+ if (t.sourcePath === file.sourcePath && t.qualifiedName === caller.qualifiedName)
221
+ continue; // self-recursion
222
+ entry.targets.set(`${t.qualifiedName}@${t.sourcePath}`, { qualifiedName: t.qualifiedName, sourcePath: t.sourcePath });
223
+ }
224
+ if (entry.targets.size === 0)
225
+ entry.other++; // only itself: neither a target nor a library call
226
+ }
227
+ else if (bound.length > 0 && bound.every((b) => b.kind === 'library'))
228
+ entry.library++;
229
+ else
230
+ entry.other++;
231
+ }
232
+ }
233
+ ts.forEachChild(node, visit);
234
+ };
235
+ if (sf)
236
+ visit(sf);
237
+ const records = [];
238
+ for (const key of order) {
239
+ const e = seen.get(key);
240
+ if (e.targets.size > 0)
241
+ records.push({ from: e.from, name: e.name, targets: [...e.targets.values()], library: false });
242
+ else if (e.library > 0 && e.other === 0)
243
+ records.push({ from: e.from, name: e.name, targets: [], library: true });
244
+ }
245
+ calls.set(file.sourcePath, records);
246
+ }
247
+ return { ok: true, calls };
248
+ }
249
+ catch (err) {
250
+ return { ok: false, skipped: `compiler failed: ${err instanceof Error ? err.message : String(err)}`.slice(0, 200) };
251
+ }
252
+ }
@@ -21,9 +21,14 @@ import type { KnownDefect, MalformedMarker } from '../rtm/known-defects';
21
21
  *
22
22
  * Pure: no I/O, no clocks. The hooks supply loaded specs + evidence.
23
23
  */
24
+ /**
25
+ * @implements A-SPEC-247.1 — `findingId` rides on an ART-7 open-critical violation, so the Stop text can ask the
26
+ * approval queue about that finding without reading the detail text.
27
+ */
24
28
  export interface ConstitutionViolation {
25
29
  article: string;
26
30
  detail: string;
31
+ findingId?: string;
27
32
  }
28
33
  export interface ConstitutionContext {
29
34
  specs: Spec[];
@@ -180,7 +180,7 @@ function verifyConstitution(ctx) {
180
180
  // (the CLI catches and exits 0). The gate must never be crashable by its own evidence.
181
181
  const gist = typeof f.summary === 'string' && f.summary ? ` (${f.summary.slice(0, 80)})` : '';
182
182
  if (f.status === 'open' && f.severity === 'critical') {
183
- v.push({ article: 'ART-7', detail: `finding ${f.id}${gist}: 열린 치명 발견 — 결함을 고치고 재리뷰로 resolved 를 기록하기 전까지 이 작업은 완료될 수 없습니다` });
183
+ v.push({ article: 'ART-7', detail: `finding ${f.id}${gist}: 열린 치명 발견 — 결함을 고치고 재리뷰로 resolved 를 기록하기 전까지 이 작업은 완료될 수 없습니다`, ...(typeof f.id === 'string' ? { findingId: f.id } : {}) });
184
184
  continue;
185
185
  }
186
186
  // @implements A-SPEC-191 (§4c) — the judgement class ART-6 exists to reject ("sealed in an