@seanhogg/builderforce-memory 2026.10.75 → 2026.10.77
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/facts/factsHash.d.ts +27 -0
- package/dist/knowledge/facts/factsHash.d.ts.map +1 -0
- package/dist/knowledge/facts/factsHash.js +67 -0
- package/dist/knowledge/facts/factsHash.js.map +1 -0
- package/dist/knowledge/facts/fileFacts.d.ts +70 -12
- package/dist/knowledge/facts/fileFacts.d.ts.map +1 -1
- package/dist/knowledge/facts/fileFacts.js +42 -33
- package/dist/knowledge/facts/fileFacts.js.map +1 -1
- package/dist/knowledge/facts/guards.d.ts +101 -0
- package/dist/knowledge/facts/guards.d.ts.map +1 -0
- package/dist/knowledge/facts/guards.js +260 -0
- package/dist/knowledge/facts/guards.js.map +1 -0
- package/dist/knowledge/index.d.ts +9 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +7 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -1
- package/dist/knowledge/rules/evaluateRules.js +2 -1
- package/dist/knowledge/rules/evaluateRules.js.map +1 -1
- package/dist/knowledge/rules/factGraph.d.ts +2 -0
- package/dist/knowledge/rules/factGraph.d.ts.map +1 -1
- package/dist/knowledge/rules/factGraph.js +6 -2
- package/dist/knowledge/rules/factGraph.js.map +1 -1
- package/dist/knowledge/rules/factStore.d.ts +139 -0
- package/dist/knowledge/rules/factStore.d.ts.map +1 -0
- package/dist/knowledge/rules/factStore.js +252 -0
- package/dist/knowledge/rules/factStore.js.map +1 -0
- package/dist/stats/prng.d.ts +5 -1
- package/dist/stats/prng.d.ts.map +1 -1
- package/dist/stats/prng.js +11 -3
- package/dist/stats/prng.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +14 -0
- package/src/contract/regression.prng.test.ts +126 -0
- package/src/contract/types.contract.test.ts +57 -2
- package/src/knowledge/facts/factsHash.test.ts +50 -0
- package/src/knowledge/facts/factsHash.ts +71 -0
- package/src/knowledge/facts/fileFacts.test.ts +2 -1
- package/src/knowledge/facts/fileFacts.ts +104 -36
- package/src/knowledge/facts/guards.test.ts +276 -0
- package/src/knowledge/facts/guards.ts +296 -0
- package/src/knowledge/index.ts +13 -1
- package/src/knowledge/rules/evaluateRules.ts +2 -1
- package/src/knowledge/rules/factGraph.ts +8 -2
- package/src/knowledge/rules/factStore.test.ts +303 -0
- package/src/knowledge/rules/factStore.ts +317 -0
- package/src/stats/prng.ts +11 -3
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/facts/guards.test.ts — golden tests for the guard-chain semantics (PRD 41 §C5.1): a path-scoped `use`
|
|
3
|
+
* guards only routes registered after it; router identity; a mounted sub-router inherits its mounting router's guards;
|
|
4
|
+
* mount guards; unknown order; depth and cycles; path patterns; the additive `mounts` / `uses` fields.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { FACTS_EXTRACTOR_VERSION, factsExtractorTag } from './extractorVersion.js';
|
|
8
|
+
import { canonicalFileFacts, readFileFacts, type EntryPointFact, type FileFacts } from './fileFacts.js';
|
|
9
|
+
import { factKindHashes, factsHash } from './factsHash.js';
|
|
10
|
+
import { effectiveGuards, joinRoutePath, MAX_MOUNT_DEPTH, rootRouters, routePathCovers, type EffectiveGuardsResult, type ResolvedMount } from './guards.js';
|
|
11
|
+
|
|
12
|
+
const base = (over: Partial<FileFacts> = {}): FileFacts => ({
|
|
13
|
+
factsVersion: FACTS_EXTRACTOR_VERSION, extractor: factsExtractorTag({ family: 'tree-sitter' }, 'typescript'), language: 'typescript',
|
|
14
|
+
contentHash: 'c', symbols: [], imports: [], exports: [], entryPoints: [], calls: [], complexity: [], capabilityImports: [], ...over,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const route = (key: string, order: number | undefined, guards: string[] = [], router?: string): EntryPointFact =>
|
|
18
|
+
({ kind: 'http-route', key, symbol: `h${order ?? 'x'}`, guards, inputs: [], chain: [], ...(order !== undefined ? { order } : {}), ...(router ? { router } : {}) });
|
|
19
|
+
|
|
20
|
+
const guardsOf = (r: EffectiveGuardsResult) => Object.fromEntries(r.entryPoints.map((e) => [e.key, e.guards]));
|
|
21
|
+
|
|
22
|
+
describe('effectiveGuards: a use guards only routes registered after it', () => {
|
|
23
|
+
it('golden: a path-scoped use registered AFTER a route does not guard it', () => {
|
|
24
|
+
// app.get('/admin/early', h0); app.use('/admin', requireAuth); app.get('/admin/late', h2); app.get('/public', h3)
|
|
25
|
+
const app = base({
|
|
26
|
+
entryPoints: [route('GET /admin/early', 0), route('GET /admin/late', 2), route('GET /public', 3)],
|
|
27
|
+
uses: [{ path: '/admin', guards: ['requireAuth'], order: 1 }],
|
|
28
|
+
});
|
|
29
|
+
expect(guardsOf(effectiveGuards(app, []))).toEqual({
|
|
30
|
+
'GET /admin/early': [],
|
|
31
|
+
'GET /admin/late': ['requireAuth'],
|
|
32
|
+
'GET /public': [],
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('a path-less use covers every later route; a route keeps its own inline guards', () => {
|
|
37
|
+
const app = base({
|
|
38
|
+
entryPoints: [route('POST /a', 0, ['csrf']), route('POST /b', 2, ['csrf'])],
|
|
39
|
+
uses: [{ path: '', guards: ['requireAuth'], order: 1 }],
|
|
40
|
+
});
|
|
41
|
+
expect(guardsOf(effectiveGuards(app, []))).toEqual({ 'POST /a': ['csrf'], 'POST /b': ['csrf', 'requireAuth'] });
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe('effectiveGuards: unknown order', () => {
|
|
46
|
+
it('a route with no order takes every covering use, reported as inferred', () => {
|
|
47
|
+
const app = base({ entryPoints: [route('GET /x', undefined, ['own'])], uses: [{ path: '/', guards: ['g', 'own'], order: 5 }] });
|
|
48
|
+
const [ep] = effectiveGuards(app, []).entryPoints;
|
|
49
|
+
expect(ep!.guards).toEqual(['g', 'own']);
|
|
50
|
+
expect(ep!.guardsInferred).toEqual(['g']);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('a route with a known order infers nothing', () => {
|
|
54
|
+
const app = base({ entryPoints: [route('GET /x', 6)], uses: [{ path: '/', guards: ['g'], order: 5 }] });
|
|
55
|
+
const [ep] = effectiveGuards(app, []).entryPoints;
|
|
56
|
+
expect(ep!.guards).toEqual(['g']);
|
|
57
|
+
expect(ep!.guardsInferred).toEqual([]);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('effectiveGuards: router identity', () => {
|
|
62
|
+
it('golden: two routers in one file — an adminRouter use never guards publicRouter routes', () => {
|
|
63
|
+
const file = base({
|
|
64
|
+
entryPoints: [route('GET /dash', 1, [], 'adminRouter'), route('GET /home', 2, [], 'publicRouter')],
|
|
65
|
+
uses: [{ path: '', guards: ['requireSuperadmin'], order: 0, router: 'adminRouter' }],
|
|
66
|
+
});
|
|
67
|
+
expect(guardsOf(effectiveGuards(file, []))).toEqual({ 'GET /dash': ['requireSuperadmin'], 'GET /home': [] });
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('golden: a same-file local mount does not re-emit the parent router\'s own routes', () => {
|
|
71
|
+
// app.use(requireAuth); app.get('/health', h1); adminRouter.get('/users', h2); app.route('/admin', adminRouter)
|
|
72
|
+
const file = base({
|
|
73
|
+
entryPoints: [route('GET /health', 1, [], 'app'), route('GET /users', 2, [], 'adminRouter')],
|
|
74
|
+
uses: [{ path: '', guards: ['requireAuth'], order: 0, router: 'app' }],
|
|
75
|
+
mounts: [{ prefix: '/admin', target: 'adminRouter', order: 3, router: 'app' }],
|
|
76
|
+
});
|
|
77
|
+
const r = effectiveGuards(file, [], { path: 'src/app.ts' });
|
|
78
|
+
expect(r.entryPoints.map((e) => [e.key, e.guards, e.via])).toEqual([
|
|
79
|
+
['GET /admin/users', ['requireAuth'], ['/admin']],
|
|
80
|
+
['GET /health', ['requireAuth'], []],
|
|
81
|
+
]);
|
|
82
|
+
expect(r.entryPoints.every((e) => e.file === 'src/app.ts' && !e.chain.includes('src/app.ts'))).toBe(true);
|
|
83
|
+
expect([r.truncated, r.unresolved]).toEqual([0, 0]);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe('effectiveGuards: a mounted sub-router inherits the mounting app guards', () => {
|
|
88
|
+
const sub = base({
|
|
89
|
+
contentHash: 'sub',
|
|
90
|
+
entryPoints: [route('GET /projects/:id', 1, ['RoleGate']), route('POST /admin/reset', 2)],
|
|
91
|
+
uses: [{ path: '/admin/*', guards: ['requireSuperadmin'], order: 0 }],
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('golden: guards registered before the mount, covering the prefix, apply to every sub-router route (prefix-joined)', () => {
|
|
95
|
+
// app.use('/api/*', requireAuth); app.route('/api', sub); app.use('/api/*', lateAudit)
|
|
96
|
+
const app = base({
|
|
97
|
+
uses: [{ path: '/api/*', guards: ['requireAuth'], order: 0 }, { path: '/api/*', guards: ['lateAudit'], order: 2 }],
|
|
98
|
+
mounts: [{ prefix: '/api', target: './sub', order: 1 }],
|
|
99
|
+
});
|
|
100
|
+
const r = effectiveGuards(app, [{ target: './sub', path: 'src/sub.ts', facts: sub }], { path: 'src/app.ts' });
|
|
101
|
+
expect(guardsOf(r)).toEqual({
|
|
102
|
+
'GET /api/projects/:id': ['RoleGate', 'requireAuth'],
|
|
103
|
+
'POST /api/admin/reset': ['requireAuth', 'requireSuperadmin'],
|
|
104
|
+
});
|
|
105
|
+
expect(r.entryPoints.every((e) => e.file === 'src/sub.ts' && e.via.join() === '/api' && e.chain.includes('src/app.ts'))).toBe(true);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('golden: inline mount guards — router.use(\'/api\', requireAuth, apiRouter) — apply to every mounted route', () => {
|
|
109
|
+
const app = base({ mounts: [{ prefix: '/api', target: './sub', order: 0, guards: ['requireAuth'] }] });
|
|
110
|
+
expect(guardsOf(effectiveGuards(app, [{ target: './sub', path: 'src/sub.ts', facts: sub }]))).toEqual({
|
|
111
|
+
'GET /api/projects/:id': ['RoleGate', 'requireAuth'],
|
|
112
|
+
'POST /api/admin/reset': ['requireAuth', 'requireSuperadmin'],
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('a mounting use scoped below the prefix guards only the sub-routes under it', () => {
|
|
117
|
+
const app = base({
|
|
118
|
+
uses: [{ path: '/api/admin', guards: ['requireSuperadmin2'], order: 0 }],
|
|
119
|
+
mounts: [{ prefix: '/api', target: './sub', order: 1 }],
|
|
120
|
+
});
|
|
121
|
+
expect(guardsOf(effectiveGuards(app, [{ target: './sub', path: 'src/sub.ts', facts: sub }]))).toEqual({
|
|
122
|
+
'GET /api/projects/:id': ['RoleGate'],
|
|
123
|
+
'POST /api/admin/reset': ['requireSuperadmin', 'requireSuperadmin2'],
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('nested mounts compose transitively; maxDepth truncates and says so', () => {
|
|
128
|
+
const leaf = base({ contentHash: 'leaf', entryPoints: [route('GET /ping', 0)] });
|
|
129
|
+
const mid = base({ contentHash: 'mid', uses: [{ path: '', guards: ['mid'], order: 0 }], mounts: [{ prefix: '/v1', target: './leaf', order: 1 }] });
|
|
130
|
+
const app = base({ uses: [{ path: '', guards: ['top'], order: 0 }], mounts: [{ prefix: '/api', target: './mid', order: 1 }] });
|
|
131
|
+
const resolved: ResolvedMount[] = [{ target: './mid', path: 'mid.ts', facts: mid, mounts: [{ target: './leaf', path: 'leaf.ts', facts: leaf }] }];
|
|
132
|
+
const r = effectiveGuards(app, resolved, { path: 'app.ts' });
|
|
133
|
+
expect(r.entryPoints.map((e) => [e.key, e.guards, e.via, e.chain])).toEqual([['GET /api/v1/ping', ['mid', 'top'], ['/api', '/v1'], ['app.ts', 'mid.ts']]]);
|
|
134
|
+
expect(r.truncated).toBe(0);
|
|
135
|
+
const shallow = effectiveGuards(app, resolved, { maxDepth: 1 });
|
|
136
|
+
expect([shallow.entryPoints, shallow.truncated]).toEqual([[], 1]);
|
|
137
|
+
expect(effectiveGuards(app, resolved, { maxDepth: Number.NaN }).entryPoints).toHaveLength(1);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('a mount cycle is cut and counted, never looped', () => {
|
|
141
|
+
const a = base({ contentHash: 'a', entryPoints: [route('GET /a', 0)], mounts: [{ prefix: '/b', target: './b', order: 1 }] });
|
|
142
|
+
const b = base({ contentHash: 'b', entryPoints: [route('GET /b', 0)], mounts: [{ prefix: '/a', target: './a', order: 1 }] });
|
|
143
|
+
const resolvedB: ResolvedMount = { target: './b', path: 'b.ts', facts: b };
|
|
144
|
+
const resolvedA: ResolvedMount = { target: './a', path: 'a.ts', facts: a, mounts: [resolvedB] };
|
|
145
|
+
(resolvedB as { mounts?: readonly ResolvedMount[] }).mounts = [resolvedA];
|
|
146
|
+
const r = effectiveGuards(a, [resolvedB], { path: 'a.ts' });
|
|
147
|
+
expect(r.entryPoints.map((e) => e.key)).toEqual(['GET /a', 'GET /b/b']);
|
|
148
|
+
expect(r.truncated).toBe(1);
|
|
149
|
+
expect(MAX_MOUNT_DEPTH).toBe(8);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('an unresolved mount is counted; non-route entries of a sub-router are not mounted', () => {
|
|
153
|
+
const withCmd = base({ entryPoints: [{ kind: 'vscode-command', key: 'bf.run', symbol: 'run', guards: [], inputs: [], chain: [] }] });
|
|
154
|
+
const app = base({ mounts: [{ prefix: '/api', target: './x', order: 0 }] });
|
|
155
|
+
expect(effectiveGuards(app, [])).toEqual({ entryPoints: [], truncated: 0, unresolved: 1 });
|
|
156
|
+
expect(effectiveGuards(app, [{ target: './x', path: 'x.ts', facts: withCmd }]).entryPoints).toEqual([]);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
describe('rootRouters (per router)', () => {
|
|
161
|
+
it('drops routers another file mounts, keeps local mounts within their file', () => {
|
|
162
|
+
const files = new Map<string, FileFacts>([
|
|
163
|
+
['app.ts', base({ entryPoints: [route('GET /', 0)], mounts: [{ prefix: '/api', target: './sub', order: 1 }, { prefix: '/x', target: 'local', order: 2 }] })],
|
|
164
|
+
['sub.ts', base({ contentHash: 's', entryPoints: [route('GET /p', 0)] })],
|
|
165
|
+
['other.ts', base({ contentHash: 'o', entryPoints: [route('GET /o', 0, [], 'local')] })],
|
|
166
|
+
['lib.ts', base({ contentHash: 'l' })],
|
|
167
|
+
]);
|
|
168
|
+
expect(rootRouters(files, (_from, m) => (m.target === './sub' ? { path: 'sub.ts' } : undefined)))
|
|
169
|
+
.toEqual([{ path: 'app.ts', router: '' }, { path: 'other.ts', router: 'local' }]);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('a mounted file\'s second, unmounted router is still a root; its locally mounted router is not', () => {
|
|
173
|
+
const files = new Map<string, FileFacts>([
|
|
174
|
+
['app.ts', base({ entryPoints: [route('GET /', 0)], mounts: [{ prefix: '/api', target: './routers', order: 1 }] })],
|
|
175
|
+
['routers.ts', base({
|
|
176
|
+
contentHash: 'r',
|
|
177
|
+
entryPoints: [route('GET /a', 0, [], 'apiRouter'), route('GET /w', 1, [], 'webhookRouter'), route('GET /n', 2, [], 'nested')],
|
|
178
|
+
mounts: [{ prefix: '/n', target: 'nested', order: 3, router: 'apiRouter' }],
|
|
179
|
+
})],
|
|
180
|
+
]);
|
|
181
|
+
const roots = rootRouters(files, (_from, m) => (m.target === './routers' ? { path: 'routers.ts', router: 'apiRouter' } : undefined));
|
|
182
|
+
expect(roots).toEqual([{ path: 'app.ts', router: '' }, { path: 'routers.ts', router: 'webhookRouter' }]);
|
|
183
|
+
const webhook = effectiveGuards(files.get('routers.ts')!, [], roots[1]!);
|
|
184
|
+
expect(webhook.entryPoints.map((e) => e.key)).toEqual(['GET /w']);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it('files that mount each other: the lowest path becomes the root, deterministically', () => {
|
|
188
|
+
const a = base({ contentHash: 'a', entryPoints: [route('GET /a', 0)], mounts: [{ prefix: '/b', target: './b', order: 1 }] });
|
|
189
|
+
const b = base({ contentHash: 'b', entryPoints: [route('GET /b', 0)], mounts: [{ prefix: '/a', target: './a', order: 1 }] });
|
|
190
|
+
const resolve = (_from: string, m: { target: string }) => ({ path: m.target === './a' ? 'a.ts' : 'b.ts' });
|
|
191
|
+
expect(rootRouters(new Map([['b.ts', b], ['a.ts', a]]), resolve)).toEqual([{ path: 'a.ts', router: '' }]);
|
|
192
|
+
expect(rootRouters(new Map([['a.ts', a], ['b.ts', b]]), resolve)).toEqual([{ path: 'a.ts', router: '' }]);
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
describe('route path patterns', () => {
|
|
197
|
+
it('prefix, exact, params and wildcards', () => {
|
|
198
|
+
expect(routePathCovers('/api', '/api/x')).toBe(true);
|
|
199
|
+
expect(routePathCovers('/api', '/api/x', 'exact')).toBe(false);
|
|
200
|
+
expect(routePathCovers('/api', '/apix')).toBe(false);
|
|
201
|
+
expect(routePathCovers('/api/*', '/api')).toBe(true);
|
|
202
|
+
expect(routePathCovers('/p/:id/k', '/p/7/k/w')).toBe(true);
|
|
203
|
+
expect(routePathCovers('*', '/anything')).toBe(true);
|
|
204
|
+
expect(joinRoutePath('/api/', '/')).toBe('/api');
|
|
205
|
+
expect(joinRoutePath('', '/x')).toBe('/x');
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('a trailing * on the last segment (/api*) is a prefix of that segment and the rest', () => {
|
|
209
|
+
expect(routePathCovers('/api*', '/api')).toBe(true);
|
|
210
|
+
expect(routePathCovers('/api*', '/apiv2/x')).toBe(true);
|
|
211
|
+
expect(routePathCovers('/api*', '/ap')).toBe(false);
|
|
212
|
+
expect(routePathCovers('/api*', '/other')).toBe(false);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it('an optional :x? matches one segment or none', () => {
|
|
216
|
+
expect(routePathCovers('/p/:id?', '/p', 'exact')).toBe(true);
|
|
217
|
+
expect(routePathCovers('/p/:id?', '/p/7', 'exact')).toBe(true);
|
|
218
|
+
expect(routePathCovers('/p/:id?', '/p/7/8', 'exact')).toBe(false);
|
|
219
|
+
expect(routePathCovers('/p/:id', '/p', 'exact')).toBe(false);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('a Hono :id{regex} param matches one segment', () => {
|
|
223
|
+
expect(routePathCovers('/p/:id{[0-9]+}', '/p/42', 'exact')).toBe(true);
|
|
224
|
+
expect(routePathCovers('/p/:id{[0-9]+}/k', '/p/42/k')).toBe(true);
|
|
225
|
+
expect(routePathCovers('/p/:id{[0-9]+}', '/p', 'exact')).toBe(false);
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
describe('FileFacts mounts / uses: additive, non-breaking', () => {
|
|
230
|
+
it('readFileFacts of an older object gives mounts: [] and uses: []; its hashes do not move', () => {
|
|
231
|
+
const old = base();
|
|
232
|
+
const read = readFileFacts(old);
|
|
233
|
+
expect(read.mounts).toEqual([]);
|
|
234
|
+
expect(read.uses).toEqual([]);
|
|
235
|
+
expect(factsHash(read)).toBe(factsHash({ ...old, mounts: [], uses: [] }));
|
|
236
|
+
expect(factKindHashes(read)).toEqual(factKindHashes({ ...old, mounts: [], uses: [] }));
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it('mounts and uses are structure facts, sorted canonically', () => {
|
|
240
|
+
const a = base({ mounts: [{ prefix: '/b', target: './b', order: 10 }, { prefix: '/a', target: './a', order: 2 }], uses: [{ path: '/', guards: ['y', 'x'], order: 1 }] });
|
|
241
|
+
const c = canonicalFileFacts(a);
|
|
242
|
+
expect(c.mounts!.map((m) => m.order)).toEqual([2, 10]);
|
|
243
|
+
expect(c.uses![0]!.guards).toEqual(['x', 'y']);
|
|
244
|
+
const reversed = base({ mounts: [...a.mounts!].reverse(), uses: a.uses });
|
|
245
|
+
expect(factsHash(reversed)).toBe(factsHash(a));
|
|
246
|
+
const before = factKindHashes(base());
|
|
247
|
+
const after = factKindHashes(a);
|
|
248
|
+
expect(after.structure).not.toBe(before.structure);
|
|
249
|
+
expect(after.body).toBe(before.body);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it('canonical form: match "prefix" dropped, mount prefix normalized, empty mount guards and absent router omitted', () => {
|
|
253
|
+
const c = canonicalFileFacts(base({
|
|
254
|
+
mounts: [{ prefix: 'api/', target: './a', order: 0, guards: [] }],
|
|
255
|
+
uses: [{ path: '/x', match: 'prefix', guards: [], order: 1 }, { path: '/y', match: 'exact', guards: [], order: 2 }],
|
|
256
|
+
}));
|
|
257
|
+
expect(c.mounts).toEqual([{ prefix: '/api', target: './a', order: 0 }]);
|
|
258
|
+
expect(c.uses).toEqual([{ path: '/x', guards: [], order: 1 }, { path: '/y', match: 'exact', guards: [], order: 2 }]);
|
|
259
|
+
expect(factsHash(base({ mounts: [{ prefix: '/api', target: './a', order: 0 }] })))
|
|
260
|
+
.toBe(factsHash(base({ mounts: [{ prefix: '/api/', target: './a', order: 0, guards: [] }] })));
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it('a use path is normalized: \'/admin/\' and \'/admin\' hash the same; \'\' stays the every-path form', () => {
|
|
264
|
+
const use = (path: string) => base({ uses: [{ path, guards: ['g'], order: 0 }] });
|
|
265
|
+
expect(factsHash(use('/admin/'))).toBe(factsHash(use('/admin')));
|
|
266
|
+
expect(factsHash(use('admin//'))).toBe(factsHash(use('/admin')));
|
|
267
|
+
expect(canonicalFileFacts(use('')).uses![0]!.path).toBe('');
|
|
268
|
+
expect(canonicalFileFacts(use('/admin/*/')).uses![0]!.path).toBe('/admin/*');
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it('an order that is not a non-negative integer is refused', () => {
|
|
272
|
+
expect(() => canonicalFileFacts(base({ uses: [{ path: '', guards: [], order: -1 }] }))).toThrow(/file_facts_invalid_order:use/);
|
|
273
|
+
expect(() => canonicalFileFacts(base({ mounts: [{ prefix: '/', target: 'x', order: 1.5 }] }))).toThrow(/file_facts_invalid_order:mount/);
|
|
274
|
+
expect(() => canonicalFileFacts(base({ entryPoints: [route('GET /x', Number.NaN)] }))).toThrow(/file_facts_invalid_order:entryPoint/);
|
|
275
|
+
});
|
|
276
|
+
});
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/facts/guards.ts — the guard-chain semantics of entry points across `use()` registrations and router mounts
|
|
3
|
+
* (PRD 41 §C5.1). Pure: the host resolves each imported mount's target to a file and its facts; this module composes.
|
|
4
|
+
*
|
|
5
|
+
* The rules, explicit:
|
|
6
|
+
* 1. ROUTER IDENTITY. Routes, uses and mounts belong to the router binding that registers them (`router`; absent = the
|
|
7
|
+
* file's one default router). A `use` on `adminRouter` never guards a route on `publicRouter`, even in one file.
|
|
8
|
+
* 2. ORDER. A `use(path?, guard)` ({@link UseFact}) guards a route of its router only when it was registered BEFORE the
|
|
9
|
+
* route (`order`) and its path pattern covers the route's path. A path-scoped `use` registered after a route never
|
|
10
|
+
* guards it. A route with no `order` takes every covering `use`, and those guards are reported in `guardsInferred`
|
|
11
|
+
* (a C5.1 rule downgrades them to heuristic). A producer that emits `uses` MUST set `order` on every entry point.
|
|
12
|
+
* 3. MOUNTS. A mounted sub-router (`app.route('/api', sub)`, `app.use('/api', subRouter)`, {@link MountFact}) answers its
|
|
13
|
+
* routes under the prefix-joined path, and inherits every `use` of the mounting router registered before the mount
|
|
14
|
+
* that covers the joined path, plus the mount's own inline `guards` — transitively, up to {@link MAX_MOUNT_DEPTH}
|
|
15
|
+
* levels. A target naming a local router binding of the same file is resolved here; other targets come from the host
|
|
16
|
+
* ({@link ResolvedMount}). Cycles are cut by the (file, router) pairs on the stack.
|
|
17
|
+
* 4. A route's own `guards` (inline middleware, wrappers) always apply.
|
|
18
|
+
*
|
|
19
|
+
* CALL SITES. `effectiveGuards` is called on ROOT routers only: files no other file mounts ({@link rootRouters}), and
|
|
20
|
+
* within a file the routers no local mount targets. A sub-router's routes are reported through their root (prefix-joined,
|
|
21
|
+
* with the inherited guards); calling it on a mounted file as well would report a bare, under-guarded copy of each route.
|
|
22
|
+
* Consumers that read `entryPoints[].guards` directly must switch to this function in the same change in which a producer
|
|
23
|
+
* starts emitting `uses`.
|
|
24
|
+
*
|
|
25
|
+
* Route paths come from the entry key: `'<METHOD> /path'` or `'/path'`. An entry point without a path (a VS Code command,
|
|
26
|
+
* an exported API) gets only path-less (`''`, `'*'`, `'/*'`) uses of its router, and is never mounted.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { compareStr, sortBy } from '../refs.js';
|
|
30
|
+
import { canonicalFileFacts, type EntryPointFact, type FileFacts, type MountFact, type UseFact } from './fileFacts.js';
|
|
31
|
+
|
|
32
|
+
/** How many mount levels `effectiveGuards` descends at most (mount nesting, not import hops). */
|
|
33
|
+
export const MAX_MOUNT_DEPTH = 8;
|
|
34
|
+
|
|
35
|
+
/** A mount the host resolved: the target (as written in {@link MountFact.target}) → the sub-router's file and facts. */
|
|
36
|
+
export interface ResolvedMount {
|
|
37
|
+
/** The {@link MountFact.target} this resolves (a file may mount one target at several prefixes). */
|
|
38
|
+
target: string;
|
|
39
|
+
/** The sub-router's root-relative file. */
|
|
40
|
+
path: string;
|
|
41
|
+
facts: FileFacts;
|
|
42
|
+
/** The router binding in that file that is mounted. Absent ⇒ that file's root routers. */
|
|
43
|
+
router?: string;
|
|
44
|
+
/** The sub-router file's own imported mounts, resolved the same way (nested routers). */
|
|
45
|
+
mounts?: readonly ResolvedMount[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** An entry point with its effective guards: prefix-joined key, composed guards, the mounting files on its chain. */
|
|
49
|
+
export interface EffectiveEntryPoint extends EntryPointFact {
|
|
50
|
+
/** The file that registers the handler: `opts.path` (default '') for the given file, the sub-router's path otherwise. */
|
|
51
|
+
file: string;
|
|
52
|
+
/** The mount prefixes from the root router down to the registering router, outermost first; empty for root routes. */
|
|
53
|
+
via: string[];
|
|
54
|
+
/** Guards in `guards` that apply only because the route has no `order` (rule 2), sorted. Empty when the order is known. */
|
|
55
|
+
guardsInferred: string[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface EffectiveGuardsOptions {
|
|
59
|
+
/** The given file's root-relative path: reported as `file`, and added to a mounted route's `chain`. */
|
|
60
|
+
path?: string;
|
|
61
|
+
/** The root router binding to start from ('' = the file's default router). Absent ⇒ every router of the file that no local mount targets. */
|
|
62
|
+
router?: string;
|
|
63
|
+
/** Mount levels to descend (0..{@link MAX_MOUNT_DEPTH}). Default {@link MAX_MOUNT_DEPTH}. */
|
|
64
|
+
maxDepth?: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface EffectiveGuardsResult {
|
|
68
|
+
/** Sorted by file, kind, key, symbol, via. */
|
|
69
|
+
entryPoints: EffectiveEntryPoint[];
|
|
70
|
+
/** Mounts not followed because of the depth limit or a cycle. */
|
|
71
|
+
truncated: number;
|
|
72
|
+
/** Mounts whose target was neither a local router nor in `resolvedMounts`. */
|
|
73
|
+
unresolved: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const WILDCARD_PATHS = new Set(['', '*', '/*']);
|
|
77
|
+
const segments = (path: string) => path.split('/').filter((s) => s !== '');
|
|
78
|
+
|
|
79
|
+
/** Joins a mount prefix and a route path into one `/`-rooted path ('/api' + '/x' → '/api/x'; '/api' + '/' → '/api'). */
|
|
80
|
+
export function joinRoutePath(prefix: string, path: string): string {
|
|
81
|
+
return `/${[...segments(prefix), ...segments(path)].join('/')}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const isParam = (seg: string) => seg.startsWith(':');
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Whether a `use` path pattern covers `path` (rule 2's path half). Segments: a literal matches itself; `:x`, `:x{regex}`
|
|
88
|
+
* match one segment; `:x?` matches one segment or none; `*` as the last segment matches the rest (zero or more segments);
|
|
89
|
+
* a last segment ending in `*` (`api*`) matches any segment starting with its stem, and the rest. `prefix` (default)
|
|
90
|
+
* covers every path under the pattern; `exact` that path only.
|
|
91
|
+
*/
|
|
92
|
+
export function routePathCovers(pattern: string, path: string, match: UseFact['match'] = 'prefix'): boolean {
|
|
93
|
+
if (WILDCARD_PATHS.has(pattern)) return true;
|
|
94
|
+
const pat = segments(pattern);
|
|
95
|
+
const segs = segments(path);
|
|
96
|
+
const last = pat.length - 1;
|
|
97
|
+
const at = (pi: number, si: number): boolean => {
|
|
98
|
+
if (pi === pat.length) return match === 'exact' ? si === segs.length : true;
|
|
99
|
+
const p = pat[pi]!;
|
|
100
|
+
if (pi === last && p === '*') return true;
|
|
101
|
+
if (pi === last && p.endsWith('*') && !isParam(p)) return si < segs.length && segs[si]!.startsWith(p.slice(0, -1));
|
|
102
|
+
if (isParam(p)) {
|
|
103
|
+
if (si < segs.length && at(pi + 1, si + 1)) return true;
|
|
104
|
+
return p.endsWith('?') && at(pi + 1, si);
|
|
105
|
+
}
|
|
106
|
+
if (p === '*') return si < segs.length && at(pi + 1, si + 1);
|
|
107
|
+
return si < segs.length && segs[si] === p && at(pi + 1, si + 1);
|
|
108
|
+
};
|
|
109
|
+
return at(0, 0);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** `'<METHOD> /path'` → method + path; `'/path'` → path; anything else → null (not a routed entry point). */
|
|
113
|
+
function parseRouteKey(key: string): { method: string; path: string } | null {
|
|
114
|
+
const m = /^(?:(\S+)\s+)?(\/\S*)$/.exec(key.trim());
|
|
115
|
+
return m ? { method: m[1] ?? '', path: m[2]! } : null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A use lifted to absolute paths: its pattern joined with the prefix of the router that registered it. */
|
|
119
|
+
interface ScopedUse { pattern: string; match: UseFact['match']; guards: readonly string[]; wildcard: boolean }
|
|
120
|
+
|
|
121
|
+
const everything = (prefix: string, guards: readonly string[], wildcard: boolean): ScopedUse =>
|
|
122
|
+
({ pattern: `${joinRoutePath(prefix, '')}/*`, match: 'prefix', guards, wildcard });
|
|
123
|
+
|
|
124
|
+
const scoped = (u: UseFact, prefix: string): ScopedUse => (WILDCARD_PATHS.has(u.path)
|
|
125
|
+
? everything(prefix, u.guards, true)
|
|
126
|
+
: { pattern: joinRoutePath(prefix, u.path), match: u.match, guards: u.guards, wildcard: false });
|
|
127
|
+
|
|
128
|
+
/** The router key of a registration ('' = the file's default router). */
|
|
129
|
+
const routerOf = (x: { router?: string }) => x.router ?? '';
|
|
130
|
+
|
|
131
|
+
/** Every router binding that registers something in `f`. */
|
|
132
|
+
function routersOf(f: FileFacts): Set<string> {
|
|
133
|
+
return new Set([...f.entryPoints.map(routerOf), ...(f.uses ?? []).map(routerOf), ...(f.mounts ?? []).map(routerOf)]);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The routers of `f` no local mount targets (rule 3), sorted. */
|
|
137
|
+
function rootRoutersOf(f: FileFacts): string[] {
|
|
138
|
+
const routers = routersOf(f);
|
|
139
|
+
for (const m of f.mounts ?? []) if (routers.has(m.target) && m.target !== routerOf(m)) routers.delete(m.target);
|
|
140
|
+
return [...routers].sort(compareStr);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Every entry point of the root router(s) of `fileFacts` and of the sub-routers they mount, with its EFFECTIVE guards
|
|
145
|
+
* (rules 1–4 of the header). Mounted routes get prefix-joined keys and the mounting files added to their `chain`.
|
|
146
|
+
*/
|
|
147
|
+
export function effectiveGuards(fileFacts: FileFacts, resolvedMounts: readonly ResolvedMount[], opts: EffectiveGuardsOptions = {}): EffectiveGuardsResult {
|
|
148
|
+
const requested = opts.maxDepth ?? MAX_MOUNT_DEPTH;
|
|
149
|
+
const maxDepth = Number.isFinite(requested) ? Math.max(0, Math.min(MAX_MOUNT_DEPTH, Math.floor(requested))) : MAX_MOUNT_DEPTH;
|
|
150
|
+
const out: EffectiveEntryPoint[] = [];
|
|
151
|
+
let truncated = 0;
|
|
152
|
+
let unresolved = 0;
|
|
153
|
+
|
|
154
|
+
interface Frame {
|
|
155
|
+
facts: FileFacts; file: string; router: string; prefix: string; via: readonly string[];
|
|
156
|
+
inherited: readonly ScopedUse[]; chainFiles: readonly string[]; resolved: readonly ResolvedMount[]; depth: number; stack: ReadonlySet<string>;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const visit = (fr: Frame) => {
|
|
160
|
+
const f = fr.facts;
|
|
161
|
+
const uses = (f.uses ?? []).filter((u) => routerOf(u) === fr.router);
|
|
162
|
+
for (const ep of f.entryPoints) {
|
|
163
|
+
if (routerOf(ep) !== fr.router) continue;
|
|
164
|
+
const route = parseRouteKey(ep.key);
|
|
165
|
+
if (fr.depth > 0 && !route) continue; // only routes answer under a mount
|
|
166
|
+
const absPath = route ? joinRoutePath(fr.prefix, route.path) : null;
|
|
167
|
+
const applies = (u: ScopedUse) => (absPath === null ? u.wildcard : routePathCovers(u.pattern, absPath, u.match));
|
|
168
|
+
const known = new Set(ep.guards);
|
|
169
|
+
for (const u of fr.inherited) if (applies(u)) for (const g of u.guards) known.add(g);
|
|
170
|
+
const inferred = new Set<string>();
|
|
171
|
+
for (const u of uses) {
|
|
172
|
+
if (ep.order !== undefined && u.order >= ep.order) continue;
|
|
173
|
+
if (!applies(scoped(u, fr.prefix))) continue;
|
|
174
|
+
for (const g of u.guards) (ep.order === undefined && !known.has(g) ? inferred : known).add(g);
|
|
175
|
+
}
|
|
176
|
+
const key = route && fr.depth > 0 ? (route.method ? `${route.method} ${absPath}` : absPath!) : ep.key;
|
|
177
|
+
out.push({
|
|
178
|
+
...ep,
|
|
179
|
+
key,
|
|
180
|
+
guards: [...new Set([...known, ...inferred])].sort(compareStr),
|
|
181
|
+
guardsInferred: [...inferred].sort(compareStr),
|
|
182
|
+
chain: [...new Set([...ep.chain, ...fr.chainFiles.filter((c) => c !== fr.file)])].sort(compareStr),
|
|
183
|
+
file: fr.file,
|
|
184
|
+
via: [...fr.via],
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
const local = routersOf(f);
|
|
188
|
+
for (const m of f.mounts ?? []) {
|
|
189
|
+
if (routerOf(m) !== fr.router) continue;
|
|
190
|
+
const prefix = joinRoutePath(fr.prefix, m.prefix);
|
|
191
|
+
const inherited = [
|
|
192
|
+
...fr.inherited,
|
|
193
|
+
...uses.filter((u) => u.order < m.order).map((u) => scoped(u, fr.prefix)),
|
|
194
|
+
...((m.guards?.length ?? 0) > 0 ? [everything(prefix, m.guards!, false)] : []),
|
|
195
|
+
];
|
|
196
|
+
let targets = fr.resolved.filter((r) => r.target === m.target);
|
|
197
|
+
if (targets.length === 0 && local.has(m.target)) {
|
|
198
|
+
targets = [{ target: m.target, path: fr.file, facts: f, router: m.target, mounts: fr.resolved }];
|
|
199
|
+
}
|
|
200
|
+
if (targets.length === 0) { unresolved++; continue; }
|
|
201
|
+
if (fr.depth >= maxDepth) { truncated += targets.length; continue; }
|
|
202
|
+
const chainFiles = fr.file === '' || fr.chainFiles.includes(fr.file) ? fr.chainFiles : [...fr.chainFiles, fr.file];
|
|
203
|
+
for (const r of targets) {
|
|
204
|
+
const sub = canonicalFileFacts(r.facts);
|
|
205
|
+
for (const router of r.router !== undefined ? [r.router] : rootRoutersOf(sub)) {
|
|
206
|
+
const id = `${r.path}\u0000${router}`;
|
|
207
|
+
if (fr.stack.has(id)) { truncated++; continue; }
|
|
208
|
+
visit({
|
|
209
|
+
facts: sub, file: r.path, router, prefix, via: [...fr.via, m.prefix], inherited, chainFiles,
|
|
210
|
+
resolved: r.mounts ?? [], depth: fr.depth + 1, stack: new Set([...fr.stack, id]),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const root = canonicalFileFacts(fileFacts);
|
|
218
|
+
const file = opts.path ?? '';
|
|
219
|
+
for (const router of opts.router !== undefined ? [opts.router] : rootRoutersOf(root)) {
|
|
220
|
+
visit({
|
|
221
|
+
facts: root, file, router, prefix: '', via: [], inherited: [], chainFiles: [], resolved: resolvedMounts, depth: 0,
|
|
222
|
+
stack: new Set([`${file}\u0000${router}`]),
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
entryPoints: sortBy(out, (e) => e.file, (e) => e.kind, (e) => e.key, (e) => e.symbol, (e) => e.via.join('\u0000')),
|
|
227
|
+
truncated,
|
|
228
|
+
unresolved,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** One root router: a file and the router binding in it ('' = the file's default router). */
|
|
233
|
+
export interface RootRouter {
|
|
234
|
+
path: string;
|
|
235
|
+
router: string;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Where an imported mount lands: the mounted file, and the router binding in it (absent ⇒ that file's root routers). */
|
|
239
|
+
export interface MountTarget {
|
|
240
|
+
path: string;
|
|
241
|
+
router?: string;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The ROOT routers of a set of files, PER ROUTER: every (file, router) that registers something and that no other router's
|
|
246
|
+
* mount reaches — so a mounted file's second, unmounted router is still a root. Routers mounted only inside a cycle (files
|
|
247
|
+
* mounting each other) are not dropped: the lowest unreached (path, router) becomes a root, then everything it reaches is
|
|
248
|
+
* covered, repeated until every router is covered (deterministic). `resolveMount` maps a mount of the file at `from` to
|
|
249
|
+
* its target (undefined when unresolved); local-binding mounts stay within their file. Sorted by path, then router. Call
|
|
250
|
+
* `effectiveGuards(facts, mounts, { path, router })` on each (see CALL SITES in the header).
|
|
251
|
+
*/
|
|
252
|
+
export function rootRouters(files: ReadonlyMap<string, FileFacts>, resolveMount: (from: string, mount: MountFact) => MountTarget | undefined): RootRouter[] {
|
|
253
|
+
const id = (path: string, router: string) => `${path}\u0000${router}`;
|
|
254
|
+
const nodes = new Map<string, RootRouter>();
|
|
255
|
+
const canon = new Map<string, FileFacts>();
|
|
256
|
+
for (const [path, raw] of files) {
|
|
257
|
+
const f = canonicalFileFacts(raw);
|
|
258
|
+
canon.set(path, f);
|
|
259
|
+
for (const router of routersOf(f)) nodes.set(id(path, router), { path, router });
|
|
260
|
+
}
|
|
261
|
+
const edges = new Map<string, Set<string>>();
|
|
262
|
+
const incoming = new Set<string>();
|
|
263
|
+
const link = (from: string, to: string) => {
|
|
264
|
+
if (to === from || !nodes.has(to)) return;
|
|
265
|
+
let s = edges.get(from);
|
|
266
|
+
if (!s) edges.set(from, (s = new Set()));
|
|
267
|
+
s.add(to);
|
|
268
|
+
incoming.add(to);
|
|
269
|
+
};
|
|
270
|
+
for (const [path, f] of canon) {
|
|
271
|
+
const local = routersOf(f);
|
|
272
|
+
for (const m of f.mounts ?? []) {
|
|
273
|
+
const from = id(path, routerOf(m));
|
|
274
|
+
if (local.has(m.target)) { link(from, id(path, m.target)); continue; }
|
|
275
|
+
const target = resolveMount(path, m);
|
|
276
|
+
const sub = target ? canon.get(target.path) : undefined;
|
|
277
|
+
if (!target || !sub) continue;
|
|
278
|
+
for (const router of target.router !== undefined ? [target.router] : rootRoutersOf(sub)) link(from, id(target.path, router));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const order = [...nodes.keys()].sort(compareStr);
|
|
282
|
+
const covered = new Set<string>();
|
|
283
|
+
const cover = (start: string) => {
|
|
284
|
+
const stack = [start];
|
|
285
|
+
while (stack.length > 0) {
|
|
286
|
+
const n = stack.pop()!;
|
|
287
|
+
if (covered.has(n)) continue;
|
|
288
|
+
covered.add(n);
|
|
289
|
+
for (const next of edges.get(n) ?? []) stack.push(next);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
const roots: string[] = order.filter((n) => !incoming.has(n));
|
|
293
|
+
for (const r of roots) cover(r);
|
|
294
|
+
for (const n of order) if (!covered.has(n)) { roots.push(n); cover(n); }
|
|
295
|
+
return roots.sort(compareStr).map((n) => nodes.get(n)!);
|
|
296
|
+
}
|
package/src/knowledge/index.ts
CHANGED
|
@@ -53,8 +53,9 @@ export {
|
|
|
53
53
|
} from './findings.js';
|
|
54
54
|
// PRD 41 §B1/§B3/§B5: FileFacts v3, the composite extractor version, FactRule + the incremental evaluator, the fact graph.
|
|
55
55
|
export {
|
|
56
|
-
FACT_KINDS, FACT_KIND_FIELDS, MATCHER_STRENGTH_ORDER, canonicalFileFacts,
|
|
56
|
+
FACT_KINDS, FACT_KIND_FIELDS, MATCHER_STRENGTH_ORDER, canonicalFileFacts, readFileFacts, isFileFactsV3, projectFileFacts,
|
|
57
57
|
} from './facts/fileFacts.js';
|
|
58
|
+
export { factKindHashes, factsHash } from './facts/factsHash.js';
|
|
58
59
|
export type {
|
|
59
60
|
FactKind, FileFacts, SymbolFact, ImportFact, ExportFact, CallFact, ComplexityFact, EntryPointKind, EntryPointFact, CapabilityKind,
|
|
60
61
|
CapabilityImportFact, MatcherStrength, MatcherUse, TestModifier, TestCaseFact, TestFacts,
|
|
@@ -69,6 +70,17 @@ export { emptyFactGraph, updateFactGraph, buildFactGraph, factGraphDump, FACT_GR
|
|
|
69
70
|
export type { FactGraph, FactManifestEntry, FactChange, FactGraphOptions, FactGraphUpdate } from './rules/factGraph.js';
|
|
70
71
|
export { knowledgeFacts, knowledgeInputHash, runKnowledgeRules, packOfRef, KNOWLEDGE_INPUT } from './rules/knowledgeInput.js';
|
|
71
72
|
export type { KnowledgeFacts, KnowledgeRuleExtra, KnowledgeRule } from './rules/knowledgeInput.js';
|
|
73
|
+
// PRD 41 §B4: the fact store port (pure; hosts implement it) + §C5.1: router mounts and `use` guard semantics.
|
|
74
|
+
export { saveFactGraph, loadFactGraph, factStoreDump, sweepFactStore, memoryFactStore, FACT_STORE_LOAD_ATTEMPTS } from './rules/factStore.js';
|
|
75
|
+
export type {
|
|
76
|
+
Awaitable, FactStorePort, FactStoreVersion, FactStoreManifest, FactManifestDelta, FactStoreSaveResult, StoredFactGraph,
|
|
77
|
+
LoadFactGraphOptions, MemoryFactStore,
|
|
78
|
+
} from './rules/factStore.js';
|
|
79
|
+
export { factsJson, factsWireForm } from './facts/factsHash.js';
|
|
80
|
+
export { normalizeMountPrefix } from './facts/fileFacts.js';
|
|
81
|
+
export type { MountFact, UseFact } from './facts/fileFacts.js';
|
|
82
|
+
export { effectiveGuards, rootRouters, routePathCovers, joinRoutePath, MAX_MOUNT_DEPTH } from './facts/guards.js';
|
|
83
|
+
export type { ResolvedMount, EffectiveEntryPoint, EffectiveGuardsOptions, EffectiveGuardsResult, RootRouter, MountTarget } from './facts/guards.js';
|
|
72
84
|
export { refAnchor, type FindingAnchor } from './findingBuilder.js';
|
|
73
85
|
export {
|
|
74
86
|
identityOf, defaultAnchorOf, composeAnchor, anchorWithSnippet, anchorKindOfRef, kindOfAnchor, normalizeSnippet, DEFAULT_RULE_VERSION,
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
import { compareStr } from '../refs.js';
|
|
20
20
|
import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
|
|
21
21
|
import type { Finding } from '../findingModel.js';
|
|
22
|
-
import { canonicalFileFacts,
|
|
22
|
+
import { canonicalFileFacts, projectFileFacts, type FactKind, type FileFacts } from '../facts/fileFacts.js';
|
|
23
|
+
import { factKindHashes } from '../facts/factsHash.js';
|
|
23
24
|
import { DEFAULT_RULE_HOPS, type FactRule } from './factRule.js';
|
|
24
25
|
|
|
25
26
|
/** What the evaluator reads: the current facts by path, the import neighbourhood, and the hashed extra inputs. */
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
import { canonicalJson, compareStr, isRootFilePath, normalizePath } from '../refs.js';
|
|
13
13
|
import type { Finding } from '../findingModel.js';
|
|
14
|
-
import { canonicalFileFacts,
|
|
14
|
+
import { canonicalFileFacts, type FactKind, type FileFacts } from '../facts/fileFacts.js';
|
|
15
|
+
import { factKindHashes, factsHash, factsWireForm } from '../facts/factsHash.js';
|
|
15
16
|
import type { FactRule } from './factRule.js';
|
|
16
17
|
import { evaluateRules, type DerivedRows, type RuleTraceEntry, type RuleWorld } from './evaluateRules.js';
|
|
17
18
|
|
|
@@ -21,6 +22,11 @@ export interface FactManifestEntry {
|
|
|
21
22
|
kinds: Readonly<Record<FactKind, string>>;
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
/** Whether two manifest entries are the same (facts hash, content hash and every kind hash). */
|
|
26
|
+
export const sameManifestEntry = (a: FactManifestEntry | undefined, b: FactManifestEntry | undefined): boolean =>
|
|
27
|
+
a !== undefined && b !== undefined && a.factsHash === b.factsHash && a.contentHash === b.contentHash
|
|
28
|
+
&& a.kinds.body === b.kinds.body && a.kinds.content === b.kinds.content && a.kinds.structure === b.kinds.structure;
|
|
29
|
+
|
|
24
30
|
export interface FactGraph {
|
|
25
31
|
manifest: ReadonlyMap<string, FactManifestEntry>;
|
|
26
32
|
/** Facts by facts hash — only those the manifest references. */
|
|
@@ -101,7 +107,7 @@ export function factGraphDump(graph: FactGraph): string {
|
|
|
101
107
|
return canonicalJson({
|
|
102
108
|
version: FACT_GRAPH_DUMP_VERSION,
|
|
103
109
|
manifest: sortedEntries(graph.manifest).map(([path, e]) => ({ path, ...e })),
|
|
104
|
-
objects: sortedEntries(graph.objects).map(([hash, facts]) => ({ hash, facts })),
|
|
110
|
+
objects: sortedEntries(graph.objects).map(([hash, facts]) => ({ hash, facts: factsWireForm(facts) })),
|
|
105
111
|
derived: sortedEntries(graph.derived).map(([, row]) => row),
|
|
106
112
|
});
|
|
107
113
|
}
|