@seanhogg/builderforce-memory 2026.10.76 → 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.
Files changed (41) hide show
  1. package/dist/knowledge/facts/factsHash.d.ts +27 -0
  2. package/dist/knowledge/facts/factsHash.d.ts.map +1 -0
  3. package/dist/knowledge/facts/factsHash.js +67 -0
  4. package/dist/knowledge/facts/factsHash.js.map +1 -0
  5. package/dist/knowledge/facts/fileFacts.d.ts +70 -12
  6. package/dist/knowledge/facts/fileFacts.d.ts.map +1 -1
  7. package/dist/knowledge/facts/fileFacts.js +42 -33
  8. package/dist/knowledge/facts/fileFacts.js.map +1 -1
  9. package/dist/knowledge/facts/guards.d.ts +101 -0
  10. package/dist/knowledge/facts/guards.d.ts.map +1 -0
  11. package/dist/knowledge/facts/guards.js +260 -0
  12. package/dist/knowledge/facts/guards.js.map +1 -0
  13. package/dist/knowledge/index.d.ts +9 -1
  14. package/dist/knowledge/index.d.ts.map +1 -1
  15. package/dist/knowledge/index.js +7 -1
  16. package/dist/knowledge/index.js.map +1 -1
  17. package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -1
  18. package/dist/knowledge/rules/evaluateRules.js +2 -1
  19. package/dist/knowledge/rules/evaluateRules.js.map +1 -1
  20. package/dist/knowledge/rules/factGraph.d.ts +2 -0
  21. package/dist/knowledge/rules/factGraph.d.ts.map +1 -1
  22. package/dist/knowledge/rules/factGraph.js +6 -2
  23. package/dist/knowledge/rules/factGraph.js.map +1 -1
  24. package/dist/knowledge/rules/factStore.d.ts +139 -0
  25. package/dist/knowledge/rules/factStore.d.ts.map +1 -0
  26. package/dist/knowledge/rules/factStore.js +252 -0
  27. package/dist/knowledge/rules/factStore.js.map +1 -0
  28. package/package.json +1 -1
  29. package/src/contract/exports.snapshot.json +14 -0
  30. package/src/contract/types.contract.test.ts +57 -2
  31. package/src/knowledge/facts/factsHash.test.ts +50 -0
  32. package/src/knowledge/facts/factsHash.ts +71 -0
  33. package/src/knowledge/facts/fileFacts.test.ts +2 -1
  34. package/src/knowledge/facts/fileFacts.ts +104 -36
  35. package/src/knowledge/facts/guards.test.ts +276 -0
  36. package/src/knowledge/facts/guards.ts +296 -0
  37. package/src/knowledge/index.ts +13 -1
  38. package/src/knowledge/rules/evaluateRules.ts +2 -1
  39. package/src/knowledge/rules/factGraph.ts +8 -2
  40. package/src/knowledge/rules/factStore.test.ts +303 -0
  41. package/src/knowledge/rules/factStore.ts +317 -0
