@holmes-lab/holmes-kit 0.35.10 → 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 (37) hide show
  1. package/CHANGELOG.md +75 -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/mcp/handlers/graph-operations.js +9 -3
  12. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +29 -4
  13. package/dist/holmes/mcp/handlers/requirement-triage.js +51 -4
  14. package/dist/holmes/mcp/handlers.d.ts +14 -4
  15. package/dist/holmes/mcp/handlers.js +9 -2
  16. package/dist/holmes/mcp/maintenance-analyze.d.ts +8 -0
  17. package/dist/holmes/mcp/maintenance-analyze.js +69 -4
  18. package/dist/holmes/review/graph-resolution.d.ts +61 -0
  19. package/dist/holmes/review/graph-resolution.js +158 -0
  20. package/dist/holmes/review/requirement-triage.js +3 -2
  21. package/dist/holmes/review/run-replay.d.ts +49 -0
  22. package/dist/holmes/review/run-replay.js +132 -13
  23. package/dist/holmes/review/semantic-retrieval.d.ts +2 -0
  24. package/dist/holmes/review/semantic-retrieval.js +4 -1
  25. package/dist/holmes/rtm/anchor-binding.d.ts +34 -0
  26. package/dist/holmes/rtm/anchor-binding.js +43 -0
  27. package/dist/holmes/rtm/anchor-history.d.ts +39 -0
  28. package/dist/holmes/rtm/anchor-history.js +97 -0
  29. package/dist/holmes/rtm/anchor-ids.d.ts +21 -0
  30. package/dist/holmes/rtm/anchor-ids.js +51 -5
  31. package/dist/holmes/rtm/localize.d.ts +7 -0
  32. package/dist/holmes/rtm/localize.js +11 -2
  33. package/dist/holmes/rtm/rtm-builder.d.ts +12 -0
  34. package/dist/holmes/rtm/rtm-builder.js +64 -2
  35. package/dist/holmes/rtm/rtm-graph.d.ts +11 -0
  36. package/dist/holmes/rtm/rtm-graph.js +20 -0
  37. package/package.json +1 -1
@@ -11,7 +11,24 @@ export interface RequirementTriageHandlerContext {
11
11
  status: 'spawned' | 'coalesced' | 'failed';
12
12
  generation?: string;
13
13
  };
14
+ /**
15
+ * @implements A-SPEC-723.1 — how long a call that asked for intake evidence (`persist: true`) waits
16
+ * for the refresh it requested. Absent or 0: no wait, the behaviour of A-SPEC-723.
17
+ */
18
+ freshnessWaitMs?: number;
19
+ /** Injected in tests; the wait polls the receipt between sleeps and does nothing else. */
20
+ sleep?(ms: number): Promise<void>;
21
+ now?(): number;
14
22
  }
23
+ /** @implements A-SPEC-723.1 — the wait bound wired into the server, and its ceiling. */
24
+ export declare const TRIAGE_WAIT_MS = 20000;
25
+ export declare const TRIAGE_WAIT_MAX_MS = 60000;
26
+ /**
27
+ * @implements A-SPEC-723.1
28
+ * `HOLMES_TRIAGE_WAIT_MS`: a non-negative integer overrides the bound (0 disables the wait, anything
29
+ * above the ceiling is the ceiling); every other value leaves the default.
30
+ */
31
+ export declare function triageWaitMsFrom(env: Record<string, string | undefined>): number;
15
32
  type GraphStatus = 'current' | 'stale' | 'unverified' | 'absent' | 'unreadable' | 'empty';
