@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
@@ -36,6 +36,14 @@ export declare function collectCiVerdicts(root: string, now?: Date): CiVerdict[]
36
36
  * Pure and testable: evaluateStop takes the loaded spec set (+ optional evidence); the CLI does I/O.
37
37
  */
38
38
  export interface StopEvidence {
39
+ /**
40
+ * @implements A-SPEC-247.1
41
+ * The approval queue's pending requests, supplied by the hook. They decide only which HEADING a blocking line is
42
+ * printed under; absent means every line is printed as the session's. Never read for the verdict.
43
+ */
44
+ pendingRequests?: Pick<PendingRequest, 'id' | 'target'>[];
45
+ /** The launcher the block text prints before `holmes-kit approve` (default: this platform's npx). */
46
+ launcher?: string;
39
47
  /** A-SPEC id -> number of real test cases (`it(`/`test(`) found in test files anchored to it. */
40
48
  testCasesByAspec?: Record<string, number>;
41
49
  /**
@@ -260,12 +268,32 @@ export declare function evaluateStop(specs: Spec[], evidence?: StopEvidence): {
260
268
  violations?: {
261
269
  article: string;
262
270
  detail: string;
271
+ findingId?: string;
263
272
  }[];
264
273
  tracked?: {
265
274
  article: string;
266
275
  detail: string;
267
276
  }[];
268
277
  };
278
+ /**
279
+ * @implements A-SPEC-247.1
280
+ * The text of a Stop block: every violation under the heading that says who acts next.
281
+ *
282
+ * Measured 2026-10-04: the gate repeated the same three violations on more than eight stops while every exit needed
283
+ * the operator, and the text named neither the pending request nor who acts. A first design made those violations
284
+ * "waiting" so the stop would be acknowledged; a review found that an acknowledged stop clears debt, so a session
285
+ * could end its turn with one tool call. That design is withdrawn: this function decides TEXT and nothing else.
286
+ *
287
+ * A violation waits on the operator only when the approval queue holds a pending request for its own subject: the
288
+ * leading document id of an ART-4, the finding id FIELD of an ART-7 open critical. No id is read out of ART-7 prose,
289
+ * so the diverged-resolution and unreadable-ledger shapes are always the session's. The first line is unchanged, and
290
+ * no request id has to be copied into a command.
291
+ */
292
+ export declare function stopBlockText(violations: {
293
+ article: string;
294
+ detail: string;
295
+ findingId?: string;
296
+ }[], pending: Pick<PendingRequest, 'id' | 'target'>[], launcher: string): string;
269
297
  /**
270
298
  * @implements A-SPEC-134
271
299
  * Pure decision for the constitution-debt state at a turn boundary. Replaces the Stop gate's silent
@@ -50,6 +50,7 @@ exports.governanceLostPreflight = governanceLostPreflight;
50
50
  exports.outsideAnyProject = outsideAnyProject;
51
51
  exports.trackedLines = trackedLines;
52
52
  exports.evaluateStop = evaluateStop;
53
+ exports.stopBlockText = stopBlockText;
53
54
  exports.stopDebtAction = stopDebtAction;
54
55
  exports.acknowledgeStop = acknowledgeStop;
55
56
  exports.describeTokenHealth = describeTokenHealth;
@@ -812,7 +813,8 @@ function evaluateStop(specs, evidence) {
812
813
  const problems = violations.map((x) => `[${x.article}] ${x.detail}`);
813
814
  // @implements A-SPEC-247 — structured list so the caller can ask acknowledgeStop which of these
814
815
  // are waiting on an owner. Mirrors `problems` exactly, including the two synthesized below.
815
- const structured = violations.map((x) => ({ article: x.article, detail: x.detail }));
816
+ // @implements A-SPEC-247.1 — an ART-7 open critical keeps its finding id, which the block text asks the queue about.
817
+ const structured = violations.map((x) => ({ article: x.article, detail: x.detail, ...(x.findingId !== undefined ? { findingId: x.findingId } : {}) }));
816
818
  // Tampered audit trail blocks finishing — wires the provenance chain's verify into the live gate
817
819
  // (review finding: verify() previously had no product caller, so the chain's guarantee was inert).
818
820
  if (evidence?.provenance && !evidence.provenance.ok) {
@@ -852,8 +854,6 @@ function evaluateStop(specs, evidence) {
852
854
  }
853
855
  if (problems.length === 0)
854
856
  return { block: false, ...(tracked ? { tracked } : {}) };
855
- const shown = problems.slice(0, 20);
856
- const more = problems.length > shown.length ? `\n…and ${problems.length - shown.length} more` : '';
857
857
  // @implements A-SPEC-134 — the distinct articles feed the constitution-debt state on a cap-yield.
858
858
  const articles = [...new Set(violations.map((x) => x.article)
859
859
  .concat(evidence?.provenance && !evidence.provenance.ok ? ['ART-2'] : [])
@@ -866,10 +866,66 @@ function evaluateStop(specs, evidence) {
866
866
  articles,
867
867
  violations: structured,
868
868
  ...(tracked ? { tracked } : {}),
869
- reason: `[Holmes-Kit] constitution gate: ${problems.length} article violation(s) must be ` +
870
- `fixed before finishing:\n${shown.join('\n')}${more}`,
869
+ // @implements A-SPEC-247.1 — the same lines, each under the heading that says who acts next. Text only.
870
+ reason: stopBlockText(structured, evidence?.pendingRequests ?? [], evidence?.launcher ?? (0, npx_bin_1.npxBin)()),
871
871
  };
872
872
  }
873
+ /** The leading document id of an ART-4 detail (`T-SPEC-752.4: declared coverage …`). */
874
+ const LEADING_SPEC_ID_RE = /^([A-Z]-SPEC-\d+(?:\.\d+)?)\b/;
875
+ const REQUEST_ID_RE = /^req-[0-9a-f]+$/;
876
+ const STOP_BLOCK_LINES = 20;
877
+ /**
878
+ * @implements A-SPEC-247.1
879
+ * The text of a Stop block: every violation under the heading that says who acts next.
880
+ *
881
+ * Measured 2026-10-04: the gate repeated the same three violations on more than eight stops while every exit needed
882
+ * the operator, and the text named neither the pending request nor who acts. A first design made those violations
883
+ * "waiting" so the stop would be acknowledged; a review found that an acknowledged stop clears debt, so a session
884
+ * could end its turn with one tool call. That design is withdrawn: this function decides TEXT and nothing else.
885
+ *
886
+ * A violation waits on the operator only when the approval queue holds a pending request for its own subject: the
887
+ * leading document id of an ART-4, the finding id FIELD of an ART-7 open critical. No id is read out of ART-7 prose,
888
+ * so the diverged-resolution and unreadable-ledger shapes are always the session's. The first line is unchanged, and
889
+ * no request id has to be copied into a command.
890
+ */
891
+ function stopBlockText(violations, pending, launcher) {
892
+ const requestFor = new Map();
893
+ for (const p of Array.isArray(pending) ? pending : []) {
894
+ if (typeof p?.target !== 'string' || typeof p?.id !== 'string' || !REQUEST_ID_RE.test(p.id))
895
+ continue;
896
+ if (!requestFor.has(p.target))
897
+ requestFor.set(p.target, p.id);
898
+ }
899
+ const operator = [];
900
+ const session = [];
901
+ for (const v of Array.isArray(violations) ? violations : []) {
902
+ const line = `[${v.article}] ${v.detail}`;
903
+ const subject = v.article === 'ART-4' ? (LEADING_SPEC_ID_RE.exec(String(v.detail)) ?? [])[1]
904
+ : v.article === 'ART-7' ? v.findingId : undefined;
905
+ const request = subject === undefined ? undefined : requestFor.get(subject);
906
+ if (request !== undefined) {
907
+ operator.push(`${line} — request ${request} is pending: the operator decides it, in the session's approval dialog or with ${launcher} holmes-kit approve`);
908
+ }
909
+ else if (v.article === 'ART-4') {
910
+ session.push(`${line} — anchor real covering tests, or, when the design is withdrawn, retire the spec with spec_retire`);
911
+ }
912
+ else if (v.article === 'ART-7' && v.findingId !== undefined) {
913
+ session.push(`${line} — fix the defect, have it re-reviewed, then record resolved with review_record (that asks the operator for a grant)`);
914
+ }
915
+ else {
916
+ session.push(line);
917
+ }
918
+ }
919
+ const total = operator.length + session.length;
920
+ const shownOperator = operator.slice(0, STOP_BLOCK_LINES);
921
+ const shownSession = session.slice(0, STOP_BLOCK_LINES - shownOperator.length);
922
+ const lines = [`[Holmes-Kit] constitution gate: ${total} article violation(s) must be fixed before finishing:`];
923
+ if (shownOperator.length > 0)
924
+ lines.push('Waiting on the operator:', ...shownOperator);
925
+ if (shownSession.length > 0)
926
+ lines.push('The session acts:', ...shownSession);
927
+ return lines.join('\n') + (total > STOP_BLOCK_LINES ? `\n…and ${total - STOP_BLOCK_LINES} more` : '');
928
+ }
873
929
  /**
874
930
  * @implements A-SPEC-134
875
931
  * Pure decision for the constitution-debt state at a turn boundary. Replaces the Stop gate's silent
@@ -1569,7 +1625,14 @@ if (require.main === module) {
1569
1625
  catch { /* the notice is best-effort */ }
