@seanhogg/builderforce-memory 2026.10.71 → 2026.10.73
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/coChange.d.ts +3 -1
- package/dist/knowledge/coChange.d.ts.map +1 -1
- package/dist/knowledge/coChange.js +24 -12
- package/dist/knowledge/coChange.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 +14 -2
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +8 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/model.d.ts +23 -0
- package/dist/knowledge/model.d.ts.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/pack/sections/index.d.ts +4 -1
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/index.js +7 -3
- package/dist/knowledge/pack/sections/index.js.map +1 -1
- package/dist/knowledge/pack/sections/rows.d.ts +9 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/rows.js +46 -1
- package/dist/knowledge/pack/sections/rows.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/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 +7 -2
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +18 -1
- 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 +13 -0
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +14 -0
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +5 -0
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- 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 +17 -1
- package/dist/stats/distributions.d.ts.map +1 -1
- package/dist/stats/distributions.js +26 -1
- 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 +37 -1
- package/src/contract/regression.extractorKey.test.ts +202 -0
- package/src/contract/regression.scopeMeasured.test.ts +121 -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 +66 -2
- package/src/knowledge/coChange.test.ts +15 -2
- package/src/knowledge/coChange.ts +22 -10
- 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 +20 -1
- package/src/knowledge/model.ts +24 -0
- package/src/knowledge/owedFiles.ts +36 -8
- package/src/knowledge/pack/pack.testkit.test-util.ts +4 -1
- package/src/knowledge/pack/sections/index.ts +7 -3
- package/src/knowledge/pack/sections/rows.ts +39 -1
- package/src/knowledge/plan.ts +16 -4
- package/src/knowledge/review.ts +1 -0
- package/src/knowledge/reviewContext.ts +5 -2
- package/src/knowledge/reviewFinish.ts +7 -2
- package/src/knowledge/reviewModel.ts +18 -1
- 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 +16 -0
- package/src/knowledge/stores/localSnapshotStore.ts +4 -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 +29 -2
- package/src/stats/fitting.ts +1 -6
- package/src/stats/index.ts +12 -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
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/rules/evaluateRules.test.ts — the trace tests (PRD 41 §8 Part B):
|
|
3
|
+
* - a body-only edit reruns `body`-reading rules (io-in-loop) and skips `structure`-only rules;
|
|
4
|
+
* - global rules are skipped when the fact kinds they read did not change anywhere;
|
|
5
|
+
* plus neighbourhood hops, guard chains, extra inputs and rule validation.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { FileFacts } from '../facts/fileFacts.js';
|
|
9
|
+
import { defineRule } from './factRule.js';
|
|
10
|
+
import { evaluateRules, type RuleEvaluation } from './evaluateRules.js';
|
|
11
|
+
import { callTotal, contentTag, emptyFacts, exportCount, FIXTURE_RULES, ioInLoop, mutualImport, routeGuard, unresolvedImport } from './rules.testkit.test-util.js';
|
|
12
|
+
|
|
13
|
+
const base = (): Map<string, FileFacts> => new Map([
|
|
14
|
+
['a.ts', { ...emptyFacts('ha'), imports: [{ specifier: './b', resolved: 'b.ts', names: [] }], exports: [{ name: 'a', kind: 'function', signatureHash: 's' }],
|
|
15
|
+
calls: [{ callee: 'db.get', enclosing: 'a', awaited: true, inLoop: true, count: 1 }] }],
|
|
16
|
+
['b.ts', { ...emptyFacts('hb'), imports: [{ specifier: './c', resolved: 'c.ts', names: [] }] }],
|
|
17
|
+
['c.ts', emptyFacts('hc')],
|
|
18
|
+
['d.ts', emptyFacts('hd')],
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
const ran = (e: RuleEvaluation) => e.trace.filter((t) => t.outcome === 'ran').map((t) => `${t.rule}@${t.focus}`).sort();
|
|
22
|
+
const outcome = (e: RuleEvaluation, rule: string, focus = '') => e.trace.find((t) => t.rule === rule && t.focus === focus)?.outcome;
|
|
23
|
+
|
|
24
|
+
describe('evaluateRules: verifying traces and early cutoff', () => {
|
|
25
|
+
it('a first evaluation runs every row; an identical one reuses every row', () => {
|
|
26
|
+
const files = base();
|
|
27
|
+
const first = evaluateRules(FIXTURE_RULES, { files });
|
|
28
|
+
expect(first.trace.every((t) => t.outcome === 'ran')).toBe(true);
|
|
29
|
+
const second = evaluateRules(FIXTURE_RULES, { files: base() }, first.rows);
|
|
30
|
+
expect(ran(second)).toEqual([]);
|
|
31
|
+
expect(second.findings).toEqual(first.findings);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('a body-only edit reruns body-reading rules (io-in-loop) and skips structure-only rules', () => {
|
|
35
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
36
|
+
const files = base();
|
|
37
|
+
files.set('a.ts', { ...files.get('a.ts')!, calls: [] });
|
|
38
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
39
|
+
expect(ran(second)).toEqual(['call-total@', 'io-in-loop@a.ts']);
|
|
40
|
+
expect(outcome(second, 'export-count', 'a.ts')).toBe('reused');
|
|
41
|
+
expect(outcome(second, 'unresolved-import', 'a.ts')).toBe('reused');
|
|
42
|
+
expect(outcome(second, 'mutual-import')).toBe('reused');
|
|
43
|
+
expect(second.findings.some((x) => x.kind === 'io-in-loop')).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('global rules are skipped when their read kinds did not change anywhere (a comment edit)', () => {
|
|
47
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
48
|
+
const files = base();
|
|
49
|
+
files.set('c.ts', { ...files.get('c.ts')!, contentHash: 'hc2' });
|
|
50
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
51
|
+
expect(ran(second)).toEqual(['content-tag@c.ts']);
|
|
52
|
+
expect(outcome(second, 'mutual-import')).toBe('reused');
|
|
53
|
+
expect(outcome(second, 'call-total')).toBe('reused');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('a structure edit reruns the global structure rule and the neighbourhood of the edited file only', () => {
|
|
57
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
58
|
+
const files = base();
|
|
59
|
+
files.set('c.ts', { ...files.get('c.ts')!, imports: [{ specifier: './b', resolved: 'b.ts', names: [] }] });
|
|
60
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
61
|
+
// Graph a–b–c, d alone. unresolved-import (1 hop): b {a,b,c} and c {b,c} see c; a {a,b} and d do not.
|
|
62
|
+
// route-guard (2 hops): a, b and c all reach c; d does not.
|
|
63
|
+
expect(ran(second)).toEqual([
|
|
64
|
+
'export-count@c.ts', 'mutual-import@', 'route-guard@a.ts', 'route-guard@b.ts', 'route-guard@c.ts',
|
|
65
|
+
'unresolved-import@b.ts', 'unresolved-import@c.ts',
|
|
66
|
+
]);
|
|
67
|
+
expect(second.findings.map((x) => x.id)).toContain('mutual-import:b.ts<->c.ts');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('a file added or deleted drops or adds its rows, and its neighbours see the new set', () => {
|
|
71
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
72
|
+
const files = base();
|
|
73
|
+
files.delete('c.ts');
|
|
74
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
75
|
+
expect([...second.rows.keys()].some((k) => k.endsWith('\u0000c.ts'))).toBe(false);
|
|
76
|
+
expect(second.findings.map((x) => x.id)).toContain('unresolved-import:b.ts->c.ts');
|
|
77
|
+
expect(outcome(second, 'unresolved-import', 'b.ts')).toBe('ran');
|
|
78
|
+
expect(outcome(second, 'unresolved-import', 'd.ts')).toBe('reused');
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('evaluateRules: derive sees only what its trace covers', () => {
|
|
83
|
+
it('a rule that reads an undeclared field sees it empty, and an undeclared extra input absent', () => {
|
|
84
|
+
const seen: unknown[] = [];
|
|
85
|
+
const sneaky = defineRule<{ secret: string }>({
|
|
86
|
+
id: 'sneaky', version: 1, reads: ['body'], scope: 'file',
|
|
87
|
+
derive: ({ focus, files, extra }) => {
|
|
88
|
+
const f = files.get(focus!)!;
|
|
89
|
+
seen.push({ exports: f.exports, imports: f.imports, contentHash: f.contentHash, calls: f.calls.length, secret: extra.secret });
|
|
90
|
+
return [];
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
evaluateRules([sneaky], { files: new Map([['a.ts', base().get('a.ts')!]]), extra: { secret: 's' } });
|
|
94
|
+
expect(seen).toEqual([{ exports: [], imports: [], contentHash: '', calls: 1, secret: undefined }]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('a global rule reading only extra inputs (reads: []) sees no files', () => {
|
|
98
|
+
let count = -1;
|
|
99
|
+
const onlyExtra = defineRule<{ g: string }>({
|
|
100
|
+
id: 'only-extra', version: 1, reads: [], scope: 'global', extraInputs: ['g'],
|
|
101
|
+
derive: ({ files }) => { count = files.size; return []; },
|
|
102
|
+
});
|
|
103
|
+
evaluateRules([onlyExtra], { files: base(), extra: { g: 'x' }, extraHashes: { g: 'h' } });
|
|
104
|
+
expect(count).toBe(0);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe('evaluateRules: guard chains', () => {
|
|
109
|
+
const routed = (): Map<string, FileFacts> => new Map([
|
|
110
|
+
['routes.ts', { ...emptyFacts('r'), entryPoints: [{ kind: 'http-route', key: 'POST /x', symbol: 'h', guards: ['requireAuth'], inputs: [], chain: ['far/auth.ts'] }] }],
|
|
111
|
+
['far/auth.ts', { ...emptyFacts('m'), exports: [{ name: 'requireAuth', kind: 'function', signatureHash: 's' }] }],
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
it('a route reads its guard-chain file however far it is, and reruns when that file loses the guard', () => {
|
|
115
|
+
const first = evaluateRules([routeGuard], { files: routed() });
|
|
116
|
+
expect(first.findings).toEqual([]);
|
|
117
|
+
const files = routed();
|
|
118
|
+
files.set('far/auth.ts', { ...files.get('far/auth.ts')!, exports: [] });
|
|
119
|
+
const second = evaluateRules([routeGuard], { files }, first.rows);
|
|
120
|
+
expect(outcome(second, 'route-guard', 'routes.ts')).toBe('ran');
|
|
121
|
+
expect(second.findings.map((x) => x.id)).toEqual(['route-guard:routes.ts#POST /x']);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe('evaluateRules: extra inputs', () => {
|
|
126
|
+
const readsGraph = defineRule<{ graph: string }>({
|
|
127
|
+
id: 'reads-graph', version: 1, reads: ['structure'], scope: 'global', extraInputs: ['graph'],
|
|
128
|
+
derive: ({ extra }) => [{ id: `g:${extra.graph}`, kind: 'g', pack: 'p', nodes: [], severity: 'info', params: {} }],
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('reruns when the extra input hash moves, and reuses when it holds', () => {
|
|
132
|
+
const files = base();
|
|
133
|
+
const first = evaluateRules([readsGraph], { files, extra: { graph: 'v1' }, extraHashes: { graph: 'h1' } });
|
|
134
|
+
expect(outcome(evaluateRules([readsGraph], { files, extra: { graph: 'v1' }, extraHashes: { graph: 'h1' } }, first.rows), 'reads-graph')).toBe('reused');
|
|
135
|
+
const moved = evaluateRules([readsGraph], { files, extra: { graph: 'v2' }, extraHashes: { graph: 'h2' } }, first.rows);
|
|
136
|
+
expect(outcome(moved, 'reads-graph')).toBe('ran');
|
|
137
|
+
expect(moved.findings.map((x) => x.id)).toEqual(['g:v2']);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('throws when a declared extra input has no hash', () => {
|
|
141
|
+
expect(() => evaluateRules([readsGraph], { files: base(), extra: { graph: 'v1' } })).toThrow('rule_extra_input_unhashed:reads-graph:graph');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('a rule version bump reruns the rule', () => {
|
|
145
|
+
const first = evaluateRules([ioInLoop], { files: base() });
|
|
146
|
+
const bumped = defineRule({ ...ioInLoop, version: 2 });
|
|
147
|
+
expect(ran(evaluateRules([bumped], { files: base() }, first.rows))).toEqual(['io-in-loop@a.ts', 'io-in-loop@b.ts', 'io-in-loop@c.ts', 'io-in-loop@d.ts']);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe('defineRule', () => {
|
|
152
|
+
it('rejects invalid declarations', () => {
|
|
153
|
+
const ok = { id: 'r', version: 1, reads: ['body'] as const, scope: 'neighbourhood' as const, derive: () => [] };
|
|
154
|
+
expect(() => defineRule({ ...ok, hops: 3 })).toThrow('fact_rule_invalid:r:hops');
|
|
155
|
+
expect(() => defineRule({ ...ok, scope: 'file', hops: 1 })).toThrow('fact_rule_invalid:r:hops-outside-neighbourhood');
|
|
156
|
+
expect(() => defineRule({ ...ok, reads: [] })).toThrow('fact_rule_invalid:r:reads');
|
|
157
|
+
expect(() => defineRule({ ...ok, scope: 'global', reads: [] })).toThrow('fact_rule_invalid:r:reads');
|
|
158
|
+
expect(defineRule<{ g: number }>({ ...ok, scope: 'global', reads: [], extraInputs: ['g'] }).reads).toEqual([]);
|
|
159
|
+
expect(() => defineRule({ ...ok, version: 0 })).toThrow('fact_rule_invalid:r:version');
|
|
160
|
+
expect(() => defineRule({ ...ok, scope: 'global', readsGuardChain: true })).toThrow('fact_rule_invalid:r:guard-chain-outside-neighbourhood');
|
|
161
|
+
expect(defineRule({ ...ok, reads: ['structure', 'body', 'body'] }).reads).toEqual(['body', 'structure']);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('evaluateRules refuses two rules with one id', () => {
|
|
165
|
+
expect(() => evaluateRules([exportCount, { ...contentTag, id: 'export-count' }], { files: base() })).toThrow('fact_rule_duplicate:export-count');
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('uses every fixture rule', () => {
|
|
169
|
+
expect([ioInLoop, exportCount, contentTag, unresolvedImport, routeGuard, mutualImport, callTotal].map((r) => r.id).sort())
|
|
170
|
+
.toEqual(FIXTURE_RULES.map((r) => r.id).sort());
|
|
171
|
+
});
|
|
172
|
+
});
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/evaluateRules.ts — the incremental FactRule evaluator (PRD 41 §B1, §B5).
|
|
3
|
+
*
|
|
4
|
+
* Verifying traces with early cutoff (Mokhov, Mitchell, Peyton Jones, *Build Systems à la Carte*): every
|
|
5
|
+
* derived row stores the hash of the inputs it read — the rule's id and version, its focus, and for each
|
|
6
|
+
* file in its scope the hash of each fact kind it `reads`, plus the hash of each declared extra input. On
|
|
7
|
+
* the next evaluation a row whose input hash is unchanged is REUSED without calling `derive`; otherwise
|
|
8
|
+
* the rule reruns. No dirty flags: validity is recomputed from the current facts, so a thrown-away row
|
|
9
|
+
* store rebuilds to the same rows.
|
|
10
|
+
*
|
|
11
|
+
* The trace is ENFORCED, not trusted: `derive` receives each file projected to the kinds the rule reads
|
|
12
|
+
* (`projectFileFacts`, every other field empty) and `extra` cut to its declared `extraInputs`, so an undeclared
|
|
13
|
+
* read sees nothing instead of silently breaking early cutoff.
|
|
14
|
+
*
|
|
15
|
+
* Consequences the trace tests pin: a body-only edit reruns `body`-reading rules for that file and skips
|
|
16
|
+
* `structure`-only rules; a global rule is skipped when no file's read kinds changed anywhere.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { compareStr } from '../refs.js';
|
|
20
|
+
import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
|
|
21
|
+
import type { Finding } from '../findingModel.js';
|
|
22
|
+
import { canonicalFileFacts, factKindHashes, projectFileFacts, type FactKind, type FileFacts } from '../facts/fileFacts.js';
|
|
23
|
+
import { DEFAULT_RULE_HOPS, type FactRule } from './factRule.js';
|
|
24
|
+
|
|
25
|
+
/** What the evaluator reads: the current facts by path, the import neighbourhood, and the hashed extra inputs. */
|
|
26
|
+
export interface RuleWorld<X = Record<never, never>> {
|
|
27
|
+
files: ReadonlyMap<string, FileFacts>;
|
|
28
|
+
/** Undirected one-hop neighbours of a path. Default: from the facts' resolved imports ({@link importNeighbours}). */
|
|
29
|
+
neighbours?: (path: string) => readonly string[];
|
|
30
|
+
extra?: X;
|
|
31
|
+
/** The hash of each extra input. A rule that declares an extra input with no hash here throws `rule_extra_input_unhashed`. */
|
|
32
|
+
extraHashes?: Readonly<Record<string, string>>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** One derived result and the hash of the inputs it read. `focus` is '' for a global rule. */
|
|
36
|
+
export interface DerivedRow {
|
|
37
|
+
rule: string;
|
|
38
|
+
version: number;
|
|
39
|
+
focus: string;
|
|
40
|
+
inputs: string;
|
|
41
|
+
findings: Finding[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type DerivedRows = ReadonlyMap<string, DerivedRow>;
|
|
45
|
+
|
|
46
|
+
/** What happened to one row in an evaluation. Sorted by rule, then focus. */
|
|
47
|
+
export interface RuleTraceEntry {
|
|
48
|
+
rule: string;
|
|
49
|
+
focus: string;
|
|
50
|
+
outcome: 'ran' | 'reused';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface RuleEvaluation {
|
|
54
|
+
rows: Map<string, DerivedRow>;
|
|
55
|
+
trace: RuleTraceEntry[];
|
|
56
|
+
/** Every row's findings, deduped by id, sorted by id. */
|
|
57
|
+
findings: Finding[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The key of a derived row. */
|
|
61
|
+
export const derivedRowKey = (rule: string, focus: string): string => `${rule}\u0000${focus}`;
|
|
62
|
+
|
|
63
|
+
/** Undirected one-hop import neighbours from each file's resolved imports (only files present), each list sorted. */
|
|
64
|
+
export function importNeighbours(files: ReadonlyMap<string, FileFacts>): (path: string) => readonly string[] {
|
|
65
|
+
const adj = new Map<string, Set<string>>();
|
|
66
|
+
const link = (a: string, b: string) => {
|
|
67
|
+
let s = adj.get(a);
|
|
68
|
+
if (!s) adj.set(a, (s = new Set()));
|
|
69
|
+
s.add(b);
|
|
70
|
+
};
|
|
71
|
+
for (const [path, f] of files) {
|
|
72
|
+
for (const i of f.imports) {
|
|
73
|
+
if (i.resolved === undefined || i.resolved === path || !files.has(i.resolved)) continue;
|
|
74
|
+
link(path, i.resolved);
|
|
75
|
+
link(i.resolved, path);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const sorted = new Map([...adj].map(([k, v]) => [k, [...v].sort(compareStr)] as const));
|
|
79
|
+
return (path) => sorted.get(path) ?? [];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The paths a neighbourhood evaluation reads: BFS to `hops`, plus the guard-chain files when declared. Sorted. */
|
|
83
|
+
function neighbourhoodOf(rule: FactRule<any>, focus: string, world: RuleWorld<any>, neighbours: (p: string) => readonly string[]): string[] {
|
|
84
|
+
const seen = new Set([focus]);
|
|
85
|
+
let frontier = [focus];
|
|
86
|
+
for (let hop = 0; hop < (rule.hops ?? DEFAULT_RULE_HOPS); hop++) {
|
|
87
|
+
const next: string[] = [];
|
|
88
|
+
for (const p of frontier) for (const n of neighbours(p)) if (!seen.has(n)) { seen.add(n); next.push(n); }
|
|
89
|
+
frontier = next;
|
|
90
|
+
}
|
|
91
|
+
if (rule.readsGuardChain) {
|
|
92
|
+
for (const e of world.files.get(focus)?.entryPoints ?? []) for (const c of e.chain) if (world.files.has(c)) seen.add(c);
|
|
93
|
+
}
|
|
94
|
+
return [...seen].sort(compareStr);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `path\0hash\n` of one kind over every file, hashed once per evaluation and shared by every global rule reading that kind. */
|
|
98
|
+
function kindRoots(world: RuleWorld<any>, paths: readonly string[]): (kind: FactKind) => string {
|
|
99
|
+
const roots = new Map<FactKind, string>();
|
|
100
|
+
return (kind) => {
|
|
101
|
+
let root = roots.get(kind);
|
|
102
|
+
if (root === undefined) {
|
|
103
|
+
root = sha256Hex(paths.map((p) => `${p}\u0000${factKindHashes(world.files.get(p)!)[kind]}\n`).join(''));
|
|
104
|
+
roots.set(kind, root);
|
|
105
|
+
}
|
|
106
|
+
return root;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The trace hash: rule identity, focus, the read kind hashes of each in-scope file (a global rule: the kind roots,
|
|
112
|
+
* which cover every file), each declared extra input's hash.
|
|
113
|
+
*/
|
|
114
|
+
function inputsHash(rule: FactRule<any>, focus: string, paths: readonly string[], world: RuleWorld<any>, roots: (kind: FactKind) => string): string {
|
|
115
|
+
const parts = [`${rule.id}\u0000${rule.version}\u0000${rule.scope}\u0000${focus}\n`];
|
|
116
|
+
if (rule.scope === 'global') {
|
|
117
|
+
for (const k of rule.reads) parts.push(`#${k}=${roots(k)}\n`);
|
|
118
|
+
} else {
|
|
119
|
+
for (const p of paths) {
|
|
120
|
+
const kinds = factKindHashes(world.files.get(p)!);
|
|
121
|
+
parts.push(p);
|
|
122
|
+
for (const k of rule.reads) parts.push(`\u0000${k}=${kinds[k]}`);
|
|
123
|
+
parts.push('\n');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const name of [...(rule.extraInputs ?? [])].sort(compareStr)) {
|
|
127
|
+
const hash = world.extraHashes?.[name];
|
|
128
|
+
if (hash === undefined) throw new Error(`rule_extra_input_unhashed:${rule.id}:${name}`);
|
|
129
|
+
parts.push(`@${name}=${hash}\n`);
|
|
130
|
+
}
|
|
131
|
+
return sha256Hex(parts.join(''));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const byId = (a: Finding, b: Finding) => compareStr(a.id, b.id);
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Evaluates `rules` against `world`, reusing every row of `previous` whose input hash still holds. Rows for files
|
|
138
|
+
* that no longer exist (and for rules no longer registered) are dropped. Pure: `previous` is not mutated.
|
|
139
|
+
*/
|
|
140
|
+
export function evaluateRules<X>(rules: readonly FactRule<X>[], world: RuleWorld<X>, previous: DerivedRows = new Map()): RuleEvaluation {
|
|
141
|
+
const ids = new Set<string>();
|
|
142
|
+
for (const r of rules) {
|
|
143
|
+
if (ids.has(r.id)) throw new Error(`fact_rule_duplicate:${r.id}`);
|
|
144
|
+
ids.add(r.id);
|
|
145
|
+
}
|
|
146
|
+
const paths = [...world.files.keys()].sort(compareStr);
|
|
147
|
+
// Canonical (deep-frozen) facts: the hash and projection caches key on them, and a caller's later mutation never reaches a row.
|
|
148
|
+
const w: RuleWorld<X> = { ...world, files: new Map(paths.map((p) => [p, canonicalFileFacts(world.files.get(p)!)] as const)) };
|
|
149
|
+
let neighbours = w.neighbours;
|
|
150
|
+
const rows = new Map<string, DerivedRow>();
|
|
151
|
+
const trace: RuleTraceEntry[] = [];
|
|
152
|
+
const roots = kindRoots(w, paths);
|
|
153
|
+
|
|
154
|
+
const evaluate = (rule: FactRule<X>, focus: string, scopePaths: readonly string[]) => {
|
|
155
|
+
const key = derivedRowKey(rule.id, focus);
|
|
156
|
+
// The version is part of the hash, so a bumped rule never matches its old row.
|
|
157
|
+
const inputs = inputsHash(rule, focus, scopePaths, w, roots);
|
|
158
|
+
const prior = previous.get(key);
|
|
159
|
+
if (prior && prior.inputs === inputs) {
|
|
160
|
+
rows.set(key, prior);
|
|
161
|
+
trace.push({ rule: rule.id, focus, outcome: 'reused' });
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// `derive` sees ONLY what its trace covers: each file projected to the kinds it reads, `extra` cut to its declared inputs.
|
|
165
|
+
// A rule reading no fact kind (extra inputs only) sees no files: not even which paths exist is in its trace.
|
|
166
|
+
const files = new Map(rule.reads.length === 0 ? [] : scopePaths.map((p) => [p, projectFileFacts(w.files.get(p)!, rule.reads)] as const));
|
|
167
|
+
const all = (w.extra ?? {}) as Record<string, unknown>;
|
|
168
|
+
const extra = Object.fromEntries((rule.extraInputs ?? []).filter((n) => n in all).map((n) => [n, all[n]])) as X;
|
|
169
|
+
const findings = rule.derive({ scope: rule.scope, ...(focus ? { focus } : {}), files, extra });
|
|
170
|
+
rows.set(key, { rule: rule.id, version: rule.version, focus, inputs, findings: [...findings].sort(byId) });
|
|
171
|
+
trace.push({ rule: rule.id, focus, outcome: 'ran' });
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
for (const rule of [...rules].sort((a, b) => compareStr(a.id, b.id))) {
|
|
175
|
+
if (rule.scope === 'global') { evaluate(rule, '', paths); continue; }
|
|
176
|
+
for (const p of paths) {
|
|
177
|
+
if (rule.scope === 'file') { evaluate(rule, p, [p]); continue; }
|
|
178
|
+
neighbours ??= importNeighbours(w.files);
|
|
179
|
+
evaluate(rule, p, neighbourhoodOf(rule, p, w, neighbours));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const found = new Map<string, Finding>();
|
|
184
|
+
for (const row of rows.values()) for (const f of row.findings) if (!found.has(f.id)) found.set(f.id, f);
|
|
185
|
+
return { rows, trace, findings: [...found.values()].sort(byId) };
|
|
186
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/rules/factGraph.oracle.test.ts — the determinism oracle (PRD 41 §B8.6, §8 Part B).
|
|
3
|
+
*
|
|
4
|
+
* For a fixture tree and 500 seeded sequences of edits, adds, deletes, renames and EOL rewrites, the canonical
|
|
5
|
+
* dump of the graph after the INCREMENTAL updates must equal a FROM-SCRATCH build of the final tree, byte for
|
|
6
|
+
* byte. The incremental side writes some files with CRLF (a Windows `core.autocrlf` checkout); the scratch
|
|
7
|
+
* side reads the same tree LF-only (a Linux checkout) — content identity is EOL-normalized (contentHash.ts),
|
|
8
|
+
* so the dumps still agree. The second-OS leg runs in CI; this is its same-process half.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createRng, type Rng } from '../../stats/prng.js';
|
|
12
|
+
import { contentHash } from '../contentHash.js';
|
|
13
|
+
import type { CallFact, FileFacts } from '../facts/fileFacts.js';
|
|
14
|
+
import { buildFactGraph, factGraphDump, updateFactGraph, type FactChange, type FactGraph } from './factGraph.js';
|
|
15
|
+
import { emptyFacts, FIXTURE_RULES } from './rules.testkit.test-util.js';
|
|
16
|
+
|
|
17
|
+
/** 500 by default (the §8 done-check); `FACT_ORACLE_SEQUENCES` overrides it for a CI budget. */
|
|
18
|
+
const SEQUENCES = Number(process.env.FACT_ORACLE_SEQUENCES) > 0 ? Math.floor(Number(process.env.FACT_ORACLE_SEQUENCES)) : 500;
|
|
19
|
+
const STEPS = 6;
|
|
20
|
+
const encoder = new TextEncoder();
|
|
21
|
+
|
|
22
|
+
/** The fixture extractor: one fact per line, EOL-insensitive (as every real extractor must be). */
|
|
23
|
+
function extract(text: string): FileFacts {
|
|
24
|
+
const facts = emptyFacts(contentHash(encoder.encode(text)));
|
|
25
|
+
const calls = new Map<string, CallFact>();
|
|
26
|
+
for (const line of text.split(/\r\n|\r|\n/)) {
|
|
27
|
+
const [op, a, b] = line.trim().split(/\s+/);
|
|
28
|
+
if (op === 'import' && a) facts.imports.push({ specifier: a, resolved: a, names: [] });
|
|
29
|
+
else if (op === 'export' && a) {
|
|
30
|
+
facts.exports.push({ name: a, kind: 'function', signatureHash: a });
|
|
31
|
+
facts.symbols.push({ name: a, kind: 'function' });
|
|
32
|
+
} else if (op === 'call' && a) {
|
|
33
|
+
const loop = b === 'loop';
|
|
34
|
+
const key = `${a}|${loop}`;
|
|
35
|
+
const prior = calls.get(key);
|
|
36
|
+
calls.set(key, prior ? { ...prior, count: prior.count + 1 } : { callee: a, enclosing: 'main', awaited: loop || undefined, inLoop: loop || undefined, count: 1 });
|
|
37
|
+
} else if (op === 'route' && a && b) {
|
|
38
|
+
facts.entryPoints.push({ kind: 'http-route', key: `GET ${a}`, symbol: 'main', guards: [], inputs: [], chain: [b] });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
facts.calls.push(...calls.values());
|
|
42
|
+
return facts;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const lf = (text: string) => text.replace(/\r\n|\r/g, '\n');
|
|
46
|
+
const crlf = (text: string) => lf(text).replace(/\n/g, '\r\n');
|
|
47
|
+
|
|
48
|
+
const pick = <T>(rng: Rng, xs: readonly T[]): T => xs[Math.floor(rng() * xs.length)]!;
|
|
49
|
+
const int = (rng: Rng, n: number) => Math.floor(rng() * n);
|
|
50
|
+
|
|
51
|
+
function fixtureTree(): Map<string, string> {
|
|
52
|
+
return new Map([
|
|
53
|
+
['src/a.ts', 'import src/b.ts\nexport a\ncall db.get loop\n'],
|
|
54
|
+
['src/b.ts', 'import src/c.ts\nexport b\ncall fetch\n// note\n'],
|
|
55
|
+
['src/c.ts', 'import src/b.ts\nexport c\n'],
|
|
56
|
+
['src/auth.ts', 'export requireAuth\n'],
|
|
57
|
+
['src/routes.ts', 'import src/a.ts\nroute /x src/auth.ts\nroute /y src/a.ts\n'],
|
|
58
|
+
['src/win.ts', crlf('import src/a.ts\nexport w1\nexport w2\nexport w3\ncall kv.put loop\n')],
|
|
59
|
+
['lib/u.ts', 'call helper\n'],
|
|
60
|
+
]);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One random step over the working tree; returns the paths it touched. */
|
|
64
|
+
function step(rng: Rng, tree: Map<string, string>, n: number): string[] {
|
|
65
|
+
const paths = [...tree.keys()].sort();
|
|
66
|
+
const path = pick(rng, paths);
|
|
67
|
+
const text = tree.get(path)!;
|
|
68
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
69
|
+
const append = (line: string) => { tree.set(path, `${text}${line}${eol}`); return [path]; };
|
|
70
|
+
switch (int(rng, 10)) {
|
|
71
|
+
case 0: return append(`// comment ${n}`);
|
|
72
|
+
case 1: return append(`call fn${int(rng, 4)}${rng() < 0.5 ? ' loop' : ''}`);
|
|
73
|
+
case 2: return append(`export e${int(rng, 5)}`);
|
|
74
|
+
case 3: return append(`import ${pick(rng, paths)}`);
|
|
75
|
+
case 4: return append(`route /r${int(rng, 3)} ${pick(rng, [...paths, 'src/auth.ts'])}`);
|
|
76
|
+
case 5: {
|
|
77
|
+
const lines = text.split(eol).filter((l) => l !== '');
|
|
78
|
+
if (lines.length === 0) return [];
|
|
79
|
+
lines.splice(int(rng, lines.length), 1);
|
|
80
|
+
tree.set(path, lines.map((l) => `${l}${eol}`).join(''));
|
|
81
|
+
return [path];
|
|
82
|
+
}
|
|
83
|
+
case 6:
|
|
84
|
+
if (tree.size <= 3) return [];
|
|
85
|
+
tree.delete(path);
|
|
86
|
+
return [path];
|
|
87
|
+
case 7: {
|
|
88
|
+
const added = `src/new${n}.ts`;
|
|
89
|
+
tree.set(added, `import ${pick(rng, paths)}\nexport n${n}\ncall fn${int(rng, 4)} loop\n`);
|
|
90
|
+
return [added];
|
|
91
|
+
}
|
|
92
|
+
case 8: {
|
|
93
|
+
const to = `moved/${n}.ts`;
|
|
94
|
+
tree.delete(path);
|
|
95
|
+
tree.set(to, text);
|
|
96
|
+
return [path, to];
|
|
97
|
+
}
|
|
98
|
+
default:
|
|
99
|
+
tree.set(path, eol === '\r\n' ? lf(text) : crlf(text));
|
|
100
|
+
return [path];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const changesOf = (tree: ReadonlyMap<string, string>, paths: readonly string[]): FactChange[] =>
|
|
105
|
+
paths.map((path) => ({ path, facts: tree.has(path) ? extract(tree.get(path)!) : null }));
|
|
106
|
+
|
|
107
|
+
/** The Linux checkout of the same tree: LF only. */
|
|
108
|
+
const scratchOf = (tree: ReadonlyMap<string, string>) =>
|
|
109
|
+
factGraphDump(buildFactGraph([...tree].map(([p, t]) => [p, extract(lf(t))] as const), FIXTURE_RULES).graph);
|
|
110
|
+
|
|
111
|
+
describe('determinism oracle (B8.6): incremental dump === scratch dump', () => {
|
|
112
|
+
it(`holds byte for byte over ${SEQUENCES} seeded edit sequences, with CRLF files on the incremental side`, () => {
|
|
113
|
+
let reused = 0;
|
|
114
|
+
for (let seed = 0; seed < SEQUENCES; seed++) {
|
|
115
|
+
const rng = createRng(seed);
|
|
116
|
+
const tree = fixtureTree();
|
|
117
|
+
let graph: FactGraph = buildFactGraph([...tree].map(([p, t]) => [p, extract(t)] as const), FIXTURE_RULES).graph;
|
|
118
|
+
for (let n = 0; n < STEPS; n++) {
|
|
119
|
+
const touched = step(rng, tree, n);
|
|
120
|
+
const update = updateFactGraph(graph, changesOf(tree, touched), FIXTURE_RULES);
|
|
121
|
+
reused += update.trace.filter((t) => t.outcome === 'reused').length;
|
|
122
|
+
graph = update.graph;
|
|
123
|
+
}
|
|
124
|
+
const incremental = factGraphDump(graph);
|
|
125
|
+
const scratch = scratchOf(tree);
|
|
126
|
+
if (incremental !== scratch) throw new Error(`oracle failed at seed ${seed}`);
|
|
127
|
+
}
|
|
128
|
+
// The oracle exercised the incremental path, not a full recompute each step.
|
|
129
|
+
expect(reused).toBeGreaterThan(SEQUENCES * STEPS);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('an EOL-only rewrite (autocrlf) is no change at all: every row reused, the dump unmoved', () => {
|
|
133
|
+
const tree = fixtureTree();
|
|
134
|
+
const built = buildFactGraph([...tree].map(([p, t]) => [p, extract(t)] as const), FIXTURE_RULES);
|
|
135
|
+
const update = updateFactGraph(built.graph, [...tree].map(([path, t]) => ({ path, facts: extract(crlf(t)) })), FIXTURE_RULES);
|
|
136
|
+
expect(update.changed).toEqual([]);
|
|
137
|
+
expect(update.trace.every((t) => t.outcome === 'reused')).toBe(true);
|
|
138
|
+
expect(factGraphDump(update.graph)).toBe(factGraphDump(built.graph));
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('a Windows (CRLF, backslashed paths) checkout and a Linux (LF) checkout build the same dump', () => {
|
|
142
|
+
const tree = fixtureTree();
|
|
143
|
+
const bs = (p: string) => p.replace(/\//g, '\\');
|
|
144
|
+
const windowsFacts = (t: string): FileFacts => {
|
|
145
|
+
const f = extract(crlf(t));
|
|
146
|
+
return {
|
|
147
|
+
...f,
|
|
148
|
+
imports: f.imports.map((i) => ({ ...i, resolved: bs(i.resolved!) })),
|
|
149
|
+
entryPoints: f.entryPoints.map((e) => ({ ...e, chain: e.chain.map(bs) })),
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
const windows = factGraphDump(buildFactGraph([...tree].map(([p, t]) => [bs(p), windowsFacts(t)] as const), FIXTURE_RULES).graph);
|
|
153
|
+
expect(windows).toBe(scratchOf(tree));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('`changed` compares against the pre-batch graph: an edit reverted in the same batch is no change', () => {
|
|
157
|
+
const tree = fixtureTree();
|
|
158
|
+
const built = buildFactGraph([...tree].map(([p, t]) => [p, extract(t)] as const), FIXTURE_RULES);
|
|
159
|
+
const a = tree.get('src/a.ts')!;
|
|
160
|
+
const update = updateFactGraph(built.graph, [
|
|
161
|
+
{ path: 'src/a.ts', facts: extract(`${a}export z\n`) }, { path: 'src/a.ts', facts: extract(a) },
|
|
162
|
+
{ path: 'src/tmp.ts', facts: extract('export t\n') }, { path: 'src/tmp.ts', facts: null },
|
|
163
|
+
], FIXTURE_RULES);
|
|
164
|
+
expect(update.changed).toEqual([]);
|
|
165
|
+
expect(factGraphDump(update.graph)).toBe(factGraphDump(built.graph));
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('the dump is independent of the order files arrive in', () => {
|
|
169
|
+
const entries = [...fixtureTree()].map(([p, t]) => [p, extract(t)] as const);
|
|
170
|
+
const forward = factGraphDump(buildFactGraph(entries, FIXTURE_RULES).graph);
|
|
171
|
+
const reverse = factGraphDump(buildFactGraph([...entries].reverse(), FIXTURE_RULES).graph);
|
|
172
|
+
expect(reverse).toBe(forward);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/factGraph.ts — the content-addressed fact graph in memory (PRD 41 §B1, §B8.6): the
|
|
3
|
+
* manifest (path → content hash, facts hash, kind hashes), the facts objects by facts hash, and the
|
|
4
|
+
* derived rule rows with their traces. Pure and immutable: an update returns a new graph.
|
|
5
|
+
*
|
|
6
|
+
* {@link factGraphDump} is the canonical dump the determinism oracle compares: sorted canonical JSON of
|
|
7
|
+
* the manifest, the referenced objects and the derived rows — never a trace outcome, a time or an order of
|
|
8
|
+
* arrival. An incremental graph and a from-scratch build of the same files dump to the same bytes.
|
|
9
|
+
* A durable host persists the same three tables behind its store; this module does no I/O.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { canonicalJson, compareStr, isRootFilePath, normalizePath } from '../refs.js';
|
|
13
|
+
import type { Finding } from '../findingModel.js';
|
|
14
|
+
import { canonicalFileFacts, factKindHashes, factsHash, type FactKind, type FileFacts } from '../facts/fileFacts.js';
|
|
15
|
+
import type { FactRule } from './factRule.js';
|
|
16
|
+
import { evaluateRules, type DerivedRows, type RuleTraceEntry, type RuleWorld } from './evaluateRules.js';
|
|
17
|
+
|
|
18
|
+
export interface FactManifestEntry {
|
|
19
|
+
contentHash: string;
|
|
20
|
+
factsHash: string;
|
|
21
|
+
kinds: Readonly<Record<FactKind, string>>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface FactGraph {
|
|
25
|
+
manifest: ReadonlyMap<string, FactManifestEntry>;
|
|
26
|
+
/** Facts by facts hash — only those the manifest references. */
|
|
27
|
+
objects: ReadonlyMap<string, FileFacts>;
|
|
28
|
+
derived: DerivedRows;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One file's new facts, or `null` when it was deleted. A rename is a delete plus an add. */
|
|
32
|
+
export interface FactChange {
|
|
33
|
+
path: string;
|
|
34
|
+
facts: FileFacts | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type FactGraphOptions<X> = Pick<RuleWorld<X>, 'neighbours' | 'extra' | 'extraHashes'>;
|
|
38
|
+
|
|
39
|
+
export interface FactGraphUpdate {
|
|
40
|
+
graph: FactGraph;
|
|
41
|
+
trace: RuleTraceEntry[];
|
|
42
|
+
findings: Finding[];
|
|
43
|
+
/** Paths whose facts hash changed (added, edited or deleted), sorted. Empty ⇒ every rule row was reused (early cutoff). */
|
|
44
|
+
changed: string[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The current dump format. */
|
|
48
|
+
export const FACT_GRAPH_DUMP_VERSION = 1;
|
|
49
|
+
|
|
50
|
+
export const emptyFactGraph = (): FactGraph => ({ manifest: new Map(), objects: new Map(), derived: new Map() });
|
|
51
|
+
|
|
52
|
+
/** The ONE path form of the graph (§B8.1); throws `fact_graph_bad_path` for a path outside the root. */
|
|
53
|
+
function pathOf(raw: string): string {
|
|
54
|
+
const p = normalizePath(raw);
|
|
55
|
+
if (!isRootFilePath(p)) throw new Error(`fact_graph_bad_path:${raw}`);
|
|
56
|
+
return p;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Applies `changes` (the last change of a path wins) and re-evaluates `rules`, reusing every derived row whose
|
|
61
|
+
* trace still holds. Unreferenced objects are dropped, so the graph never depends on its history.
|
|
62
|
+
*/
|
|
63
|
+
export function updateFactGraph<X>(graph: FactGraph, changes: readonly FactChange[], rules: readonly FactRule<X>[], opts: FactGraphOptions<X> = {}): FactGraphUpdate {
|
|
64
|
+
const manifest = new Map(graph.manifest);
|
|
65
|
+
const objects = new Map(graph.objects);
|
|
66
|
+
const touched = new Set<string>();
|
|
67
|
+
for (const c of changes) {
|
|
68
|
+
const path = pathOf(c.path);
|
|
69
|
+
touched.add(path);
|
|
70
|
+
if (c.facts === null) { manifest.delete(path); continue; }
|
|
71
|
+
// Canonical facts are deep-frozen: the stored object can never be mutated under its hash.
|
|
72
|
+
const facts = canonicalFileFacts(c.facts);
|
|
73
|
+
const hash = factsHash(facts);
|
|
74
|
+
if (manifest.get(path)?.factsHash === hash) continue;
|
|
75
|
+
if (!objects.has(hash)) objects.set(hash, facts);
|
|
76
|
+
manifest.set(path, { contentHash: facts.contentHash, factsHash: hash, kinds: factKindHashes(objects.get(hash)!) });
|
|
77
|
+
}
|
|
78
|
+
// Against the PRE-batch manifest, so a path edited and reverted (or added and deleted) in one batch is no change.
|
|
79
|
+
const changed = [...touched].filter((p) => graph.manifest.get(p)?.factsHash !== manifest.get(p)?.factsHash);
|
|
80
|
+
const live = new Set([...manifest.values()].map((e) => e.factsHash));
|
|
81
|
+
for (const h of [...objects.keys()]) if (!live.has(h)) objects.delete(h);
|
|
82
|
+
|
|
83
|
+
const files = new Map([...manifest].map(([p, e]) => [p, objects.get(e.factsHash)!] as const));
|
|
84
|
+
const result = evaluateRules(rules, { files, ...opts }, graph.derived);
|
|
85
|
+
return {
|
|
86
|
+
graph: { manifest, objects, derived: result.rows },
|
|
87
|
+
trace: result.trace,
|
|
88
|
+
findings: result.findings,
|
|
89
|
+
changed: changed.sort(compareStr),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A from-scratch build: every file added to an empty graph. */
|
|
94
|
+
export function buildFactGraph<X>(files: Iterable<readonly [string, FileFacts]>, rules: readonly FactRule<X>[], opts: FactGraphOptions<X> = {}): FactGraphUpdate {
|
|
95
|
+
return updateFactGraph(emptyFactGraph(), [...files].map(([path, facts]) => ({ path, facts })), rules, opts);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The canonical dump: sorted canonical JSON of the manifest, the referenced objects and the derived rows. */
|
|
99
|
+
export function factGraphDump(graph: FactGraph): string {
|
|
100
|
+
const sortedEntries = <V>(m: ReadonlyMap<string, V>) => [...m].sort((a, b) => compareStr(a[0], b[0]));
|
|
101
|
+
return canonicalJson({
|
|
102
|
+
version: FACT_GRAPH_DUMP_VERSION,
|
|
103
|
+
manifest: sortedEntries(graph.manifest).map(([path, e]) => ({ path, ...e })),
|
|
104
|
+
objects: sortedEntries(graph.objects).map(([hash, facts]) => ({ hash, facts })),
|
|
105
|
+
derived: sortedEntries(graph.derived).map(([, row]) => row),
|
|
106
|
+
});
|
|
107
|
+
}
|