16
33
  export declare function createRequirementTriageHandlers(context: RequirementTriageHandlerContext): {
17
34
  requirement_triage(a: {
@@ -67,10 +84,12 @@ export declare function createRequirementTriageHandlers(context: RequirementTria
67
84
  state: string;
68
85
  };
69
86
  refresh: {
87
+ waitedMs?: number | undefined;
88
+ outcome?: "current" | "timeout" | "ended" | undefined;
70
89
  status: "spawned" | "coalesced" | "failed";
71
90
  generation?: string;
72
91
  } | {
73
- status: "unavailable" | "not-needed";
92
+ status: string;
74
93
  };
75
94
  lexicalOnly?: true | undefined;
76
95
  verdict: import("../../review/requirement-triage").RequirementVerdict;
@@ -125,10 +144,12 @@ export declare function createRequirementTriageHandlers(context: RequirementTria
125
144
  state: string;
126
145
  };
127
146
  refresh: {
147
+ waitedMs?: number | undefined;
148
+ outcome?: "current" | "timeout" | "ended" | undefined;
128
149
  status: "spawned" | "coalesced" | "failed";
129
150
  generation?: string;
130
151
  } | {
131
- status: "unavailable" | "not-needed";
152
+ status: string;
132
153
  };
133
154
  lexicalOnly?: true | undefined;
134
155
  candidates: {
@@ -205,10 +226,12 @@ export declare function createRequirementTriageHandlers(context: RequirementTria
205
226
  state: string;
206
227
  };
207
228
  refresh: {
229
+ waitedMs?: number | undefined;
230
+ outcome?: "current" | "timeout" | "ended" | undefined;
208
231
  status: "spawned" | "coalesced" | "failed";
209
232
  generation?: string;
210
233
  } | {
211
- status: "unavailable" | "not-needed";
234
+ status: string;
212
235
  };
213
236
  lexicalOnly?: true | undefined;
214
237
  verdict: import("../../review/requirement-triage").RequirementVerdict;
@@ -269,10 +292,12 @@ export declare function createRequirementTriageHandlers(context: RequirementTria
269
292
  state: string;
270
293
  };
271
294
  refresh: {
295
+ waitedMs?: number | undefined;
296
+ outcome?: "current" | "timeout" | "ended" | undefined;
272
297
  status: "spawned" | "coalesced" | "failed";
273
298
  generation?: string;
274
299
  } | {
275
- status: "unavailable" | "not-needed";
300
+ status: string;
276
301
  };
277
302
  lexicalOnly?: true | undefined;
278
303
  candidates: {
@@ -33,8 +33,10 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.TRIAGE_WAIT_MAX_MS = exports.TRIAGE_WAIT_MS = void 0;
37
+ exports.triageWaitMsFrom = triageWaitMsFrom;
36
38
  exports.createRequirementTriageHandlers = createRequirementTriageHandlers;
37
- // @implements A-SPEC-743, A-SPEC-742, A-SPEC-729, A-SPEC-723, A-SPEC-719, A-SPEC-734
39
+ // @implements A-SPEC-743, A-SPEC-742, A-SPEC-729, A-SPEC-723, A-SPEC-719, A-SPEC-734, A-SPEC-723.1
38
40
  // @implements A-SPEC-713
39
41
  /** Read-only MCP projection of the pure requirement lifecycle triage model. */
40
42
  const node_child_process_1 = require("node:child_process");
@@ -50,6 +52,23 @@ const model_cache_1 = require("../../semantic/model-cache");
50
52
  const graph_store_1 = require("../../rtm/graph-store");
51
53
  const freshness_coordinator_1 = require("../../refresh/freshness-coordinator");
52
54
  const bounded_io_1 = require("../../project/bounded-io");
55
+ /** @implements A-SPEC-723.1 — the wait bound wired into the server, and its ceiling. */
56
+ exports.TRIAGE_WAIT_MS = 20_000;
57
+ exports.TRIAGE_WAIT_MAX_MS = 60_000;
58
+ const TRIAGE_POLL_MS = 250;
59
+ /**
60
+ * @implements A-SPEC-723.1
61
+ * `HOLMES_TRIAGE_WAIT_MS`: a non-negative integer overrides the bound (0 disables the wait, anything
62
+ * above the ceiling is the ceiling); every other value leaves the default.
63
+ */
64
+ function triageWaitMsFrom(env) {
65
+ const raw = env.HOLMES_TRIAGE_WAIT_MS;
66
+ if (raw === undefined || !/^\d+$/.test(raw.trim()))
67
+ return exports.TRIAGE_WAIT_MS;
68
+ return Math.min(Number(raw.trim()), exports.TRIAGE_WAIT_MAX_MS);
69
+ }
70
+ /** Receipt states a refresh will not leave by being waited on. */
71
+ const SETTLED_UNUSABLE = new Set(['failed', 'retry-at', 'suppressed', 'not-adopted', 'current']);
53
72
  const requirementKinds = new Set(['REQ', 'H-SPEC', 'A-SPEC', 'T-SPEC']);
54
73
  const cosine = (a, b) => {
55
74
  if (a.length === 0 || a.length !== b.length)
@@ -119,10 +138,11 @@ function createRequirementTriageHandlers(context) {
119
138
  const scanned = context.cachedScan(root, root);
120
139
  const evidence = (0, test_evidence_1.readTestEvidence)(root);
121
140
  const currentHead = headOf(root);
122
- const freshness = (0, freshness_coordinator_1.readFreshnessReceipt)(root, { workspaceId: (0, freshness_coordinator_1.workspaceIdFor)(root), head: currentHead || null, now: new Date() });
141
+ const readReceipt = () => (0, freshness_coordinator_1.readFreshnessReceipt)(root, { workspaceId: (0, freshness_coordinator_1.workspaceIdFor)(root), head: currentHead || null, now: new Date() });
142
+ let freshness = readReceipt();
123
143
  // A-SPEC-719: graph current plus a requirement lane that is current or the owner-chosen
124
144
  // lexical-only not-adopted/suppressed. The source lane is reported, never required.
125
- const freshnessCurrent = (0, freshness_coordinator_1.intakeUsable)(freshness);
145
+ let freshnessCurrent = (0, freshness_coordinator_1.intakeUsable)(freshness);
126
146
  // Triage remains read-only with respect to its decision: unavailable or
127
147
  // stale evidence still returns ambiguity. The optional bridge merely
128
148
  // requests the same detached, lease-coalesced refresh as the Stop hook.
@@ -135,6 +155,33 @@ function createRequirementTriageHandlers(context) {
135
155
  refresh = { status: 'failed' };
136
156
  }
137
157
  }
158
+ // @implements A-SPEC-723.1 — the call that asked for intake evidence waits, within the bound,
159
+ // for the refresh it just requested. Measured: four of four intakes after a commit needed two or
160
+ // three calls because this handler returned before a 12–16 s refresh had finished. The refresh
161
+ // still runs in the detached child; this only re-reads the receipt, which stays the one
162
+ // authority for currency (same workspace, same HEAD, or it is not accepted).
163
+ let wait;
164
+ const bound = context.freshnessWaitMs ?? 0;
165
+ if (!freshnessCurrent && a.persist === true && refresh !== undefined && refresh.status !== 'failed' && bound > 0) {
166
+ const now = context.now ?? (() => Date.now());
167
+ const sleep = context.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
168
+ const started = now();
169
+ let outcome = 'timeout';
170
+ while (now() - started < bound) {
171
+ await sleep(TRIAGE_POLL_MS);
172
+ freshness = readReceipt();
173
+ if ((0, freshness_coordinator_1.intakeUsable)(freshness)) {
174
+ freshnessCurrent = true;
175
+ outcome = 'current';
176
+ break;
177
+ }
178
+ if (freshness !== null && SETTLED_UNUSABLE.has(freshness.state)) {
179
+ outcome = 'ended';
180
+ break;
181
+ }
182
+ }
183
+ wait = { waitedMs: now() - started, outcome };
184
+ }
138
185
  const graph = readGraphEvidence(root, currentHead, documents);
139
186
  const fresh = (0, test_evidence_1.isFresh)(evidence, currentHead) && evidence?.passed === true;
140
187
  const lineageEvidence = {};
@@ -218,7 +265,7 @@ function createRequirementTriageHandlers(context) {
218
265
  graph: { status: graph.status, sourceCommit: graph.sourceCommit, graphAsOf: graph.graphAsOf, resolutionLimits: graph.resolutionLimits },
219
266
  graphBasis: { head: currentHead, governedDocumentCount: documents.length, scannedSourceCount: scanned.length },
220
267
  freshness: freshness === null ? { state: 'absent' } : freshness,
221
- refresh: refresh ?? { status: freshnessCurrent ? 'not-needed' : 'unavailable' } };
268
+ refresh: refresh !== undefined ? { ...refresh, ...(wait ?? {}) } : { status: freshnessCurrent ? 'not-needed' : 'unavailable' } };
222
269
  if (!a.persist || !freshnessCurrent || freshness === null)
223
270
  return answer;
224
271
  // @implements A-SPEC-729 — persisted AND issued on the ledger; intake accepts nothing else.
@@ -22,6 +22,8 @@ export declare class HandlerRefusal extends Error {
22
22
  readonly holmesRefusal = true;
23
23
  constructor(message: string);
24
24
  }
25
+ /** GET a localhost JSON endpoint (used by rtm_dashboard to read the census off the server it launched). */
26
+ export declare function fetchJson(url: string): Promise<any>;
25
27
  /** Marker test that survives realm boundaries (jest's instanceof does not). */
26
28
  export declare function isHandlerRefusal(e: unknown): e is Error;
27
29
  import { ChangeSourceInfo } from '../project/change-source';
@@ -747,10 +749,12 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
747
749
  state: string;
748
750
  };
749
751
  refresh: {
752
+ waitedMs?: number | undefined;
753
+ outcome?: "current" | "timeout" | "ended" | undefined;
750
754
  status: "spawned" | "coalesced" | "failed";
751
755
  generation?: string;
752
756
  } | {
753
- status: "unavailable" | "not-needed";
757
+ status: string;
754
758
  };
755
759
  lexicalOnly?: true | undefined;
756
760
  verdict: import("../review/requirement-triage").RequirementVerdict;
@@ -805,10 +809,12 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
805
809
  state: string;
806
810
  };
807
811
  refresh: {
812
+ waitedMs?: number | undefined;
813
+ outcome?: "current" | "timeout" | "ended" | undefined;
808
814
  status: "spawned" | "coalesced" | "failed";
809
815
  generation?: string;
810
816
  } | {
811
- status: "unavailable" | "not-needed";
817
+ status: string;
812
818
  };
813
819
  lexicalOnly?: true | undefined;
814
820
  candidates: {
@@ -885,10 +891,12 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
885
891
  state: string;
886
892
  };
887
893
  refresh: {
894
+ waitedMs?: number | undefined;
895
+ outcome?: "current" | "timeout" | "ended" | undefined;
888
896
  status: "spawned" | "coalesced" | "failed";
889
897
  generation?: string;
890
898
  } | {
891
- status: "unavailable" | "not-needed";
899
+ status: string;
892
900
  };
893
901
  lexicalOnly?: true | undefined;
894
902
  verdict: import("../review/requirement-triage").RequirementVerdict;
@@ -949,10 +957,12 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
949
957
  state: string;
950
958
  };
951
959
  refresh: {
960
+ waitedMs?: number | undefined;
961
+ outcome?: "current" | "timeout" | "ended" | undefined;
952
962
  status: "spawned" | "coalesced" | "failed";
953
963
  generation?: string;
954
964
  } | {
955
- status: "unavailable" | "not-needed";
965
+ status: string;
956
966
  };
957
967
  lexicalOnly?: true | undefined;
958
968
  candidates: {
@@ -34,11 +34,12 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.HandlerRefusal = void 0;
37
+ exports.fetchJson = fetchJson;
37
38
  exports.isHandlerRefusal = isHandlerRefusal;
38
39
  exports.unreadableAmong = unreadableAmong;
39
40
  exports.makeHandlers = makeHandlers;
40
41
  exports.collectDecisions = collectDecisions;
41
- // @implements A-SPEC-718.1, A-SPEC-718.2, A-SPEC-723, A-SPEC-720, A-SPEC-718, A-SPEC-703, A-SPEC-629, A-SPEC-628, A-SPEC-599, A-SPEC-603, A-SPEC-604, A-SPEC-605, A-SPEC-606, A-SPEC-607, A-SPEC-608, A-SPEC-609, A-SPEC-610, A-SPEC-611, A-SPEC-612, A-SPEC-613, A-SPEC-614, A-SPEC-615, A-SPEC-616, A-SPEC-617, A-SPEC-618, A-SPEC-621, A-SPEC-622, A-SPEC-624, A-SPEC-625, A-SPEC-627, A-SPEC-713, A-SPEC-732, A-SPEC-754
42
+ // @implements A-SPEC-718.1, A-SPEC-718.2, A-SPEC-723, A-SPEC-723.1, A-SPEC-545.6, A-SPEC-720, A-SPEC-718, A-SPEC-703, A-SPEC-629, A-SPEC-628, A-SPEC-599, A-SPEC-603, A-SPEC-604, A-SPEC-605, A-SPEC-606, A-SPEC-607, A-SPEC-608, A-SPEC-609, A-SPEC-610, A-SPEC-611, A-SPEC-612, A-SPEC-613, A-SPEC-614, A-SPEC-615, A-SPEC-616, A-SPEC-617, A-SPEC-618, A-SPEC-621, A-SPEC-622, A-SPEC-624, A-SPEC-625, A-SPEC-627, A-SPEC-713, A-SPEC-732, A-SPEC-754
42
43
  const operator_recovery_1 = require("./operator-recovery");
43
44
  // @implements A-SPEC-643
44
45
  // @implements A-SPEC-642
@@ -148,7 +149,11 @@ exports.HandlerRefusal = HandlerRefusal;
148
149
  /** GET a localhost JSON endpoint (used by rtm_dashboard to read the census off the server it launched). */
149
150
  function fetchJson(url) {
150
151
  return new Promise((resolve, reject) => {
151
- http.get(url, (res) => {
152
+ // @implements A-SPEC-545.6 — `agent: false`: one connection per read, never a pooled socket. The
153
+ // caller does seconds of synchronous work between reads; with a kept-alive socket the dashboard
154
+ // server had closed it by then, this process had not yet seen the close, and the next read failed
155
+ // with ECONNRESET (measured: the second `rtm_dashboard` call, 7 of 7 whole-suite runs).
156
+ http.get(url, { agent: false }, (res) => {
152
157
  let data = '';
153
158
  res.on('data', (c) => (data += c));
154
159
  res.on('end', () => { try {
@@ -780,6 +785,8 @@ function makeRawHandlers(store, opts) {
780
785
  assertStoreReachable: (tool, root) => assertSpecStoreReachable(tool, store, root),
781
786
  refusal: reason => new HandlerRefusal(reason),
782
787
  requestFreshness: rtm_refresh_1.requestBackgroundFreshness,
788
+ // @implements A-SPEC-723.1 — an intake call waits for the refresh it requested, within this bound.
789
+ freshnessWaitMs: (0, requirement_triage_1.triageWaitMsFrom)(process.env),
783
790
  });
784
791
  const resolver = (specs) => (id) => specs.find((s) => s.id === id) ?? null;
785
792
  // @implements A-SPEC-100.2, A-SPEC-128, A-SPEC-138, A-SPEC-140.2, A-SPEC-189, A-SPEC-461, A-SPEC-512.2, A-SPEC-513.1, A-SPEC-524.1
@@ -449,6 +449,14 @@ export interface MaintenanceAnalysis {
449
449
  };
450
450
  evidenceDigest: string;
451
451
  }
452
+ /**
453
+ * @implements A-SPEC-745.1
454
+ * Is this test file named after that source file? The convention a person greps by: the test's
455
+ * basename without its extension and test markers (`.test`, `.spec`, a leading `test_`, a trailing
456
+ * `_test`, a trailing `Test`/`Tests`) equals the source's basename without extension, or starts with
457
+ * it followed by `-`, `_` or `.`. A name that merely CONTAINS the source name is not a match.
458
+ */
459
+ export declare function testNameMatches(testPath: string, sourcePath: string): boolean;
452
460
  /**
453
461
  * Decode a pathname as git prints it in `--name-only`/`--name-status` output. With the default
454
462
  * `core.quotepath=true`, any non-ASCII or control byte makes git wrap the name in double quotes and
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ANALYZE_TEXT_CAP = exports.ANALYZE_LIST_CAP = exports.PRIMARY_TIER_WIDTH = exports.EVIDENCE_DIMENSIONS = exports.CONFIDENCE_NOTE = exports.MAINTENANCE_ANALYSIS_EXTRACTOR = exports.MAINTENANCE_ANALYSIS_SCHEMA = void 0;
4
+ exports.testNameMatches = testNameMatches;
4
5
  exports.unquoteGitPath = unquoteGitPath;
5
6
  exports.analyzeMaintenance = analyzeMaintenance;
6
7
  exports.boundAnalysis = boundAnalysis;
7
- // @implements A-SPEC-745, A-SPEC-741, A-SPEC-741.1, A-SPEC-740, A-SPEC-725, A-SPEC-310
8
+ // @implements A-SPEC-745, A-SPEC-745.1, A-SPEC-741, A-SPEC-741.1, A-SPEC-740, A-SPEC-725, A-SPEC-310
8
9
  // @implements A-SPEC-295
9
10
  // @implements A-SPEC-294
10
11
  // @implements A-SPEC-293
@@ -28,6 +29,7 @@ const admission_1 = require("../semantic/admission");
28
29
  const unreadable_paths_1 = require("../semantic/unreadable-paths");
29
30
  const dense_retrieval_1 = require("../review/dense-retrieval");
30
31
  const test_scope_1 = require("../rtm/test-scope");
32
+ const test_files_1 = require("../cpg/test-files");
31
33
  const scope_1 = require("../review/scope");
32
34
  // @implements A-SPEC-469 — the SAME code path the S-484 measurement ran; identity is the reason
33
35
  // the measured numbers transfer to the shipped surface.
@@ -98,6 +100,24 @@ exports.EVIDENCE_DIMENSIONS = [
98
100
  * precision), and tuning a threshold on 12 samples would be fitting noise.
99
101
  */
100
102
  exports.PRIMARY_TIER_WIDTH = 3;
103
+ /**
104
+ * @implements A-SPEC-745.1
105
+ * Is this test file named after that source file? The convention a person greps by: the test's
106
+ * basename without its extension and test markers (`.test`, `.spec`, a leading `test_`, a trailing
107
+ * `_test`, a trailing `Test`/`Tests`) equals the source's basename without extension, or starts with
108
+ * it followed by `-`, `_` or `.`. A name that merely CONTAINS the source name is not a match.
109
+ */
110
+ function testNameMatches(testPath, sourcePath) {
111
+ const base = (p) => p.slice(p.lastIndexOf('/') + 1);
112
+ const stem = base(sourcePath).replace(/\.[^.]+$/, '');
113
+ if (stem === '')
114
+ return false;
115
+ let name = base(testPath).replace(/\.[^.]+$/, '').replace(/\.(test|spec)$/i, '');
116
+ if (/^test_/i.test(name))
117
+ name = name.slice(5);
118
+ name = name.replace(/_test$/i, '').replace(/Tests?$/, '');
119
+ return name === stem || name.startsWith(`${stem}-`) || name.startsWith(`${stem}_`) || name.startsWith(`${stem}.`);
120
+ }
101
121
  function sortedUnique(values) {
102
122
  return [...new Set(values)].sort((a, b) => a.localeCompare(b));
103
123
  }
@@ -402,6 +422,14 @@ function analyzeMaintenance(input) {
402
422
  // symbols the request actually named keep the front, and the data-flow neighbours are appended.
403
423
  const defUseTerms = input.defUse === undefined ? [] : (0, localize_1.significantTerms)(input.request);
404
424
  const symbolsByFile = new Map(scanned.map((f) => [f.sourcePath, f.symbols.map((sy) => sy.qualifiedName)]));
425
+ // @implements A-SPEC-756.4 — MEASURED AND WITHDRAWN: "the functions bound to the specs this
426
+ // request cites or matches lead a candidate's list" (rule R of A-SPEC-756.1, weight c/n per bound
427
+ // function, five leading). On the fixed replay windows it changed the list in 92 of 120 cases on
428
+ // this repository and moved function-axis recall at 10 by +0.0056 against a detectable bound of
429
+ // 0.0157; with history binding −0.0037 against 0.0247; no case moved on the second corpus. A
430
+ // function-level spec link does not find the changed function better than the name match below.
431
+ // Do not re-add an ordering by bound specs without a new pre-registered measurement; the replay's
432
+ // `anchorArms` reproduces this one (build d47d6523 for the rule itself).
405
433
  const symbolsOf = (file, matched) => {
406
434
  const facts = input.defUse?.[file];
407
435
  if (facts === undefined)
@@ -566,9 +594,17 @@ function analyzeMaintenance(input) {
566
594
  const seeds = direct.flatMap((qualifiedName) => input.graph.codeNodeIds(qualifiedName));
567
595
  const seen = new Set(seeds);
568
596
  const candidateSpecs = new Set(localization.matchedSpecs);
597
+ // @implements A-SPEC-756.1 — gathered per FILE, not per function. These specs choose the tests,
598
+ // and a function no longer carries what its siblings implement: gathering function by function
599
+ // dropped test recall 0.454 -> 0.425 on the first place-binding build. `specsOfFile` returns for
600
+ // any function exactly what `specsOf` returned before anchors were bound to functions.
601
+ const specsOfCode = (id) => {
602
+ const at = id.lastIndexOf('@');
603
+ return at < 0 ? input.graph.specsOf(id) : input.graph.specsOfFile(id.slice(at + 1));
604
+ };
569
605
  for (const qualifiedName of direct) {
570
606
  for (const id of input.graph.codeNodeIds(qualifiedName)) {
571
- for (const specId of input.graph.specsOf(id))
607
+ for (const specId of specsOfCode(id))
572
608
  candidateSpecs.add(specId.replace(/^SPEC:/, ''));
573
609
  }
574
610
  }
@@ -632,7 +668,7 @@ function analyzeMaintenance(input) {
632
668
  const transitive = sortedUnique([...transitiveIds].map(codeQualifiedName).filter((qn) => !direct.includes(qn)));
633
669
  for (const qualifiedName of transitive) {
634
670
  for (const id of input.graph.codeNodeIds(qualifiedName)) {
635
- for (const specId of input.graph.specsOf(id))
671
+ for (const specId of specsOfCode(id))
636
672
  candidateSpecs.add(specId.replace(/^SPEC:/, ''));
637
673
  }
638
674
  }
@@ -1098,6 +1134,35 @@ function analyzeMaintenance(input) {
1098
1134
  specRank.set(id, index);
1099
1135
  });
1100
1136
  const relevanceOrderedSpecs = [...specIds].sort((a, b) => (specRank.get(a) ?? Infinity) - (specRank.get(b) ?? Infinity) || a.localeCompare(b));
1137
+ // @implements A-SPEC-745.1 — the same for `relevantTests`: the same set, in relevance order. Path
1138
+ // order made the ten the response keeps `src/holmes/assoc/…` for every request here. Seeds are the
1139
+ // changed source files when given, else the ranked candidates. A test named after a seed comes
1140
+ // first, then a test anchoring a spec the seed anchors, then the rest; ties keep path order.
1141
+ // Measured on the fixed replay windows: recall@10 of the returned list 0.206 -> 0.481 here.
1142
+ const changedSources = (input.changedFiles ?? []).filter((file) => !(0, test_files_1.isTestFile)(file));
1143
+ const testSeeds = changedSources.length > 0 ? changedSources : candidates.map((candidate) => candidate.file);
1144
+ // The first seed that anchors each spec, computed once: a seed can anchor a hundred specs and the
1145
+ // list can hold hundreds of tests.
1146
+ const firstSeedOfSpec = new Map();
1147
+ testSeeds.forEach((seed, index) => {
1148
+ for (const id of anchorsOf.get(seed) ?? [])
1149
+ if (!firstSeedOfSpec.has(id))
1150
+ firstSeedOfSpec.set(id, index);
1151
+ });
1152
+ const testRank = (test) => {
1153
+ const byName = testSeeds.findIndex((seed) => testNameMatches(test, seed));
1154
+ if (byName >= 0)
1155
+ return byName;
1156
+ let bySpec = Infinity;
1157
+ for (const id of input.testAnchors[test] ?? [])
1158
+ bySpec = Math.min(bySpec, firstSeedOfSpec.get(id) ?? Infinity);
1159
+ return bySpec === Infinity ? Infinity : testSeeds.length + bySpec;
1160
+ };
1161
+ const testRanks = new Map(relevantTests.map((test) => [test, testRank(test)]));
1162
+ const relevanceOrderedTests = [...relevantTests].sort((a, b) => {
1163
+ const ra = testRanks.get(a), rb = testRanks.get(b);
1164
+ return ra === rb ? a.localeCompare(b) : ra - rb;
1165
+ });
1101
1166
  const evidence = {
1102
1167
  schemaVersion: exports.MAINTENANCE_ANALYSIS_SCHEMA,
1103
1168
  extractorVersion: exports.MAINTENANCE_ANALYSIS_EXTRACTOR,
@@ -1143,7 +1208,7 @@ function analyzeMaintenance(input) {
1143
1208
  unactionableCriteria,
1144
1209
  intent,
1145
1210
  testScope,
1146
- relevantTests,
1211
+ relevantTests: relevanceOrderedTests,
1147
1212
  relevantTestSpecs,
1148
1213
  historicalRationale: history,
1149
1214
  contextBundle: input.contextBundle ?? null,
@@ -0,0 +1,61 @@
1
+ export interface GraphRows {
2
+ nodes: Array<{
3
+ id: string;
4
+ kind: string;
5
+ sourcePath: string | null;
6
+ }>;
7
+ edges: Array<{
8
+ src: string;
9
+ dst: string;
10
+ rel: string;
11
+ derivation: string | null;
12
+ observedAt: string | null;
13
+ validUntil: string | null;
14
+ evidenceDigest: string | null;
15
+ }>;
16
+ }
17
+ export interface GraphResolution {
18
+ nodesByKind: Record<string, number>;
19
+ edgesByRel: Record<string, number>;
20
+ specLink: {
21
+ linkedSymbols: number;
22
+ filesWithTwoOrMore: number;
23
+ uniformFiles: number;
24
+ uniformShare: number | null;
25
+ specsPerSymbolMedian: number | null;
26
+ specsPerSymbolMax: number | null;
27
+ siteBoundEdges: number;
28
+ };
29
+ verification: {
30
+ caseNodes: number;
31
+ criterionNodes: number;
32
+ executesEdges: number;
33
+ verifiesEdges: number;
34
+ };
35
+ calls: {
36
+ resolved: number;
37
+ ambiguous: number;
38
+ ambiguousShare: number | null;
39
+ };
40
+ flowEdges: number;
41
+ provenance: {
42
+ edges: number;
43
+ withObservedAt: number;
44
+ withValidUntil: number;
45
+ withEvidenceDigest: number;
46
+ };
47
+ }
48
+ export type GraphRowsRead = {
49
+ ok: true;
50
+ rows: GraphRows;
51
+ } | {
52
+ ok: false;
53
+ reason: 'missing' | 'not-a-graph-store';
54
+ };
55
+ export declare function graphResolution(rows: GraphRows): GraphResolution;
56
+ /**
57
+ * The rows of a graph store, read without ever writing to it. `fileMustExist` matters: the driver
58
+ * creates an empty database for an absent path, and an empty store would then read as "a graph with
59
+ * nothing in it" — the zero result this instrument must never report for a missing one.
60
+ */
61
+ export declare function readGraphRows(dbPath: string): GraphRowsRead;
@@ -0,0 +1,158 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.graphResolution = graphResolution;
40
+ exports.readGraphRows = readGraphRows;
41
+ // @implements A-SPEC-755
42
+ /**
43
+ * How far a built traceability graph is from the resolution the design claims.
44
+ *
45
+ * Measured by hand on 2026-10-07: in 330 of 330 files with two or more symbols every symbol carried
46
+ * the identical spec set (the file's anchors copied onto each function), there was no node for a test
47
+ * case or a success criterion, 41% of call edges were ambiguous and no edge carried an observation
48
+ * time, a validity bound or an evidence digest. Those numbers came from throw-away scripts; this is
49
+ * the same measurement with its definitions fixed in A-SPEC-755, so a later change to the graph is
50
+ * judged by it and not by a node count.
51
+ *
52
+ * Read-only by construction: the census is pure, and the reader opens the store read-only.
53
+ */
54
+ const fs = __importStar(require("node:fs"));
55
+ const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
56
+ const filled = (v) => v !== null && v !== '';
57
+ function graphResolution(rows) {
58
+ const nodesByKind = {};
59
+ const fileOfCode = new Map();
60
+ for (const n of rows.nodes) {
61
+ nodesByKind[n.kind] = (nodesByKind[n.kind] ?? 0) + 1;
62
+ if (n.kind === 'CODE')
63
+ fileOfCode.set(n.id, n.sourcePath);
64
+ }
65
+ const edgesByRel = {};
66
+ // Targets per linked symbol. A Set, so an edge stated twice does not make two symbols look different.
67
+ const specsOfSymbol = new Map();
68
+ let siteBoundEdges = 0, withObservedAt = 0, withValidUntil = 0, withEvidenceDigest = 0;
69
+ for (const e of rows.edges) {
70
+ edgesByRel[e.rel] = (edgesByRel[e.rel] ?? 0) + 1;
71
+ if (filled(e.observedAt))
72
+ withObservedAt++;
73
+ if (filled(e.validUntil))
74
+ withValidUntil++;
75
+ if (filled(e.evidenceDigest))
76
+ withEvidenceDigest++;
77
+ // An edge whose source is not a CODE node in these rows has no file to be attributed to.
78
+ if (e.rel !== 'implements' || !fileOfCode.has(e.src))
79
+ continue;
80
+ if (e.derivation === 'anchor-site')
81
+ siteBoundEdges++;
82
+ const set = specsOfSymbol.get(e.src);
83
+ if (set)
84
+ set.add(e.dst);
85
+ else
86
+ specsOfSymbol.set(e.src, new Set([e.dst]));
87
+ }
88
+ // Per file: the distinct spec sets its linked symbols carry. One distinct set = the file is uniform.
89
+ const setsOfFile = new Map();
90
+ const sizes = [];
91
+ for (const [id, set] of specsOfSymbol) {
92
+ sizes.push(set.size);
93
+ const file = fileOfCode.get(id) ?? null;
94
+ const entry = setsOfFile.get(file) ?? { symbols: 0, distinct: new Set() };
95
+ entry.symbols++;
96
+ entry.distinct.add([...set].sort().join('\n'));
97
+ setsOfFile.set(file, entry);
98
+ }
99
+ let filesWithTwoOrMore = 0, uniformFiles = 0;
100
+ for (const entry of setsOfFile.values()) {
101
+ if (entry.symbols < 2)
102
+ continue;
103
+ filesWithTwoOrMore++;
104
+ if (entry.distinct.size === 1)
105
+ uniformFiles++;
106
+ }
107
+ sizes.sort((a, b) => a - b);
108
+ const count = (m, k) => m[k] ?? 0;
109
+ const resolved = count(edgesByRel, 'calls');
110
+ const ambiguous = count(edgesByRel, 'calls_ambiguous');
111
+ return {
112
+ nodesByKind, edgesByRel,
113
+ specLink: {
114
+ linkedSymbols: sizes.length,
115
+ filesWithTwoOrMore, uniformFiles,
116
+ uniformShare: filesWithTwoOrMore === 0 ? null : uniformFiles / filesWithTwoOrMore,
117
+ // Lower middle for an even count: a median that is always a value some symbol really has.
118
+ specsPerSymbolMedian: sizes.length === 0 ? null : sizes[Math.floor((sizes.length - 1) / 2)],
119
+ specsPerSymbolMax: sizes.length === 0 ? null : sizes[sizes.length - 1],
120
+ siteBoundEdges,
121
+ },
122
+ verification: {
123
+ caseNodes: count(nodesByKind, 'CASE'),
124
+ criterionNodes: count(nodesByKind, 'CRITERION') + count(nodesByKind, 'RULE'),
125
+ executesEdges: count(edgesByRel, 'executes'),
126
+ verifiesEdges: count(edgesByRel, 'verifies'),
127
+ },
128
+ calls: { resolved, ambiguous, ambiguousShare: resolved + ambiguous === 0 ? null : ambiguous / (resolved + ambiguous) },
129
+ flowEdges: count(edgesByRel, 'data_dep') + count(edgesByRel, 'control_dep'),
130
+ provenance: { edges: rows.edges.length, withObservedAt, withValidUntil, withEvidenceDigest },
131
+ };
132
+ }
133
+ /**
134
+ * The rows of a graph store, read without ever writing to it. `fileMustExist` matters: the driver
135
+ * creates an empty database for an absent path, and an empty store would then read as "a graph with
136
+ * nothing in it" — the zero result this instrument must never report for a missing one.
137
+ */
138
+ function readGraphRows(dbPath) {
139
+ if (!fs.existsSync(dbPath))
140
+ return { ok: false, reason: 'missing' };
141
+ let db = null;
142
+ try {
143
+ db = new better_sqlite3_1.default(dbPath, { readonly: true, fileMustExist: true });
144
+ const nodes = db.prepare('SELECT id, kind, source_path AS sourcePath FROM nodes').all();
145
+ const edges = db.prepare(`SELECT src, dst, rel, derivation, observed_at AS observedAt, valid_until AS validUntil,
146
+ evidence_digest AS evidenceDigest FROM edges`).all();
147
+ return { ok: true, rows: { nodes, edges } };
148
+ }
149
+ catch {
150
+ return { ok: false, reason: 'not-a-graph-store' };
151
+ }
152
+ finally {
153
+ try {
154
+ db?.close();
155
+ }
156
+ catch { /* a handle that never opened has nothing to close */ }
157
+ }
158
+ }
@@ -4,7 +4,7 @@ exports.canonicalRequirementDocument = void 0;
4
4
  exports.requestIdentifiers = requestIdentifiers;
5
5
  exports.triageRequirements = triageRequirements;
6
6
  exports.requirementSemanticCoverage = requirementSemanticCoverage;
7
- // @implements A-SPEC-713.1, A-SPEC-713.2, A-SPEC-713.3, A-SPEC-713.4, A-SPEC-742, A-SPEC-713
7
+ // @implements A-SPEC-713.1, A-SPEC-713.2, A-SPEC-713.3, A-SPEC-713.4, A-SPEC-742, A-SPEC-713, A-SPEC-757
8
8
  /** Pure, conservative lifecycle triage over governed requirement documents. */
9
9
  const semantic_retrieval_1 = require("./semantic-retrieval");
10
10
  const localize_1 = require("../rtm/localize");
@@ -92,7 +92,8 @@ function rankCompare(a, b, cited) {
92
92
  return b.lexicalScore - a.lexicalScore || a.reqId.localeCompare(b.reqId);
93
93
  }
94
94
  function bm25(query, docs) {
95
- const terms = docs.map((text) => (0, semantic_retrieval_1.normalisedTerms)(text));
95
+ // @implements A-SPEC-757 — the document form: `normalisedTerms` is the request's (distinct, first 64).
96
+ const terms = docs.map((text) => (0, semantic_retrieval_1.normalisedDocumentTerms)(text));
96
97
  const avg = terms.reduce((n, row) => n + row.length, 0) / (terms.length || 1);
97
98
  const df = new Map();
98
99
  for (const row of terms)