@seanhogg/builderforce-memory 2026.10.58 → 2026.10.60

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 (104) hide show
  1. package/README.md +3 -3
  2. package/dist/ingest/docsExtract.d.ts.map +1 -1
  3. package/dist/ingest/docsExtract.js +8 -4
  4. package/dist/ingest/docsExtract.js.map +1 -1
  5. package/dist/ingest/parserSupport.d.ts +2 -2
  6. package/dist/ingest/parserSupport.js +3 -3
  7. package/dist/ingest/parserSupport.js.map +1 -1
  8. package/dist/knowledge/assetFile.d.ts +25 -0
  9. package/dist/knowledge/assetFile.d.ts.map +1 -0
  10. package/dist/knowledge/assetFile.js +31 -0
  11. package/dist/knowledge/assetFile.js.map +1 -0
  12. package/dist/knowledge/backfillNoExtract.d.ts +11 -13
  13. package/dist/knowledge/backfillNoExtract.d.ts.map +1 -1
  14. package/dist/knowledge/backfillNoExtract.js +34 -43
  15. package/dist/knowledge/backfillNoExtract.js.map +1 -1
  16. package/dist/knowledge/build.d.ts.map +1 -1
  17. package/dist/knowledge/build.js +11 -7
  18. package/dist/knowledge/build.js.map +1 -1
  19. package/dist/knowledge/extractFile.d.ts.map +1 -1
  20. package/dist/knowledge/extractFile.js +4 -3
  21. package/dist/knowledge/extractFile.js.map +1 -1
  22. package/dist/knowledge/findings.js +4 -4
  23. package/dist/knowledge/findings.js.map +1 -1
  24. package/dist/knowledge/importance.d.ts +5 -0
  25. package/dist/knowledge/importance.d.ts.map +1 -1
  26. package/dist/knowledge/importance.js +7 -0
  27. package/dist/knowledge/importance.js.map +1 -1
  28. package/dist/knowledge/index.d.ts +3 -3
  29. package/dist/knowledge/index.d.ts.map +1 -1
  30. package/dist/knowledge/index.js +2 -2
  31. package/dist/knowledge/index.js.map +1 -1
  32. package/dist/knowledge/model.d.ts +11 -3
  33. package/dist/knowledge/model.d.ts.map +1 -1
  34. package/dist/knowledge/outline.d.ts.map +1 -1
  35. package/dist/knowledge/outline.js +4 -2
  36. package/dist/knowledge/outline.js.map +1 -1
  37. package/dist/knowledge/owedFiles.d.ts +26 -4
  38. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  39. package/dist/knowledge/owedFiles.js +58 -8
  40. package/dist/knowledge/owedFiles.js.map +1 -1
  41. package/dist/knowledge/plan.d.ts +8 -2
  42. package/dist/knowledge/plan.d.ts.map +1 -1
  43. package/dist/knowledge/plan.js +17 -9
  44. package/dist/knowledge/plan.js.map +1 -1
  45. package/dist/knowledge/refs.d.ts +2 -0
  46. package/dist/knowledge/refs.d.ts.map +1 -1
  47. package/dist/knowledge/refs.js +2 -0
  48. package/dist/knowledge/refs.js.map +1 -1
  49. package/dist/knowledge/resolve.d.ts.map +1 -1
  50. package/dist/knowledge/resolve.js +2 -2
  51. package/dist/knowledge/resolve.js.map +1 -1
  52. package/dist/knowledge/review.d.ts +2 -1
  53. package/dist/knowledge/review.d.ts.map +1 -1
  54. package/dist/knowledge/review.js +44 -10
  55. package/dist/knowledge/review.js.map +1 -1
  56. package/dist/knowledge/reviewModel.d.ts +7 -1
  57. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  58. package/dist/knowledge/reviewPrefetch.d.ts +10 -2
  59. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  60. package/dist/knowledge/reviewPrefetch.js +4 -0
  61. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  62. package/dist/knowledge/reviewRun.js +1 -1
  63. package/dist/knowledge/reviewRun.js.map +1 -1
  64. package/dist/knowledge/reviewRunModel.d.ts +2 -2
  65. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  66. package/dist/knowledge/sources.d.ts +16 -2
  67. package/dist/knowledge/sources.d.ts.map +1 -1
  68. package/dist/knowledge/sources.js +40 -7
  69. package/dist/knowledge/sources.js.map +1 -1
  70. package/dist/knowledge/truncate.d.ts.map +1 -1
  71. package/dist/knowledge/truncate.js +6 -5
  72. package/dist/knowledge/truncate.js.map +1 -1
  73. package/package.json +3 -3
  74. package/src/contract/exports.snapshot.json +2 -0
  75. package/src/contract/regression.assets.test.ts +206 -0
  76. package/src/contract/regression.recheck.test.ts +5 -5
  77. package/src/contract/regression.review.test.ts +184 -5
  78. package/src/contract/types.contract.test.ts +2 -2
  79. package/src/ingest/docsExtract.ts +9 -4
  80. package/src/ingest/parserSupport.ts +3 -3
  81. package/src/knowledge/assetFile.ts +34 -0
  82. package/src/knowledge/backfillNoExtract.ts +29 -35
  83. package/src/knowledge/build.ts +10 -5
  84. package/src/knowledge/docs.test.ts +5 -2
  85. package/src/knowledge/extractFile.ts +4 -3
  86. package/src/knowledge/findings.ts +4 -4
  87. package/src/knowledge/importance.ts +8 -0
  88. package/src/knowledge/index.ts +3 -3
  89. package/src/knowledge/model.ts +8 -3
  90. package/src/knowledge/outline.ts +4 -2
  91. package/src/knowledge/owedFiles.ts +59 -7
  92. package/src/knowledge/plan.ts +25 -9
  93. package/src/knowledge/refs.ts +3 -0
  94. package/src/knowledge/resolve.ts +2 -2
  95. package/src/knowledge/review.fixes.test.ts +3 -2
  96. package/src/knowledge/review.gaps.test.ts +5 -3
  97. package/src/knowledge/review.test.ts +4 -2
  98. package/src/knowledge/review.ts +38 -13
  99. package/src/knowledge/reviewModel.ts +7 -1
  100. package/src/knowledge/reviewPrefetch.ts +10 -2
  101. package/src/knowledge/reviewRun.ts +1 -1
  102. package/src/knowledge/reviewRunModel.ts +2 -2
  103. package/src/knowledge/sources.ts +44 -8
  104. package/src/knowledge/truncate.ts +6 -5
