@seanhogg/builderforce-memory 2026.10.66 → 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 (106) 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 +12 -1
  35. package/dist/knowledge/index.d.ts.map +1 -1
  36. package/dist/knowledge/index.js +8 -1
  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 +18 -2
  57. package/dist/knowledge/refs.d.ts.map +1 -1
  58. package/dist/knowledge/refs.js +38 -8
  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 +29 -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/regression.refs.test.ts +49 -0
  79. package/src/contract/types.contract.test.ts +57 -0
  80. package/src/knowledge/comparability.analysis.test.ts +73 -0
  81. package/src/knowledge/comparability.test.ts +44 -0
  82. package/src/knowledge/comparability.ts +182 -0
  83. package/src/knowledge/contentHash.test.ts +81 -0
  84. package/src/knowledge/contentHash.ts +55 -0
  85. package/src/knowledge/extractFile.ts +4 -2
  86. package/src/knowledge/extractJob.ts +5 -3
  87. package/src/knowledge/findingBuilder.ts +17 -2
  88. package/src/knowledge/findingIdentity.test.ts +102 -0
  89. package/src/knowledge/findingIdentity.ts +92 -0
  90. package/src/knowledge/findingModel.ts +32 -0
  91. package/src/knowledge/findings.ts +17 -9
  92. package/src/knowledge/godModule.ts +2 -2
  93. package/src/knowledge/index.ts +18 -1
  94. package/src/knowledge/lineage.test.ts +106 -0
  95. package/src/knowledge/lineage.ts +123 -0
  96. package/src/knowledge/merkle.test.ts +137 -0
  97. package/src/knowledge/merkle.ts +164 -0
  98. package/src/knowledge/model.ts +4 -18
  99. package/src/knowledge/owedFiles.contentHash.test.ts +58 -0
  100. package/src/knowledge/owedFiles.ts +23 -5
  101. package/src/knowledge/plan.ts +28 -6
  102. package/src/knowledge/refs.ts +36 -8
  103. package/src/knowledge/resolve.ts +2 -0
  104. package/src/knowledge/reviewModel.ts +8 -1
  105. package/src/knowledge/reviewPrefetch.ts +10 -6
  106. package/src/knowledge/sources.ts +20 -2
