@seanhogg/builderforce-memory 2026.10.67 → 2026.10.68

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 (105) hide show
  1. package/dist/knowledge/comparability.d.ts +100 -0
  2. package/dist/knowledge/comparability.d.ts.map +1 -0
  3. package/dist/knowledge/comparability.js +149 -0
  4. package/dist/knowledge/comparability.js.map +1 -0
  5. package/dist/knowledge/contentHash.d.ts +28 -0
  6. package/dist/knowledge/contentHash.d.ts.map +1 -0
  7. package/dist/knowledge/contentHash.js +54 -0
  8. package/dist/knowledge/contentHash.js.map +1 -0
  9. package/dist/knowledge/extractFile.d.ts +2 -0
  10. package/dist/knowledge/extractFile.d.ts.map +1 -1
  11. package/dist/knowledge/extractFile.js +1 -1
  12. package/dist/knowledge/extractFile.js.map +1 -1
  13. package/dist/knowledge/extractJob.d.ts +5 -2
  14. package/dist/knowledge/extractJob.d.ts.map +1 -1
  15. package/dist/knowledge/extractJob.js +1 -1
  16. package/dist/knowledge/extractJob.js.map +1 -1
  17. package/dist/knowledge/findingBuilder.d.ts +12 -2
  18. package/dist/knowledge/findingBuilder.d.ts.map +1 -1
  19. package/dist/knowledge/findingBuilder.js +9 -2
  20. package/dist/knowledge/findingBuilder.js.map +1 -1
  21. package/dist/knowledge/findingIdentity.d.ts +52 -0
  22. package/dist/knowledge/findingIdentity.d.ts.map +1 -0
  23. package/dist/knowledge/findingIdentity.js +70 -0
  24. package/dist/knowledge/findingIdentity.js.map +1 -0
  25. package/dist/knowledge/findingModel.d.ts +30 -0
  26. package/dist/knowledge/findingModel.d.ts.map +1 -0
  27. package/dist/knowledge/findingModel.js +6 -0
  28. package/dist/knowledge/findingModel.js.map +1 -0
  29. package/dist/knowledge/findings.d.ts.map +1 -1
  30. package/dist/knowledge/findings.js +17 -9
  31. package/dist/knowledge/findings.js.map +1 -1
  32. package/dist/knowledge/godModule.js +2 -2
  33. package/dist/knowledge/godModule.js.map +1 -1
  34. package/dist/knowledge/index.d.ts +11 -0
  35. package/dist/knowledge/index.d.ts.map +1 -1
  36. package/dist/knowledge/index.js +7 -0
  37. package/dist/knowledge/index.js.map +1 -1
  38. package/dist/knowledge/lineage.d.ts +35 -0
  39. package/dist/knowledge/lineage.d.ts.map +1 -0
  40. package/dist/knowledge/lineage.js +114 -0
  41. package/dist/knowledge/lineage.js.map +1 -0
  42. package/dist/knowledge/merkle.d.ts +65 -0
  43. package/dist/knowledge/merkle.d.ts.map +1 -0
  44. package/dist/knowledge/merkle.js +158 -0
  45. package/dist/knowledge/merkle.js.map +1 -0
  46. package/dist/knowledge/model.d.ts +3 -16
  47. package/dist/knowledge/model.d.ts.map +1 -1
  48. package/dist/knowledge/owedFiles.d.ts +5 -2
  49. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  50. package/dist/knowledge/owedFiles.js +20 -5
  51. package/dist/knowledge/owedFiles.js.map +1 -1
  52. package/dist/knowledge/plan.d.ts +8 -0
  53. package/dist/knowledge/plan.d.ts.map +1 -1
  54. package/dist/knowledge/plan.js +20 -6
  55. package/dist/knowledge/plan.js.map +1 -1
  56. package/dist/knowledge/refs.d.ts +4 -0
  57. package/dist/knowledge/refs.d.ts.map +1 -1
  58. package/dist/knowledge/refs.js +8 -0
  59. package/dist/knowledge/refs.js.map +1 -1
  60. package/dist/knowledge/resolve.d.ts.map +1 -1
  61. package/dist/knowledge/resolve.js +2 -0
  62. package/dist/knowledge/resolve.js.map +1 -1
  63. package/dist/knowledge/reviewModel.d.ts +8 -1
  64. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  65. package/dist/knowledge/reviewPrefetch.d.ts +2 -1
  66. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  67. package/dist/knowledge/reviewPrefetch.js +8 -4
  68. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  69. package/dist/knowledge/sources.d.ts +10 -1
  70. package/dist/knowledge/sources.d.ts.map +1 -1
  71. package/dist/knowledge/sources.js +17 -2
  72. package/dist/knowledge/sources.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/contract/exports.snapshot.json +28 -0
  75. package/src/contract/regression.contentHash.test.ts +30 -0
  76. package/src/contract/regression.lineage.test.ts +27 -0
  77. package/src/contract/regression.listing.test.ts +85 -0
  78. package/src/contract/types.contract.test.ts +57 -0
  79. package/src/knowledge/comparability.analysis.test.ts +73 -0
  80. package/src/knowledge/comparability.test.ts +44 -0
  81. package/src/knowledge/comparability.ts +182 -0
  82. package/src/knowledge/contentHash.test.ts +81 -0
  83. package/src/knowledge/contentHash.ts +55 -0
  84. package/src/knowledge/extractFile.ts +4 -2
  85. package/src/knowledge/extractJob.ts +5 -3
  86. package/src/knowledge/findingBuilder.ts +17 -2
  87. package/src/knowledge/findingIdentity.test.ts +102 -0
  88. package/src/knowledge/findingIdentity.ts +92 -0
  89. package/src/knowledge/findingModel.ts +32 -0
  90. package/src/knowledge/findings.ts +17 -9
  91. package/src/knowledge/godModule.ts +2 -2
  92. package/src/knowledge/index.ts +17 -0
  93. package/src/knowledge/lineage.test.ts +106 -0
  94. package/src/knowledge/lineage.ts +123 -0
  95. package/src/knowledge/merkle.test.ts +137 -0
  96. package/src/knowledge/merkle.ts +164 -0
  97. package/src/knowledge/model.ts +4 -18
  98. package/src/knowledge/owedFiles.contentHash.test.ts +58 -0
  99. package/src/knowledge/owedFiles.ts +23 -5
  100. package/src/knowledge/plan.ts +28 -6
  101. package/src/knowledge/refs.ts +10 -0
  102. package/src/knowledge/resolve.ts +2 -0
  103. package/src/knowledge/reviewModel.ts +8 -1
  104. package/src/knowledge/reviewPrefetch.ts +10 -6
  105. package/src/knowledge/sources.ts +20 -2