@@ -287,6 +287,7 @@
287
287
  "EXTERNAL_SERVICE_IDS",
288
288
  "EXTRACTOR_VERSION",
289
289
  "ExtractFailed",
290
+ "FALLBACK_PACK_ID",
290
291
  "GOD_MODULE_KIND",
291
292
  "GOD_MODULE_LIMITS",
292
293
  "LocalSnapshotStore",
@@ -358,6 +359,7 @@
358
359
  "hashDocText",
359
360
  "ignoreMatcher",
360
361
  "ignoreSourcesOf",
362
+ "isAssetPath",
361
363
  "isBinaryPath",
362
364
  "isBinaryText",
363
365
  "isDocumentPath",
@@ -0,0 +1,206 @@
1
+ /**
2
+ * src/contract/regression.assets.test.ts — assets (binary files stored as a file node, never read): how their asset-ness follows the
3
+ * packs, how a cut treats them, and what the upgrade and the removal of one do. Each bug pinned by one test named `regression: …`.
4
+ */
5
+
6
+ import { hashText } from '../ingest/hash.js';
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { isBinaryDocumentType } from '../ingest/parserSupport.js';
9
+ import { assetExtracted } from '../knowledge/assetFile.js';
10
+ import { buildGraph } from '../knowledge/build.js';
11
+ import type { KnowledgePack, KnowledgeParser } from '../knowledge/model.js';
12
+ import { DOCS_PACK } from '../knowledge/packs/docs.js';
13
+ import { planDetail, planReview } from '../knowledge/plan.js';
14
+ import { srcRef } from '../knowledge/refs.js';
15
+ import { reviewDirectory } from '../knowledge/review.js';
16
+ import { extractJob, type ExtractPool } from '../knowledge/extractJob.js';
17
+ import { EXTRACTOR_VERSION, extractorManifestKey, filesManifestKey, isBinaryText, manifestMap, mediaTypeOfPath, saveManifestMap } from '../knowledge/sources.js';
18
+ import { args, edge, extractedOf, fileNode, memSource, memStore, ROOT, stateOf } from '../knowledge/testkit.test-util.js';
19
+
20
+ const PNG = 'PNGDATA';
21
+ const pdfParser: KnowledgeParser = {
22
+ id: 'pdf-text',
23
+ accepts: (s) => s.content.kind === 'text' && s.content.mediaType === 'application/pdf',
24
+ parse: (s) => [{ text: s.content.kind === 'text' ? s.content.text : '' }],
25
+ };
26
+ const withPdf: KnowledgePack = { ...DOCS_PACK, parsers: [pdfParser, ...DOCS_PACK.parsers] };
27
+
28
+ describe('regression: asset-ness follows the packs', () => {
29
+ it('regression: a pdf reviewed as an asset is re-processed when a host parser arrives, and an extracted one when it leaves', async () => {
30
+ const source = memSource({ 'a.pdf': 'pdf text', 'b.md': '# B\n' });
31
+ const manifest = new InMemoryIngestManifest();
32
+ const store = memStore();
33
+ const hash = hashText('pdf text');
34
+ await reviewDirectory(args(source, store, manifest)); // no parser: a.pdf is an asset
35
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual([]);
36
+
37
+ // A parser arrives: the bytes did not move, the version did not move — the file is still owed.
38
+ const arrived = await planReview(source, manifest, [withPdf]);
39
+ expect(arrived).toMatchObject({ changed: ['a.pdf'], assets: 0 });
40
+ const report = await reviewDirectory(args(source, store, manifest, { packs: [withPdf] }));
41
+ expect(report.extracted).toBe(1);
42
+ expect((await store.getExtracted(hash))![0]!.nodes[0]!.badges?.asset).toBeUndefined();
43
+ expect((await planReview(source, manifest, [withPdf])).changed).toEqual([]);
44
+ expect((await stateOf(manifest)).owed).toEqual([]);
45
+
46
+ // The parser leaves: the extraction is replaced by the asset node.
47
+ const gone = await planReview(source, manifest, [DOCS_PACK]);
48
+ expect(gone).toMatchObject({ changed: ['a.pdf'], assets: 1 });
49
+ await reviewDirectory(args(source, store, manifest, { packs: [DOCS_PACK] }));
50
+ expect((await store.getExtracted(hash))![0]!.nodes).toMatchObject([{ kind: 'file', badges: { asset: 1, mediaType: 'application/pdf' } }]);
51
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual([]);
52
+ });
53
+
54
+ it('regression: a plan handed to Continue keeps the flip, so the files it owes are still re-processed', async () => {
55
+ const source = memSource({ 'a.pdf': 'pdf text' });
56
+ const manifest = new InMemoryIngestManifest();
57
+ const store = memStore(); // ONE store across the runs, so a stale asset entry in the extract cache cannot hide
58
+ await reviewDirectory(args(source, store, manifest));
59
+ const detail = await planDetail(source, manifest, [withPdf]);
60
+ expect(detail.plan.changed).toEqual(['a.pdf']);
61
+ const report = await reviewDirectory(args(source, store, manifest, { packs: [withPdf], plan: detail }));
62
+ expect(report.extracted).toBe(1);
63
+ expect((await store.getExtracted(hashText('pdf text')))![0]!.nodes[0]!.badges?.asset).toBeUndefined();
64
+ });
65
+
66
+ it('regression: an aborted run during a documents flip records the new types, and the files it did not finish stay owed for the next run', async () => {
67
+ const files = Object.fromEntries(['a.pdf', 'b.pdf', 'c.pdf'].map((p) => [p, `text of ${p}`]));
68
+ const source = memSource({ ...files });
69
+ const manifest = new InMemoryIngestManifest();
70
+ const store = memStore();
71
+ await reviewDirectory(args(source, store, manifest)); // all three are assets
72
+ const stop = new AbortController();
73
+ const first = await reviewDirectory(args(source, store, manifest, {
74
+ packs: [withPdf], signal: stop.signal, concurrency: 1, onProgress: (p) => { if (p.phase === 'write') stop.abort(); },
75
+ }));
76
+ expect(first.aborted).toBe(true);
77
+ const owed = (await stateOf(manifest)).owed;
78
+ expect(owed.length).toBeGreaterThan(0); // unfinished flipped files stay owed although `documents` is already 'pdf'
79
+ expect(owed.every((p) => p in files)).toBe(true);
80
+
81
+ const next = await reviewDirectory(args(source, store, manifest, { packs: [withPdf] }));
82
+ expect(next.aborted).toBe(false);
83
+ expect((await stateOf(manifest)).owed).toEqual([]);
84
+ for (const text of Object.values(files)) expect((await store.getExtracted(hashText(text)))![0]!.nodes[0]!.badges?.asset).toBeUndefined();
85
+ });
86
+ });
87
+
88
+ describe('regression: assets in a cut graph', () => {
89
+ it('regression: a truncated graph never fills its slice with assets, nor keeps the ones beside a kept file', () => {
90
+ const docs = ['d0.md', 'd1.md', 'd2.md', 'd3.md'];
91
+ const icons = Array.from({ length: 6 }, (_, i) => `icons/i${i}.png`);
92
+ const extracted = [
93
+ extractedOf(fileNode('d0.md'), icons.map((p) => edge('d0.md', p))),
94
+ ...docs.slice(1).map((p) => extractedOf(fileNode(p))),
95
+ ...icons.map((p) => assetExtracted(ROOT, { path: p, hash: `h:${p}`, size: 1 })),
96
+ ];
97
+ // The control: uncut, the linked assets OUTRANK an isolated doc by importance (computed by PageRank, not the node's stored 0),
98
+ // so only the assets-last order keeps them out of the slice.
99
+ const whole = buildGraph({ rootId: ROOT, extracted, packs: [DOCS_PACK], facts: [], relations: [] });
100
+ const importanceOf = (path: string) => whole.nodes.find((n) => n.ref === srcRef(ROOT, path))!.importance;
101
+ expect(importanceOf('icons/i0.png')).toBeGreaterThan(importanceOf('d1.md'));
102
+
103
+ const g = buildGraph({ rootId: ROOT, extracted, packs: [DOCS_PACK], facts: [], relations: [] }, { maxNodes: 3 });
104
+ expect(g.stats.truncated).toBe(true);
105
+ expect(g.nodes.filter((n) => n.badges?.['asset'] !== undefined)).toEqual([]);
106
+ expect(g.nodes.filter((n) => n.kind === 'file').length).toBeGreaterThan(0);
107
+ // The outline still lists every file, assets included, with their badges.
108
+ expect(g.outline!.files.filter((f) => f.badges?.['asset'] === 1)).toHaveLength(icons.length);
109
+ });
110
+ });
111
+
112
+ describe('regression: lockfiles and fonts', () => {
113
+ it('regression: lockfiles are ignored (not assets, not extracted as text); a sqlite db stays an asset', async () => {
114
+ const source = memSource({ 'yarn.lock': 'x', 'crate/Cargo.lock': 'y', 'app.db': 'z', 'a.md': '# A\n' });
115
+ const plan = await planReview(source, new InMemoryIngestManifest(), [DOCS_PACK]);
116
+ expect(plan.skipped).toEqual(expect.arrayContaining([{ path: 'yarn.lock', reason: 'ignored' }, { path: 'crate/Cargo.lock', reason: 'ignored' }]));
117
+ expect(plan).toMatchObject({ files: 2, assets: 1 });
118
+ });
119
+
120
+ it('regression: a font object is not a binary document type (only pdf and office are), and an .eot is an asset', async () => {
121
+ expect(mediaTypeOfPath('f.eot')).toBe('application/vnd.ms-fontobject');
122
+ expect(isBinaryDocumentType('application/vnd.ms-fontobject')).toBe(false);
123
+ for (const type of ['application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'application/pdf']) expect(isBinaryDocumentType(type)).toBe(true);
124
+ expect((await planReview(memSource({ 'f.eot': 'x' }), new InMemoryIngestManifest(), [DOCS_PACK])).assets).toBe(1);
125
+ });
126
+ });
127
+
128
+ describe('regression: html references', () => {
129
+ it('regression: img, source, link and svg image references are followed; external and protocol-relative ones are not', async () => {
130
+ const html = [
131
+ '<img src="icons/a.png"><source src="v/b.webm"><link rel="stylesheet" href="css/c.css">',
132
+ '<svg><image xlink:href="icons/d.png"/></svg><a href="//cdn.example.com/x.png">x</a><img src="https://x.test/y.png">',
133
+ ].join('\n');
134
+ const source = memSource({ 'page.html': html });
135
+ const store = memStore();
136
+ await reviewDirectory(args(source, store, new InMemoryIngestManifest()));
137
+ const ex = (await store.getExtracted(hashText(html)))!.find((e) => e.sourceRef === srcRef(ROOT, 'page.html'))!;
138
+ expect(ex.edges.filter((e) => e.kind === 'links').map((e) => e.to)).toEqual(['css/c.css', 'icons/a.png', 'icons/d.png', 'v/b.webm'].map((p) => srcRef(ROOT, p)));
139
+ });
140
+
141
+ it('regression: a protocol-relative markdown link is external, not a missing file', async () => {
142
+ const md = '# R\n[cdn](//cdn.example.com/x.png) and [local](icons/a.png)\n';
143
+ const store = memStore();
144
+ await reviewDirectory(args(memSource({ 'README.md': md }), store, new InMemoryIngestManifest()));
145
+ const ex = (await store.getExtracted(hashText(md)))![0]!;
146
+ expect(ex.edges.filter((e) => e.kind === 'links').map((e) => e.to)).toEqual([srcRef(ROOT, 'icons/a.png')]);
147
+ });
148
+ });
149
+
150
+ describe('regression: the asset lifecycle', () => {
151
+ it('regression: a manifest at the file\'s current hash with no stored body queues the asset, so its node is written without a read', async () => {
152
+ const source = memSource({ 'icons/a.png': PNG, 'a.md': '# A\n' });
153
+ const manifest = new InMemoryIngestManifest();
154
+ await reviewDirectory(args(source, memStore(), manifest));
155
+ const fresh = memStore(); // the manifest names the files; this store holds no body
156
+ source.reads.length = 0;
157
+ await reviewDirectory(args(source, fresh, manifest));
158
+ expect(source.reads).toEqual([]); // the asset is never read
159
+ expect((await fresh.getExtracted(hashText(PNG)))![0]!.nodes[0]).toMatchObject({ kind: 'file', badges: { asset: 1, mediaType: 'image/png' } });
160
+ });
161
+
162
+ it('regression: a v3 root whose binary files hold a legacy [] gets their asset nodes at v4', async () => {
163
+ const source = memSource({ 'icons/a.png': PNG, 'a.md': '# A\n' });
164
+ const manifest = new InMemoryIngestManifest();
165
+ await saveManifestMap(manifest, filesManifestKey(ROOT), new Map([['icons/a.png', hashText(PNG)], ['a.md', hashText('# A\n')]]));
166
+ await manifest.set(extractorManifestKey(ROOT), [{ id: 'version', hash: String(EXTRACTOR_VERSION - 1) }]);
167
+ const store = memStore();
168
+ await store.putExtracted(hashText(PNG), []); // what v3 stored for a binary file
169
+ await reviewDirectory(args(source, store, manifest));
170
+ expect((await store.getExtracted(hashText(PNG)))![0]!.nodes[0]).toMatchObject({ kind: 'file', badges: { asset: 1, size: PNG.length } });
171
+ expect((await stateOf(manifest)).version).toBe(EXTRACTOR_VERSION);
172
+ });
173
+
174
+ it('regression: a removed asset is retired like any removed file', async () => {
175
+ const source = memSource({ 'icons/a.png': PNG, 'a.md': '# A\n' });
176
+ const manifest = new InMemoryIngestManifest();
177
+ const store = memStore();
178
+ await reviewDirectory(args(source, store, manifest));
179
+ expect((await manifestMap(manifest, filesManifestKey(ROOT))).has('icons/a.png')).toBe(true);
180
+
181
+ delete source.files['icons/a.png'];
182
+ expect((await planReview(source, manifest, [DOCS_PACK])).removed).toEqual(['icons/a.png']);
183
+ const report = await reviewDirectory(args(source, store, manifest));
184
+ expect(report.staleMarked).toBe(1);
185
+ expect((await manifestMap(manifest, filesManifestKey(ROOT))).has('icons/a.png')).toBe(false);
186
+ });
187
+
188
+ it('regression: with an extractPool that reads (deferRead) an asset is never sent to the pool, and a file the pool finds binary becomes an asset node', async () => {
189
+ const nul = 'bin\u0000ary';
190
+ const source = memSource({ 'a.md': '# A\nalpha\n', 'icons/a.png': PNG, 'blob.txt': nul });
191
+ const sent: string[] = [];
192
+ const pool: ExtractPool = async (job) => {
193
+ sent.push(job.path);
194
+ const doc = await source.read(job.path);
195
+ if (doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { binary: true, extracted: [] };
196
+ return extractJob({ ...job, doc } as never, [DOCS_PACK]);
197
+ };
198
+ const store = memStore();
199
+ const report = await reviewDirectory(args(source, store, new InMemoryIngestManifest(), { extractPool: pool, deferRead: true }));
200
+ expect(report.failures).toEqual([]);
201
+ expect(sent).not.toContain('icons/a.png');
202
+ expect(sent).toContain('blob.txt');
203
+ expect((await store.getExtracted(hashText(PNG)))![0]!.nodes[0]).toMatchObject({ badges: { asset: 1, mediaType: 'image/png' } });
204
+ expect((await store.getExtracted(hashText(nul)))![0]!.nodes[0]).toMatchObject({ badges: { asset: 1, mediaType: 'text/plain' } });
205
+ });
206
+ });
@@ -26,7 +26,7 @@ describe('regression: a root reviewed before binary files were recorded is settl
26
26
  expect(source.reads).not.toContain('img.png');
27
27
  });
28
28
 
29
- it('regression: the review reads ONLY the files a replica asked to re-check: a NUL-binary gets [], a text file is extracted, the set is cleared', async () => {
29
+ it('regression: the review reads ONLY the files a replica asked to re-check: a NUL-binary gets its asset node, a text file is extracted, the set is cleared', async () => {
30
30
  const binary = 'bin\u0000ary';
31
31
  const files = { 'blob.txt': binary, 'a.md': text, 'b.md': '# B\nbeta\n' };
32
32
  const manifest = new InMemoryIngestManifest();
@@ -37,7 +37,7 @@ describe('regression: a root reviewed before binary files were recorded is settl
37
37
  const source = memSource(files);
38
38
  await reviewDirectory(args(source, legacy, manifest));
39
39
  expect(new Set(source.reads)).toEqual(new Set(['blob.txt', 'a.md'])); // b.md was never named
40
- expect(await legacy.getExtracted(hashText(binary))).toEqual([]);
40
+ expect((await legacy.getExtracted(hashText(binary)))![0]!.nodes[0]!.badges).toMatchObject({ asset: 1, size: binary.length });
41
41
  expect((await legacy.getExtracted(hashText(text)))!.length).toBeGreaterThan(0);
42
42
  expect(await legacy.getExtracted(hashText(files['b.md']))).toBeUndefined();
43
43
  expect(await legacy.recheckHashes()).toEqual([]);
@@ -86,12 +86,12 @@ describe('regression: a root reviewed before binary files were recorded is settl
86
86
  return legacy;
87
87
  };
88
88
 
89
- it('regression: a review stopped mid-way (after the backfill queued the file) keeps the re-check request and records no terminal [], and a complete one clears it', async () => {
89
+ it('regression: a review stopped mid-way (on the read of the file the backfill queued) keeps the re-check request and records no terminal [], and a complete one clears it', async () => {
90
90
  const manifest = new InMemoryIngestManifest();
91
91
  const legacy = await legacyStore(manifest);
92
92
  const stop = new AbortController();
93
- // Read 1 is the backfill's, read 2 is the review's: the run is stopped there and the read rejects.
94
- const source = watched((n) => { if (n === 2) { stop.abort(); throw new Error('aborted'); } });
93
+ // The backfill only queues the file (it reads nothing); read 1 is the review's: the run is stopped there and the read rejects.
94
+ const source = watched((n) => { if (n === 1) { stop.abort(); throw new Error('aborted'); } });
95
95
  await reviewDirectory(args(source, legacy, manifest, { signal: stop.signal })).catch(() => undefined);
96
96
  expect(await legacy.recheckHashes()).toEqual([hashText(text)]);
97
97
  expect(await legacy.getExtracted(hashText(text))).toBeUndefined();
@@ -5,19 +5,21 @@
5
5
  */
6
6
 
7
7
  import { hashText } from '../ingest/hash.js';
8
+ import { buildGraph } from '../knowledge/build.js';
8
9
  import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
10
+ import type { ReviewProgress } from '../knowledge/model.js';
9
11
  import type { ReviewStep } from '../knowledge/reviewRunModel.js';
10
12
  import { extractJob, type ExtractJob, type ExtractPool } from '../knowledge/extractJob.js';
11
- import type { JudgementRequest, KnowledgePack, KnowledgeStore } from '../knowledge/model.js';
13
+ import type { JudgementRequest, KnowledgePack, KnowledgeParser, KnowledgeStore } from '../knowledge/model.js';
12
14
  import { DOCS_PACK } from '../knowledge/packs/docs.js';
13
15
  import { putNoExtract } from '../knowledge/extractFile.js';
14
16
  import { planReview } from '../knowledge/plan.js';
15
17
  import { srcRef } from '../knowledge/refs.js';
16
18
  import { reviewDirectory } from '../knowledge/review.js';
17
19
  import { applyRunEvent, failuresOf, failureTotal, REVIEW_RUN_FAILURE_CHUNK, startRun } from '../knowledge/reviewRun.js';
18
- import { extractorManifestKey, filesManifestKey, judgedManifestKey, manifestMap } from '../knowledge/sources.js';
20
+ import { extractorManifestKey, filesManifestKey, judgedManifestKey, manifestMap, mediaTypeOfPath } from '../knowledge/sources.js';
19
21
  import {
20
- ALL, args, fakeJudge, FILES, memSource, memStore, quietPack, ROOT, stateOf, type SpySource,
22
+ ALL, args, fakeJudge, FILES, graphOf, memSource, memStore, quietPack, ROOT, stateOf, type SpySource,
21
23
  } from '../knowledge/testkit.test-util.js';
22
24
 
23
25
  const sixFiles = () => Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`d${i}.md`, `# T${i}\nbody ${i}\n`]));
@@ -158,6 +160,60 @@ describe('regression: pass 2 and pass 1', () => {
158
160
  expect(retired).toEqual([srcRef(ROOT, 'c.md')]);
159
161
  });
160
162
 
163
+ it('regression: the review leaves "write" for an "analyse" phase the moment the last file is written, and forwards analyzer progress', async () => {
164
+ const pack: KnowledgePack = {
165
+ ...quietPack,
166
+ analyzers: { async analyse(_root, _signal, onProgress) { onProgress?.({ done: 1, total: 2 }); onProgress?.({ done: 2, total: 2 }); return []; } },
167
+ };
168
+ const events: Array<{ phase: string; done: number; total: number }> = [];
169
+ const source = memSource({ ...FILES });
170
+ await reviewDirectory(args(source, memStore(), new InMemoryIngestManifest(), {
171
+ judgement: fakeJudge(), packs: [pack], onProgress: (p) => events.push({ phase: p.phase, done: p.done, total: p.total }),
172
+ }));
173
+ const lastWrite = events.map((e) => e.phase).lastIndexOf('write');
174
+ const analyse = events.map((e, i) => (e.phase === 'analyse' ? i : -1)).filter((i) => i >= 0);
175
+ const firstResolve = events.findIndex((e) => e.phase === 'resolve');
176
+ expect(analyse.length).toBe(4);
177
+ expect(analyse[0]!).toBeGreaterThan(lastWrite);
178
+ expect(analyse[3]!).toBeLessThan(firstResolve);
179
+ expect(analyse.map((i) => [events[i]!.done, events[i]!.total])).toEqual([[0, 1], [1, 2], [2, 2], [2, 2]]); // open, two forwarded, close
180
+ });
181
+
182
+ it('regression: an analyzer that never reports keeps the "analyse" row active while it runs, and the row ends before resolve', async () => {
183
+ let release!: () => void;
184
+ const gate = new Promise<void>((r) => { release = r; });
185
+ let entered!: () => void;
186
+ const inside = new Promise<void>((r) => { entered = r; });
187
+ const pack: KnowledgePack = { ...quietPack, analyzers: { async analyse() { entered(); await gate; return []; } } };
188
+ const events: ReviewProgress[] = [];
189
+ const done = reviewDirectory(args(memSource({ ...FILES }), memStore(), new InMemoryIngestManifest(), {
190
+ judgement: fakeJudge(), packs: [pack], onProgress: (p) => events.push(p),
191
+ }));
192
+ await inside;
193
+ const fold = () => events.reduce((run, progress) => applyRunEvent(run, { type: 'progress', progress }, 1), startRun({ id: 'r', root: 'r', kind: 'review', at: 0 }));
194
+ const during = fold().phases.find((p) => p.phase === 'analyse');
195
+ expect(during).toBeDefined();
196
+ expect(during!.endedAt).toBeUndefined();
197
+ release();
198
+ await done;
199
+ const after = fold().phases.find((p) => p.phase === 'analyse')!;
200
+ expect(after.endedAt).toBeDefined();
201
+ expect(after.done).toBe(after.total);
202
+ expect(events.findIndex((e) => e.phase === 'resolve')).toBeGreaterThan(events.map((e) => e.phase).lastIndexOf('analyse'));
203
+ });
204
+
205
+ it('regression: a Stop while the analyzers run ends the review as aborted and never reaches resolve', async () => {
206
+ const stop = new AbortController();
207
+ const pack: KnowledgePack = { ...quietPack, analyzers: { async analyse() { stop.abort(); return []; } } };
208
+ const phases: string[] = [];
209
+ const report = await reviewDirectory(args(memSource({ ...FILES }), memStore(), new InMemoryIngestManifest(), {
210
+ judgement: fakeJudge(), packs: [pack], signal: stop.signal, onProgress: (p) => phases.push(p.phase),
211
+ }));
212
+ expect(report.aborted).toBe(true);
213
+ expect(phases).toContain('analyse');
214
+ expect(phases).not.toContain('resolve');
215
+ });
216
+
161
217
  it('regression: pass 1 neither owes nor stale-marks a file whose sections are all reused', async () => {
162
218
  const store = memStore();
163
219
  const manifest = new InMemoryIngestManifest();
@@ -237,11 +293,13 @@ describe('regression: changed since plan', () => {
237
293
  });
238
294
 
239
295
  describe('regression: a file with nothing to extract is told apart from one not extracted yet', () => {
240
- it('regression: a file found binary on read has an explicit stored [] (and a stale mark), never an absent body', async () => {
296
+ it('regression: a file found binary on read has a stored asset node (and a stale mark), never an absent body', async () => {
241
297
  const text = 'bin\u0000ary';
242
298
  const store = memStore();
243
299
  await reviewDirectory(args(memSource({ 'blob.txt': text }), store, new InMemoryIngestManifest()));
244
- expect(await store.getExtracted(hashText(text))).toEqual([]);
300
+ const stored = await store.getExtracted(hashText(text));
301
+ expect(stored).toHaveLength(1);
302
+ expect(stored![0]!.nodes).toMatchObject([{ kind: 'file', badges: { asset: 1, mediaType: 'text/plain', size: text.length } }]);
245
303
  });
246
304
 
247
305
  it('regression: a text file that is not extracted (here: its review failed) has NO stored body, so it is never mistaken for binary', async () => {
@@ -262,3 +320,124 @@ describe('regression: a file with nothing to extract is told apart from one not
262
320
  expect(await store.getExtracted(hashText(text))).toEqual(before);
263
321
  });
264
322
  });
323
+
324
+ describe('regression: a binary file is an asset with a node, not a skipped file', () => {
325
+ const PNG = 'PNGDATA';
326
+
327
+ it('regression: a .png in a reviewed directory has a file node with mediaType, size and asset, is never read, and is not in plan.skipped', async () => {
328
+ const source = memSource({ 'a.md': '# A\nalpha\n', 'icons/icon128.png': PNG });
329
+ const store = memStore();
330
+ const manifest = new InMemoryIngestManifest();
331
+ const plan = await planReview(source, manifest, [DOCS_PACK]);
332
+ expect(plan.skipped.map((s) => s.path)).not.toContain('icons/icon128.png');
333
+ expect(plan).toMatchObject({ files: 2, assets: 1, byPack: { docs: 1 }, changed: ['a.md', 'icons/icon128.png'] });
334
+
335
+ const report = await reviewDirectory(args(source, store, manifest));
336
+ expect(report.failures).toEqual([]);
337
+ expect(source.reads).not.toContain('icons/icon128.png');
338
+ const stored = await store.getExtracted(hashText(PNG));
339
+ expect(stored).toHaveLength(1);
340
+ expect(stored![0]!.nodes).toEqual([expect.objectContaining({
341
+ ref: srcRef(ROOT, 'icons/icon128.png'), kind: 'file', label: 'icon128.png',
342
+ badges: { asset: 1, mediaType: 'image/png', size: PNG.length },
343
+ })]);
344
+ expect((await manifestMap(manifest, filesManifestKey(ROOT))).get('icons/icon128.png')).toBe(hashText(PNG));
345
+
346
+ // Diffed like any file: unchanged is not reviewed again, a new byte string is.
347
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual([]);
348
+ source.files['icons/icon128.png'] = 'OTHER';
349
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual(['icons/icon128.png']);
350
+ });
351
+
352
+ it('regression: an asset over maxFileBytes is still an asset, and costs no model call', async () => {
353
+ const plan = await planReview(memSource({ 'big.zip': 'x'.repeat(50) }), new InMemoryIngestManifest(), [DOCS_PACK], { maxFileBytes: 10 });
354
+ expect(plan).toMatchObject({ files: 1, assets: 1, skipped: [], estimatedModelCalls: 0 });
355
+ });
356
+
357
+ it('regression: mediaTypeOfPath knows the image, font and archive types; an unknown binary extension is octet-stream; text stays text/plain', () => {
358
+ expect(mediaTypeOfPath('x.png')).toBe('image/png');
359
+ expect(mediaTypeOfPath('a/b/favicon.ICO')).toBe('image/vnd.microsoft.icon');
360
+ expect(mediaTypeOfPath('f.woff2')).toBe('font/woff2');
361
+ expect(mediaTypeOfPath('a.zip')).toBe('application/zip');
362
+ expect(mediaTypeOfPath('lib.so')).toBe('application/octet-stream');
363
+ expect(mediaTypeOfPath('notes.txt')).toBe('text/plain');
364
+ expect(mediaTypeOfPath('Makefile')).toBe('text/plain');
365
+ });
366
+
367
+ it('regression: a document linking to an asset path has a links edge to the asset node, not to a missing placeholder', async () => {
368
+ // The docs pack resolves written links; a host code pack resolves its path references through the same `ctx.resolvePath` and srcRef.
369
+ const source = memSource({ 'README.md': '# R\nSee [the logo](icons/icon128.png).\n', 'icons/icon128.png': PNG, 'other.md': '# O\n[gone](icons/gone.png)\n' });
370
+ const store = memStore();
371
+ await reviewDirectory(args(source, store, new InMemoryIngestManifest()));
372
+ const g = await graphOf(source, store);
373
+ const asset = g.nodes.find((n) => n.ref === srcRef(ROOT, 'icons/icon128.png'));
374
+ expect(asset).toMatchObject({ kind: 'file', badges: { asset: 1, mediaType: 'image/png' } });
375
+ const into = g.edges.filter((e) => e.kind === 'links' && e.to === asset!.ref);
376
+ expect(into).toHaveLength(1);
377
+ expect(into[0]!.from.startsWith(srcRef(ROOT, 'README.md'))).toBe(true); // from the file or the section holding the link
378
+ expect(g.nodes.find((n) => n.ref === srcRef(ROOT, 'icons/gone.png'))?.kind).toBe('missing'); // a truly absent target still is
379
+ });
380
+
381
+ it('regression: a markdown image ![alt](path) references its target like a link, so it lands on the asset node', async () => {
382
+ const source = memSource({ 'README.md': '# R\n![logo](icons/icon128.png) and ![ref][shot]\n\n[shot]: shots/s.png\n', 'icons/icon128.png': PNG, 'shots/s.png': 'SHOT' });
383
+ const store = memStore();
384
+ await reviewDirectory(args(source, store, new InMemoryIngestManifest()));
385
+ const g = await graphOf(source, store);
386
+ for (const p of ['icons/icon128.png', 'shots/s.png']) {
387
+ const to = srcRef(ROOT, p);
388
+ expect(g.nodes.find((n) => n.ref === to)).toMatchObject({ kind: 'file', badges: { asset: 1 } });
389
+ expect(g.edges.filter((e) => e.kind === 'links' && e.to === to)).toHaveLength(1);
390
+ }
391
+ });
392
+
393
+ it('regression: an outlined, truncated graph keeps the asset badges (asset, mediaType, size) of its files', async () => {
394
+ const files: Record<string, string> = { 'icons/icon128.png': PNG };
395
+ for (let i = 0; i < 12; i++) files[`d${i}.md`] = `# T${i}\nbody ${i}\n`;
396
+ const source = memSource(files);
397
+ const store = memStore();
398
+ await reviewDirectory(args(source, store, new InMemoryIngestManifest()));
399
+ const extracted = [];
400
+ for await (const f of source.list()) {
401
+ const hit = (await store.getExtracted(f.hash))?.find((e) => e.sourceRef === srcRef(ROOT, f.path));
402
+ if (hit) extracted.push(hit);
403
+ }
404
+ const g = buildGraph({ rootId: ROOT, extracted, packs: [DOCS_PACK], facts: [], relations: [] }, { maxNodes: 3 });
405
+ expect(g.stats.truncated).toBe(true);
406
+ const png = g.outline!.files.find((f) => f.path === 'icons/icon128.png');
407
+ expect(png?.badges).toEqual({ asset: 1, mediaType: 'image/png', size: PNG.length });
408
+ });
409
+
410
+ it('regression: an .svg stays text: its title and text become a section and its href a link; it is not an asset', async () => {
411
+ const svg = '<svg xmlns="http://www.w3.org/2000/svg"><title>Logo</title><text>Hello brand</text><a href="icons/icon128.png"><rect width="1" height="1"/></a></svg>';
412
+ const source = memSource({ 'logo.svg': svg, 'icons/icon128.png': PNG });
413
+ const store = memStore();
414
+ const manifest = new InMemoryIngestManifest();
415
+ expect((await planReview(source, manifest, [DOCS_PACK])).assets).toBe(1); // only the png
416
+ await reviewDirectory(args(source, store, manifest));
417
+ const ex = (await store.getExtracted(hashText(svg)))!.find((e) => e.sourceRef === srcRef(ROOT, 'logo.svg'))!;
418
+ expect(mediaTypeOfPath('logo.svg')).toBe('image/svg+xml');
419
+ expect(ex.nodes[0]).toMatchObject({ kind: 'file', pack: 'docs' });
420
+ expect(ex.nodes[0]!.badges?.asset).toBeUndefined();
421
+ expect(ex.nodes.some((n) => n.kind === 'section' && String(n.badges?.excerpt).includes('Hello brand'))).toBe(true);
422
+ expect(ex.edges.filter((e) => e.kind === 'links').map((e) => e.to)).toEqual([srcRef(ROOT, 'icons/icon128.png')]);
423
+ });
424
+
425
+ it('regression: a pdf with no host parser becomes an asset node; with a host parser it is still extracted', async () => {
426
+ const pdf: KnowledgeParser = {
427
+ id: 'pdf-text',
428
+ accepts: (s) => s.content.kind === 'text' && s.content.mediaType === 'application/pdf',
429
+ parse: (s) => [{ text: s.content.kind === 'text' ? s.content.text : '' }],
430
+ };
431
+ const files = { 'doc.pdf': 'pdf text' };
432
+ const bare = memStore();
433
+ const bareReport = await reviewDirectory(args(memSource({ ...files }), bare, new InMemoryIngestManifest()));
434
+ expect(bareReport.extracted).toBe(0);
435
+ expect((await bare.getExtracted(hashText('pdf text')))![0]!.nodes[0]).toMatchObject({ kind: 'file', badges: { asset: 1, mediaType: 'application/pdf' } });
436
+
437
+ const hosted = memStore();
438
+ const withPdf: KnowledgePack = { ...DOCS_PACK, parsers: [pdf, ...DOCS_PACK.parsers] };
439
+ const hostedReport = await reviewDirectory(args(memSource({ ...files }), hosted, new InMemoryIngestManifest(), { packs: [withPdf] }));
440
+ expect(hostedReport.extracted).toBe(1);
441
+ expect((await hosted.getExtracted(hashText('pdf text')))![0]!.nodes[0]!.badges?.asset).toBeUndefined();
442
+ });
443
+ });
@@ -74,7 +74,7 @@ export type ReviewStep_fields = Expect<Equal<
74
74
  { path: string; phase: ReviewPhase; ms: number; reason?: string; lane?: number }
75
75
  >>;
76
76
  // `mapped` is the end of the mechanical pass: a view that switches on phases must know it.
77
- export type ReviewPhase_values = Expect<Equal<ReviewPhase, 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'index' | 'mapped' | 'done'>>;
77
+ export type ReviewPhase_values = Expect<Equal<ReviewPhase, 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'analyse' | 'index' | 'mapped' | 'done'>>;
78
78
 
79
79
  /* ── ExtractJob: a union of "the review read it" (doc) and "the pool reads it" (readByPool) ──────────────────── */
80
80
  const aDocument: SourceDocument = { id: 'a.md', tenantId: 't', content: { kind: 'text', text: '# A\n' } };
@@ -193,7 +193,7 @@ export type KNode_system_fields = Expect<Equal<
193
193
  export type GraphSystem_fields = Expect<Equal<
194
194
  GraphSystem,
195
195
  {
196
- path: string; name: string; files: number; apps: GraphApp[]; truncated?: boolean; copyOf?: string; copySimilarity?: number;
196
+ path: string; name: string; files: number; assets?: number; apps: GraphApp[]; truncated?: boolean; copyOf?: string; copySimilarity?: number;
197
197
  copyReason?: 'no-git' | 'name-mismatch' | 'later-name'; graphRead?: { read: number; skipped: GraphReadSkip[] };
198
198
  }
199
199
  >>;
@@ -92,7 +92,8 @@ class ExtractBuilder {
92
92
  /** A `links` edge to the target, unless it is the root itself (or a folder above it). */
93
93
  link(from: NodeRef, target: string, byName?: string): void {
94
94
  const clean = target.split('#')[0]!.split('?')[0]!.trim();
95
- if (!clean || /^[a-z][a-z0-9+.-]*:/i.test(clean)) return;
95
+ // A scheme (`https:`, `data:`, `mailto:`) or a protocol-relative `//cdn/x.png` is external, never a file of the root.
96
+ if (!clean || clean.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(clean)) return;
96
97
  let decoded = clean;
97
98
  try { decoded = decodeURI(clean); } catch { /* keep the raw target */ }
98
99
  // Written as directory navigation (`.`, `./`, `..`, `/`, `docs/`): a folder, not a file link.
@@ -234,10 +235,11 @@ export function withoutCode(text: string, opts: { indented?: boolean } = {}): st
234
235
  return out.join('\n').replace(INLINE_CODE, ' ');
235
236
  }
236
237
 
237
- const MD_LINK = /(?<!!)\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;
238
+ /** `[text](target)` and the image form `![alt](target)`: both reference the target (an image file is an asset node). */
239
+ const MD_LINK = /\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g;
238
240
  /** `[id]: target` definitions (reference-style links); the use is `[text][id]` or `[id][]`. */
239
241
  const MD_REF_DEF = /^ {0,3}\[([^\]]+)\]:\s*<?(\S+?)>?(?:\s+["'(].*)?[ \t\r]*$/gm;
240
- const MD_REF_USE = /(?<!!)\[([^\]]*)\]\[([^\]]*)\]/g;
242
+ const MD_REF_USE = /\[([^\]]*)\]\[([^\]]*)\]/g;
241
243
 
242
244
  /** Reference-link definitions of a whole markdown text, by lower-cased label. */
243
245
  function refDefinitions(text: string): Map<string, string> {
@@ -308,11 +310,14 @@ export function extractMarkdown(source: SourceDocument, sections: ParsedSection[
308
310
  return b.build();
309
311
  }
310
312
 
313
+ /** The first `href` / `src` / `xlink:href` of an `<a>`, `<img>`, `<source>`, `<link>` or svg `<image>` tag: a file the page references. */
314
+ const HTML_REF = /<(?:a|img|source|link|image)(?=\s)[^>]*?\s(?:xlink:)?(?:href|src)\s*=\s*["']([^"']+)["']/gi;
315
+
311
316
  export function extractHtml(source: SourceDocument, sections: ParsedSection[], ctx: Ctx): Extracted {
312
317
  const title = sections[0]?.metadata?.['htmlTitle'];
313
318
  const b = new ExtractBuilder(source, ctx, typeof title === 'string' ? title : undefined);
314
319
  if (typeof title === 'string' && title) b.key(b.fileRef, normalizeKey(title));
315
- for (const m of textOf(source).matchAll(/<a\s[^>]*href\s*=\s*["']([^"']+)["']/gi)) {
320
+ for (const m of textOf(source).matchAll(HTML_REF)) {
316
321
  if (!m[1]!.startsWith('#')) b.link(b.fileRef, m[1]!);
317
322
  }
318
323
  sections.forEach((section, index) => b.mentions(b.bodySection(index, section.text), section.text));
@@ -12,13 +12,13 @@ export const mediaTypeOf = (source: SourceDocument): string =>
12
12
  source.content.kind === 'text' ? (source.content.mediaType ?? 'text/plain').toLowerCase() : '';
13
13
 
14
14
  /**
15
- * Binary documents — pdf, legacy and OOXML/OpenDocument office files. Their bytes are not
16
- * text. The ingest pipeline's builtin parsers are unchanged (the html/xml and plain-text
15
+ * Binary documents — pdf, legacy (`vnd.ms-excel|powerpoint|word`, not other `vnd.ms-*` such as a font object) and OOXML/OpenDocument office
16
+ * files. Their bytes are not text. The ingest pipeline's builtin parsers are unchanged (the html/xml and plain-text
17
17
  * matchers still accept these types); the knowledge composition (`composePacks`) is what
18
18
  * makes the builtin docs parsers refuse them, so only a host extractor that turns them into
19
19
  * text claims them there, in any pack order.
20
20
  */
21
21
  export function isBinaryDocumentType(mediaType: string): boolean {
22
- return /^application\/(?:pdf|msword|vnd\.(?:openxmlformats-officedocument\.|ms-|oasis\.opendocument\.))/
22
+ return /^application\/(?:pdf|msword|vnd\.(?:openxmlformats-officedocument\.|ms-(?:excel|powerpoint|word)|oasis\.opendocument\.))/
23
23
  .test(mediaType.trim().toLowerCase());
24
24
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * knowledge/assetFile.ts — the file node of an ASSET: a binary file (image, font, archive …) that is in the
3
+ * root but has no text to extract. It is planned, hashed and diffed like any file and never read, extracted or
4
+ * judged; this module writes the ONE node that stands for it, so a reference to its path (an `<img src>`, an
5
+ * import, a link) resolves to a real node instead of a `missing` placeholder.
6
+ *
7
+ * The node is the SAME file node a text file gets (kind `file`, ref `srcRef(rootId, path)`, key = path, the
8
+ * content hash as `sourceHash`), stored in the same extract cache under the file's hash. What marks it is its
9
+ * `badges` (the node's pack-data field): `asset: 1`, `mediaType` (string) and `size` (bytes). A host that finds a
10
+ * text-extension file binary on read gets the same node, with the path-derived media type.
11
+ */
12
+
13
+ import type { Extracted, KnowledgeStore } from './model.js';
14
+ import { basenameOf, FALLBACK_PACK_ID, srcRef } from './refs.js';
15
+ import { EXTRACTOR_VERSION, mediaTypeOfPath } from './sources.js';
16
+ import { putExtract } from './extractFile.js';
17
+
18
+ /** The `Extracted` of one asset: one file node, no edges. Pure: the same inputs give the same bytes. */
19
+ export function assetExtracted(rootId: string, file: { path: string; hash: string; size: number }): Extracted {
20
+ const ref = srcRef(rootId, file.path);
21
+ return {
22
+ sourceRef: ref, sourceHash: file.hash, extractorVersion: EXTRACTOR_VERSION, edges: [], keys: [{ ref, key: file.path }],
23
+ nodes: [{
24
+ // No pack extracts an asset: it belongs to the generic pack, as a `missing` placeholder does.
25
+ ref, kind: 'file', label: basenameOf(file.path), pack: FALLBACK_PACK_ID, importance: 0, origin: 'extracted', sourceHash: file.hash,
26
+ badges: { asset: 1, mediaType: mediaTypeOfPath(file.path), size: file.size },
27
+ }],
28
+ };
29
+ }
30
+
31
+ /** Stores the asset node in the extract cache under the file's hash (the entries of other files sharing the hash are kept). */
32
+ export async function putAsset(store: KnowledgeStore, rootId: string, file: { path: string; hash: string; size: number }): Promise<void> {
33
+ await putExtract(store, file.hash, assetExtracted(rootId, file));
34
+ }