@seanhogg/builderforce-memory 2026.10.70 → 2026.10.72
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.
- package/dist/knowledge/build.d.ts +3 -1
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +5 -1
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/coChange.d.ts +106 -0
- package/dist/knowledge/coChange.d.ts.map +1 -0
- package/dist/knowledge/coChange.js +309 -0
- package/dist/knowledge/coChange.js.map +1 -0
- package/dist/knowledge/communities.d.ts +2 -0
- package/dist/knowledge/communities.d.ts.map +1 -1
- package/dist/knowledge/communities.js +5 -1
- package/dist/knowledge/communities.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +10 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +16 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +18 -1
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +10 -4
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/facts/extractorVersion.d.ts +45 -0
- package/dist/knowledge/facts/extractorVersion.d.ts.map +1 -0
- package/dist/knowledge/facts/extractorVersion.js +56 -0
- package/dist/knowledge/facts/extractorVersion.js.map +1 -0
- package/dist/knowledge/facts/fileFacts.d.ts +166 -0
- package/dist/knowledge/facts/fileFacts.d.ts.map +1 -0
- package/dist/knowledge/facts/fileFacts.js +156 -0
- package/dist/knowledge/facts/fileFacts.js.map +1 -0
- package/dist/knowledge/findings.d.ts +17 -14
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +29 -129
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/index.d.ts +17 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +10 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/model.d.ts +6 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +2 -0
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +14 -4
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js +30 -8
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/plan.d.ts +10 -1
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +9 -4
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/refs.d.ts.map +1 -1
- package/dist/knowledge/refs.js +3 -1
- package/dist/knowledge/refs.js.map +1 -1
- package/dist/knowledge/review.js +1 -0
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewContext.d.ts.map +1 -1
- package/dist/knowledge/reviewContext.js +5 -2
- package/dist/knowledge/reviewContext.js.map +1 -1
- package/dist/knowledge/reviewFinish.d.ts.map +1 -1
- package/dist/knowledge/reviewFinish.js +3 -1
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +12 -0
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +2 -0
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +1 -0
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/rules/cloneGroup.d.ts +10 -0
- package/dist/knowledge/rules/cloneGroup.d.ts.map +1 -0
- package/dist/knowledge/rules/cloneGroup.js +46 -0
- package/dist/knowledge/rules/cloneGroup.js.map +1 -0
- package/dist/knowledge/rules/components.d.ts +8 -0
- package/dist/knowledge/rules/components.d.ts.map +1 -0
- package/dist/knowledge/rules/components.js +34 -0
- package/dist/knowledge/rules/components.js.map +1 -0
- package/dist/knowledge/rules/cycle.d.ts +7 -0
- package/dist/knowledge/rules/cycle.d.ts.map +1 -0
- package/dist/knowledge/rules/cycle.js +18 -0
- package/dist/knowledge/rules/cycle.js.map +1 -0
- package/dist/knowledge/rules/duplicateCopy.d.ts +7 -0
- package/dist/knowledge/rules/duplicateCopy.d.ts.map +1 -0
- package/dist/knowledge/rules/duplicateCopy.js +18 -0
- package/dist/knowledge/rules/duplicateCopy.js.map +1 -0
- package/dist/knowledge/rules/evaluateRules.d.ts +60 -0
- package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -0
- package/dist/knowledge/rules/evaluateRules.js +164 -0
- package/dist/knowledge/rules/evaluateRules.js.map +1 -0
- package/dist/knowledge/rules/factGraph.d.ts +51 -0
- package/dist/knowledge/rules/factGraph.d.ts.map +1 -0
- package/dist/knowledge/rules/factGraph.js +77 -0
- package/dist/knowledge/rules/factGraph.js.map +1 -0
- package/dist/knowledge/rules/factRule.d.ts +56 -0
- package/dist/knowledge/rules/factRule.d.ts.map +1 -0
- package/dist/knowledge/rules/factRule.js +46 -0
- package/dist/knowledge/rules/factRule.js.map +1 -0
- package/dist/knowledge/rules/godModule.d.ts +8 -0
- package/dist/knowledge/rules/godModule.d.ts.map +1 -0
- package/dist/knowledge/rules/godModule.js +16 -0
- package/dist/knowledge/rules/godModule.js.map +1 -0
- package/dist/knowledge/rules/knowledgeInput.d.ts +35 -0
- package/dist/knowledge/rules/knowledgeInput.d.ts.map +1 -0
- package/dist/knowledge/rules/knowledgeInput.js +33 -0
- package/dist/knowledge/rules/knowledgeInput.js.map +1 -0
- package/dist/knowledge/rules/nearDuplicate.d.ts +7 -0
- package/dist/knowledge/rules/nearDuplicate.d.ts.map +1 -0
- package/dist/knowledge/rules/nearDuplicate.js +20 -0
- package/dist/knowledge/rules/nearDuplicate.js.map +1 -0
- package/dist/knowledge/rules/partitionViolation.d.ts +10 -0
- package/dist/knowledge/rules/partitionViolation.d.ts.map +1 -0
- package/dist/knowledge/rules/partitionViolation.js +27 -0
- package/dist/knowledge/rules/partitionViolation.js.map +1 -0
- package/dist/knowledge/rules/possibleSame.d.ts +7 -0
- package/dist/knowledge/rules/possibleSame.d.ts.map +1 -0
- package/dist/knowledge/rules/possibleSame.js +15 -0
- package/dist/knowledge/rules/possibleSame.js.map +1 -0
- package/dist/knowledge/rules/stale.d.ts +7 -0
- package/dist/knowledge/rules/stale.d.ts.map +1 -0
- package/dist/knowledge/rules/stale.js +28 -0
- package/dist/knowledge/rules/stale.js.map +1 -0
- package/dist/knowledge/rules/unpartitioned.d.ts +7 -0
- package/dist/knowledge/rules/unpartitioned.d.ts.map +1 -0
- package/dist/knowledge/rules/unpartitioned.js +26 -0
- package/dist/knowledge/rules/unpartitioned.js.map +1 -0
- package/dist/knowledge/sources.d.ts +14 -1
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +17 -1
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/transitions.d.ts +59 -0
- package/dist/knowledge/transitions.d.ts.map +1 -0
- package/dist/knowledge/transitions.js +90 -0
- package/dist/knowledge/transitions.js.map +1 -0
- package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/sha256.js +2 -2
- package/dist/retrieval/knowledge-index/sha256.js.map +1 -1
- package/dist/stats/distributions.d.ts +40 -2
- package/dist/stats/distributions.d.ts.map +1 -1
- package/dist/stats/distributions.js +128 -20
- package/dist/stats/distributions.js.map +1 -1
- package/dist/stats/fitting.d.ts.map +1 -1
- package/dist/stats/fitting.js +1 -6
- package/dist/stats/fitting.js.map +1 -1
- package/dist/stats/index.d.ts +10 -3
- package/dist/stats/index.d.ts.map +1 -1
- package/dist/stats/index.js +10 -3
- package/dist/stats/index.js.map +1 -1
- package/dist/stats/logistic.d.ts +30 -0
- package/dist/stats/logistic.d.ts.map +1 -0
- package/dist/stats/logistic.js +43 -0
- package/dist/stats/logistic.js.map +1 -0
- package/dist/stats/multivariate.d.ts +8 -13
- package/dist/stats/multivariate.d.ts.map +1 -1
- package/dist/stats/multivariate.js +7 -53
- package/dist/stats/multivariate.js.map +1 -1
- package/dist/stats/policies.d.ts.map +1 -1
- package/dist/stats/policies.js +4 -22
- package/dist/stats/policies.js.map +1 -1
- package/package.json +4 -3
- package/src/contract/exports.snapshot.json +57 -1
- package/src/contract/regression.assets.test.ts +4 -0
- package/src/contract/regression.extractorKey.test.ts +202 -0
- package/src/contract/regression.statsEngineFree.test.ts +70 -0
- package/src/contract/regression.thompsonDeterminism.test.ts +23 -0
- package/src/contract/types.contract.test.ts +104 -1
- package/src/knowledge/build.ts +5 -1
- package/src/knowledge/coChange.test.ts +310 -0
- package/src/knowledge/coChange.ts +345 -0
- package/src/knowledge/communities.ts +6 -1
- package/src/knowledge/extractFile.ts +27 -5
- package/src/knowledge/extractJob.ts +24 -5
- package/src/knowledge/facts/extractorVersion.ts +73 -0
- package/src/knowledge/facts/fileFacts.test.ts +157 -0
- package/src/knowledge/facts/fileFacts.ts +305 -0
- package/src/knowledge/findings.ts +30 -127
- package/src/knowledge/index.ts +26 -0
- package/src/knowledge/model.ts +6 -0
- package/src/knowledge/outline.ts +2 -0
- package/src/knowledge/owedFiles.ts +36 -8
- package/src/knowledge/plan.ts +16 -4
- package/src/knowledge/refs.ts +4 -1
- package/src/knowledge/review.ts +1 -0
- package/src/knowledge/reviewContext.ts +5 -2
- package/src/knowledge/reviewFinish.ts +3 -1
- package/src/knowledge/reviewModel.ts +12 -0
- package/src/knowledge/reviewPrefetch.ts +3 -0
- package/src/knowledge/rules/cloneGroup.ts +45 -0
- package/src/knowledge/rules/components.ts +31 -0
- package/src/knowledge/rules/cycle.ts +20 -0
- package/src/knowledge/rules/duplicateCopy.ts +22 -0
- package/src/knowledge/rules/evaluateRules.test.ts +172 -0
- package/src/knowledge/rules/evaluateRules.ts +186 -0
- package/src/knowledge/rules/factGraph.oracle.test.ts +174 -0
- package/src/knowledge/rules/factGraph.ts +107 -0
- package/src/knowledge/rules/factRule.ts +74 -0
- package/src/knowledge/rules/godModule.ts +18 -0
- package/src/knowledge/rules/knowledgeInput.ts +60 -0
- package/src/knowledge/rules/knowledgeRules.test.ts +78 -0
- package/src/knowledge/rules/nearDuplicate.ts +22 -0
- package/src/knowledge/rules/partitionViolation.ts +31 -0
- package/src/knowledge/rules/possibleSame.ts +17 -0
- package/src/knowledge/rules/rules.testkit.test-util.ts +78 -0
- package/src/knowledge/rules/stale.ts +31 -0
- package/src/knowledge/rules/unpartitioned.ts +27 -0
- package/src/knowledge/sources.ts +19 -1
- package/src/knowledge/transitions.test.ts +135 -0
- package/src/knowledge/transitions.ts +115 -0
- package/src/retrieval/knowledge-index/sha256.test.ts +25 -0
- package/src/retrieval/knowledge-index/sha256.ts +2 -1
- package/src/stats/distributions.ts +132 -22
- package/src/stats/fitting.ts +1 -6
- package/src/stats/index.ts +15 -2
- package/src/stats/logistic.test.ts +89 -0
- package/src/stats/logistic.ts +49 -0
- package/src/stats/multivariate.ts +8 -59
- package/src/stats/policies.ts +4 -24
- package/src/stats/stats.test.ts +89 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/facts/fileFacts.test.ts — FileFacts v3 (PRD 41 §B1, §B3): canonical order, per-kind hashes
|
|
3
|
+
* (a body edit never moves the structure hash), v2 reads, and the composite extractor version.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { comparable } from '../comparability.js';
|
|
7
|
+
import { canonicalFileFacts, factKindHashes, factsHash, readFileFacts, isFileFactsV3, projectFileFacts, type FileFacts } from './fileFacts.js';
|
|
8
|
+
import { extractorStampMeta, factsExtractorTag, FACTS_EXTRACTOR_VERSION, isFactsCurrent, type ExtractorStamp } from './extractorVersion.js';
|
|
9
|
+
|
|
10
|
+
const STAMP: ExtractorStamp = { family: 'tree-sitter', grammars: { typescript: '0.23.2', python: '0.23.6' } };
|
|
11
|
+
|
|
12
|
+
const facts = (over: Partial<FileFacts> = {}): FileFacts => ({
|
|
13
|
+
factsVersion: FACTS_EXTRACTOR_VERSION,
|
|
14
|
+
extractor: factsExtractorTag(STAMP, 'typescript'),
|
|
15
|
+
language: 'typescript',
|
|
16
|
+
contentHash: 'c1',
|
|
17
|
+
symbols: [{ name: 'b', kind: 'function' }, { name: 'a', kind: 'function' }],
|
|
18
|
+
imports: [{ specifier: './z', resolved: 'z.ts', names: ['y', 'x'] }, { specifier: './a', resolved: 'a.ts', names: [] }],
|
|
19
|
+
exports: [{ name: 'b', kind: 'function', signatureHash: 's2' }, { name: 'a', kind: 'function', signatureHash: 's1' }],
|
|
20
|
+
entryPoints: [{ kind: 'http-route', key: 'POST /x', symbol: 'h', guards: ['requireAuth', 'audit'], inputs: ['req.body'], chain: ['mw.ts', 'app.ts'] }],
|
|
21
|
+
calls: [{ callee: 'fetch', enclosing: 'b', awaited: true, inLoop: true, count: 1 }, { callee: 'db.select', enclosing: 'a', count: 2 }],
|
|
22
|
+
complexity: [{ symbol: 'b', cyclomatic: 3 }, { symbol: 'a', cyclomatic: 1 }],
|
|
23
|
+
capabilityImports: [{ capability: 'network-client', module: 'node:http' }, { capability: 'crypto', module: 'node:crypto', algorithm: 'md5' }],
|
|
24
|
+
...over,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('canonicalFileFacts', () => {
|
|
28
|
+
it('sorts every array by its declared key, so producer order never reaches a hash', () => {
|
|
29
|
+
const a = facts();
|
|
30
|
+
const b = facts({ symbols: [...a.symbols].reverse(), imports: [...a.imports].reverse(), calls: [...a.calls].reverse() });
|
|
31
|
+
expect(factsHash(a)).toBe(factsHash(b));
|
|
32
|
+
const c = canonicalFileFacts(a);
|
|
33
|
+
expect(c.symbols.map((s) => s.name)).toEqual(['a', 'b']);
|
|
34
|
+
expect(c.imports[1]!.names).toEqual(['x', 'y']);
|
|
35
|
+
expect(c.entryPoints[0]!.guards).toEqual(['audit', 'requireAuth']);
|
|
36
|
+
expect(c.entryPoints[0]!.chain).toEqual(['app.ts', 'mw.ts']);
|
|
37
|
+
expect(canonicalFileFacts(c)).toEqual(c);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe('canonicalFileFacts: paths, tie-breaks, immutability', () => {
|
|
42
|
+
it('normalizes every path field (resolved imports, guard chains, snapshot files)', () => {
|
|
43
|
+
const ep = facts().entryPoints[0]!;
|
|
44
|
+
const c = canonicalFileFacts(facts({
|
|
45
|
+
imports: [{ specifier: '..\\b', resolved: 'src\\b.ts', names: [] }],
|
|
46
|
+
entryPoints: [{ ...ep, chain: ['.\\src\\mw.ts', 'src/app.ts'] }],
|
|
47
|
+
testFacts: { tests: [], snapshotFiles: ['__snapshots__\\a.snap'] },
|
|
48
|
+
}));
|
|
49
|
+
expect(c.imports[0]!.resolved).toBe('src/b.ts');
|
|
50
|
+
expect(c.entryPoints[0]!.chain).toEqual(['src/app.ts', 'src/mw.ts']);
|
|
51
|
+
expect(c.testFacts!.snapshotFiles).toEqual(['__snapshots__/a.snap']);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('items equal on the declared keys still sort one way (the whole item breaks the tie)', () => {
|
|
55
|
+
const i1 = { specifier: './a', resolved: 'a.ts', names: [], typeOnly: true };
|
|
56
|
+
const i2 = { specifier: './a', resolved: 'a.ts', names: [], dynamic: true };
|
|
57
|
+
expect(factsHash(facts({ imports: [i1, i2] }))).toBe(factsHash(facts({ imports: [i2, i1] })));
|
|
58
|
+
const t1 = { name: 't', assertions: 1, matchers: [{ matcher: 'toBe', strength: 'exact' as const, count: 1 }] };
|
|
59
|
+
const t2 = { ...t1, assertions: 2 };
|
|
60
|
+
expect(factsHash(facts({ testFacts: { tests: [t1, t2], snapshotFiles: [] } }))).toBe(factsHash(facts({ testFacts: { tests: [t2, t1], snapshotFiles: [] } })));
|
|
61
|
+
expect(factsHash(facts({ complexity: [{ symbol: 'a', cyclomatic: 1 }, { symbol: 'a', cyclomatic: 2 }] })))
|
|
62
|
+
.toBe(factsHash(facts({ complexity: [{ symbol: 'a', cyclomatic: 2 }, { symbol: 'a', cyclomatic: 1 }] })));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('is deep-frozen, copies (never freezes) the input, and returns a canonical object as is', () => {
|
|
66
|
+
const raw = facts();
|
|
67
|
+
const c = canonicalFileFacts(raw);
|
|
68
|
+
expect(Object.isFrozen(c) && Object.isFrozen(c.calls) && Object.isFrozen(c.calls[0])).toBe(true);
|
|
69
|
+
expect(Object.isFrozen(raw.calls[0])).toBe(false);
|
|
70
|
+
expect(canonicalFileFacts(c)).toBe(c);
|
|
71
|
+
// A mutated non-canonical input is hashed again, never served a stale cached hash.
|
|
72
|
+
const before = factKindHashes(raw).body;
|
|
73
|
+
raw.calls = [];
|
|
74
|
+
expect(factKindHashes(raw).body).not.toBe(before);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('projectFileFacts keeps the header and the read kinds, empties the rest', () => {
|
|
78
|
+
const p = projectFileFacts(facts(), ['structure']);
|
|
79
|
+
expect(p.exports).toHaveLength(2);
|
|
80
|
+
expect(p.calls).toEqual([]);
|
|
81
|
+
expect(p.testFacts).toBeUndefined();
|
|
82
|
+
expect(p.contentHash).toBe('');
|
|
83
|
+
expect(p.extractor).toBe(facts().extractor);
|
|
84
|
+
const c = canonicalFileFacts(facts());
|
|
85
|
+
expect(projectFileFacts(c, ['structure'])).toBe(projectFileFacts(c, ['structure']));
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe('factKindHashes', () => {
|
|
90
|
+
it('a body-only change moves the body hash and nothing else', () => {
|
|
91
|
+
const before = factKindHashes(facts());
|
|
92
|
+
const after = factKindHashes(facts({ calls: [{ callee: 'fetch', enclosing: 'b', count: 1 }] }));
|
|
93
|
+
expect(after.body).not.toBe(before.body);
|
|
94
|
+
expect(after.structure).toBe(before.structure);
|
|
95
|
+
expect(after.content).toBe(before.content);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('a structure change (a guard removed from a route) moves only the structure hash', () => {
|
|
99
|
+
const before = factKindHashes(facts());
|
|
100
|
+
const ep = facts().entryPoints[0]!;
|
|
101
|
+
const after = factKindHashes(facts({ entryPoints: [{ ...ep, guards: ['audit'] }] }));
|
|
102
|
+
expect(after.structure).not.toBe(before.structure);
|
|
103
|
+
expect(after.body).toBe(before.body);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('content is the content hash; another extractor moves structure and body', () => {
|
|
107
|
+
const h = factKindHashes(facts());
|
|
108
|
+
expect(h.content).toBe('c1');
|
|
109
|
+
const other = factKindHashes(facts({ extractor: factsExtractorTag({ family: 'regex' }, 'typescript') }));
|
|
110
|
+
expect(other.structure).not.toBe(h.structure);
|
|
111
|
+
expect(other.body).not.toBe(h.body);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe('readFileFacts (v2 compatibility)', () => {
|
|
116
|
+
it('reads a v2 object as factsVersion 2 with every v3 list empty', () => {
|
|
117
|
+
const v2 = readFileFacts({ contentHash: 'c', symbols: [{ name: 'f', kind: 'function' }] });
|
|
118
|
+
expect(v2.factsVersion).toBe(2);
|
|
119
|
+
expect(isFileFactsV3(v2)).toBe(false);
|
|
120
|
+
expect(v2.exports).toEqual([]);
|
|
121
|
+
expect(v2.calls).toEqual([]);
|
|
122
|
+
expect(v2.entryPoints).toEqual([]);
|
|
123
|
+
expect(v2.testFacts).toBeUndefined();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('keeps a v3 object (canonicalized)', () => {
|
|
127
|
+
const v3 = readFileFacts(facts());
|
|
128
|
+
expect(isFileFactsV3(v3)).toBe(true);
|
|
129
|
+
expect(factsHash(v3)).toBe(factsHash(facts()));
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
describe('composite extractor version', () => {
|
|
134
|
+
it('composes code version, revision, the language grammar and the EOL rule', () => {
|
|
135
|
+
expect(factsExtractorTag(STAMP, 'typescript')).toBe('tree-sitter@3.0/typescript=0.23.2/eol-lf@1');
|
|
136
|
+
expect(factsExtractorTag({ ...STAMP, revision: 2 }, 'go')).toBe('tree-sitter@3.2/eol-lf@1');
|
|
137
|
+
expect(factsExtractorTag(STAMP)).toBe('tree-sitter@3.0/python=0.23.6,typescript=0.23.2/eol-lf@1');
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('a grammar bump owes re-extraction only for files of that language', () => {
|
|
141
|
+
const ts = facts();
|
|
142
|
+
const py = facts({ language: 'python', extractor: factsExtractorTag(STAMP, 'python') });
|
|
143
|
+
const bumped: ExtractorStamp = { ...STAMP, grammars: { ...STAMP.grammars, python: '0.24.0' } };
|
|
144
|
+
expect(isFactsCurrent(ts, bumped)).toBe(true);
|
|
145
|
+
expect(isFactsCurrent(py, bumped)).toBe(false);
|
|
146
|
+
expect(isFactsCurrent(readFileFacts({ ...ts, factsVersion: 2 }), STAMP)).toBe(false);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('comparability names what moved: grammar, family, EOL rule', () => {
|
|
150
|
+
const base = extractorStampMeta(STAMP);
|
|
151
|
+
expect(comparable(base, extractorStampMeta(STAMP))).toEqual({ comparable: true, reasons: [] });
|
|
152
|
+
expect(comparable(base, extractorStampMeta({ ...STAMP, grammars: { ...STAMP.grammars, python: '0.24.0' } })).reasons)
|
|
153
|
+
.toEqual(['tool-version-changed:grammar:python']);
|
|
154
|
+
expect(comparable(base, extractorStampMeta({ family: 'regex' })).reasons).toContain('extractor-mismatch');
|
|
155
|
+
expect(comparable(base, extractorStampMeta({ ...STAMP, contentHashRule: 'eol-lf@2' })).reasons).toEqual(['content-hash-rule-changed']);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/facts/fileFacts.ts — the per-file fact contract, `FileFacts` v3 (PRD 41 §B1, §B3, §4).
|
|
3
|
+
*
|
|
4
|
+
* What ONE extractor (tree-sitter in Node hosts, regex in the Worker) emits for one file. Pure data: no
|
|
5
|
+
* positions (a line number would move every fact on an edit above it and defeat early cutoff), every
|
|
6
|
+
* array sorted by a declared key ({@link canonicalFileFacts}), canonical-serialized for every hash.
|
|
7
|
+
*
|
|
8
|
+
* The fields split into three FACT KINDS ({@link FACT_KIND_FIELDS}), each with its own hash, so a rule
|
|
9
|
+
* that `reads` only `structure` never reruns for a body or comment edit (early cutoff, §B1):
|
|
10
|
+
* - `structure`: symbols, imports, exports, entry points (the declared surface; a guard added to or
|
|
11
|
+
* removed from a route registration moves it);
|
|
12
|
+
* - `body`: calls, complexity, capability imports, test facts;
|
|
13
|
+
* - `content`: the EOL-normalized bytes themselves, i.e. `contentHash` (contentHash.ts).
|
|
14
|
+
*
|
|
15
|
+
* The header (`factsVersion`, `extractor`, `language`) enters every kind's hash: facts of another
|
|
16
|
+
* extractor are never "the same structure". The extractors live in the hosts (Builderforce.ai
|
|
17
|
+
* agent-tools); memory owns only this shape and its hashing.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { canonicalJson, compareStr, normalizePath, sortBy } from '../refs.js';
|
|
21
|
+
import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
|
|
22
|
+
import { FACTS_EXTRACTOR_VERSION } from './extractorVersion.js';
|
|
23
|
+
|
|
24
|
+
/** The three fact kinds a rule may read (§B1). Sorted. */
|
|
25
|
+
export type FactKind = 'body' | 'content' | 'structure';
|
|
26
|
+
export const FACT_KINDS: readonly FactKind[] = Object.freeze(['body', 'content', 'structure'] as const);
|
|
27
|
+
|
|
28
|
+
/** A definition. `name` is the symbol path (`Class.method`); `signatureHash` hashes its normalized signature text. */
|
|
29
|
+
export interface SymbolFact {
|
|
30
|
+
name: string;
|
|
31
|
+
/** 'function' | 'class' | 'method' | 'interface' | 'type' | 'enum' | 'variable' | 'constant' | 'module' … */
|
|
32
|
+
kind: string;
|
|
33
|
+
signatureHash?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** One import statement. `resolved` is the root-relative target file when the host resolved it. */
|
|
37
|
+
export interface ImportFact {
|
|
38
|
+
specifier: string;
|
|
39
|
+
resolved?: string;
|
|
40
|
+
/** Imported binding names (sorted); `*` for a namespace import, `default` for the default binding. */
|
|
41
|
+
names: string[];
|
|
42
|
+
typeOnly?: boolean;
|
|
43
|
+
dynamic?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** One exported name (§B3): its kind and the hash of its signature, so a changed signature is a changed export (C7 `api-breaking`). */
|
|
47
|
+
export interface ExportFact {
|
|
48
|
+
name: string;
|
|
49
|
+
kind: string;
|
|
50
|
+
signatureHash: string;
|
|
51
|
+
/** A re-export's source specifier. */
|
|
52
|
+
from?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Calls of one callee from one enclosing symbol, deduped by every field but `count` (no positions). */
|
|
56
|
+
export interface CallFact {
|
|
57
|
+
/** The callee as written (`db.select`, `fetch`, `fs.readFileSync`). */
|
|
58
|
+
callee: string;
|
|
59
|
+
/** The enclosing symbol path; '' at module top level. */
|
|
60
|
+
enclosing: string;
|
|
61
|
+
awaited?: boolean;
|
|
62
|
+
/** Inside `for` / `while` / `.map` / `.forEach` / `.reduce` (C6.1 `io-in-loop`). */
|
|
63
|
+
inLoop?: boolean;
|
|
64
|
+
count: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** McCabe cyclomatic complexity of one function-like symbol. */
|
|
68
|
+
export interface ComplexityFact {
|
|
69
|
+
symbol: string;
|
|
70
|
+
cyclomatic: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type EntryPointKind = 'http-route' | 'ws-handler' | 'webview-message' | 'vscode-command' | 'cli-command'
|
|
74
|
+
| 'mcp-tool' | 'queue-consumer' | 'cron' | 'exported-api';
|
|
75
|
+
|
|
76
|
+
/** One entry point (§C5.1, Manadhata–Wing attack surface). */
|
|
77
|
+
export interface EntryPointFact {
|
|
78
|
+
kind: EntryPointKind;
|
|
79
|
+
/** e.g. 'POST /api/projects/:id/knowledge/write'. */
|
|
80
|
+
key: string;
|
|
81
|
+
/** The handler symbol path. */
|
|
82
|
+
symbol: string;
|
|
83
|
+
/** Guard names found on its chain (middleware, wrappers), sorted. Which names are guards is registry data (run-delta). */
|
|
84
|
+
guards: string[];
|
|
85
|
+
/** Untrusted input accessors the handler uses (`req.body`, `c.req.json`, `msg.data`, `argv`), sorted. */
|
|
86
|
+
inputs: string[];
|
|
87
|
+
/**
|
|
88
|
+
* The GUARD CHAIN (§B5): root-relative files of the router, middleware and wrappers resolved from the route
|
|
89
|
+
* registration, sorted. A neighbourhood rule with `readsGuardChain` reads these files' facts whatever their import distance.
|
|
90
|
+
*/
|
|
91
|
+
chain: string[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type CapabilityKind = 'process-exec' | 'fs-write' | 'network-client' | 'network-server' | 'dynamic-code' | 'native-addon'
|
|
95
|
+
| 'crypto' | 'env-read' | 'secret-read';
|
|
96
|
+
|
|
97
|
+
/** One capability the file reaches (§C5.3): the module (and member) that grants it, and the algorithm for crypto. */
|
|
98
|
+
export interface CapabilityImportFact {
|
|
99
|
+
capability: CapabilityKind;
|
|
100
|
+
module: string;
|
|
101
|
+
symbol?: string;
|
|
102
|
+
/** Crypto only: the algorithm named at the call (`md5`, `sha1`, `aes-128-ecb`); weak ones are registry data. */
|
|
103
|
+
algorithm?: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Matcher strength class (§C8.2), strongest first: `exact` (toEqual, toBe) > `partial` (toMatchObject, toContain) > `presence` (toBeTruthy, toBeDefined). */
|
|
107
|
+
export type MatcherStrength = 'exact' | 'partial' | 'presence';
|
|
108
|
+
export const MATCHER_STRENGTH_ORDER: readonly MatcherStrength[] = Object.freeze(['exact', 'partial', 'presence'] as const);
|
|
109
|
+
|
|
110
|
+
export interface MatcherUse {
|
|
111
|
+
matcher: string;
|
|
112
|
+
strength: MatcherStrength;
|
|
113
|
+
count: number;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export type TestModifier = 'skip' | 'only' | 'todo';
|
|
117
|
+
|
|
118
|
+
/** One test case (§C8.2). */
|
|
119
|
+
export interface TestCaseFact {
|
|
120
|
+
/** The full title path, `describe › it`. */
|
|
121
|
+
name: string;
|
|
122
|
+
assertions: number;
|
|
123
|
+
matchers: MatcherUse[];
|
|
124
|
+
/** `.skip` / `.only` / `.todo` / `xit`. */
|
|
125
|
+
modifier?: TestModifier;
|
|
126
|
+
timeoutMs?: number;
|
|
127
|
+
/** Hash of the test's normalized expected-value texts, so an edited expectation is detectable (`assertion-edited-with-impl`). */
|
|
128
|
+
expectedHash?: string;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A test file's facts (§C8.2). Absent on a file that is not a test file. */
|
|
132
|
+
export interface TestFacts {
|
|
133
|
+
framework?: string;
|
|
134
|
+
tests: TestCaseFact[];
|
|
135
|
+
/** Snapshot files the tests read, root-relative, sorted. */
|
|
136
|
+
snapshotFiles: string[];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** FileFacts v3. Every array is sorted by its declared key ({@link canonicalFileFacts}). */
|
|
140
|
+
export interface FileFacts {
|
|
141
|
+
/** {@link FACTS_EXTRACTOR_VERSION} for v3; 2 for facts read through {@link readFileFacts} from a v2 producer. */
|
|
142
|
+
factsVersion: number;
|
|
143
|
+
/** The composite extractor tag for this file's language (`factsExtractorTag`, e.g. `tree-sitter@3.0/typescript=0.23.2/eol-lf@1`). */
|
|
144
|
+
extractor: string;
|
|
145
|
+
language: string;
|
|
146
|
+
/** `contentHash()` of the file's bytes — the `content` kind. */
|
|
147
|
+
contentHash: string;
|
|
148
|
+
// structure
|
|
149
|
+
symbols: SymbolFact[];
|
|
150
|
+
imports: ImportFact[];
|
|
151
|
+
exports: ExportFact[];
|
|
152
|
+
entryPoints: EntryPointFact[];
|
|
153
|
+
// body
|
|
154
|
+
calls: CallFact[];
|
|
155
|
+
complexity: ComplexityFact[];
|
|
156
|
+
capabilityImports: CapabilityImportFact[];
|
|
157
|
+
testFacts?: TestFacts;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Which fields each kind hashes (data: the ONE place the split is declared). */
|
|
161
|
+
export const FACT_KIND_FIELDS: Readonly<Record<FactKind, readonly (keyof FileFacts)[]>> = Object.freeze({
|
|
162
|
+
structure: ['symbols', 'imports', 'exports', 'entryPoints'],
|
|
163
|
+
body: ['calls', 'complexity', 'capabilityImports', 'testFacts'],
|
|
164
|
+
content: ['contentHash'],
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const str = (v: unknown) => (v === undefined ? '' : String(v));
|
|
168
|
+
const sorted = (xs: readonly string[] | undefined) => [...(xs ?? [])].sort(compareStr);
|
|
169
|
+
const paths = (xs: readonly string[] | undefined) => sorted((xs ?? []).map(normalizePath));
|
|
170
|
+
/** The final sort key of every list: the whole item, so items equal on the declared keys still sort one way. */
|
|
171
|
+
const whole = (x: unknown) => canonicalJson(x);
|
|
172
|
+
|
|
173
|
+
/** Facts objects produced by {@link canonicalFileFacts}: deep-frozen, so every cache keyed by object identity holds. */
|
|
174
|
+
const canonicalSet = new WeakSet<FileFacts>();
|
|
175
|
+
|
|
176
|
+
function deepFreeze<T>(value: T): T {
|
|
177
|
+
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
178
|
+
for (const v of Object.values(value as Record<string, unknown>)) deepFreeze(v);
|
|
179
|
+
Object.freeze(value);
|
|
180
|
+
}
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The canonical form: a deep copy with every array sorted by its declared keys then by the whole item, nested string
|
|
186
|
+
* lists sorted, and every path field (`imports[].resolved`, `entryPoints[].chain`, `testFacts.snapshotFiles`) in the
|
|
187
|
+
* ONE path form (`normalizePath`, §B8.1). The result is DEEP-FROZEN: facts are immutable values, and the kind-hash and
|
|
188
|
+
* projection caches key on the object. Idempotent; a canonical object is returned as is.
|
|
189
|
+
*/
|
|
190
|
+
export function canonicalFileFacts(f: FileFacts): FileFacts {
|
|
191
|
+
if (canonicalSet.has(f)) return f;
|
|
192
|
+
const out: FileFacts = {
|
|
193
|
+
...f,
|
|
194
|
+
symbols: sortBy(f.symbols.map((s) => ({ ...s })), (s) => s.name, (s) => s.kind, (s) => str(s.signatureHash), whole),
|
|
195
|
+
imports: sortBy(
|
|
196
|
+
f.imports.map((i) => ({ ...i, names: sorted(i.names), ...(i.resolved !== undefined ? { resolved: normalizePath(i.resolved) } : {}) })),
|
|
197
|
+
(i) => i.specifier, (i) => str(i.resolved), (i) => i.names.join('\u0000'), whole,
|
|
198
|
+
),
|
|
199
|
+
exports: sortBy(f.exports.map((e) => ({ ...e })), (e) => e.name, (e) => e.kind, (e) => e.signatureHash, (e) => str(e.from), whole),
|
|
200
|
+
entryPoints: sortBy(
|
|
201
|
+
f.entryPoints.map((e) => ({ ...e, guards: sorted(e.guards), inputs: sorted(e.inputs), chain: paths(e.chain) })),
|
|
202
|
+
(e) => e.kind, (e) => e.key, (e) => e.symbol, whole,
|
|
203
|
+
),
|
|
204
|
+
calls: sortBy(f.calls.map((c) => ({ ...c })), (c) => c.enclosing, (c) => c.callee, (c) => str(c.awaited), (c) => str(c.inLoop), whole),
|
|
205
|
+
complexity: sortBy(f.complexity.map((c) => ({ ...c })), (c) => c.symbol, whole),
|
|
206
|
+
capabilityImports: sortBy(f.capabilityImports.map((c) => ({ ...c })), (c) => c.capability, (c) => c.module, (c) => str(c.symbol), (c) => str(c.algorithm), whole),
|
|
207
|
+
};
|
|
208
|
+
if (f.testFacts) {
|
|
209
|
+
out.testFacts = {
|
|
210
|
+
...f.testFacts,
|
|
211
|
+
tests: sortBy(
|
|
212
|
+
f.testFacts.tests.map((t) => ({ ...t, matchers: sortBy(t.matchers.map((m) => ({ ...m })), (m) => m.matcher, (m) => m.strength, whole) })),
|
|
213
|
+
(t) => t.name, whole,
|
|
214
|
+
),
|
|
215
|
+
snapshotFiles: paths(f.testFacts.snapshotFiles),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
deepFreeze(out);
|
|
219
|
+
canonicalSet.add(out);
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The header every kind hash includes. */
|
|
224
|
+
const headerOf = (f: FileFacts) => ({ factsVersion: f.factsVersion, extractor: f.extractor, language: f.language });
|
|
225
|
+
|
|
226
|
+
const kindCache = new WeakMap<FileFacts, Readonly<Record<FactKind, string>>>();
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The hash of each fact kind of `f` (canonicalized first). `content` is the content hash itself; `structure` and `body`
|
|
230
|
+
* are sha256 over the canonical JSON of the header plus that kind's fields. Cached per CANONICAL (deep-frozen) object;
|
|
231
|
+
* a non-canonical input is canonicalized and hashed again on every call, so mutating it can never serve a stale hash.
|
|
232
|
+
*/
|
|
233
|
+
export function factKindHashes(f: FileFacts): Readonly<Record<FactKind, string>> {
|
|
234
|
+
const c = canonicalFileFacts(f);
|
|
235
|
+
const hit = kindCache.get(c);
|
|
236
|
+
if (hit) return hit;
|
|
237
|
+
const of = (kind: FactKind) => {
|
|
238
|
+
const body: Record<string, unknown> = { header: headerOf(c) };
|
|
239
|
+
for (const field of FACT_KIND_FIELDS[kind]) body[field] = c[field];
|
|
240
|
+
return sha256Hex(canonicalJson(body));
|
|
241
|
+
};
|
|
242
|
+
const hashes = Object.freeze({ body: of('body'), content: c.contentHash, structure: of('structure') });
|
|
243
|
+
kindCache.set(c, hashes);
|
|
244
|
+
return hashes;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The empty value of every kind's fields: what a rule that does not read that kind sees. */
|
|
248
|
+
const EMPTY_FIELDS: Readonly<Record<FactKind, Partial<FileFacts>>> = Object.freeze({
|
|
249
|
+
structure: { symbols: [], imports: [], exports: [], entryPoints: [] },
|
|
250
|
+
body: { calls: [], complexity: [], capabilityImports: [], testFacts: undefined },
|
|
251
|
+
content: { contentHash: '' },
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
const projectionCache = new WeakMap<FileFacts, Map<string, FileFacts>>();
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* `f` (canonicalized) as a rule that reads `reads` sees it: the header plus the fields of the read kinds; every other
|
|
258
|
+
* kind's fields empty. So an undeclared read sees nothing, and can never hide a dependency from the trace (§B5).
|
|
259
|
+
* Deep-frozen; cached per (canonical object, reads).
|
|
260
|
+
*/
|
|
261
|
+
export function projectFileFacts(f: FileFacts, reads: readonly FactKind[]): FileFacts {
|
|
262
|
+
const c = canonicalFileFacts(f);
|
|
263
|
+
const key = [...reads].sort().join(',');
|
|
264
|
+
let byReads = projectionCache.get(c);
|
|
265
|
+
if (!byReads) projectionCache.set(c, (byReads = new Map()));
|
|
266
|
+
let hit = byReads.get(key);
|
|
267
|
+
if (!hit) {
|
|
268
|
+
const out: FileFacts = { ...c };
|
|
269
|
+
for (const kind of FACT_KINDS) if (!reads.includes(kind)) Object.assign(out, EMPTY_FIELDS[kind]);
|
|
270
|
+
if (out.testFacts === undefined) delete out.testFacts;
|
|
271
|
+
hit = deepFreeze(out);
|
|
272
|
+
byReads.set(key, hit);
|
|
273
|
+
}
|
|
274
|
+
return hit;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The content address of a facts object: sha256 of its canonical JSON. */
|
|
278
|
+
export function factsHash(f: FileFacts): string {
|
|
279
|
+
return sha256Hex(canonicalJson(canonicalFileFacts(f)));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Reads facts from any producer: a v3 object as is (canonicalized), a v2 one (repo-map's symbols + imports, no
|
|
284
|
+
* `factsVersion`) with every v3 list empty and `factsVersion: 2`. A v2 fact set is never comparable with a v3 one
|
|
285
|
+
* (its `factsVersion` and extractor tag differ, C9), so the empty lists never read as "everything was removed".
|
|
286
|
+
*/
|
|
287
|
+
export function readFileFacts(raw: Partial<FileFacts> & Pick<FileFacts, 'contentHash'>): FileFacts {
|
|
288
|
+
return canonicalFileFacts({
|
|
289
|
+
factsVersion: raw.factsVersion ?? 2,
|
|
290
|
+
extractor: raw.extractor ?? '',
|
|
291
|
+
language: raw.language ?? '',
|
|
292
|
+
contentHash: raw.contentHash,
|
|
293
|
+
symbols: raw.symbols ?? [],
|
|
294
|
+
imports: raw.imports ?? [],
|
|
295
|
+
exports: raw.exports ?? [],
|
|
296
|
+
entryPoints: raw.entryPoints ?? [],
|
|
297
|
+
calls: raw.calls ?? [],
|
|
298
|
+
complexity: raw.complexity ?? [],
|
|
299
|
+
capabilityImports: raw.capabilityImports ?? [],
|
|
300
|
+
...(raw.testFacts ? { testFacts: raw.testFacts } : {}),
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Whether a facts object is v3 (current shape). */
|
|
305
|
+
export const isFileFactsV3 = (f: Pick<FileFacts, 'factsVersion'>): boolean => f.factsVersion === FACTS_EXTRACTOR_VERSION;
|
|
@@ -1,141 +1,44 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* knowledge/findings.ts — what a person can act on (PRD 38 §3.5)
|
|
2
|
+
* knowledge/findings.ts — what a person can act on (PRD 38 §3.5): the REGISTRY of the generic finding
|
|
3
|
+
* rules and the compat facade over them (PRD 41 §B5).
|
|
3
4
|
*
|
|
4
|
-
* Generic findings, for every pack: cycle, clone group, near-duplicate, partition
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* kind and refs) and a `requestKey`
|
|
8
|
-
* Fix-with-agent request, never a model call.
|
|
5
|
+
* Generic findings, for every pack: cycle, clone group, near-duplicate, partition violation,
|
|
6
|
+
* duplicate copy, unpartitioned share, stale knowledge, god module — plus `possible-same` entities.
|
|
7
|
+
* Each is ONE FactRule under knowledge/rules/, registered here as data. Packs add their own through
|
|
8
|
+
* {@link FindingRule}s. Every finding has a stable id (a hash of its kind and refs) and a `requestKey`
|
|
9
|
+
* under `knowledgeGraph.fix.*`: the fixed, prefilled Fix-with-agent request, never a model call.
|
|
9
10
|
*/
|
|
10
11
|
|
|
11
|
-
import { finding, findingId, MAX_FINDING_NODES,
|
|
12
|
-
import type {
|
|
12
|
+
import { finding, findingId, MAX_FINDING_NODES, requestKeyFor } from './findingBuilder.js';
|
|
13
|
+
import type { Finding, KnowledgeGraph, KnowledgePack, PartitionRegistry } from './model.js';
|
|
13
14
|
import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
15
|
+
import { compareStr } from './refs.js';
|
|
16
|
+
import { knowledgeFacts, runKnowledgeRules, type KnowledgeRule } from './rules/knowledgeInput.js';
|
|
17
|
+
import { cycleRule } from './rules/cycle.js';
|
|
18
|
+
import { cloneGroupRule, CLONE_GROUP_BADGE } from './rules/cloneGroup.js';
|
|
19
|
+
import { nearDuplicateRule } from './rules/nearDuplicate.js';
|
|
20
|
+
import { partitionSeverity, partitionViolationRule } from './rules/partitionViolation.js';
|
|
21
|
+
import { duplicateCopyRule } from './rules/duplicateCopy.js';
|
|
22
|
+
import { unpartitionedRule } from './rules/unpartitioned.js';
|
|
23
|
+
import { staleRule } from './rules/stale.js';
|
|
24
|
+
import { godModuleRule } from './rules/godModule.js';
|
|
25
|
+
import { possibleSameRule } from './rules/possibleSame.js';
|
|
26
|
+
import { components } from './rules/components.js';
|
|
17
27
|
|
|
18
|
-
|
|
19
|
-
export const CLONE_GROUP_BADGE = 'cloneGroup';
|
|
28
|
+
export { finding, findingId, requestKeyFor, MAX_FINDING_NODES, CLONE_GROUP_BADGE, partitionSeverity, components };
|
|
20
29
|
|
|
21
30
|
const SEVERITY_RANK = { error: 0, warn: 1, info: 2 } as const;
|
|
22
31
|
|
|
23
|
-
/**
|
|
24
|
-
export
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
export { finding, findingId, requestKeyFor, MAX_FINDING_NODES };
|
|
32
|
+
/** The generic finding rules, in emission order. */
|
|
33
|
+
export const GENERIC_FINDING_RULES: readonly KnowledgeRule[] = Object.freeze([
|
|
34
|
+
cycleRule, cloneGroupRule, nearDuplicateRule, partitionViolationRule, duplicateCopyRule, unpartitionedRule, staleRule, godModuleRule,
|
|
35
|
+
]);
|
|
29
36
|
|
|
30
|
-
/**
|
|
31
|
-
export
|
|
32
|
-
const parent = new Map<NodeRef, NodeRef>();
|
|
33
|
-
const find = (x: NodeRef): NodeRef => {
|
|
34
|
-
let r = x;
|
|
35
|
-
while (parent.get(r) !== r) r = parent.get(r)!;
|
|
36
|
-
parent.set(x, r);
|
|
37
|
-
return r;
|
|
38
|
-
};
|
|
39
|
-
for (const e of edges) {
|
|
40
|
-
for (const r of [e.from, e.to]) if (!parent.has(r)) parent.set(r, r);
|
|
41
|
-
const a = find(e.from), b = find(e.to);
|
|
42
|
-
if (a !== b) parent.set(compareStr(a, b) < 0 ? b : a, compareStr(a, b) < 0 ? a : b);
|
|
43
|
-
}
|
|
44
|
-
const groups = new Map<NodeRef, NodeRef[]>();
|
|
45
|
-
for (const r of [...parent.keys()].sort(compareStr)) {
|
|
46
|
-
const root = find(r);
|
|
47
|
-
let g = groups.get(root);
|
|
48
|
-
if (!g) groups.set(root, (g = []));
|
|
49
|
-
g.push(r);
|
|
50
|
-
}
|
|
51
|
-
return [...groups.values()].sort((a, b) => compareStr(a[0]!, b[0]!));
|
|
52
|
-
}
|
|
37
|
+
/** Every knowledge rule `computeFindings` runs: the generic ones plus `possible-same`. */
|
|
38
|
+
export const KNOWLEDGE_FINDING_RULES: readonly KnowledgeRule[] = Object.freeze([...GENERIC_FINDING_RULES, possibleSameRule]);
|
|
53
39
|
|
|
54
40
|
export function genericFindings(g: KnowledgeGraph, registries: ReadonlyMap<string, PartitionRegistry>): Finding[] {
|
|
55
|
-
|
|
56
|
-
const packOf = (ref: NodeRef) => byRef.get(ref)?.pack ?? FALLBACK_PACK_ID;
|
|
57
|
-
const out: Finding[] = [];
|
|
58
|
-
|
|
59
|
-
// Anchors (PRD 41 §C3) — one primary per kind, never a line or the member set:
|
|
60
|
-
// cycle → its sorted-first member · clone-group → the clone-group badge, else its sorted-first member ·
|
|
61
|
-
// near-duplicate → the sorted-first of the pair · partition-violation → from→to layer pair @ the from FILE ·
|
|
62
|
-
// duplicate-copy → the copy's FILE · unpartitioned → the pack · stale → the stale source.
|
|
63
|
-
for (const refs of components(g.edges.filter((e) => e.cycle))) {
|
|
64
|
-
out.push(finding('cycle', packOf(refs[0]!), refs, 'warn', { nodes: refs.length }, undefined, refAnchor(refs[0]!)));
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Clone groups: duplicate edges grouped by the clone-group badge, else by component.
|
|
68
|
-
const dup = g.edges.filter((e) => e.kind === 'duplicate');
|
|
69
|
-
const byBadge = new Map<string, KEdge[]>();
|
|
70
|
-
const unbadged: KEdge[] = [];
|
|
71
|
-
for (const e of dup) {
|
|
72
|
-
const badge = byRef.get(e.from)?.badges?.[CLONE_GROUP_BADGE] ?? byRef.get(e.to)?.badges?.[CLONE_GROUP_BADGE];
|
|
73
|
-
if (badge === undefined) { unbadged.push(e); continue; }
|
|
74
|
-
const list = byBadge.get(String(badge)) ?? [];
|
|
75
|
-
list.push(e);
|
|
76
|
-
byBadge.set(String(badge), list);
|
|
77
|
-
}
|
|
78
|
-
const groups: Array<{ group: string; refs: NodeRef[] }> = [
|
|
79
|
-
...[...byBadge].map(([group, es]) => ({ group, refs: es.flatMap((e) => [e.from, e.to]) })),
|
|
80
|
-
...components(unbadged).map((refs) => ({ group: '', refs })),
|
|
81
|
-
];
|
|
82
|
-
for (const { group, refs } of groups) {
|
|
83
|
-
const unique = [...new Set(refs)];
|
|
84
|
-
const first = unique.sort(compareStr)[0]!;
|
|
85
|
-
const anchor: FindingAnchor = group ? { anchor: `${CLONE_GROUP_BADGE}:${group}`, anchorKind: 'group' } : refAnchor(first);
|
|
86
|
-
out.push(finding('clone-group', packOf(first), unique, 'warn', { group, members: unique.length }, undefined, anchor));
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
for (const e of g.edges) {
|
|
90
|
-
if (e.kind === 'near-duplicate') {
|
|
91
|
-
const first = compareStr(e.from, e.to) <= 0 ? e.from : e.to;
|
|
92
|
-
out.push(finding('near-duplicate', packOf(e.from), [e.from, e.to], 'info', { similarity: round6(e.weight) }, undefined, refAnchor(first)));
|
|
93
|
-
}
|
|
94
|
-
if (e.verdict === 'upward' || e.verdict === 'skips') {
|
|
95
|
-
const from = byRef.get(e.from), to = byRef.get(e.to);
|
|
96
|
-
const layers = `${from?.partition ?? ''}->${to?.partition ?? ''}`;
|
|
97
|
-
out.push(finding('partition-violation', packOf(e.from), [e.from, e.to], partitionSeverity(e.verdict), {
|
|
98
|
-
verdict: e.verdict, from: from?.partition ?? '', to: to?.partition ?? '', kind: e.kind,
|
|
99
|
-
}, undefined, { anchor: `${layers}@${fileRefOf(e.from)}`, anchorKind: 'file' }));
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// A copy of another system in the same root (PRD 41 A9): its refs name the two systems' folders.
|
|
104
|
-
for (const s of g.meta?.systems ?? []) {
|
|
105
|
-
if (s.copyOf === undefined) continue;
|
|
106
|
-
out.push(finding('duplicate-copy', FALLBACK_PACK_ID, [srcRef(g.scope.rootId, s.path), srcRef(g.scope.rootId, s.copyOf)], 'warn', {
|
|
107
|
-
copy: s.path, original: s.copyOf, similarity: s.copySimilarity ?? 1, reason: s.copyReason ?? 'later-name',
|
|
108
|
-
}, [s.path, s.copyOf], { anchor: srcRef(g.scope.rootId, s.path), anchorKind: 'file' }));
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
for (const [pack, reg] of [...registries].sort((a, b) => compareStr(a[0], b[0]))) {
|
|
112
|
-
if (!reg.allow) continue;
|
|
113
|
-
const files = g.nodes.filter((n) => n.pack === pack && n.kind === 'file');
|
|
114
|
-
const loose = files.filter((n) => n.partition === undefined).map((n) => n.ref);
|
|
115
|
-
if (loose.length === 0) continue;
|
|
116
|
-
out.push(finding('unpartitioned', pack, loose, 'info', {
|
|
117
|
-
count: loose.length, total: files.length, share: Math.round((loose.length / files.length) * 100),
|
|
118
|
-
}, undefined, { anchor: `pack:${pack}`, anchorKind: 'group' }));
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
out.push(...staleFindings(g, byRef));
|
|
122
|
-
out.push(...godModuleFindings(g));
|
|
123
|
-
return out;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** One finding per source whose stored knowledge went stale (unanchored stale nodes: one each). */
|
|
127
|
-
function staleFindings(g: KnowledgeGraph, byRef: ReadonlyMap<NodeRef, KNode>): Finding[] {
|
|
128
|
-
const about = aboutTargets(g.edges);
|
|
129
|
-
const bySource = new Map<NodeRef, NodeRef[]>();
|
|
130
|
-
for (const n of g.nodes) {
|
|
131
|
-
if (!n.stale) continue;
|
|
132
|
-
const target = about.get(n.ref) ?? n.ref;
|
|
133
|
-
const list = bySource.get(target) ?? [];
|
|
134
|
-
list.push(n.ref);
|
|
135
|
-
bySource.set(target, list);
|
|
136
|
-
}
|
|
137
|
-
return [...bySource].map(([source, refs]) =>
|
|
138
|
-
finding('stale', byRef.get(source)?.pack ?? FALLBACK_PACK_ID, [source, ...refs], 'warn', { count: refs.length }, undefined, refAnchor(source)));
|
|
41
|
+
return runKnowledgeRules(GENERIC_FINDING_RULES, knowledgeFacts(g, registries));
|
|
139
42
|
}
|
|
140
43
|
|
|
141
44
|
/** Generic + possible-same + every pack's rules; deduped by id; severity, then id. */
|
|
@@ -145,7 +48,7 @@ export function computeFindings(
|
|
|
145
48
|
registries: ReadonlyMap<string, PartitionRegistry>,
|
|
146
49
|
nearDuplicates: readonly SimilarPair[],
|
|
147
50
|
): Finding[] {
|
|
148
|
-
const all =
|
|
51
|
+
const all = runKnowledgeRules(KNOWLEDGE_FINDING_RULES, knowledgeFacts(g, registries, nearDuplicates));
|
|
149
52
|
for (const pack of [...packs].sort((a, b) => compareStr(a.id, b.id))) {
|
|
150
53
|
for (const rule of pack.findings ?? []) {
|
|
151
54
|
for (const f of rule.find(g)) {
|