@@ -0,0 +1,50 @@
1
+ /**
2
+ * src/knowledge/facts/factsHash.test.ts — the pinned content address (PRD 41 §B4, §B8). The literals below were computed by
3
+ * the FileFacts code as released in 2026.10.72 (before `mounts` / `uses` / `router` / `order` existed). A facts object with
4
+ * none of the added fields must keep exactly this address and these kind hashes, or every stored object would be orphaned.
5
+ */
6
+
7
+ import type { FileFacts } from './fileFacts.js';
8
+ import { readFileFacts } from './fileFacts.js';
9
+ import { factKindHashes, factsHash, factsJson } from './factsHash.js';
10
+
11
+ const GOLDEN: FileFacts = {
12
+ factsVersion: 3,
13
+ extractor: 'tree-sitter@3.0/typescript=0.23.2/eol-lf@1',
14
+ language: 'typescript',
15
+ contentHash: 'golden-content',
16
+ symbols: [{ name: 'b', kind: 'function', signatureHash: 'sb' }, { name: 'a', kind: 'class' }],
17
+ imports: [{ specifier: './x', resolved: 'src/x.ts', names: ['y', 'x'], typeOnly: true }],
18
+ exports: [{ name: 'a', kind: 'class', signatureHash: 'sa' }],
19
+ entryPoints: [{ kind: 'http-route', key: 'POST /api/x', symbol: 'a.post', guards: ['requireAuth'], inputs: ['req.body'], chain: ['src/mw.ts'] }],
20
+ calls: [{ callee: 'fetch', enclosing: 'b', awaited: true, inLoop: true, count: 2 }],
21
+ complexity: [{ symbol: 'b', cyclomatic: 4 }],
22
+ capabilityImports: [{ capability: 'crypto', module: 'node:crypto', algorithm: 'md5' }],
23
+ testFacts: { framework: 'jest', tests: [{ name: 't', assertions: 1, matchers: [{ matcher: 'toBe', strength: 'exact', count: 1 }] }], snapshotFiles: [] },
24
+ };
25
+
26
+ const GOLDEN_FACTS_HASH = 'ac6cc429237854783c0d22fcae60db7163ffe27685b802ef9537bacb31337e27';
27
+ const GOLDEN_KINDS = {
28
+ body: '913d8f716d4f2938942b93d42cbdcea8a9b4d653531f35f132a5ab4613fa433b',
29
+ content: 'golden-content',
30
+ structure: '9f2297f03ad517e864cfb9dfbaeba3df522fea94502e4ecee9dda4c16a1d9a33',
31
+ };
32
+
33
+ describe('factsHash: pinned golden address', () => {
34
+ it('a v3 object without the added fields keeps its released address and kind hashes', () => {
35
+ expect(factsHash(GOLDEN)).toBe(GOLDEN_FACTS_HASH);
36
+ expect({ ...factKindHashes(GOLDEN) }).toEqual(GOLDEN_KINDS);
37
+ });
38
+
39
+ it('read back through readFileFacts (mounts: [], uses: []) the address does not move', () => {
40
+ const read = readFileFacts(JSON.parse(factsJson(GOLDEN)) as FileFacts);
41
+ expect(read.mounts).toEqual([]);
42
+ expect(factsHash(read)).toBe(GOLDEN_FACTS_HASH);
43
+ expect({ ...factKindHashes(read) }).toEqual(GOLDEN_KINDS);
44
+ });
45
+
46
+ it('the wire form omits the empty added lists', () => {
47
+ expect(factsJson(GOLDEN)).not.toContain('"mounts"');
48
+ expect(factsJson(GOLDEN)).not.toContain('"uses"');
49
+ });
50
+ });
@@ -0,0 +1,71 @@
1
+ /**
2
+ * knowledge/facts/factsHash.ts — the identity of a `FileFacts` object (PRD 41 §B1, §B4, §B8): its WIRE form, its canonical
3
+ * JSON, its content address (`factsHash`) and the per-kind hashes early cutoff compares.
4
+ *
5
+ * Hash stability across additive fields: `mounts` and `uses` (§C5.1) were added after v3 shipped. A canonical object always
6
+ * carries them (`[]` when none), but the wire form OMITS them when empty — as it omits every absent optional field — so a
7
+ * facts object written before they existed keeps its `factsHash` and kind hashes when read back. A golden test pins one
8
+ * address computed by the code before the change (factsHash.test.ts).
9
+ */
10
+
11
+ import { canonicalJson } from '../refs.js';
12
+ import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
13
+ import { canonicalFileFacts, FACT_KIND_FIELDS, type FactKind, type FileFacts } from './fileFacts.js';
14
+
15
+ /** The optional list fields added after v3 shipped; omitted from the wire form when empty. */
16
+ const ADDED_LIST_FIELDS = ['mounts', 'uses'] as const;
17
+
18
+ const wireCache = new WeakMap<FileFacts, FileFacts>();
19
+
20
+ /**
21
+ * The WIRE form of `f` (canonicalized): the canonical object with each empty added list field (`mounts`, `uses`) omitted.
22
+ * What every hash, the stored object JSON and the dump are built from. Frozen; cached per canonical object.
23
+ */
24
+ export function factsWireForm(f: FileFacts): FileFacts {
25
+ const c = canonicalFileFacts(f);
26
+ let hit = wireCache.get(c);
27
+ if (!hit) {
28
+ const out: FileFacts = { ...c };
29
+ for (const field of ADDED_LIST_FIELDS) if ((out[field]?.length ?? 0) === 0) delete out[field];
30
+ hit = Object.freeze(out);
31
+ wireCache.set(c, hit);
32
+ }
33
+ return hit;
34
+ }
35
+
36
+ /** The canonical JSON of a facts object (its wire form): the bytes a fact store keeps under {@link factsHash}. */
37
+ export function factsJson(f: FileFacts): string {
38
+ return canonicalJson(factsWireForm(f));
39
+ }
40
+
41
+ /** The content address of a facts object: sha256 of its canonical JSON ({@link factsJson}). */
42
+ export function factsHash(f: FileFacts): string {
43
+ return sha256Hex(factsJson(f));
44
+ }
45
+
46
+ /** The header every kind hash includes. */
47
+ const headerOf = (f: FileFacts) => ({ factsVersion: f.factsVersion, extractor: f.extractor, language: f.language });
48
+
49
+ const kindCache = new WeakMap<FileFacts, Readonly<Record<FactKind, string>>>();
50
+
51
+ /**
52
+ * The hash of each fact kind of `f` (canonicalized first). `content` is the content hash itself; `structure` and `body`
53
+ * are sha256 over the canonical JSON of the header plus that kind's fields (from the wire form). Cached per CANONICAL
54
+ * (deep-frozen) object; a non-canonical input is canonicalized and hashed again on every call, so mutating it can never
55
+ * serve a stale hash.
56
+ */
57
+ export function factKindHashes(f: FileFacts): Readonly<Record<FactKind, string>> {
58
+ const c = canonicalFileFacts(f);
59
+ const hit = kindCache.get(c);
60
+ if (hit) return hit;
61
+ const w = factsWireForm(c);
62
+ const of = (kind: FactKind) => {
63
+ const body: Record<string, unknown> = { header: headerOf(c) };
64
+ // An empty added list is absent from the wire form, so it never enters the hash (canonicalJson drops undefined).
65
+ for (const field of FACT_KIND_FIELDS[kind]) body[field] = w[field];
66
+ return sha256Hex(canonicalJson(body));
67
+ };
68
+ const hashes = Object.freeze({ body: of('body'), content: c.contentHash, structure: of('structure') });
69
+ kindCache.set(c, hashes);
70
+ return hashes;
71
+ }
@@ -4,7 +4,8 @@
4
4
  */
