@holmes-lab/holmes-kit 0.28.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +24 -21
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/agents-guidance-history.d.ts +1 -1
  5. package/dist/holmes/cli/agents-guidance-history.js +11 -2
  6. package/dist/holmes/cli/agents-guidance.d.ts +1 -0
  7. package/dist/holmes/cli/agents-guidance.js +11 -8
  8. package/dist/holmes/cli/codex-toml.d.ts +23 -1
  9. package/dist/holmes/cli/codex-toml.js +151 -4
  10. package/dist/holmes/cli/doctor.d.ts +11 -1
  11. package/dist/holmes/cli/doctor.js +113 -13
  12. package/dist/holmes/cli/init.d.ts +2 -0
  13. package/dist/holmes/cli/init.js +20 -40
  14. package/dist/holmes/cli/interactive-prompt.js +2 -2
  15. package/dist/holmes/cli/worktree-readiness.d.ts +1 -0
  16. package/dist/holmes/cli/worktree-readiness.js +17 -3
  17. package/dist/holmes/cpg/ast-mutation.d.ts +2 -0
  18. package/dist/holmes/cpg/ast-mutation.js +4 -2
  19. package/dist/holmes/cpg/foundation/cfg.d.ts +10 -0
  20. package/dist/holmes/cpg/foundation/cfg.js +27 -1
  21. package/dist/holmes/governance/autonomy.d.ts +9 -0
  22. package/dist/holmes/governance/autonomy.js +28 -1
  23. package/dist/holmes/hooks/rtm-refresh-child.d.ts +22 -1
  24. package/dist/holmes/hooks/rtm-refresh-child.js +100 -18
  25. package/dist/holmes/hooks/rtm-refresh.d.ts +20 -1
  26. package/dist/holmes/hooks/rtm-refresh.js +56 -15
  27. package/dist/holmes/mcp/approval-adapters.d.ts +22 -0
  28. package/dist/holmes/mcp/approval-adapters.js +21 -0
  29. package/dist/holmes/mcp/approval-commit.d.ts +21 -0
  30. package/dist/holmes/mcp/approval-commit.js +92 -0
  31. package/dist/holmes/mcp/approval-intent.d.ts +44 -0
  32. package/dist/holmes/mcp/approval-intent.js +67 -0
  33. package/dist/holmes/mcp/approval-policy.d.ts +14 -0
  34. package/dist/holmes/mcp/approval-policy.js +18 -0
  35. package/dist/holmes/mcp/elicit-approval.d.ts +2 -0
  36. package/dist/holmes/mcp/elicit-approval.js +5 -2
  37. package/dist/holmes/mcp/handlers/graph-operations.d.ts +24 -1
  38. package/dist/holmes/mcp/handlers/graph-operations.js +38 -6
  39. package/dist/holmes/mcp/handlers/maintenance-evidence.js +1 -1
  40. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +142 -0
  41. package/dist/holmes/mcp/handlers/requirement-triage.js +220 -0
  42. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -1
  43. package/dist/holmes/mcp/handlers/review-evidence.js +9 -5
  44. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +7 -0
  45. package/dist/holmes/mcp/handlers/slice-orchestration.js +8 -1
  46. package/dist/holmes/mcp/handlers/spec-approval.d.ts +26 -2
  47. package/dist/holmes/mcp/handlers/spec-approval.js +72 -47
  48. package/dist/holmes/mcp/handlers/spec-authoring.js +20 -2
  49. package/dist/holmes/mcp/handlers.d.ts +153 -0
  50. package/dist/holmes/mcp/handlers.js +67 -13
  51. package/dist/holmes/mcp/maintenance-analyze.js +28 -4
  52. package/dist/holmes/mcp/maintenance-evidence.js +1 -1
  53. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +45 -0
  54. package/dist/holmes/mcp/requirement-triage-evidence.js +149 -0
  55. package/dist/holmes/mcp/server.js +5 -3
  56. package/dist/holmes/mcp/supervisor.js +7 -3
  57. package/dist/holmes/mcp/tool-schemas.d.ts +8 -0
  58. package/dist/holmes/mcp/tool-schemas.js +44 -1
  59. package/dist/holmes/refresh/freshness-coordinator.d.ts +67 -0
  60. package/dist/holmes/refresh/freshness-coordinator.js +230 -0
  61. package/dist/holmes/review/condition-hunk-replay.d.ts +45 -0
  62. package/dist/holmes/review/condition-hunk-replay.js +122 -0
  63. package/dist/holmes/review/condition-hunk-resolution.d.ts +65 -0
  64. package/dist/holmes/review/condition-hunk-resolution.js +258 -0
  65. package/dist/holmes/review/requirement-triage-benchmark.d.ts +45 -0
  66. package/dist/holmes/review/requirement-triage-benchmark.js +72 -0
  67. package/dist/holmes/review/requirement-triage-human-records.d.ts +59 -0
  68. package/dist/holmes/review/requirement-triage-human-records.js +119 -0
  69. package/dist/holmes/review/requirement-triage.d.ts +61 -0
  70. package/dist/holmes/review/requirement-triage.js +143 -0
  71. package/dist/holmes/review/scope.js +6 -1
  72. package/dist/holmes/review/test-outcomes.d.ts +28 -0
  73. package/dist/holmes/review/test-outcomes.js +90 -1
  74. package/dist/holmes/semantic/local-model.d.ts +3 -3
  75. package/dist/holmes/semantic/local-model.js +10 -12
  76. package/dist/holmes/semantic/model-cache.d.ts +15 -6
  77. package/dist/holmes/semantic/model-cache.js +77 -21
  78. package/dist/holmes/semantic/tier.d.ts +5 -1
  79. package/dist/holmes/semantic/tier.js +7 -6
  80. package/dist/holmes/semantic/vector-coverage.d.ts +17 -0
  81. package/dist/holmes/semantic/vector-coverage.js +37 -0
  82. package/docs/install-guide.md +19 -24
  83. package/package.json +1 -1
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canonicalRequirementDocument = void 0;
4
+ exports.triageRequirements = triageRequirements;
5
+ // @implements A-SPEC-713
6
+ /** Pure, conservative lifecycle triage over governed requirement documents. */
7
+ const semantic_retrieval_1 = require("./semantic-retrieval");
8
+ const vector_coverage_1 = require("../semantic/vector-coverage");
9
+ /** Re-exported for triage callers; the cache contract belongs to vector coverage. */
10
+ exports.canonicalRequirementDocument = vector_coverage_1.canonicalRequirementDocument;
11
+ function rankLimit(value) {
12
+ if (!Number.isInteger(value))
13
+ return 10;
14
+ return Math.min(20, Math.max(1, value));
15
+ }
16
+ function rootOf(id, byId) {
17
+ const seen = new Set();
18
+ let current = byId.get(id);
19
+ while (current) {
20
+ if (seen.has(current.id))
21
+ return null;
22
+ seen.add(current.id);
23
+ if (current.type === 'REQ')
24
+ return current.id;
25
+ const parent = (current.dependsOn ?? []).map((p) => byId.get(p)).find((p) => p !== undefined);
26
+ if (!parent)
27
+ return null;
28
+ current = parent;
29
+ }
30
+ return null;
31
+ }
32
+ function bm25(query, docs) {
33
+ const terms = docs.map((text) => (0, semantic_retrieval_1.normalisedTerms)(text));
34
+ const avg = terms.reduce((n, row) => n + row.length, 0) / (terms.length || 1);
35
+ const df = new Map();
36
+ for (const row of terms)
37
+ for (const term of new Set(row))
38
+ df.set(term, (df.get(term) ?? 0) + 1);
39
+ return terms.map((row) => {
40
+ const frequencies = new Map();
41
+ for (const term of row)
42
+ frequencies.set(term, (frequencies.get(term) ?? 0) + 1);
43
+ return query.reduce((score, term) => {
44
+ const count = frequencies.get(term) ?? 0;
45
+ if (count === 0)
46
+ return score;
47
+ const n = df.get(term) ?? 0;
48
+ const idf = Math.max(Math.log(1 + (terms.length - n + 0.5) / (n + 0.5)), 0);
49
+ return score + idf * (count * 2.2) / (count + 1.2 * (0.25 + 0.75 * row.length / avg));
50
+ }, 0);
51
+ });
52
+ }
53
+ /**
54
+ * Retrieval only admits candidates. The verdict requires independent content and operational facts.
55
+ */
56
+ function triageRequirements(input) {
57
+ const promptTerms = [...new Set((0, semantic_retrieval_1.normalisedTerms)(input.prompt))];
58
+ if (promptTerms.length === 0)
59
+ return { verdict: 'ambiguous', candidates: [], reasons: ['empty-prompt'], uncertainty: ['empty-prompt'] };
60
+ const governed = input.documents.filter((d) => d.type === 'REQ' || d.type === 'H-SPEC' || d.type === 'A-SPEC' || d.type === 'T-SPEC');
61
+ if (governed.length === 0)
62
+ return { verdict: 'ambiguous', candidates: [], reasons: ['empty-or-unreadable-corpus'], uncertainty: ['empty-or-unreadable-corpus'] };
63
+ const byId = new Map(governed.map((d) => [d.id, d]));
64
+ const lineages = new Map();
65
+ for (const doc of governed) {
66
+ const root = rootOf(doc.id, byId);
67
+ if (root === null)
68
+ continue;
69
+ const bucket = lineages.get(root) ?? [];
70
+ bucket.push(doc);
71
+ lineages.set(root, bucket);
72
+ }
73
+ if (lineages.size === 0)
74
+ return { verdict: 'ambiguous', candidates: [], reasons: ['no-readable-lineage'], uncertainty: ['no-readable-lineage'] };
75
+ const documents = [...lineages.entries()].map(([reqId, docs]) => ({
76
+ reqId,
77
+ docs: [...docs].sort((a, b) => a.id.localeCompare(b.id)),
78
+ text: docs.map((d) => (0, exports.canonicalRequirementDocument)(d, reqId)).join('\n'),
79
+ })).sort((a, b) => a.reqId.localeCompare(b.reqId));
80
+ const lexical = bm25(promptTerms, documents.map((d) => d.text));
81
+ const semantic = new Map();
82
+ for (const c of input.semanticCandidates ?? []) {
83
+ if (!Number.isFinite(c.score) || c.score <= 0)
84
+ continue;
85
+ const root = rootOf(c.id, byId);
86
+ if (root !== null)
87
+ semantic.set(root, Math.max(semantic.get(root) ?? 0, c.score));
88
+ }
89
+ const allCandidates = documents.map((row, i) => {
90
+ const semanticScore = semantic.get(row.reqId);
91
+ if (lexical[i] <= 0 && semanticScore === undefined)
92
+ return null;
93
+ const textLower = row.text.toLowerCase();
94
+ const contentTerms = promptTerms.filter((term) => textLower.includes(term));
95
+ const operational = input.evidence?.[row.reqId] ?? {};
96
+ const approved = row.docs.length === 4 && row.docs.every((d) => d.status === 'approved');
97
+ const anchors = [...new Set(operational.implementationAnchors ?? [])].sort();
98
+ const reasons = [
99
+ ...(lexical[i] > 0 ? ['bm25'] : []),
100
+ ...(semanticScore !== undefined ? ['semantic-candidate'] : []),
101
+ ...(contentTerms.length > 0 ? ['content-supported'] : ['content-unsupported']),
102
+ ...(approved ? ['approved-lineage'] : ['lineage-not-approved']),
103
+ ...(anchors.length > 0 ? ['implementation-anchors'] : ['implementation-anchors-absent']),
104
+ ...(operational.freshGreenTests === true ? ['fresh-green-execution'] : ['fresh-green-execution-absent']),
105
+ ...(operational.contradictory === true ? ['contradictory-evidence'] : []),
106
+ ];
107
+ return { reqId: row.reqId, documents: row.docs, lexicalScore: lexical[i],
108
+ ...(semanticScore !== undefined ? { semanticScore } : {}), contentTerms, approved,
109
+ implementationAnchors: anchors, freshGreenTests: operational.freshGreenTests === true, reasons };
110
+ }).filter((candidate) => candidate !== null)
111
+ .sort((a, b) => Math.max(b.lexicalScore, b.semanticScore ?? 0) - Math.max(a.lexicalScore, a.semanticScore ?? 0)
112
+ || a.reqId.localeCompare(b.reqId));
113
+ const candidates = allCandidates.slice(0, rankLimit(input.topK));
114
+ const semanticInadequate = input.semantic !== undefined
115
+ && input.semantic.state !== 'covered' && input.semantic.state !== 'not-adopted';
116
+ const graphInadequate = input.graph !== undefined && input.graph.state !== 'current';
117
+ if (graphInadequate)
118
+ return { verdict: 'ambiguous', candidates, reasons: ['graph-coverage-inadequate'], uncertainty: ['graph-coverage-inadequate'] };
119
+ if (semanticInadequate)
120
+ return { verdict: 'ambiguous', candidates, reasons: ['semantic-coverage-inadequate'], uncertainty: ['semantic-coverage-inadequate'] };
121
+ if (allCandidates.length === 0)
122
+ return { verdict: 'new', candidates, reasons: ['semantic-coverage-not-required-for-bm25-baseline'], uncertainty: ['semantic-coverage-not-required-for-bm25-baseline'] };
123
+ const top = allCandidates[0];
124
+ const topScore = Math.max(top.lexicalScore, top.semanticScore ?? 0);
125
+ const tied = allCandidates.filter((c) => Math.max(c.lexicalScore, c.semanticScore ?? 0) === topScore);
126
+ if (tied.length > 1 || top.contentTerms.length === 0 || top.reasons.includes('contradictory-evidence')) {
127
+ const uncertainty = [
128
+ ...(tied.length > 1 ? ['tied-candidates'] : []),
129
+ ...(top.contentTerms.length === 0 ? ['candidate-content-unsupported'] : []),
130
+ ...(top.reasons.includes('contradictory-evidence') ? ['contradictory-evidence'] : []),
131
+ ];
132
+ return { verdict: 'ambiguous', candidates, reasons: uncertainty, uncertainty };
133
+ }
134
+ if (top.approved && top.implementationAnchors.length > 0 && top.freshGreenTests) {
135
+ return { verdict: 'fulfilled', candidates, reasons: ['approved-lineage', 'implementation-anchors', 'fresh-green-execution'], uncertainty: [] };
136
+ }
137
+ const uncertainty = [
138
+ ...(top.approved ? [] : ['lineage-not-approved']),
139
+ ...(top.implementationAnchors.length > 0 ? [] : ['implementation-anchors-absent']),
140
+ ...(top.freshGreenTests ? [] : ['fresh-green-execution-absent']),
141
+ ];
142
+ return { verdict: 'existing-change', candidates, reasons: ['supported-existing-lineage', ...uncertainty], uncertainty };
143
+ }
@@ -36,7 +36,12 @@ function obligationGapsFor(specs, impactedSpecIds) {
36
36
  const parent = specs.find((s) => s.type === 'H-SPEC' && (a.dependsOn ?? []).includes(s.id));
37
37
  if (!parent)
38
38
  continue;
39
- const tspecs = specs.filter((s) => s.type === 'T-SPEC' && (s.dependsOn ?? []).includes(a.id));
39
+ const siblingAspecIds = new Set(specs
40
+ .filter((s) => s.type === 'A-SPEC' && s.status === 'approved' && (s.dependsOn ?? []).includes(parent.id))
41
+ .map((s) => s.id));
42
+ // The impacted slice's own T-SPECs count as they always did; approved siblings only add to them.
43
+ const tspecs = specs.filter((s) => s.type === 'T-SPEC' && ((s.dependsOn ?? []).includes(a.id)
44
+ || (s.status === 'approved' && (s.dependsOn ?? []).some((id) => siblingAspecIds.has(id)))));
40
45
  for (const o of (0, nonfunctional_1.unmetObligations)(parent.sections?.['Non-Functional'] ?? '', tspecs.map((t) => t.sections ?? {}))) {
41
46
  out.push(`${a.id} [${o.tag}]`);
42
47
  }
@@ -1,6 +1,34 @@
1
1
  import { ExecutionContext } from '../project/execution-context';
2
2
  import { TestOutcome } from './test-runner';
3
3
  export declare const OUTCOMES_FILE: string;
4
+ export declare const RELEASE_TEST_LANE_FILE: string;
5
+ export declare const RELEASE_TEST_LANE_SCHEMA: "release-test-lane/1";
6
+ export interface ReleaseTestLaneReceipt {
7
+ schema: typeof RELEASE_TEST_LANE_SCHEMA;
8
+ root: string;
9
+ head: string;
10
+ completedAt: string;
11
+ passed: true;
12
+ externalAccess: 'forbidden';
13
+ command: string[];
14
+ include: string[];
15
+ exclusions: Array<{
16
+ pattern: string;
17
+ reason: string;
18
+ }>;
19
+ digest: string;
20
+ }
21
+ export type ReleaseTestLaneValidation = {
22
+ valid: true;
23
+ receipt: ReleaseTestLaneReceipt;
24
+ } | {
25
+ valid: false;
26
+ reason: string;
27
+ };
28
+ /** Persist only evidence whose scope is explicit and bounded; callers cannot choose its path. */
29
+ export declare function writeReleaseTestLaneReceipt(root: string, input: Omit<ReleaseTestLaneReceipt, 'schema' | 'digest'>): ReleaseTestLaneReceipt | null;
30
+ /** Read the sole project-local receipt and fail closed for every missing or unprovable condition. */
31
+ export declare function validateReleaseTestLaneReceipt(root: string, head: string, now?: number): ReleaseTestLaneValidation;
4
32
  export declare function outcomesFilename(replica: string): string;
5
33
  export declare function isOutcomesFilename(name: string): boolean;
6
34
  /**
@@ -33,20 +33,109 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.OUTCOMES_FILE = void 0;
36
+ exports.RELEASE_TEST_LANE_SCHEMA = exports.RELEASE_TEST_LANE_FILE = exports.OUTCOMES_FILE = void 0;
37
+ exports.writeReleaseTestLaneReceipt = writeReleaseTestLaneReceipt;
38
+ exports.validateReleaseTestLaneReceipt = validateReleaseTestLaneReceipt;
37
39
  exports.outcomesFilename = outcomesFilename;
38
40
  exports.isOutcomesFilename = isOutcomesFilename;
39
41
  exports.appendOutcomes = appendOutcomes;
40
42
  exports.readOutcomes = readOutcomes;
41
43
  exports.buildOutcomeRecords = buildOutcomeRecords;
42
44
  exports.groupOutcomesByAspec = groupOutcomesByAspec;
45
+ // @implements A-SPEC-724.1, A-SPEC-714
43
46
  // @implements A-SPEC-534.3, A-SPEC-625
44
47
  // @implements A-SPEC-645
48
+ const node_crypto_1 = require("node:crypto");
45
49
  const execution_context_1 = require("../project/execution-context");
46
50
  const fs = __importStar(require("node:fs"));
47
51
  const path = __importStar(require("node:path"));
48
52
  const replica_id_1 = require("../governance/replica-id");
49
53
  exports.OUTCOMES_FILE = path.join('.ax', 'ledger', 'test-outcomes.jsonl');
54
+ exports.RELEASE_TEST_LANE_FILE = path.join('.ax', 'evidence', 'release-test-lane.json');
55
+ exports.RELEASE_TEST_LANE_SCHEMA = 'release-test-lane/1';
56
+ const RELEASE_TEST_LANE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
57
+ const stableReceipt = (receipt) => JSON.stringify({
58
+ schema: receipt.schema, root: receipt.root, head: receipt.head, completedAt: receipt.completedAt,
59
+ passed: receipt.passed, externalAccess: receipt.externalAccess, command: receipt.command,
60
+ include: receipt.include, exclusions: receipt.exclusions,
61
+ });
62
+ const releaseReceiptDigest = (receipt) => `sha256:${(0, node_crypto_1.createHash)('sha256').update(stableReceipt(receipt)).digest('hex')}`;
63
+ /** Persist only evidence whose scope is explicit and bounded; callers cannot choose its path. */
64
+ function writeReleaseTestLaneReceipt(root, input) {
65
+ // The writer owns the current schema; only persisted input is required to
66
+ // state it explicitly so an older or unknown schema cannot be reinterpreted.
67
+ const receipt = normalizeReleaseTestLaneReceipt(root, { ...input, schema: exports.RELEASE_TEST_LANE_SCHEMA });
68
+ if (receipt === null)
69
+ return null;
70
+ const file = path.join(path.resolve(root), exports.RELEASE_TEST_LANE_FILE);
71
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
72
+ try {
73
+ fs.mkdirSync(path.dirname(file), { recursive: true });
74
+ fs.writeFileSync(tmp, `${JSON.stringify(receipt)}\n`, { encoding: 'utf8', mode: 0o600 });
75
+ fs.renameSync(tmp, file);
76
+ return receipt;
77
+ }
78
+ catch {
79
+ try {
80
+ fs.unlinkSync(tmp);
81
+ }
82
+ catch { /* no partial receipt is valid */ }
83
+ return null;
84
+ }
85
+ }
86
+ /** Read the sole project-local receipt and fail closed for every missing or unprovable condition. */
87
+ function validateReleaseTestLaneReceipt(root, head, now = Date.now()) {
88
+ const expectedRoot = path.resolve(root);
89
+ if (typeof head !== 'string' || head === '' || head.includes('/') || head.includes('\\'))
90
+ return { valid: false, reason: 'invalid current HEAD' };
91
+ let parsed;
92
+ try {
93
+ parsed = JSON.parse(fs.readFileSync(path.join(expectedRoot, exports.RELEASE_TEST_LANE_FILE), 'utf8'));
94
+ }
95
+ catch {
96
+ return { valid: false, reason: 'release test-lane receipt is absent or malformed' };
97
+ }
98
+ const receipt = normalizeReleaseTestLaneReceipt(expectedRoot, parsed);
99
+ if (receipt === null)
100
+ return { valid: false, reason: 'release test-lane receipt omits required bounded scope or policy' };
101
+ if (receipt.digest !== parsed.digest)
102
+ return { valid: false, reason: 'release test-lane receipt digest is invalid' };
103
+ if (receipt.root !== expectedRoot)
104
+ return { valid: false, reason: 'release test-lane receipt belongs to a different root' };
105
+ if (receipt.head !== head)
106
+ return { valid: false, reason: 'release test-lane receipt HEAD does not match' };
107
+ const completedMs = Date.parse(receipt.completedAt);
108
+ if (!Number.isFinite(completedMs) || completedMs > now || now - completedMs > RELEASE_TEST_LANE_MAX_AGE_MS) {
109
+ return { valid: false, reason: 'release test-lane receipt is stale or has an invalid timestamp' };
110
+ }
111
+ return { valid: true, receipt };
112
+ }
113
+ function normalizeReleaseTestLaneReceipt(root, input) {
114
+ if (!input || typeof input !== 'object')
115
+ return null;
116
+ const value = input;
117
+ const rootPath = path.resolve(root);
118
+ if (value.schema !== exports.RELEASE_TEST_LANE_SCHEMA
119
+ || typeof value.root !== 'string' || path.resolve(value.root) !== rootPath || value.root !== rootPath
120
+ || typeof value.head !== 'string' || value.head === '' || /[\\/]/.test(value.head)
121
+ || typeof value.completedAt !== 'string' || !Number.isFinite(Date.parse(value.completedAt))
122
+ || value.passed !== true || value.externalAccess !== 'forbidden')
123
+ return null;
124
+ if (!Array.isArray(value.command) || value.command.some((part) => typeof part !== 'string' || part === '')
125
+ || value.command.length < 5 || value.command[0] !== 'npm' || value.command[1] !== 'test'
126
+ || value.command[2] !== '--' || !value.command.includes('--runInBand')
127
+ || !value.command.some((part) => part.startsWith('--testPathIgnorePatterns=')))
128
+ return null;
129
+ if (!Array.isArray(value.include) || value.include.length === 0 || value.include.some((part) => typeof part !== 'string' || part.trim() === ''))
130
+ return null;
131
+ if (!Array.isArray(value.exclusions) || value.exclusions.length === 0 || value.exclusions.some((entry) => !entry || typeof entry.pattern !== 'string'
132
+ || entry.pattern.trim() === '' || entry.pattern.includes('..') || typeof entry.reason !== 'string' || entry.reason.trim() === ''))
133
+ return null;
134
+ const unsigned = { schema: exports.RELEASE_TEST_LANE_SCHEMA, root: rootPath, head: value.head, completedAt: value.completedAt,
135
+ passed: true, externalAccess: 'forbidden', command: [...value.command], include: [...value.include],
136
+ exclusions: value.exclusions.map((entry) => ({ pattern: entry.pattern, reason: entry.reason })) };
137
+ return { ...unsigned, digest: releaseReceiptDigest(unsigned) };
138
+ }
50
139
  // @implements A-SPEC-562.1 — outcomes join the ledger's REPLICA convention (A-SPEC-148): one file per
51
140
  // machine, so two machines appending never conflict on merge and a colleague's clone carries both
52
141
  // histories. The shape mirrors `isLedgerFilename` exactly — legacy single file OR a dot-free segment —
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { modelCacheDir, modelCacheReady } from './model-cache';
3
- export { modelCacheDir, modelCacheReady };
4
- export declare const LOCAL_REVISION = "4de13258303883538bd53b696b452bf8099f0858";
2
+ import { LOCAL_REVISION, modelCacheDir, modelCacheReady, readLocalModelReadiness } from './model-cache';
3
+ export { modelCacheDir, modelCacheReady, readLocalModelReadiness };
4
+ export { LOCAL_REVISION };
5
5
  type Pipeline = (text: string, options: {
6
6
  pooling: string;
7
7
  normalize: boolean;
@@ -1,16 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOCAL_REVISION = exports.modelCacheReady = exports.modelCacheDir = void 0;
3
+ exports.LOCAL_REVISION = exports.readLocalModelReadiness = exports.modelCacheReady = exports.modelCacheDir = void 0;
4
4
  exports.loadLocalPipeline = loadLocalPipeline;
5
5
  exports.verifyLocalModel = verifyLocalModel;
6
6
  exports.runModelSetup = runModelSetup;
7
- // @implements A-SPEC-591
7
+ // @implements A-SPEC-591, A-SPEC-712
8
8
  const node_child_process_1 = require("node:child_process");
9
9
  const tier_1 = require("./tier");
10
10
  const model_cache_1 = require("./model-cache");
11
+ Object.defineProperty(exports, "LOCAL_REVISION", { enumerable: true, get: function () { return model_cache_1.LOCAL_REVISION; } });
11
12
  Object.defineProperty(exports, "modelCacheDir", { enumerable: true, get: function () { return model_cache_1.modelCacheDir; } });
12
13
  Object.defineProperty(exports, "modelCacheReady", { enumerable: true, get: function () { return model_cache_1.modelCacheReady; } });
13
- exports.LOCAL_REVISION = '4de13258303883538bd53b696b452bf8099f0858';
14
+ Object.defineProperty(exports, "readLocalModelReadiness", { enumerable: true, get: function () { return model_cache_1.readLocalModelReadiness; } });
14
15
  // TypeScript's CommonJS transform rewrites import() into require(), which cannot load this ESM
15
16
  // dependency on supported Node 20 versions. Preserve native dynamic import without shell code.
16
17
  const importRuntime = new Function('return import("@xenova/transformers")');
@@ -29,7 +30,7 @@ async function loadLocalPipeline(model = tier_1.LOCAL_MODEL, options = {}) {
29
30
  return existing;
30
31
  const pending = importer().then(runtime => runtime.pipeline('feature-extraction', model, {
31
32
  quantized: true,
32
- revision: model === tier_1.LOCAL_MODEL ? exports.LOCAL_REVISION : 'main',
33
+ revision: model === tier_1.LOCAL_MODEL ? model_cache_1.LOCAL_REVISION : 'main',
33
34
  cache_dir: cacheDir,
34
35
  local_files_only: !options.download,
35
36
  })).catch(error => { cache.delete(key); throw error; });
@@ -45,6 +46,9 @@ async function verifyLocalModel(options = {}) {
45
46
  if (data.length !== 1024 || !Array.from(data).every(Number.isFinite) || Math.abs(norm - 1) > 0.001) {
46
47
  return { ready: false, dimension: data.length, message: 'BGE-M3 produced an invalid embedding. Select a clean HOLMES_MODEL_CACHE and run holmes-kit semantic-setup.' };
47
48
  }
49
+ const receipt = (0, model_cache_1.writeVerifiedModelReceipt)(options.cacheDir ?? (0, model_cache_1.modelCacheDir)());
50
+ if (!receipt.ready)
51
+ return { ready: false, dimension: data.length, message: `BGE-M3 inference passed but ${receipt.recovery}` };
48
52
  return { ready: true, dimension: data.length, message: 'BGE-M3 ready: verified 1024-dimensional normalized local embedding.' };
49
53
  }
50
54
  catch (error) {
@@ -57,19 +61,13 @@ async function verifyLocalModel(options = {}) {
57
61
  /** Isolate setup from the MCP and bound slow downloads/inference; all platforms share this path. */
58
62
  function runModelSetup(options = {}) {
59
63
  const env = options.env ?? process.env;
60
- // @implements A-SPEC-594 — the automatic path does not start a large download the user did not
61
- // ask for. An explicit refusal outranks an opt-in: someone who set SKIP meant it, and reading
62
- // AUTO as permission to override that would silently reverse their decision. The two skips say
63
- // DIFFERENT things, because telling a user "you opted out" when they never did is a lie.
64
+ // @implements A-SPEC-712 — normal package installation prepares the public model by default.
65
+ // Explicit SKIP remains the only automatic opt-out; legacy AUTO is ignored.
64
66
  if (options.automatic) {
65
67
  if (env.HOLMES_SKIP_MODEL_INSTALL === '1') {
66
68
  process.stderr.write('BGE-M3 automatic setup skipped (HOLMES_SKIP_MODEL_INSTALL=1). Run holmes-kit semantic-setup when ready.\n');
67
69
  return 0;
68
70
  }
69
- if (env.HOLMES_AUTO_MODEL_INSTALL !== '1') {
70
- process.stderr.write('BGE-M3 is not prepared automatically. Run `holmes-kit semantic-setup` to download the public model once (shared across projects), or set HOLMES_AUTO_MODEL_INSTALL=1 to prepare it during installation. Graph features work without it.\n');
71
- return 0;
72
- }
73
71
  }
74
72
  process.stderr.write(options.offline ? 'Checking BGE-M3 offline...\n' : 'Preparing BGE-M3 (public model download on first installation)...\n');
75
73
  const result = (options.spawn ?? node_child_process_1.spawnSync)(process.execPath, [__filename, '--worker', ...(options.offline ? ['--offline'] : [])], { env, stdio: 'inherit', timeout: 900_000, windowsHide: true });
@@ -1,8 +1,17 @@
1
+ export declare const LOCAL_MODEL = "Xenova/bge-m3";
2
+ export declare const LOCAL_REVISION = "4de13258303883538bd53b696b452bf8099f0858";
3
+ export type LocalModelState = 'verified' | 'missing-cache' | 'unverified-cache' | 'invalid-receipt' | 'stale-receipt';
4
+ export interface LocalModelReadiness {
5
+ ready: boolean;
6
+ state: LocalModelState;
7
+ recovery: string;
8
+ }
1
9
  export declare function modelCacheDir(env?: NodeJS.ProcessEnv, home?: string): string;
2
- /**
3
- * Ready means the cache holds SOMETHING. An interrupted download leaves the directory created
4
- * and empty, and reading that as ready is the whole failure mode this predicate exists to stop.
5
- * Proof of a working model is `semantic-check`'s actual inference — deliberately not here, because
6
- * doctor calls this on every run and must stay cheap and offline.
7
- */
10
+ /** A metadata fingerprint cheap enough for offline tier resolution. */
11
+ export declare function modelCacheFingerprint(cacheDir?: string): string | null;
12
+ /** Missing or malformed proof is never promoted to readiness. */
13
+ export declare function readLocalModelReadiness(cacheDir?: string): LocalModelReadiness;
14
+ /** Only successful actual inference may write the same-directory atomic receipt. */
15
+ export declare function writeVerifiedModelReceipt(cacheDir?: string): LocalModelReadiness;
16
+ /** Compatibility boolean: actual verified inference, never directory presence. */
8
17
  export declare function modelCacheReady(cacheDir?: string): boolean;
@@ -33,35 +33,91 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.LOCAL_REVISION = exports.LOCAL_MODEL = void 0;
36
37
  exports.modelCacheDir = modelCacheDir;
38
+ exports.modelCacheFingerprint = modelCacheFingerprint;
39
+ exports.readLocalModelReadiness = readLocalModelReadiness;
40
+ exports.writeVerifiedModelReceipt = writeVerifiedModelReceipt;
37
41
  exports.modelCacheReady = modelCacheReady;
38
- // @implements A-SPEC-594
39
- /**
40
- * Where the local model's assets live, and whether they are actually there.
41
- *
42
- * A leaf on purpose: `tier.ts` must consult readiness, and `local-model.ts` already imports
43
- * `tier.ts`, so putting this in either one closes an import cycle. Nothing here imports
44
- * anything of ours.
45
- */
42
+ // @implements A-SPEC-594, A-SPEC-712
43
+ /** Shared local-model cache and its lightweight verified-readiness receipt. */
44
+ const crypto = __importStar(require("node:crypto"));
45
+ const fs = __importStar(require("node:fs"));
46
46
  const os = __importStar(require("node:os"));
47
47
  const path = __importStar(require("node:path"));
48
- const fs = __importStar(require("node:fs"));
48
+ exports.LOCAL_MODEL = 'Xenova/bge-m3';
49
+ exports.LOCAL_REVISION = '4de13258303883538bd53b696b452bf8099f0858';
50
+ const RECEIPT_FILE = '.holmes-bge-m3-readiness.json';
51
+ const RECEIPT_SCHEMA = 'holmes-local-model-readiness/1';
49
52
  function modelCacheDir(env = process.env, home = os.homedir()) {
50
53
  return path.resolve(env.HOLMES_MODEL_CACHE || path.join(home, '.holmes', 'models'));
51
54
  }
52
- /**
53
- * Ready means the cache holds SOMETHING. An interrupted download leaves the directory created
54
- * and empty, and reading that as ready is the whole failure mode this predicate exists to stop.
55
- * Proof of a working model is `semantic-check`'s actual inference — deliberately not here, because
56
- * doctor calls this on every run and must stay cheap and offline.
57
- */
58
- function modelCacheReady(cacheDir = modelCacheDir()) {
59
- if (cacheDir === '')
60
- return false;
55
+ function assetEntries(cacheDir) {
56
+ try {
57
+ const rows = [];
58
+ const visit = (dir, prefix) => {
59
+ for (const name of fs.readdirSync(dir).sort()) {
60
+ if (prefix === '' && name === RECEIPT_FILE)
61
+ continue;
62
+ const absolute = path.join(dir, name), relative = prefix ? `${prefix}/${name}` : name, stat = fs.statSync(absolute);
63
+ if (stat.isDirectory())
64
+ visit(absolute, relative);
65
+ else if (stat.isFile())
66
+ rows.push(`${relative}:${stat.size}:${Math.floor(stat.mtimeMs)}`);
67
+ }
68
+ };
69
+ visit(cacheDir, '');
70
+ return rows;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ /** A metadata fingerprint cheap enough for offline tier resolution. */
77
+ function modelCacheFingerprint(cacheDir = modelCacheDir()) {
78
+ const entries = assetEntries(cacheDir);
79
+ return entries === null || entries.length === 0 ? null
80
+ : `sha256:${crypto.createHash('sha256').update(entries.join('\n')).digest('hex')}`;
81
+ }
82
+ const receiptPath = (cacheDir) => path.join(cacheDir, RECEIPT_FILE);
83
+ /** Missing or malformed proof is never promoted to readiness. */
84
+ function readLocalModelReadiness(cacheDir = modelCacheDir()) {
85
+ const fingerprint = modelCacheFingerprint(cacheDir);
86
+ if (fingerprint === null)
87
+ return { ready: false, state: 'missing-cache', recovery: 'Run holmes-kit semantic-setup to download and verify BGE-M3.' };
88
+ let receipt;
89
+ try {
90
+ receipt = JSON.parse(fs.readFileSync(receiptPath(cacheDir), 'utf8'));
91
+ }
92
+ catch {
93
+ return { ready: false, state: 'unverified-cache', recovery: 'Run holmes-kit semantic-setup to verify the existing BGE-M3 cache offline.' };
94
+ }
95
+ if (receipt.schema !== RECEIPT_SCHEMA || receipt.model !== exports.LOCAL_MODEL || receipt.revision !== exports.LOCAL_REVISION || typeof receipt.fingerprint !== 'string') {
96
+ return { ready: false, state: 'invalid-receipt', recovery: 'Run holmes-kit semantic-setup to replace the invalid BGE-M3 readiness receipt.' };
97
+ }
98
+ if (receipt.fingerprint !== fingerprint)
99
+ return { ready: false, state: 'stale-receipt', recovery: 'Run holmes-kit semantic-setup to re-verify the changed BGE-M3 cache.' };
100
+ return { ready: true, state: 'verified', recovery: '' };
101
+ }
102
+ /** Only successful actual inference may write the same-directory atomic receipt. */
103
+ function writeVerifiedModelReceipt(cacheDir = modelCacheDir()) {
104
+ const fingerprint = modelCacheFingerprint(cacheDir);
105
+ if (fingerprint === null)
106
+ return { ready: false, state: 'missing-cache', recovery: 'Run holmes-kit semantic-setup to download and verify BGE-M3.' };
107
+ const target = receiptPath(cacheDir), temp = `${target}.${process.pid}.tmp`;
61
108
  try {
62
- return fs.readdirSync(cacheDir).length > 0;
109
+ fs.mkdirSync(cacheDir, { recursive: true });
110
+ fs.writeFileSync(temp, JSON.stringify({ schema: RECEIPT_SCHEMA, model: exports.LOCAL_MODEL, revision: exports.LOCAL_REVISION, fingerprint }));
111
+ fs.renameSync(temp, target);
63
112
  }
64
113
  catch {
65
- return false;
66
- } // absent, unreadable, not a directory — none of them are ready
114
+ try {
115
+ fs.rmSync(temp, { force: true });
116
+ }
117
+ catch { /* best effort */ }
118
+ return { ready: false, state: 'invalid-receipt', recovery: 'Check HOLMES_MODEL_CACHE permissions, then run holmes-kit semantic-setup.' };
119
+ }
120
+ return readLocalModelReadiness(cacheDir);
67
121
  }
122
+ /** Compatibility boolean: actual verified inference, never directory presence. */
123
+ function modelCacheReady(cacheDir = modelCacheDir()) { return readLocalModelReadiness(cacheDir).ready; }
@@ -11,8 +11,9 @@
11
11
  * network; presence signals only, so doctor can call it offline.
12
12
  */
13
13
  import { type CredentialOpts, type KeySource } from './credentials';
14
+ import { LOCAL_MODEL, type LocalModelReadiness } from './model-cache';
14
15
  /** The local tier's model. CLS-pooled — see POOLING_OF. */
15
- export declare const LOCAL_MODEL = "Xenova/bge-m3";
16
+ export { LOCAL_MODEL };
16
17
  /** The opt-in cloud tier's model (S-491 four-arm winner). */
17
18
  export declare const CLOUD_MODEL = "gemini-embedding-001";
18
19
  export interface SemanticTier {
@@ -28,6 +29,8 @@ export interface SemanticTier {
28
29
  * because reporting this one as 'local' claims a recall the tier cannot deliver.
29
30
  */
30
31
  localRuntimePresent?: boolean;
32
+ /** Why local BGE-M3 was not activated, when readiness was observed. */
33
+ localState?: LocalModelReadiness['state'];
31
34
  }
32
35
  /**
33
36
  * Which pooling a model's dense head expects. bge-m3 is CLS-pooled: mean-pooling it was the
@@ -40,5 +43,6 @@ export declare function resolveSemanticTier(opts?: {
40
43
  env?: NodeJS.ProcessEnv;
41
44
  hasLocalModule?: boolean;
42
45
  hasLocalModel?: boolean;
46
+ localReadiness?: LocalModelReadiness;
43
47
  credentials?: CredentialOpts;
44
48
  }): SemanticTier;
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // @implements A-SPEC-476
2
+ // @implements A-SPEC-476, A-SPEC-712
3
3
  /**
4
4
  * The semantic layer's tier structure — the owner's two-lever design made a contract:
5
5
  * maximize what the harness can do WITHOUT egress (a local model), and let an explicit opt-in
@@ -18,8 +18,7 @@ exports.POOLING_OF = POOLING_OF;
18
18
  exports.resolveSemanticTier = resolveSemanticTier;
19
19
  const credentials_1 = require("./credentials");
20
20
  const model_cache_1 = require("./model-cache");
21
- /** The local tier's model. CLS-pooled — see POOLING_OF. */
22
- exports.LOCAL_MODEL = 'Xenova/bge-m3';
21
+ Object.defineProperty(exports, "LOCAL_MODEL", { enumerable: true, get: function () { return model_cache_1.LOCAL_MODEL; } });
23
22
  /** The opt-in cloud tier's model (S-491 four-arm winner). */
24
23
  exports.CLOUD_MODEL = 'gemini-embedding-001';
25
24
  /**
@@ -53,8 +52,10 @@ function resolveSemanticTier(opts = {}) {
53
52
  // discriminating; a resolvable runtime with no model produces no embedding at all. Wiring
54
53
  // presence is not readiness.
55
54
  const hasModule = opts.hasLocalModule ?? localModulePresent();
56
- const hasModel = opts.hasLocalModel ?? (0, model_cache_1.modelCacheReady)();
55
+ const observed = opts.localReadiness ?? (opts.hasLocalModel === undefined ? (0, model_cache_1.readLocalModelReadiness)() : undefined);
56
+ const hasModel = opts.hasLocalModel ?? observed?.ready ?? false;
57
57
  if (hasModule && hasModel)
58
- return { tier: 'local', model: exports.LOCAL_MODEL, egress: false };
59
- return { tier: 'none', egress: false, ...(hasModule ? { localRuntimePresent: true } : {}) };
58
+ return { tier: 'local', model: model_cache_1.LOCAL_MODEL, egress: false };
59
+ return { tier: 'none', egress: false, ...(hasModule ? { localRuntimePresent: true } : {}),
60
+ ...(hasModule && observed && !observed.ready ? { localState: observed.state } : {}) };
60
61
  }
@@ -20,6 +20,15 @@ export interface ScannedLike {
20
20
  qualifiedName: string;
21
21
  }>;
22
22
  }
23
+ /** The governed fields which contribute to a requirement-document vector. */
24
+ export interface RequirementDocumentLike {
25
+ id: string;
26
+ type: string;
27
+ title: string;
28
+ status: string;
29
+ dependsOn?: readonly string[];
30
+ sections?: Readonly<Record<string, string>>;
31
+ }
23
32
  export type CoverageState = 'covered' | 'inert' | 'not-adopted' | 'unknown';
24
33
  export interface CoverageInput {
25
34
  /** The RESOLVED tier. `none` is the shipped default (zero egress) and means never opted in. */
@@ -50,6 +59,14 @@ export declare const DOC_TEXT_LIMIT = 2000;
50
59
  export declare function docTextOf(file: ScannedLike): string;
51
60
  /** The same text, indexed by source path — the form the three ranking passes consume. */
52
61
  export declare function docTextIndex(scanned: ReadonlyArray<ScannedLike>): Map<string, string>;
62
+ /** A requirement vector has its own versioned namespace and cannot share a source-file key. */
63
+ export declare function canonicalRequirementDocument(doc: RequirementDocumentLike, lineageId: string): string;
64
+ /** Every eligible REQ/H/A/T document paired with its REQ lineage and cache text. */
65
+ export declare function requirementDocumentTexts<T extends RequirementDocumentLike>(documents: readonly T[]): Array<{
66
+ document: T;
67
+ lineageId: string;
68
+ text: string;
69
+ }>;
53
70
  /**
54
71
  * Pure: the caller supplies the counts. Keeping the filesystem out means the judgement is testable
55
72
  * without a cache on disk, and it cannot be wrong about ordering or locking.