@@ -0,0 +1,164 @@
1
+ /**
2
+ * knowledge/merkle.ts — directory Merkle hashes over a root's file listing (PRD 41 §B2 step 4).
3
+ *
4
+ * A directory's hash is sha256 over the canonical JSON of its entries `{ name, kind, hash }`
5
+ * (`kind` 'file' | 'dir'), sorted by name. An equal directory hash means an equal subtree, so
6
+ * {@link changedPaths} skips it and two trees compare in O(changed).
7
+ *
8
+ * Paths go through the ONE `normalizePath` (refs.ts: POSIX, no leading `./` or `/`, NFC) and sort bytewise (§B8.1). The
9
+ * root directory's key is `""`; a nested one's is its path (`a`, `a/b`). Any input order gives
10
+ * the same tree.
11
+ */
12
+
13
+ import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
14
+ import { canonicalJson, isRootFilePath, normalizePath } from './refs.js';
15
+
16
+ export type MerkleKind = 'file' | 'dir';
17
+
18
+ export interface MerkleEntry {
19
+ name: string;
20
+ kind: MerkleKind;
21
+ /** A file's content hash, or a directory's Merkle hash. */
22
+ hash: string;
23
+ }
24
+
25
+ export interface MerkleTree {
26
+ /** The root directory's hash (`dirs.get('')`). */
27
+ root: string;
28
+ /** Directory path → its Merkle hash; the root is `""`. */
29
+ dirs: ReadonlyMap<string, string>;
30
+ /** Directory path → its entries, sorted by name. */
31
+ entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
32
+ }
33
+
34
+ /** Bytewise UTF-8 order (code-point order), which UTF-16 `<` is not for astral characters. */
35
+ export function compareBytewise(a: string, b: string): number {
36
+ const n = Math.min(a.length, b.length);
37
+ for (let i = 0; i < n; i++) {
38
+ const x = a.codePointAt(i)!, y = b.codePointAt(i)!;
39
+ if (x !== y) return x < y ? -1 : 1;
40
+ if (x > 0xffff) i++;
41
+ }
42
+ return a.length - b.length;
43
+ }
44
+
45
+ const dirOf = (path: string): string => {
46
+ const at = path.lastIndexOf('/');
47
+ return at < 0 ? '' : path.slice(0, at);
48
+ };
49
+ const nameOf = (path: string): string => path.slice(path.lastIndexOf('/') + 1);
50
+ const joinPath = (dir: string, name: string): string => (dir === '' ? name : `${dir}/${name}`);
51
+
52
+ /** Why {@link canonicalListing} left a listed path out. */
53
+ export type ListingSkipReason = 'invalid-path' | 'duplicate-path';
54
+
55
+ /**
56
+ * A host listing made safe for {@link merkleTree} — which then never throws — without depending on input order:
57
+ * • every path goes through the ONE {@link normalizePath} (POSIX, NFC); the source's own spelling is kept as `listedPath`
58
+ * when it differs, so a read still opens the file the source listed;
59
+ * • a path that is empty or has an empty, `.` or `..` segment is skipped as `invalid-path`;
60
+ * • of paths that collide once normalized (an NFC/NFD pair, a path listed twice) the FIRST by (normalized path, listed path),
61
+ * bytewise, is kept and the rest are skipped as `duplicate-path`; so is a path below a kept FILE (`a` and `a/b`).
62
+ * Skipped entries carry the listed spelling. `kept` is sorted bytewise by normalized path.
63
+ */
64
+ export function canonicalListing<T extends { path: string }>(entries: readonly T[]): {
65
+ kept: Array<T & { listedPath?: string }>;
66
+ skipped: Array<{ path: string; reason: ListingSkipReason }>;
67
+ } {
68
+ const skipped: Array<{ path: string; reason: ListingSkipReason }> = [];
69
+ const candidates: Array<{ entry: T; path: string }> = [];
70
+ for (const entry of entries) {
71
+ const path = normalizePath(entry.path);
72
+ if (isRootFilePath(path)) candidates.push({ entry, path });
73
+ else skipped.push({ path: entry.path, reason: 'invalid-path' });
74
+ }
75
+ candidates.sort((a, b) => compareBytewise(a.path, b.path) || compareBytewise(a.entry.path, b.entry.path));
76
+ const files = new Set<string>();
77
+ const kept: Array<T & { listedPath?: string }> = [];
78
+ for (const { entry, path } of candidates) {
79
+ let clash = files.has(path);
80
+ for (let dir = dirOf(path); !clash && dir !== ''; dir = dirOf(dir)) clash = files.has(dir);
81
+ if (clash) { skipped.push({ path: entry.path, reason: 'duplicate-path' }); continue; }
82
+ files.add(path);
83
+ kept.push({ ...entry, path, ...(entry.path !== path ? { listedPath: entry.path } : {}) });
84
+ }
85
+ return { kept, skipped };
86
+ }
87
+
88
+ /**
89
+ * The Merkle tree of a file listing. Throws on an invalid path, a path listed twice with different hashes, or a path
90
+ * that is both a file and a directory — each would make the root depend on input order. {@link canonicalListing}
91
+ * first makes a host listing safe.
92
+ */
93
+ export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>): MerkleTree {
94
+ const children = new Map<string, Map<string, { kind: MerkleKind; hash?: string }>>([['', new Map()]]);
95
+ const childrenOf = (dir: string) => {
96
+ let c = children.get(dir);
97
+ if (!c) children.set(dir, (c = new Map()));
98
+ return c;
99
+ };
100
+ for (const f of files) {
101
+ const path = normalizePath(f.path);
102
+ if (!isRootFilePath(path)) throw new Error(`merkleTree: not a file path: ${JSON.stringify(f.path)}`);
103
+ const own = childrenOf(dirOf(path)).get(nameOf(path));
104
+ if (own && (own.kind !== 'file' || own.hash !== f.hash)) throw new Error(`merkleTree: ${path} listed twice or as a file and a directory`);
105
+ childrenOf(dirOf(path)).set(nameOf(path), { kind: 'file', hash: f.hash });
106
+ for (let dir = dirOf(path); dir !== ''; dir = dirOf(dir)) {
107
+ const slot = childrenOf(dirOf(dir));
108
+ const was = slot.get(nameOf(dir));
109
+ if (was?.kind === 'file') throw new Error(`merkleTree: ${dir} is both a file and a directory`);
110
+ if (was) break; // its ancestors are registered already
111
+ slot.set(nameOf(dir), { kind: 'dir' });
112
+ }
113
+ }
114
+
115
+ const dirs = new Map<string, string>();
116
+ const entries = new Map<string, MerkleEntry[]>();
117
+ // Deepest first, so every child directory is hashed before its parent.
118
+ const order = [...children.keys()].sort((a, b) => depth(b) - depth(a) || compareBytewise(a, b));
119
+ for (const dir of order) {
120
+ const list = [...children.get(dir)!].map(([name, c]): MerkleEntry => ({
121
+ name, kind: c.kind, hash: c.kind === 'file' ? c.hash! : dirs.get(joinPath(dir, name))!,
122
+ })).sort((a, b) => compareBytewise(a.name, b.name));
123
+ entries.set(dir, list);
124
+ dirs.set(dir, sha256Hex(canonicalJson(list)));
125
+ }
126
+ return { root: dirs.get('')!, dirs, entries };
127
+ }
128
+
129
+ const depth = (dir: string): number => (dir === '' ? 0 : dir.split('/').length);
130
+
131
+ /** Every file path under `dir` in `tree`, appended to `out`. */
132
+ function filesUnder(tree: MerkleTree, dir: string, out: string[]): void {
133
+ for (const e of tree.entries.get(dir) ?? []) {
134
+ const path = joinPath(dir, e.name);
135
+ if (e.kind === 'file') out.push(path);
136
+ else filesUnder(tree, path, out);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * The file paths changed, added or removed between two trees, sorted bytewise. Walks top-down
142
+ * and never descends into a directory whose hash is equal on both sides.
143
+ */
144
+ export function changedPaths(before: MerkleTree, after: MerkleTree): string[] {
145
+ const out: string[] = [];
146
+ const walk = (dir: string): void => {
147
+ if (before.dirs.get(dir) === after.dirs.get(dir)) return;
148
+ const was = new Map((before.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
149
+ const is = new Map((after.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
150
+ for (const name of new Set([...was.keys(), ...is.keys()])) {
151
+ const a = was.get(name), b = is.get(name);
152
+ const path = joinPath(dir, name);
153
+ if (a?.kind === 'dir' && b?.kind === 'dir') { if (a.hash !== b.hash) walk(path); continue; }
154
+ if (a && b && a.kind === 'file' && b.kind === 'file') { if (a.hash !== b.hash) out.push(path); continue; }
155
+ // Added, removed, or a file replaced by a directory (or back): every file on either side.
156
+ for (const [side, e] of [[before, a], [after, b]] as const) {
157
+ if (e?.kind === 'file') out.push(path);
158
+ else if (e) filesUnder(side, path, out);
159
+ }
160
+ }
161
+ };
162
+ walk('');
163
+ return [...new Set(out)].sort(compareBytewise);
164
+ }
@@ -12,6 +12,10 @@
12
12
 
13
13
  import type { SourceDocument, ParsedSection } from '../ingest/types.js';
14
14
  import type { IndexDoc, SimilarPair } from '../retrieval/knowledge-index/types.js';
15
+ import type { Finding, FindingRule } from './findingModel.js';
16
+
17
+ /** The finding types live beside the rules (findingModel.ts); re-exported so one import serves. */
18
+ export type { Finding, FindingRule } from './findingModel.js';
15
19
 
16
20
  /** `src:${rootId}::${path}` · `ent:${pack}:${normalizedName}` · `fact:${key}` (claims are `fact:claim:${hash}`). */
17
21
  export type NodeRef = `src:${string}` | `ent:${string}` | `fact:${string}`;
@@ -85,24 +89,6 @@ export interface ExtractContext {
85
89
  resolvePath(fromPath: string, target: string): string | undefined;
86
90
  }
87
91
 
88
- /** A finding a person can act on. `kind` is pack-defined; `requestKey` names an i18n template. */
89
- export interface Finding {
90
- id: string;
91
- kind: string;
92
- pack: string;
93
- nodes: NodeRef[];
94
- severity: 'info' | 'warn' | 'error';
95
- /** Numbers/strings for the label and the Fix-with-agent template. */
96
- params: Record<string, string | number>;
97
- /** i18n key of the fixed Fix-with-agent request (e.g. 'knowledgeGraph.fix.cloneGroup'). */
98
- requestKey?: string;
99
- }
100
-
101
- export interface FindingRule {
102
- id: string;
103
- find(graph: KnowledgeGraph): Finding[];
104
- }
105
-
106
92
  export interface PartitionRule {
107
93
  id: string;
108
94
  /** 0 = top. */
@@ -0,0 +1,58 @@
1
+ /**
2
+ * src/knowledge/owedFiles.contentHash.test.ts — the content-hash rule in the extractor entry (PRD 41 §B2 step 0).
3
+ * The rule never owes a file by its ABSENCE: a host switching to `contentHash` moves the hash of every CRLF file, and
4
+ * those re-extract by content. Only a RECORDED rule that differs from today's owes every file one re-extraction.
5
+ */
6
+
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { CONTENT_HASH_RULE } from './contentHash.js';
9
+ import { isOwed, loadExtractorState, owedCalls, saveExtractorState } from './owedFiles.js';
10
+ import { DOCS_PACK } from './packs/docs.js';
11
+ import { planDetail } from './plan.js';
12
+ import { reviewDirectory } from './review.js';
13
+ import { EXTRACTOR_VERSION, extractorManifestKey } from './sources.js';
14
+ import { ALL, args, fakeJudge, FILES, memSource, memStore, ROOT } from './testkit.test-util.js';
15
+
16
+ const key = extractorManifestKey(ROOT);
17
+
18
+ describe('the content-hash rule in the extractor entry', () => {
19
+ it("an entry without a rule record owes nothing by it, at today's version", async () => {
20
+ const manifest = new InMemoryIngestManifest();
21
+ await manifest.set(key, [{ id: 'version', hash: String(EXTRACTOR_VERSION) }]);
22
+ const state = await loadExtractorState(manifest, ROOT);
23
+ expect(state.contentHashRule).toBeUndefined();
24
+ expect(isOwed(state, 'a.md')).toBe(false);
25
+ expect(owedCalls(state, 'a.md')).toBe(0);
26
+ expect(isOwed({ version: EXTRACTOR_VERSION, owed: new Map() }, 'a.md')).toBe(false);
27
+ });
28
+
29
+ it("today's rule recorded is read back and owes nothing", async () => {
30
+ const manifest = new InMemoryIngestManifest();
31
+ await manifest.set(key, [{ id: 'version', hash: String(EXTRACTOR_VERSION) }, { id: 'contentHash', hash: CONTENT_HASH_RULE }]);
32
+ const state = await loadExtractorState(manifest, ROOT);
33
+ expect(state.contentHashRule).toBe(CONTENT_HASH_RULE);
34
+ expect(isOwed(state, 'a.md')).toBe(false);
35
+ });
36
+
37
+ it("saving today's (first) rule writes no record, so the entry keeps its pre-rule shape", async () => {
38
+ const manifest = new InMemoryIngestManifest();
39
+ await saveExtractorState(manifest, ROOT, new Map());
40
+ expect((await manifest.get(key))!.map((f) => f.id)).toEqual(['version']);
41
+ });
42
+
43
+ it("another recorded rule at today's version owes every file one re-extraction, once", async () => {
44
+ const source = memSource({ ...FILES });
45
+ const store = memStore();
46
+ const manifest = new InMemoryIngestManifest();
47
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
48
+ const owedPaths = async () => (await planDetail(source, manifest, [DOCS_PACK])).files.filter((f) => f.owed).map((f) => f.path);
49
+ expect(await owedPaths()).toEqual([]);
50
+
51
+ await manifest.set(key, [{ id: 'version', hash: String(EXTRACTOR_VERSION) }, { id: 'contentHash', hash: 'eol-lf@0' }]);
52
+ expect(owedCalls(await loadExtractorState(manifest, ROOT), 'a.md')).toBe(1);
53
+ expect(await owedPaths()).toEqual(ALL);
54
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
55
+ expect(await owedPaths()).toEqual([]);
56
+ expect((await manifest.get(key))!.map((f) => f.id)).toEqual(['version']);
57
+ });
58
+ });
@@ -12,7 +12,8 @@
12
12
  * retired it drops out.
13
13
  *
14
14
  * Stored under {@link extractorManifestKey} as fingerprints: `{ id: 'version', hash: '<version>' }`
15
- * plus `{ id: 'documents', hash: '<pdf,docx|->' }` (the document types the packs claimed, see {@link withDocuments})
15
+ * plus `{ id: 'documents', hash: '<pdf,docx|->' }` (the document types the packs claimed, see {@link withDocuments}),
16
+ * `{ id: 'contentHash', hash: '<rule>' }` once {@link CONTENT_HASH_RULE} moves past {@link BASELINE_CONTENT_HASH_RULE} (no record reads as the baseline; another rule is an upgrade),
16
17
  * and one `{ id: 'owed:<path>', hash: '<calls>' }` per owed file, where `<calls>` is the
17
18
  * decimal number of model calls the file is still expected to cost (the plan's estimate):
18
19
  * • a file the run reached but did not finish: the sections the budget or a failed call left
@@ -27,11 +28,13 @@
27
28
  */
28
29
 
29
30
  import type { IngestManifest } from '../ingest/types.js';
31
+ import { BASELINE_CONTENT_HASH_RULE, CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
30
32
  import { compareStr } from './refs.js';
31
33
  import { EXTRACTOR_VERSION, extOf, extractorManifestKey, isBinaryPath, isDocumentPath } from './sources.js';
32
34
 
33
35
  const VERSION_ID = 'version';
34
36
  const DOCUMENTS_ID = 'documents';
37
+ const CONTENT_HASH_ID = 'contentHash';
35
38
  /** No document type claimed — also what an entry with no `documents` record means, so a root that never had a host parser stores nothing extra. */
36
39
  const NO_DOCUMENTS = '-';
37
40
  const OWED_PREFIX = 'owed:';
@@ -42,6 +45,8 @@ const UPGRADE_CALLS = 1;
42
45
  export interface ExtractorState {
43
46
  /** The version the files were last reviewed with; undefined when never recorded. */
44
47
  version: number | undefined;
48
+ /** The content-hash rule (contentHash.ts) the files were hashed under, when the entry records one; absent for `eol-lf@1` and for every entry written before the rule existed. */
49
+ contentHashRule?: string;
45
50
  /** Paths a previous run left unfinished under that version → model calls each still costs. */
46
51
  owed: ReadonlyMap<string, number>;
47
52
  /** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. Optional: a caller that builds a state by hand need not know it. */
@@ -82,6 +87,7 @@ export function withDocuments(state: ExtractorState, now: string | undefined): E
82
87
  export async function loadExtractorState(manifest: IngestManifest, rootId: string): Promise<ExtractorState> {
83
88
  let version: number | undefined;
84
89
  let documents: string | undefined;
90
+ let contentHashRule: string | undefined;
85
91
  const owed = new Map<string, number>();
86
92
  const failures = new Map<string, { hash: string; count: number }>();
87
93
  for (const { id, hash } of (await manifest.get(extractorManifestKey(rootId))) ?? []) {
@@ -90,6 +96,8 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
90
96
  if (Number.isFinite(v)) version = v;
91
97
  } else if (id === DOCUMENTS_ID) {
92
98
  documents = hash;
99
+ } else if (id === CONTENT_HASH_ID) {
100
+ contentHashRule = hash;
93
101
  } else if (id.startsWith(FAIL_PREFIX)) {
94
102
  const at = hash.indexOf(':');
95
103
  const count = Number(hash.slice(0, at));
@@ -99,15 +107,24 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
99
107
  owed.set(id.slice(OWED_PREFIX.length), Number.isFinite(calls) && calls >= 0 ? calls : UPGRADE_CALLS);
100
108
  }
101
109
  }
102
- return { version, owed, failures, documents: documents ?? NO_DOCUMENTS };
110
+ return { version, owed, failures, documents: documents ?? NO_DOCUMENTS, ...(contentHashRule !== undefined ? { contentHashRule } : {}) };
103
111
  }
104
112
 
113
+ /**
114
+ * True while the files were last reviewed under another extractor version than today's, or under another content-hash rule
115
+ * ({@link contentHashRuleOf}: no record is the baseline rule): every file owes one re-extraction. Adopting the baseline rule owes
116
+ * nothing by itself — a host switching to `contentHash` moves the hash of every CRLF file, and those re-extract by content
117
+ * (`contentChanged`, an extract-cache miss). The entry writes no record for the baseline; a later rule writes one.
118
+ */
119
+ const upgradePending = (state: ExtractorState): boolean =>
120
+ state.version !== EXTRACTOR_VERSION || contentHashRuleOf(state.contentHashRule) !== CONTENT_HASH_RULE;
121
+
105
122
  /** The file's document extension when its asset-ness flipped (a host parser arrived or left since the last run). */
106
123
  const isFlipped = (state: ExtractorState, path: string): boolean => !!state.flipped?.size && state.flipped.has(extOf(path));
107
124
 
108
- /** True when `path` is owed a re-extraction: another extractor version than today's, left unfinished before, or its asset-ness flipped. */
125
+ /** True when `path` is owed a re-extraction: another extractor version or recorded content-hash rule than today's, left unfinished before, or its asset-ness flipped. */
109
126
  export const isOwed = (state: ExtractorState, path: string): boolean =>
110
- state.version !== EXTRACTOR_VERSION || state.owed.has(path) || isFlipped(state, path);
127
+ upgradePending(state) || state.owed.has(path) || isFlipped(state, path);
111
128
 
112
129
  /** Whether `path` is an asset under the packs the plan was made with: binary, and not a document some parser claims. */
113
130
  const isAssetNow = (state: ExtractorState, path: string): boolean => {
@@ -123,7 +140,7 @@ const isAssetNow = (state: ExtractorState, path: string): boolean => {
123
140
  * An asset costs none (it is never read or judged); a file that flipped TO a document does.
124
141
  */
125
142
  export const owedCalls = (state: ExtractorState, path: string): number =>
126
- isAssetNow(state, path) ? 0 : (state.version !== EXTRACTOR_VERSION || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
143
+ isAssetNow(state, path) ? 0 : (upgradePending(state) || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
127
144
 
128
145
  /**
129
146
  * Paths in the files manifest that the plan does not list yet are owed: ignored, claimed by
@@ -169,6 +186,7 @@ export async function saveExtractorState(
169
186
  ): Promise<void> {
170
187
  await manifest.set(extractorManifestKey(rootId), [
171
188
  { id: VERSION_ID, hash: String(EXTRACTOR_VERSION) },
189
+ ...(CONTENT_HASH_RULE !== BASELINE_CONTENT_HASH_RULE ? [{ id: CONTENT_HASH_ID, hash: CONTENT_HASH_RULE }] : []),
172
190
  ...(documents !== undefined && documents !== NO_DOCUMENTS ? [{ id: DOCUMENTS_ID, hash: documents }] : []),
173
191
  ...[...owed].sort((a, b) => compareStr(a[0], b[0])).map(([path, calls]) => ({ id: `${OWED_PREFIX}${path}`, hash: String(calls) })),
174
192
  ...[...failures].filter(([path]) => owed.has(path)).sort((a, b) => compareStr(a[0], b[0])).map(([path, f]) => ({ id: `${FAIL_PREFIX}${path}`, hash: `${f.count}:${f.hash}` })),
@@ -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,24 +21,52 @@ 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
  }
27
37
 
28
- /** The root-relative path of a `src:` ref (the section suffix dropped), else undefined. */
29
- export function pathOfRef(ref: string): string | undefined {
38
+ /**
39
+ * Splits `src:<rootId>::<path>` into its root and its FULL path (never section-stripped: `src/C#/a.cs` stays whole). A root id
40
+ * may end in ':' (the linked repo's `cloud:<id>:`), so the colons after the first `::` that directly follow it belong to the
41
+ * root: `src:cloud:5:::docs/a.md` is root `cloud:5:`, path `docs/a.md`. (A path that itself starts with ':' is read as part of
42
+ * the root — root ids never hold '::' nor end in ':' when built by `rootIdFor`, so only a foreign id can make it ambiguous.)
43
+ * Pass `knownRootIds` where the root is known: a ref of one of them is split by its exact prefix, so even a path that starts
44
+ * with ':' is exact. Undefined when `ref` is not a source ref. THE grammar: every reader of a `src:` ref goes through this.
45
+ */
46
+ export function splitSourceRef(ref: string, knownRootIds: readonly string[] = []): { rootId: string; path: string } | undefined {
30
47
  if (!ref.startsWith('src:')) return undefined;
31
- const at = ref.indexOf('::');
32
- if (at < 0) return undefined;
33
- const rest = ref.slice(at + 2);
48
+ for (const rootId of knownRootIds) if (ref.startsWith(`src:${rootId}::`)) return { rootId, path: ref.slice(`src:${rootId}::`.length) };
49
+ const at = ref.indexOf('::', 4);
50
+ if (at <= 4) return undefined;
51
+ let end = at;
52
+ while (ref[end + 2] === ':') end += 1;
53
+ return { rootId: ref.slice(4, end), path: ref.slice(end + 2) };
54
+ }
55
+
56
+ /** The root-relative path of a `src:` ref (the section suffix dropped), else undefined. Splits by {@link splitSourceRef}. */
57
+ export function pathOfRef(ref: string): string | undefined {
58
+ const rest = splitSourceRef(ref)?.path;
59
+ if (rest === undefined) return undefined;
34
60
  const hash = rest.indexOf('#');
35
61
  return hash < 0 ? rest : rest.slice(0, hash);
36
62
  }
37
63
 
38
- /** The ref of the file a `src:` ref belongs to (itself for a file). */
64
+ /** The ref of the file a `src:` ref belongs to (itself for a file): the ref cut at the first '#' of its path ({@link splitSourceRef}). */
39
65
  export function fileRefOf(ref: NodeRef): NodeRef {
40
- const hash = ref.startsWith('src:') ? ref.indexOf('#', ref.indexOf('::')) : -1;
41
- return hash < 0 ? ref : (ref.slice(0, hash) as NodeRef);
66
+ const split = splitSourceRef(ref);
67
+ if (!split) return ref;
68
+ const hash = split.path.indexOf('#');
69
+ return hash < 0 ? ref : (ref.slice(0, ref.length - split.path.length + hash) as NodeRef);
42
70
  }
43
71
 
44
72
  /** The node ref of a stored fact key: `ent:` keys are refs already; the rest are `fact:`. */
@@ -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. */