5
5
 
6
6
  import { comparable } from '../comparability.js';
7
- import { canonicalFileFacts, factKindHashes, factsHash, readFileFacts, isFileFactsV3, projectFileFacts, type FileFacts } from './fileFacts.js';
7
+ import { canonicalFileFacts, readFileFacts, isFileFactsV3, projectFileFacts, type FileFacts } from './fileFacts.js';
8
+ import { factKindHashes, factsHash } from './factsHash.js';
8
9
  import { extractorStampMeta, factsExtractorTag, FACTS_EXTRACTOR_VERSION, isFactsCurrent, type ExtractorStamp } from './extractorVersion.js';
9
10
 
10
11
  const STAMP: ExtractorStamp = { family: 'tree-sitter', grammars: { typescript: '0.23.2', python: '0.23.6' } };
@@ -7,18 +7,17 @@
7
7
  *
8
8
  * The fields split into three FACT KINDS ({@link FACT_KIND_FIELDS}), each with its own hash, so a rule
9
9
  * that `reads` only `structure` never reruns for a body or comment edit (early cutoff, §B1):
10
- * - `structure`: symbols, imports, exports, entry points (the declared surface; a guard added to or
11
- * removed from a route registration moves it);
10
+ * - `structure`: symbols, imports, exports, entry points, router mounts and `use` registrations (the
11
+ * declared surface; a guard added to or removed from a route registration moves it);
12
12
  * - `body`: calls, complexity, capability imports, test facts;