1570
1626
  for (const notice of exports.STOP_NOTICES)
1571
1627
  process.stderr.write(`[Holmes-Kit] ${notice}\n`);
1572
- let out = evaluateStop(specs, { testCasesByAspec, provenance, executedByAspec, findings, findingsUnreadable, unanchoredChangedSources: unanchored, unrecordedApprovals: unrecorded, rolledBackLedgers: rolledBack, redFirstMode, changedAspecs, outcomesByAspec, ...(knownDefects ? { knownDefects } : {}), ...(ci ? { ci } : {}), ...(dist ? { dist } : {}), ...(analysis ? { analysis } : {}), ...(semantic ? { semantic } : {}), ...(forbiddenEdges ? { forbiddenEdges } : {}), ...(cycles ? { cycles } : {}) });
1628
+ // @implements A-SPEC-247.1 — the queue decides which heading a blocking line is printed under, nothing else.
1629
+ // Unreadable: every line is printed as the session's, which is what the text said before this slice.
1630
+ let pendingRequests = [];
1631
+ try {
1632
+ pendingRequests = require('../governance/approval-queue').readQueue(stopProjectRoot()).pending;
1633
+ }
1634
+ catch { /* text only */ }
1635
+ let out = evaluateStop(specs, { pendingRequests, testCasesByAspec, provenance, executedByAspec, findings, findingsUnreadable, unanchoredChangedSources: unanchored, unrecordedApprovals: unrecorded, rolledBackLedgers: rolledBack, redFirstMode, changedAspecs, outcomesByAspec, ...(knownDefects ? { knownDefects } : {}), ...(ci ? { ci } : {}), ...(dist ? { dist } : {}), ...(analysis ? { analysis } : {}), ...(semantic ? { semantic } : {}), ...(forbiddenEdges ? { forbiddenEdges } : {}), ...(cycles ? { cycles } : {}) });
1573
1636
  // @implements A-SPEC-534.4 — track mode records ART-8 findings without blocking: surface them so