@@ -11,6 +11,7 @@
11
11
 
12
12
  import type { IngestManifest } from '../ingest/types.js';
13
13
  import type { DirectorySource, KnowledgePack, ReviewPlan } from './model.js';
14
+ import { canonicalListing, merkleTree, type MerkleTree } from './merkle.js';
14
15
  import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls, withDocuments } from './owedFiles.js';
15
16
  import {
16
17
  claimedDocumentExts, compareManifestKey, composePacks, DEFAULT_MAX_FILE_BYTES, filesManifestKey, ignoreMatcher, ignoreSourcesOf,
@@ -64,8 +65,16 @@ export interface PlannedFile {
64
65
  asset?: true;
65
66
  /** An asset only because a claimed document exceeds the size cap: its node carries `badges.oversized` so a UI can say why it has no text. */
66
67
  oversized?: true;
68
+ /**
69
+ * The source's own spelling of the path, when it differs from `path` (the normalized one: POSIX, NFC — an NFD name, a `\`).
70
+ * Reads go through it (`DirectorySource.read`, `readTimeoutMs`, `hashOf`, a pool read); identity, refs and the manifest use `path`.
71
+ */
72
+ listedPath?: string;
67
73
  }
68
74
 
75
+ /** `{ listedPath }` when the listing spelled the path otherwise, else nothing. */
76
+ const listedPathOf = (e: { listedPath?: string }): { listedPath?: string } => (e.listedPath !== undefined ? { listedPath: e.listedPath } : {});
77
+
69
78
  export interface PlanDetail {
70
79
  plan: ReviewPlan;
71
80
  /** Every included file (changed and unchanged), sorted by path. */
@@ -76,6 +85,8 @@ export interface PlanDetail {
76
85
  extractor: ExtractorState;
77
86
  /** Owed paths the manifest holds that `files` does not list (ignored, no pack, an older plan, removed). */
78
87
  carried: string[];
88
+ /** The directory Merkle tree over `files` (PRD 41 §B2 step 4): `plan.merkleRoot` is its root. Optional so a hand-built detail stays valid. */
89
+ merkle?: MerkleTree;
79
90
  }
80
91
 
81
92
  /** The ONE classification of a listed file: did its content move, is it owed, is it re-processed. */
@@ -102,12 +113,16 @@ export async function planDetail(
102
113
  ): Promise<PlanDetail> {
103
114
  const maxBytes = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
104
115
  const listed: Array<{ path: string; hash: string; size: number }> = [];
105
- for await (const entry of source.list()) listed.push({ ...entry, path: entry.path.replace(/\\/g, '/').replace(/^\.?\//, '') });
106
- const entries = sortBy(listed, (e) => e.path);
116
+ for await (const entry of source.list()) listed.push(entry);
117
+ // The ONE normalization (POSIX, NFC) — so plan paths are Merkle paths — and a listing that cannot break the plan: invalid and
118
+ // colliding paths are skipped with a reason (merkle.ts canonicalListing), never thrown.
119
+ const listing = canonicalListing(listed);
120
+ const entries = sortBy(listing.kept, (e) => e.path);
121
+ const listedOf = new Map(entries.filter((e) => e.listedPath !== undefined).map((e) => [e.path, e.listedPath!] as const));
107
122
 
108
123
  const ignoreTexts: Array<{ text: string; base: string }> = [];
109
124
  for (const { path, base } of ignoreSourcesOf(entries.map((e) => e.path))) {
110
- const doc = await source.read(path);
125
+ const doc = await source.read(listedOf.get(path) ?? path);
111
126
  if (doc.content.kind === 'text') ignoreTexts.push({ text: doc.content.text, base });
112
127
  }
113
128
  const ignored = ignoreMatcher(ignoreTexts);
@@ -122,7 +137,7 @@ export async function planDetail(
122
137
  const packById = new Map(packs.map((p) => [p.id, p] as const));
123
138
 
124
139
  const files: PlannedFile[] = [];
125
- const skipped: ReviewPlan['skipped'] = [];
140
+ const skipped: ReviewPlan['skipped'] = [...listing.skipped];
126
141
  const byPack: Record<string, number> = {};
127
142
  let assets = 0;
128
143
  let estimatedSections = 0;
@@ -135,7 +150,10 @@ export async function planDetail(
135
150
  if (document && e.size > maxBytes) oversized.add(e.path);
136
151
  if (isAssetPath(e.path, !!document && e.size <= maxBytes)) {
137
152
  const { owed, changed } = classify(extractor, prior, e.path, e.hash, opts.force === true);
138
- files.push({ path: e.path, hash: e.hash, size: e.size, pack: FALLBACK_PACK_ID, changed, owed, asset: true, ...(document && e.size > maxBytes ? { oversized: true as const } : {}) });
153
+ files.push({
154
+ path: e.path, hash: e.hash, size: e.size, pack: FALLBACK_PACK_ID, changed, owed, asset: true, ...listedPathOf(e),
155
+ ...(document && e.size > maxBytes ? { oversized: true as const } : {}),
156
+ });
139
157
  assets += 1;
140
158
  continue;
141
159
  }
@@ -143,7 +161,7 @@ export async function planDetail(
143
161
  const hit = document ?? composed.resolve(stubSource(e.path));
144
162
  if (!hit) { skipped.push({ path: e.path, reason: 'no-pack' }); continue; }
145
163
  const { contentChanged, owed, changed } = classify(extractor, prior, e.path, e.hash, opts.force === true);
146
- files.push({ path: e.path, hash: e.hash, size: e.size, pack: hit.pack.id, changed, owed });
164
+ files.push({ path: e.path, hash: e.hash, size: e.size, pack: hit.pack.id, changed, owed, ...listedPathOf(e) });
147
165
  byPack[hit.pack.id] = (byPack[hit.pack.id] ?? 0) + 1;
148
166
  const spec = packById.get(hit.pack.id)?.judgement;
149
167
  if (spec && (spec.claims || spec.entities)) {
@@ -168,6 +186,7 @@ export async function planDetail(
168
186
  const awaiting = compares ? (await manifestMap(manifest, compareManifestKey(source.rootId))).size : 0;
169
187
  const compareCalls = compares ? Math.ceil((compareSections + awaiting) / SECTIONS_PER_COMPARE) : 0;
170
188
  const sortedByPack = Object.fromEntries(Object.keys(byPack).sort(compareStr).map((k) => [k, byPack[k]!]));
189
+ const merkle = merkleTree(files);
171
190
  return {
172
191
  plan: {
173
192
  rootId: source.rootId,
@@ -179,11 +198,13 @@ export async function planDetail(
179
198
  removed,
180
199
  skipped,
181
200
  estimatedModelCalls: estimatedSections + compareCalls,
201
+ merkleRoot: merkle.root,
182
202
  },
183
203
  files,
184
204
  prior,
185
205
  extractor,
186
206
  carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
207
+ merkle,
187
208
  };
188
209
  }
189
210
 
@@ -210,5 +231,6 @@ export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest):
210
231
  prior,
211
232
  extractor,
212
233
  carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
234
+ ...(detail.merkle ? { merkle: detail.merkle } : {}),
213
235
  };
214
236
  }
@@ -21,6 +21,16 @@ export function compareStr(a: string, b: string): number {
21
21
  return a < b ? -1 : a > b ? 1 : 0;
22
22
  }
23
23
 
24
+ /** The ONE root-relative path normalization (PRD 41 §B8.1): POSIX separators, no leading `./` or `/`, NFC. The plan and merkle.ts both use it. */
25
+ export function normalizePath(path: string): string {
26
+ return path.replace(/\\/g, '/').replace(/^(\.?\/)+/, '').normalize('NFC');
27
+ }
28
+
29
+ /** Whether a normalized path names a file under the root: non-empty, with no empty, `.` or `..` segment. */
30
+ export function isRootFilePath(path: string): boolean {
31
+ return path !== '' && path.split('/').every((s) => s !== '' && s !== '.' && s !== '..');
32
+ }
33
+
24
34
  export function srcRef(rootId: string, path: string): NodeRef {
25
35
  return `src:${rootId}::${path}`;
26
36
  }
@@ -60,6 +60,8 @@ export function possibleSameFindings(pairs: readonly SimilarPair[], pack = FALLB
60
60
  id, kind: 'possible-same', pack, nodes: [a as NodeRef, b as NodeRef], severity: 'info',
61
61
  params: { similarity: round6(p.similarity) },
62
62
  requestKey: 'knowledgeGraph.fix.possibleSame',
63
+ // Anchor (PRD 41 §C3): the sorted-first entity of the pair.
64
+ anchor: a, anchorKind: 'symbol',
63
65
  });
64
66
  }
65
67
  return out.sort((x, y) => compareStr(x.id, y.id));
@@ -14,6 +14,10 @@ import type { ReviewFailure, ReviewPhase, ReviewStep } from './reviewRunModel.js
14
14
  export interface DirectorySource {
15
15
  rootId: string;
16
16
  title: string;
17
+ /**
18
+ * The root's files. `read()` (and `hashOf`, `readTimeoutMs`) receive exactly the spelling `list()` yielded, so a source must not
19
+ * list paths that resolve outside its root (no leading `/`, no `..`).
20
+ */
17
21
  list(): AsyncIterable<{ path: string; hash: string; size: number }>;
18
22
  /** `signal` aborts the read when the review gives up on it (a per-job timeout, a stop); a source that cannot cancel may ignore it. */
19
23
  read(path: string, signal?: AbortSignal): Promise<SourceDocument>;
@@ -48,11 +52,14 @@ export interface ReviewPlan {
48
52
  unchanged: number;
49
53
  changed: string[];
50
54
  removed: string[];
51
- skipped: Array<{ path: string; reason: 'ignored' | 'too-large' | 'no-pack' }>;
55
+ /** `invalid-path` (empty, `.` or `..` segment) and `duplicate-path` (collides with another once normalized) carry the source's own spelling. */
56
+ skipped: Array<{ path: string; reason: 'ignored' | 'too-large' | 'no-pack' | 'invalid-path' | 'duplicate-path' }>;
52
57
  /** ≈ judgement calls for changed files (sections of judged kinds). */
53
58
  estimatedModelCalls: number;
54
59
  /** The file budget of the judge pass this run will run after the map is complete (PRD 41 A10); set by the host, so the confirm chip states it. */
55
60
  judgeFiles?: number;
61
+ /** The directory Merkle root over the planned files (PRD 41 §B2 step 4, knowledge/merkle.ts): an equal root means an equal listing. Absent on a plan from an older host. */
62
+ merkleRoot?: string;
56
63
  }
57
64
 
58
65
  export interface ReviewProgress {
@@ -67,8 +67,8 @@ export { CHANGED_SINCE_PLAN };
67
67
  export const DEFAULT_READ_TIMEOUT_MS = 5_000;
68
68
  export const DEFAULT_EXTRACT_TIMEOUT_MS = 10_000;
69
69
 
70
- /** A changed file as the prefetch sees it: a `PlannedFile`'s path, hash, size and asset flag. */
71
- export type PrefetchFile = { path: string; hash: string; size: number; asset?: true };
70
+ /** A changed file as the prefetch sees it: a `PlannedFile`'s path, hash, size, asset flag and the source's own spelling (reads use it). */
71
+ export type PrefetchFile = { path: string; hash: string; size: number; asset?: true; listedPath?: string };
72
72
 
73
73
  export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise<Prefetch> {
74
74
  // A lane is a worker: taken while the file holds an extract slot. The extract stage holds at most `extractWidth` at once, so the
@@ -95,8 +95,10 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
95
95
  if (f.asset) return { kind: 'asset' };
96
96
  let doc: SourceDocument | undefined;
97
97
  const t0 = Date.now();
98
+ // The source's own spelling opens the file; `f.path` (normalized) is its identity.
99
+ const readPath = f.listedPath ?? f.path;
98
100
  if (!byPool) {
99
- try { doc = await withDeadline(readMsOf(f.path), (signal) => c.args.source.read(f.path, signal)); } catch (error) {
101
+ try { doc = await withDeadline(readMsOf(readPath), (signal) => c.args.source.read(readPath, signal)); } catch (error) {
100
102
  return { kind: 'read-error', reason: reasonOf(error) };
101
103
  }
102
104
  parts.readMs = Date.now() - t0;
@@ -105,11 +107,13 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
105
107
  if (doc && doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
106
108
  const extraction = await extractSlots.run(async () => {
107
109
  held.lane = lanes.take();
108
- try { return await withDeadline(byPool ? extractMs + (readOverrideOf(f.path) ?? 0) : extractMs,(signal) => extractFileDetailed({
110
+ try { return await withDeadline(byPool ? extractMs + (readOverrideOf(readPath) ?? 0) : extractMs,(signal) => extractFileDetailed({
109
111
  rootId: c.rootId, path: f.path, hash: f.hash, ...(doc ? { doc } : {}), packs: c.packs, store: c.store, composed: c.composed,
110
112
  knownKeys: c.knownKeys, writeCache: false,
111
113
  onTiming: (t) => { parts.lookupMs = t.lookupMs; parts.poolMs = t.poolMs; },
112
- ...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? { readByPool: true, ...(readOverrideOf(f.path) ? { readMs: readOverrideOf(f.path)! } : {}) } : {}) } : {}),
114
+ ...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? {
115
+ readByPool: true, ...(f.listedPath !== undefined ? { readPath } : {}), ...(readOverrideOf(readPath) ? { readMs: readOverrideOf(readPath)! } : {}),
116
+ } : {}) } : {}),
113
117
  })); } finally { lanes.free(held.lane); }
114
118
  }, byPool ? c.signal : undefined);
115
119
  if (!extraction) return { kind: 'none' };
@@ -117,7 +121,7 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
117
121
  // stored, the bytes read must be the bytes planned: hashed once, from the text already in hand. The review writes the
118
122
  // extract cache only for an 'extracted' job, so nothing is stored under the stale hash.
119
123
  const hashOf = c.args.source.hashOf;
120
- if (hashOf && doc && doc.content.kind === 'text' && hashOf.call(c.args.source, doc.content.text, f.path) !== f.hash) return { kind: 'failed', reason: CHANGED_SINCE_PLAN, transient: true };
124
+ if (hashOf && doc && doc.content.kind === 'text' && hashOf.call(c.args.source, doc.content.text, readPath) !== f.hash) return { kind: 'failed', reason: CHANGED_SINCE_PLAN, transient: true };
121
125
  return { kind: 'extracted', ...(doc ? { doc } : {}), extraction };
122
126
  } catch (error) {
123
127
  if (error instanceof BinaryContent) return { kind: 'binary' };
@@ -121,9 +121,27 @@ export function claimedDocumentExts(composed: ComposedPacks): string {
121
121
  return [...DOCUMENT_EXT].filter((ext) => resolveDocument(composed, `x.${ext}`)).sort(compareStr).join(',') || '-';
122
122
  }
123
123
 
124
- /** A NUL in the first 8 KB means binary, whatever the extension said. */
124
+ /** How far the binary sniff looks, in BYTES: a NUL (0x00) among the file's first 8192 bytes means binary. */
125
+ const BINARY_SNIFF_BYTES = 8192;
126
+
127
+ /**
128
+ * THE binary rule, whatever the extension said: a 0 byte among the first {@link BINARY_SNIFF_BYTES} bytes. contentHash.ts sniffs raw
129
+ * bytes with it; {@link isBinaryText} applies it to decoded text.
130
+ */
131
+ export function isBinaryBytes(bytes: Uint8Array): boolean {
132
+ return bytes.subarray(0, BINARY_SNIFF_BYTES).includes(0);
133
+ }
134
+
135
+ const utf8 = new TextEncoder();
136
+
137
+ /**
138
+ * {@link isBinaryBytes} over decoded text: whether the text's UTF-8 bytes hold a NUL among their first 8192. UTF-8 encodes only
139
+ * U+0000 as a 0 byte, and every code unit takes at least one byte, so only a NUL within the first 8192 code units can qualify;
140
+ * its byte offset is the UTF-8 length of the text before it.
141
+ */
125
142
  export function isBinaryText(text: string): boolean {
126
- return text.slice(0, 8192).includes('\u0000');
143
+ const at = text.slice(0, BINARY_SNIFF_BYTES).indexOf('\u0000');
144
+ return at >= 0 && utf8.encode(text.slice(0, at)).length < BINARY_SNIFF_BYTES;
127
145
  }
128
146
 
129
147
  /** A read source with its id set to the root-relative path and a media type filled in. */