13
13
  * - `content`: the EOL-normalized bytes themselves, i.e. `contentHash` (contentHash.ts).
14
14
  *
15
15
  * The header (`factsVersion`, `extractor`, `language`) enters every kind's hash: facts of another
16
16
  * extractor are never "the same structure". The extractors live in the hosts (Builderforce.ai
17
- * agent-tools); memory owns only this shape and its hashing.
17
+ * agent-tools); memory owns only this shape and its hashing (the hashes and the wire form: factsHash.ts).
18
18
  */
19
19
 
20
20
  import { canonicalJson, compareStr, normalizePath, sortBy } from '../refs.js';
21
- import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
22
21
  import { FACTS_EXTRACTOR_VERSION } from './extractorVersion.js';
23
22
 
24
23
  /** The three fact kinds a rule may read (§B1). Sorted. */
@@ -80,7 +79,13 @@ export interface EntryPointFact {
80
79
  key: string;
81
80
  /** The handler symbol path. */
82
81
  symbol: string;
83
- /** Guard names found on its chain (middleware, wrappers), sorted. Which names are guards is registry data (run-delta). */
82
+ /**
83
+ * Guard names on the REGISTRATION itself (inline middleware arguments, wrappers around the handler), sorted. Which names
84
+ * are guards is registry data (run-delta). File-level `use(path?, guard)` registrations are recorded in
85
+ * {@link FileFacts.uses} and composed by `effectiveGuards` (guards.ts): a producer that records `uses` does not also fold
86
+ * them in here. A producer with no `uses` may fold them, by the same rule (a `use` guards only routes registered AFTER it
87
+ * whose path its pattern covers).
88
+ */
84
89
  guards: string[];
85
90
  /** Untrusted input accessors the handler uses (`req.body`, `c.req.json`, `msg.data`, `argv`), sorted. */
86
91
  inputs: string[];
@@ -89,6 +94,59 @@ export interface EntryPointFact {
89
94
  * registration, sorted. A neighbourhood rule with `readsGuardChain` reads these files' facts whatever their import distance.
90
95
  */
91
96
  chain: string[];
97
+ /**
98
+ * The registration ORDER within the file: the 0-based index of this registration among the file's route, `use` and
99
+ * mount registrations (ONE counter shared with {@link UseFact.order} and {@link MountFact.order}). A registration index,
100
+ * not a line number and not a byte offset, so an edit that adds no registration never moves it. A non-negative integer.
101
+ * A producer that emits `uses` MUST set `order` on every entry point; absent ⇒ unknown, and `effectiveGuards` applies
102
+ * every covering `use` but reports those guards as inferred (`guardsInferred`).
103
+ */
104
+ order?: number;
105
+ /** The local router binding the route is registered on (`app`, `adminRouter`). Absent ⇒ the file's one default router. */
106
+ router?: string;
107
+ }
108
+
109
+ /**
110
+ * One file-level middleware registration (§C5.1): `app.use(path?, guard…)`. It guards the routes of its router registered
111
+ * AFTER it (by `order`) whose path `path` covers, and every sub-router that router mounts after it ({@link MountFact}).
112
+ */
113
+ export interface UseFact {
114
+ /**
115
+ * The use-path pattern: '' (or '*', '/*') for every path; `:param` (also `:param?`, `:param{regex}`) matches one segment;
116
+ * a trailing `*` (`/api/*`, `/api*`) matches the rest.
117
+ */
118
+ path: string;
119
+ /**
120
+ * `prefix` (Express `use`, the default; canonical form omits it): the pattern covers every path under it.
121
+ * `exact` (Hono `use('/api')`): that path only.
122
+ */
123
+ match?: 'prefix' | 'exact';
124
+ /** Guard names it registers, sorted. */
125
+ guards: string[];
126
+ /** Registration order (see {@link EntryPointFact.order}). */
127
+ order: number;
128
+ /** The router binding it is registered on (see {@link EntryPointFact.router}). */
129
+ router?: string;
130
+ }
131
+
132
+ /**
133
+ * One sub-router mount (§C5.1): `app.route('/api', sub)` (Hono) / `app.use('/api', subRouter)` (Express). The sub-router's
134
+ * routes answer under `prefix`, and the mounting router's `use` guards registered before the mount apply to them.
135
+ */
136
+ export interface MountFact {
137
+ /** The mount prefix ('/api'); '/' for the root. Canonical form: leading `/`, no trailing `/`. */
138
+ prefix: string;
139
+ /**
140
+ * The sub-router: an import specifier resolved to a file by the host (`ResolvedMount`), or the name of a LOCAL router
141
+ * binding of this file (one that registers routes, uses or mounts here), which `effectiveGuards` resolves itself.
142
+ */
143
+ target: string;
144
+ /** Registration order (see {@link EntryPointFact.order}). */
145
+ order: number;
146
+ /** The router binding that registers the mount (see {@link EntryPointFact.router}). */
147
+ router?: string;
148
+ /** Guards given inline at the mount (`router.use('/api', requireAuth, apiRouter)`), sorted; applied to every mounted route. */
149
+ guards?: string[];
92
150
  }
93
151
 
94
152
  export type CapabilityKind = 'process-exec' | 'fs-write' | 'network-client' | 'network-server' | 'dynamic-code' | 'native-addon'
@@ -150,6 +208,10 @@ export interface FileFacts {
150
208
  imports: ImportFact[];
151
209
  exports: ExportFact[];
152
210
  entryPoints: EntryPointFact[];
211
+ /** Sub-router mounts (§C5.1). Optional on input; a canonical object always carries it (`[]` when none). */
212
+ mounts?: MountFact[];
213
+ /** File-level `use()` middleware registrations (§C5.1). Optional on input; a canonical object always carries it. */
214
+ uses?: UseFact[];
153
215
  // body
154
216
  calls: CallFact[];
155
217
  complexity: ComplexityFact[];
@@ -159,7 +221,7 @@ export interface FileFacts {
159
221
 
160
222
  /** Which fields each kind hashes (data: the ONE place the split is declared). */
161
223
  export const FACT_KIND_FIELDS: Readonly<Record<FactKind, readonly (keyof FileFacts)[]>> = Object.freeze({
162
- structure: ['symbols', 'imports', 'exports', 'entryPoints'],
224
+ structure: ['symbols', 'imports', 'exports', 'entryPoints', 'mounts', 'uses'],
163
225
  body: ['calls', 'complexity', 'capabilityImports', 'testFacts'],
164
226
  content: ['contentHash'],
165
227
  });
@@ -169,6 +231,25 @@ const sorted = (xs: readonly string[] | undefined) => [...(xs ?? [])].sort(compa
169
231
  const paths = (xs: readonly string[] | undefined) => sorted((xs ?? []).map(normalizePath));
170
232
  /** The final sort key of every list: the whole item, so items equal on the declared keys still sort one way. */
171
233
  const whole = (x: unknown) => canonicalJson(x);
234
+ /** A registration order as a string that sorts numerically. */
235
+ const ord = (n: number) => String(n).padStart(16, '0');
236
+
237
+ /** Refuses a registration order that is not a non-negative safe integer: `file_facts_invalid_order:<what>:<value>`. */
238
+ function checkOrder(what: string, order: number | undefined): void {
239
+ if (order === undefined) return;
240
+ if (!Number.isSafeInteger(order) || order < 0) throw new Error(`file_facts_invalid_order:${what}:${String(order)}`);
241
+ }
242
+
243
+ /** The ONE mount-prefix form: leading `/`, no trailing or doubled `/` ('' and '/' → '/', 'api/' → '/api'). */
244
+ export function normalizeMountPrefix(prefix: string): string {
245
+ return `/${prefix.split('/').filter((s) => s !== '').join('/')}`;
246
+ }
247
+
248
+ /**
249
+ * The ONE `use`-path form: '' stays '' (every path); anything else as {@link normalizeMountPrefix} ('/admin/' → '/admin',
250
+ * '*' → '/*'), so a trailing or doubled `/` never moves a hash.
251
+ */
252
+ const normalizeUsePath = (path: string): string => (path === '' ? '' : normalizeMountPrefix(path));
172
253
 
173
254
  /** Facts objects produced by {@link canonicalFileFacts}: deep-frozen, so every cache keyed by object identity holds. */
174
255
  const canonicalSet = new WeakSet<FileFacts>();
@@ -186,9 +267,15 @@ function deepFreeze<T>(value: T): T {
186
267
  * lists sorted, and every path field (`imports[].resolved`, `entryPoints[].chain`, `testFacts.snapshotFiles`) in the
187
268
  * ONE path form (`normalizePath`, §B8.1). The result is DEEP-FROZEN: facts are immutable values, and the kind-hash and
188
269
  * projection caches key on the object. Idempotent; a canonical object is returned as is.
270
+ *
271
+ * Throws `file_facts_invalid_order:<what>:<value>` when a registration `order` is not a non-negative integer; producers must
272
+ * catch it per file at extraction time and treat it as an extract failure of that file (never let it abort a whole build).
189
273
  */
190
274
  export function canonicalFileFacts(f: FileFacts): FileFacts {
191
275
  if (canonicalSet.has(f)) return f;
276
+ for (const e of f.entryPoints) checkOrder(`entryPoint:${e.key}`, e.order);
277
+ for (const u of f.uses ?? []) checkOrder(`use:${u.path}`, u.order);
278
+ for (const m of f.mounts ?? []) checkOrder(`mount:${m.prefix}`, m.order);
192
279
  const out: FileFacts = {
193
280
  ...f,
194
281
  symbols: sortBy(f.symbols.map((s) => ({ ...s })), (s) => s.name, (s) => s.kind, (s) => str(s.signatureHash), whole),
@@ -201,6 +288,14 @@ export function canonicalFileFacts(f: FileFacts): FileFacts {
201
288
  f.entryPoints.map((e) => ({ ...e, guards: sorted(e.guards), inputs: sorted(e.inputs), chain: paths(e.chain) })),
202
289
  (e) => e.kind, (e) => e.key, (e) => e.symbol, whole,
203
290
  ),
291
+ mounts: sortBy((f.mounts ?? []).map((m) => {
292
+ const { guards, ...rest } = m;
293
+ return { ...rest, prefix: normalizeMountPrefix(m.prefix), ...((guards?.length ?? 0) > 0 ? { guards: sorted(guards) } : {}) };
294
+ }), (m) => ord(m.order), (m) => m.prefix, (m) => m.target, whole),
295
+ uses: sortBy((f.uses ?? []).map((u) => {
296
+ const { match, ...rest } = u;
297
+ return { ...rest, path: normalizeUsePath(u.path), guards: sorted(u.guards), ...(match === 'exact' ? { match } : {}) };
298
+ }), (u) => ord(u.order), (u) => u.path, whole),
204
299
  calls: sortBy(f.calls.map((c) => ({ ...c })), (c) => c.enclosing, (c) => c.callee, (c) => str(c.awaited), (c) => str(c.inLoop), whole),
205
300
  complexity: sortBy(f.complexity.map((c) => ({ ...c })), (c) => c.symbol, whole),
206
301
  capabilityImports: sortBy(f.capabilityImports.map((c) => ({ ...c })), (c) => c.capability, (c) => c.module, (c) => str(c.symbol), (c) => str(c.algorithm), whole),
@@ -220,33 +315,9 @@ export function canonicalFileFacts(f: FileFacts): FileFacts {
220
315
  return out;
221
316
  }
222
317
 
223
- /** The header every kind hash includes. */
224
- const headerOf = (f: FileFacts) => ({ factsVersion: f.factsVersion, extractor: f.extractor, language: f.language });
225
-
226
- const kindCache = new WeakMap<FileFacts, Readonly<Record<FactKind, string>>>();
227
-
228
- /**
229
- * The hash of each fact kind of `f` (canonicalized first). `content` is the content hash itself; `structure` and `body`
230
- * are sha256 over the canonical JSON of the header plus that kind's fields. Cached per CANONICAL (deep-frozen) object;
231
- * a non-canonical input is canonicalized and hashed again on every call, so mutating it can never serve a stale hash.
232
- */
233
- export function factKindHashes(f: FileFacts): Readonly<Record<FactKind, string>> {
234
- const c = canonicalFileFacts(f);
235
- const hit = kindCache.get(c);
236
- if (hit) return hit;
237
- const of = (kind: FactKind) => {
238
- const body: Record<string, unknown> = { header: headerOf(c) };
239
- for (const field of FACT_KIND_FIELDS[kind]) body[field] = c[field];
240
- return sha256Hex(canonicalJson(body));
241
- };
242
- const hashes = Object.freeze({ body: of('body'), content: c.contentHash, structure: of('structure') });
243
- kindCache.set(c, hashes);
244
- return hashes;
245
- }
246
-
247
318
  /** The empty value of every kind's fields: what a rule that does not read that kind sees. */
248
319
  const EMPTY_FIELDS: Readonly<Record<FactKind, Partial<FileFacts>>> = Object.freeze({
249
- structure: { symbols: [], imports: [], exports: [], entryPoints: [] },
320
+ structure: { symbols: [], imports: [], exports: [], entryPoints: [], mounts: [], uses: [] },
250
321
  body: { calls: [], complexity: [], capabilityImports: [], testFacts: undefined },
251
322
  content: { contentHash: '' },
252
323
  });
@@ -274,11 +345,6 @@ export function projectFileFacts(f: FileFacts, reads: readonly FactKind[]): File
274
345
  return hit;
275
346
  }
276
347
 
277
- /** The content address of a facts object: sha256 of its canonical JSON. */
278
- export function factsHash(f: FileFacts): string {
279
- return sha256Hex(canonicalJson(canonicalFileFacts(f)));
280
- }
281
-
282
348
  /**
283
349
  * Reads facts from any producer: a v3 object as is (canonicalized), a v2 one (repo-map's symbols + imports, no
284
350
  * `factsVersion`) with every v3 list empty and `factsVersion: 2`. A v2 fact set is never comparable with a v3 one
@@ -294,6 +360,8 @@ export function readFileFacts(raw: Partial<FileFacts> & Pick<FileFacts, 'content
294
360
  imports: raw.imports ?? [],
295
361
  exports: raw.exports ?? [],
296
362
  entryPoints: raw.entryPoints ?? [],
363
+ mounts: raw.mounts ?? [],
364
+ uses: raw.uses ?? [],
297
365
  calls: raw.calls ?? [],
298
366
  complexity: raw.complexity ?? [],
299
367
  capabilityImports: raw.capabilityImports ?? [],
@@ -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
+ });