1574
1637
  // the operator observes RED-first gaps before an owner promotes the posture to strict.
1575
1638
  // @implements A-SPEC-559.2 — spec-evolution trigger (observe-first, NEVER blocks): a dirty
@@ -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, A-SPEC-734, A-SPEC-741.1
42
+ // @implements A-SPEC-719, A-SPEC-734, A-SPEC-741.1, A-SPEC-758.1
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"));
@@ -60,7 +60,10 @@ const vector_coverage_1 = require("../../semantic/vector-coverage");
60
60
  // @implements A-SPEC-283 — bumped whenever the graph's node/edge shape changes, so a store written
61
61
  // by an older build is rebuilt rather than read with new assumptions.
62
62
  // @implements A-SPEC-568.1 — /3: nodes gained the intent `summary` column.
63
- const RTM_GRAPH_SCHEMA = 'rtm-graph/3';
63
+ // @implements A-SPEC-756.2 — /4: an `implements` edge from a function now means the anchor was
64
+ // written in or directly above it, and anchors bound to no function sit on FILE nodes (A-SPEC-756).
65
+ // A /3 store holds the file's whole list on every function and must be rebuilt, not read anew.
66
+ const RTM_GRAPH_SCHEMA = 'rtm-graph/4';
64
67
  // @implements A-SPEC-569.3 — how many impacted specs get their intent sentence attached. A prose
65
68
  // constant, never a verdict input: the impacted list itself is never truncated.
66
69
  const SUMMARY_CAP = 40;
@@ -68,7 +71,10 @@ const SUMMARY_CAP = 40;
68
71
  // characters in the summary column, and every other basis field would still match after upgrading.
69
72
  // A-SPEC-283's own rule applies to us too: an older build's artifact is rebuilt, never read with
70
73
  // new assumptions.
71
- const RTM_EXTRACTOR_VERSION = 'holmes-rtm/2';
74
+ // @implements A-SPEC-756.2 — /3: the extractor binds anchors to functions by place.
75
+ // @implements A-SPEC-758.1 — /4: TypeScript `calls` edges are bound by the compiler; a /3 store holds
76
+ // library calls linked to unrelated symbols by name and is rebuilt.
77
+ const RTM_EXTRACTOR_VERSION = 'holmes-rtm/4';
72
78
  // @implements A-SPEC-632 — the two rebuild paths a completed integration's discharge runs are the
73
79
  // SAME functions explicit reindex runs, so a discharged graph and a reindexed graph are one artifact.
74
80
  /** Publish the complete graph for `specs` over `scanned` at the live path (A-SPEC-631 primitive). */
@@ -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,