@seanhogg/builderforce-memory 2026.10.38 → 2026.10.40

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 (45) hide show
  1. package/dist/ingest/docsExtract.d.ts +10 -0
  2. package/dist/ingest/docsExtract.d.ts.map +1 -1
  3. package/dist/ingest/docsExtract.js +48 -4
  4. package/dist/ingest/docsExtract.js.map +1 -1
  5. package/dist/ingest/fences.d.ts +15 -0
  6. package/dist/ingest/fences.d.ts.map +1 -0
  7. package/dist/ingest/fences.js +46 -0
  8. package/dist/ingest/fences.js.map +1 -0
  9. package/dist/ingest/textParsers.d.ts.map +1 -1
  10. package/dist/ingest/textParsers.js +8 -7
  11. package/dist/ingest/textParsers.js.map +1 -1
  12. package/dist/knowledge/judge.d.ts +2 -0
  13. package/dist/knowledge/judge.d.ts.map +1 -1
  14. package/dist/knowledge/judge.js +2 -0
  15. package/dist/knowledge/judge.js.map +1 -1
  16. package/dist/knowledge/orderedPool.d.ts +17 -0
  17. package/dist/knowledge/orderedPool.d.ts.map +1 -0
  18. package/dist/knowledge/orderedPool.js +39 -0
  19. package/dist/knowledge/orderedPool.js.map +1 -0
  20. package/dist/knowledge/review.d.ts +2 -0
  21. package/dist/knowledge/review.d.ts.map +1 -1
  22. package/dist/knowledge/review.js +57 -16
  23. package/dist/knowledge/review.js.map +1 -1
  24. package/dist/knowledge/reviewModel.d.ts +2 -0
  25. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  26. package/dist/knowledge/sources.d.ts +1 -1
  27. package/dist/knowledge/sources.d.ts.map +1 -1
  28. package/dist/knowledge/sources.js +6 -2
  29. package/dist/knowledge/sources.js.map +1 -1
  30. package/package.json +3 -3
  31. package/src/ingest/docsExtract.ts +43 -4
  32. package/src/ingest/fences.ts +45 -0
  33. package/src/ingest/textParsers.ts +8 -6
  34. package/src/knowledge/judge.ts +2 -0
  35. package/src/knowledge/orderedPool.test.ts +107 -0
  36. package/src/knowledge/orderedPool.ts +52 -0
  37. package/src/knowledge/review.batched.test.ts +1 -1
  38. package/src/knowledge/review.owed.test.ts +2 -2
  39. package/src/knowledge/review.parallel.test.ts +106 -0
  40. package/src/knowledge/review.test.ts +1 -0
  41. package/src/knowledge/review.ts +53 -12
  42. package/src/knowledge/review.upgrade.test.ts +1 -1
  43. package/src/knowledge/reviewModel.ts +2 -0
  44. package/src/knowledge/scripts.test.ts +125 -0
  45. package/src/knowledge/sources.ts +7 -2
@@ -0,0 +1,52 @@
1
+ /**
2
+ * knowledge/orderedPool.ts — an ORDER-PRESERVING bounded-concurrency prefetcher.
3
+ *
4
+ * `prefetchOrdered` starts up to `limit` jobs ahead of the consumer and yields their settled
5
+ * results strictly in input order, so a consumer that acts on each result in sequence behaves
6
+ * exactly as if the jobs had run one at a time — only the waiting overlaps. Jobs start only when
7
+ * the consumer pulls (`next()`), so `limit` 1 has no read-ahead at all. A rejected job is
8
+ * yielded as `rejected`, never thrown. Nothing new starts once `signal` aborts or the consumer
9
+ * stops early. No timers, no randomness.
10
+ */
11
+
12
+ export interface Prefetched<T, R> {
13
+ item: T;
14
+ i: number;
15
+ result: PromiseSettledResult<R>;
16
+ }
17
+
18
+ export async function* prefetchOrdered<T, R>(
19
+ items: readonly T[],
20
+ limit: number,
21
+ work: (item: T, i: number) => Promise<R>,
22
+ signal?: AbortSignal,
23
+ ): AsyncGenerator<Prefetched<T, R>> {
24
+ const width = Math.max(1, Math.floor(limit));
25
+ const pending: Array<Promise<PromiseSettledResult<R>>> = [];
26
+ let next = 0;
27
+ const fill = () => {
28
+ while (pending.length < width && next < items.length && !signal?.aborted) {
29
+ const i = next++;
30
+ pending.push(
31
+ (async () => work(items[i]!, i))().then(
32
+ (value): PromiseSettledResult<R> => ({ status: 'fulfilled', value }),
33
+ (reason): PromiseSettledResult<R> => ({ status: 'rejected', reason }),
34
+ ),
35
+ );
36
+ }
37
+ };
38
+ try {
39
+ for (let i = 0; i < items.length; i++) {
40
+ // The consumer's turn for item i begins here: an abort by now ends the stream, discarding read-ahead.
41
+ if (signal?.aborted) return;
42
+ fill();
43
+ const head = pending.shift();
44
+ if (!head) return; // aborted before this item started
45
+ const result = await head;
46
+ yield { item: items[i]!, i, result };
47
+ }
48
+ } finally {
49
+ // Never complete while a started job is still running: nothing outlives the consumer.
50
+ await Promise.allSettled(pending);
51
+ }
52
+ }
@@ -82,7 +82,7 @@ describe('reviewDirectory over a batched store', () => {
82
82
  };
83
83
  const p = logging();
84
84
  const store = storeOver(p);
85
- const report = await reviewDirectory(args(source, store, new InMemoryIngestManifest(), { judgement: fakeJudge(), signal: controller.signal }));
85
+ const report = await reviewDirectory(args(source, store, new InMemoryIngestManifest(), { judgement: fakeJudge(), signal: controller.signal, concurrency: 1 })); // sequential: abort fires inside a read
86
86
  expect(report.aborted).toBe(true);
87
87
  expect(report.extracted).toBeLessThan(10);
88
88
  const persisted = content(p.value!);
@@ -187,7 +187,7 @@ describe('what an upgrade run leaves owed', () => {
187
187
  if (p === 'b.md') controller.abort(); // b.md is still handled; the loop stops before c.md
188
188
  return doc;
189
189
  };
190
- const report = await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), signal: controller.signal }));
190
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), signal: controller.signal, concurrency: 1 })); // sequential: abort fires inside a read
191
191
  expect(report.aborted).toBe(true);
192
192
  expect(await stateOf(manifest)).toEqual({ version: CURRENT, owed: ['c.md'] });
193
193
 
@@ -226,7 +226,7 @@ describe('what an upgrade run leaves owed', () => {
226
226
  delete source.files['b.md'];
227
227
  const controller = new AbortController();
228
228
  controller.abort();
229
- await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), signal: controller.signal }));
229
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), signal: controller.signal, concurrency: 1 })); // sequential: pinned like the other abort tests
230
230
  expect(await stateOf(manifest)).toEqual({ version: CURRENT, owed: ALL });
231
231
 
232
232
  await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
@@ -0,0 +1,106 @@
1
+ /**
2
+ * src/knowledge/review.parallel.test.ts
3
+ * Read + extract are prefetched, judge/write stay in file order: a review whose reads resolve out
4
+ * of order stores exactly what a one-at-a-time review stores, with the same report and progress.
5
+ */
6
+
7
+ import { hashText } from '../ingest/hash.js';
8
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
9
+ import type { ReviewProgress } from './model.js';
10
+ import { reviewDirectory } from './review.js';
11
+ import { filesManifestKey, manifestMap } from './sources.js';
12
+ import { args, fakeJudge, memSource, memStore, ROOT, type SpySource } from './testkit.test-util.js';
13
+
14
+ const N = 12;
15
+ const files = () => Object.fromEntries(Array.from({ length: N }, (_, i) => [`d${i}.md`, `# T${i}\nbody ${i}\n`]));
16
+
17
+ /** A source whose read of file k waits N-k microtask turns: later files resolve first. */
18
+ function skewed(): { source: SpySource; maxInFlight: () => number } {
19
+ const source = memSource(files());
20
+ const read = source.read.bind(source);
21
+ let inFlight = 0;
22
+ let max = 0;
23
+ source.read = async (path) => {
24
+ inFlight += 1; max = Math.max(max, inFlight);
25
+ const k = Number(/d(\d+)/.exec(path)![1]);
26
+ for (let t = 0; t < N - k; t++) await Promise.resolve();
27
+ const doc = await read(path);
28
+ inFlight -= 1;
29
+ return doc;
30
+ };
31
+ return { source, maxInFlight: () => max };
32
+ }
33
+
34
+ async function run(concurrency: number) {
35
+ const { source, maxInFlight } = skewed();
36
+ const store = memStore();
37
+ const events: ReviewProgress[] = [];
38
+ // A small budget so judgement is cut part-way: the budget must be spent in file order.
39
+ const report = await reviewDirectory(args(source, store, new InMemoryIngestManifest(), {
40
+ judgement: fakeJudge(), concurrency, budget: { modelCalls: 5, ms: 60_000 }, onProgress: (p) => events.push(p),
41
+ }));
42
+ const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
43
+ return {
44
+ facts: [...(await store.facts({ rootId: ROOT }))].sort(byKey),
45
+ relations: [...(await store.relations({ rootId: ROOT }))],
46
+ report: { ...report, durationMs: 0 },
47
+ events, maxInFlight: maxInFlight(),
48
+ };
49
+ }
50
+
51
+ describe('reviewDirectory prefetch', () => {
52
+ it('stores, reports and progresses identically at concurrency 4 and 1, while reads overlap', async () => {
53
+ const parallel = await run(4);
54
+ const serial = await run(1);
55
+ expect(parallel.maxInFlight).toBeGreaterThan(1);
56
+ expect(serial.maxInFlight).toBe(1);
57
+ expect(parallel.facts.length).toBeGreaterThan(0);
58
+ expect(parallel.facts).toEqual(serial.facts);
59
+ expect(parallel.relations).toEqual(serial.relations);
60
+ expect(parallel.report).toEqual(serial.report);
61
+ expect(parallel.events).toEqual(serial.events);
62
+ });
63
+
64
+ it('an abort mid-run at default concurrency writes exactly the consumed prefix and resumes to the same store', async () => {
65
+ const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
66
+ const factsOf = async (store: ReturnType<typeof memStore>) => [...(await store.facts({ rootId: ROOT }))].sort(byKey);
67
+
68
+ const clean = memStore();
69
+ await reviewDirectory(args(skewed().source, clean, new InMemoryIngestManifest(), { judgement: fakeJudge() }));
70
+
71
+ const { source } = skewed();
72
+ const store = memStore();
73
+ const manifest = new InMemoryIngestManifest();
74
+ const controller = new AbortController();
75
+ const report = await reviewDirectory(args(source, store, manifest, {
76
+ judgement: fakeJudge(), signal: controller.signal,
77
+ onProgress: (p) => { if (p.phase === 'write' && p.done === 1) controller.abort(); },
78
+ }));
79
+ expect(report.aborted).toBe(true);
80
+ const stored = JSON.stringify(await factsOf(store));
81
+ expect(stored).toContain('d0.md');
82
+ expect(stored).toContain('d1.md');
83
+ for (let k = 2; k < N; k++) expect(stored).not.toContain(`d${k}.md`);
84
+ expect([...(await manifestMap(manifest, filesManifestKey(ROOT))).keys()].sort()).toEqual(['d0.md', 'd1.md']);
85
+
86
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
87
+ expect(await factsOf(store)).toEqual(await factsOf(clean));
88
+ });
89
+
90
+ it('files with identical content keep every sourceRef in the extract cache at any concurrency', async () => {
91
+ const SAME = '# Same\nsame body\n';
92
+ const text = { ...files(), 'x1.md': SAME, 'x2.md': SAME, 'x3.md': SAME };
93
+ const go = async (concurrency: number) => {
94
+ const source = memSource(text);
95
+ const store = memStore();
96
+ await reviewDirectory(args(source, store, new InMemoryIngestManifest(), { judgement: fakeJudge(), concurrency }));
97
+ const hash = hashText(SAME);
98
+ const refs = ((await store.getExtracted!(hash)) ?? []).map((e) => e.sourceRef).sort();
99
+ const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
100
+ return { refs, facts: [...(await store.facts({ rootId: ROOT }))].sort(byKey) };
101
+ };
102
+ const parallel = await go(4);
103
+ expect(parallel.refs).toHaveLength(3);
104
+ expect(parallel).toEqual(await go(1));
105
+ });
106
+ });
@@ -156,6 +156,7 @@ describe('reviewDirectory', () => {
156
156
  const report = await reviewDirectory(args(source, store, new InMemoryIngestManifest(), {
157
157
  judgement: fakeJudge(),
158
158
  signal: controller.signal,
159
+ concurrency: 1, // sequential: the abort is triggered from a progress callback, pin read order
159
160
  onProgress: (p) => { if (p.phase === 'write') controller.abort(); },
160
161
  }));
161
162
  expect(report.aborted).toBe(true);
@@ -7,6 +7,8 @@
7
7
  * of judged kinds, within budget) · write · markStale → analyzers → compare near-duplicate
8
8
  * claims → manifest + scope digest. Claims whose compare pairs were skipped wait in the
9
9
  * compare manifest for *Continue*.
10
+ * Read + extract are prefetched with bounded concurrency (`args.concurrency`); judge · write ·
11
+ * markStale stay in file order, so the shared model-call budget is spent deterministically.
10
12
  *
11
13
  * Store judgement, compute perception: only `model` facts and relations are written —
12
14
  * `extracted` output goes to the extracted cache, never to memory ({@link assertStoredBatch}).
@@ -28,12 +30,21 @@ import { SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
28
30
  import { owedAfterRun, owedCalls, saveExtractorState } from './owedFiles.js';
29
31
  import { planDetail, refreshPlan } from './plan.js';
30
32
  import { composePacks, filesManifestKey, isBinaryText, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
31
- import { extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
32
- import { DEFAULT_REVIEW_MODEL_CALLS, JudgedBatch, judgeSections, type CompareOutcome, type JudgeBudget } from './judge.js';
33
+ import { extractFileDetailed, knownKeysOfEntities, type FileExtraction } from './extractFile.js';
34
+ import { prefetchOrdered } from './orderedPool.js';
35
+ import { DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_MODEL_CALLS, JudgedBatch, judgeSections, type CompareOutcome, type JudgeBudget } from './judge.js';
33
36
  import { compareNew, pendingClaims, saveAwaiting } from './reviewCompare.js';
34
37
  import { factsWithoutAnchor, StoredIndex } from './reviewStored.js';
35
38
  import { canonicalJson, compareStr, srcRef } from './refs.js';
36
39
 
40
+ /** What the prefetch stage learned about one file; `failed` carries an extraction throw to be rethrown in file order. */
41
+ type Prefetch =
42
+ | { kind: 'read-error' }
43
+ | { kind: 'binary' }
44
+ | { kind: 'none' }
45
+ | { kind: 'extracted'; doc: SourceDocument; extraction: FileExtraction }
46
+ | { kind: 'failed'; error: unknown };
47
+
37
48
  /** Throws if a batch carries `extracted` items — perception is never memory. */
38
49
  export function assertStoredBatch(batch: { facts: readonly StoredFact[]; relations: readonly StoredRelation[] }): void {
39
50
  const bad = [...batch.facts, ...batch.relations].find((x) => (x.origin as string) === 'extracted');
@@ -122,30 +133,59 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
122
133
  // One bulk fetch of the extract cache for the whole run instead of a round trip per file.
123
134
  const hashes = [...new Set(changed.map((f) => f.hash))];
124
135
  if (hashes.length > 0) await store.preloadExtracted?.(hashes);
125
- for (const [i, f] of changed.entries()) {
126
- if (signal?.aborted) { report.aborted = true; break; }
136
+ // Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
137
+ // fixed above, and the content-hash extract cache); everything after stays sequential, in file order.
138
+ const concurrency = Math.min(32, Math.max(1, Math.floor(args.concurrency ?? DEFAULT_REVIEW_CONCURRENCY) || 1));
139
+ // extractFileDetailed read-modify-writes the extract cache entry of a content hash, so files sharing a hash
140
+ // extract one after another, in file order (jobs start in file order). Reads still overlap. A job always
141
+ // releases its turn, so a failed predecessor never blocks or poisons the next one.
142
+ const hashTail = new Map<string, Promise<void>>();
143
+ const prefetch = async (f: (typeof changed)[number]): Promise<Prefetch> => {
144
+ const before = hashTail.get(f.hash) ?? Promise.resolve();
145
+ let release!: () => void;
146
+ const mine = new Promise<void>((r) => { release = r; });
147
+ const tail = before.then(() => mine);
148
+ hashTail.set(f.hash, tail);
149
+ try {
150
+ let doc: SourceDocument;
151
+ try { doc = await source.read(f.path); } catch { return { kind: 'read-error' }; }
152
+ try {
153
+ if (doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
154
+ await before;
155
+ const extraction = await extractFileDetailed({
156
+ rootId, path: f.path, hash: f.hash, doc, packs, store, composed, knownKeys,
157
+ });
158
+ return extraction ? { kind: 'extracted', doc, extraction } : { kind: 'none' };
159
+ } catch (error) { return { kind: 'failed', error }; }
160
+ } finally {
161
+ release();
162
+ void tail.then(() => { if (hashTail.get(f.hash) === tail) hashTail.delete(f.hash); });
163
+ }
164
+ };
165
+ let consumed = 0;
166
+ for await (const { item: f, i, result } of prefetchOrdered(changed, concurrency, prefetch, signal)) {
167
+ consumed += 1; // the pool ends the stream at a file boundary once aborted, discarding read-ahead
127
168
  progress({ phase: 'extract', done: i, total: changed.length, path: f.path });
128
169
  // A read that throws (permissions, a lock, a race with a delete) says nothing about the file:
129
170
  // skipped with its knowledge and manifest hash intact, tried again next review.
130
- let doc: SourceDocument;
131
- try { doc = await source.read(f.path); } catch {
171
+ if (result.status === 'rejected') throw result.reason; // unreachable: a prefetch job settles to a Prefetch
172
+ const job = result.value;
173
+ if (job.kind === 'read-error') {
132
174
  report.readErrors += 1;
133
175
  measured.set(f.path, owedCalls(detail.extractor, f.path)); // a read error learns nothing: keep what it was owed
134
176
  continue;
135
177
  }
136
178
  // Recorded, so a file found binary on read is not re-read by every later review.
137
- if (doc.content.kind === 'text' && isBinaryText(doc.content.text)) {
179
+ if (job.kind === 'binary') {
138
180
  filesNow.set(f.path, f.hash);
139
181
  finished.add(f.path);
140
182
  await store.markStale(scope, srcRef(rootId, f.path), f.hash);
141
183
  report.staleMarked += 1;
142
184
  continue;
143
185
  }
144
- const extraction = await extractFileDetailed({
145
- rootId, path: f.path, hash: f.hash, doc, packs, store, composed, knownKeys,
146
- });
147
- if (!extraction) { finished.add(f.path); continue; }
148
- const { extracted: ex, sections, pack } = extraction;
186
+ if (job.kind === 'failed') throw job.error;
187
+ if (job.kind === 'none') { finished.add(f.path); continue; }
188
+ const { extracted: ex, sections, pack } = job.extraction;
149
189
  report.extracted += 1;
150
190
 
151
191
  const spec = pack.judgement;
@@ -197,6 +237,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
197
237
  report.staleMarked += 1;
198
238
  if (complete) { filesNow.set(f.path, f.hash); finished.add(f.path); }
199
239
  }
240
+ if (consumed < changed.length) report.aborted = true;
200
241
 
201
242
  if (!report.aborted) {
202
243
  await retire(detail.plan.removed);
@@ -65,7 +65,7 @@ describe('the extractor version has its own manifest entry', () => {
65
65
 
66
66
  const controller = new AbortController();
67
67
  controller.abort();
68
- const report = await reviewDirectory(args(source, store, manifest, { signal: controller.signal }));
68
+ const report = await reviewDirectory(args(source, store, manifest, { signal: controller.signal, concurrency: 1 }));
69
69
  expect(report.aborted).toBe(true);
70
70
  expect(await stateOf(manifest)).toEqual({ version: EXTRACTOR_VERSION, owed: ['a.md', 'b.md', 'c.md'] });
71
71
  expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual(['a.md', 'b.md', 'c.md']);
@@ -77,5 +77,7 @@ export interface ReviewArgs {
77
77
  /** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
78
78
  force?: boolean;
79
79
  signal?: AbortSignal;
80
+ /** Files read + extracted ahead of judging (1..32, default 8). Judge/write stay in file order. */
81
+ concurrency?: number;
80
82
  onProgress?(p: ReviewProgress): void;
81
83
  }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * src/knowledge/scripts.test.ts
3
+ * Shell scripts are never documents; `[[Name]]` and links inside markdown code are not edges.
4
+ */
5
+
6
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
7
+ import { markdownParser, plainTextParser } from '../ingest/parsers.js';
8
+ import type { SourceDocument } from '../ingest/types.js';
9
+ import type { ExtractContext, KnowledgePack } from './model.js';
10
+ import { DOCS_PACK } from './packs/docs.js';
11
+ import { planReview } from './plan.js';
12
+ import { asPathSource, resolveRelativePath } from './sources.js';
13
+ import { ROOT } from './testkit.test-util.js';
14
+
15
+ const ctx: ExtractContext = { rootId: ROOT, knownKeys: new Map(), resolvePath: resolveRelativePath };
16
+
17
+ function srcOf(path: string, text: string): SourceDocument {
18
+ return asPathSource({ id: path, tenantId: 't', content: { kind: 'text', text } }, path, 'h');
19
+ }
20
+
21
+ function linksOf(text: string, parser = markdownParser, path = 'a.md') {
22
+ const src = srcOf(path, text);
23
+ return parser.extract!(src, parser.parse(src), ctx).edges.filter((e) => e.kind === 'links');
24
+ }
25
+
26
+ function listing(files: Record<string, string>) {
27
+ return {
28
+ rootId: ROOT, title: 't',
29
+ async *list() { for (const [path, text] of Object.entries(files)) yield { path, hash: `h:${path}`, size: text.length }; },
30
+ async read(path: string): Promise<SourceDocument> {
31
+ return { id: path, tenantId: 't', content: { kind: 'text', text: files[path]! } };
32
+ },
33
+ };
34
+ }
35
+
36
+ const SHELL = 'if [[ -f x ]]; then :; fi';
37
+
38
+ describe('scripts are not documents', () => {
39
+ it.each(['run.sh', 'run.bash', 'run.zsh', 'run.ps1', 'run.bat', 'run.cmd', 'RUN.SH'])('%s is not claimed by the docs pack', async (name) => {
40
+ const plan = await planReview(listing({ [name]: SHELL, 'a.md': '# A\n' }), new InMemoryIngestManifest(), [DOCS_PACK]);
41
+ expect(plan.skipped).toContainEqual({ path: name, reason: 'no-pack' });
42
+ expect(plan.files).toBe(1);
43
+ });
44
+
45
+ it('a host parser can still claim a .sh file', async () => {
46
+ const hostPack: KnowledgePack = {
47
+ id: 'host', findings: [],
48
+ parsers: [{ id: 'sh', accepts: (s) => s.id.endsWith('.sh'), parse: () => [], extract: () => ({ sourceRef: 'x', sourceHash: 'h', nodes: [], edges: [], keys: [] }) } as never],
49
+ } as never;
50
+ const plan = await planReview(listing({ 'run.sh': SHELL }), new InMemoryIngestManifest(), [DOCS_PACK, hostPack]);
51
+ expect(plan.files).toBe(1);
52
+ expect(plan.byPack['host']).toBe(1);
53
+ });
54
+ });
55
+
56
+ describe('wiki and markdown links ignore code', () => {
57
+ it('prose links still resolve', () => {
58
+ expect(linksOf('See [[notes]].')).toHaveLength(1);
59
+ });
60
+
61
+ it('fenced, tilde-fenced, tab- and space-indented, and inline code make no link', () => {
62
+ expect(linksOf('# T\n```bash\nif [[ -f x ]]; then\n```\n')).toHaveLength(0);
63
+ expect(linksOf('# T\n~~~\n[[x]]\n~~~\n')).toHaveLength(0);
64
+ expect(linksOf('# T\n\n [[x]]\n')).toHaveLength(0);
65
+ expect(linksOf('# T\n\n\t[[x]]\n')).toHaveLength(0);
66
+ expect(linksOf('# T\nuse `[[x]]` here\n')).toHaveLength(0);
67
+ });
68
+
69
+ it('a double-backtick span and a span over a soft line break are code', () => {
70
+ expect(linksOf('# T\nuse ``a ` [[x]]`` here\n')).toHaveLength(0);
71
+ expect(linksOf('# T\nuse `a\n[[x]]` here\n')).toHaveLength(0);
72
+ });
73
+
74
+ it('handles CRLF input', () => {
75
+ expect(linksOf('# T\r\n```\r\n[[x]]\r\n```\r\nand [[y]]\r\n')).toHaveLength(1);
76
+ });
77
+
78
+ it('a closed fence ends: later prose [[y]] is a link', () => {
79
+ const links = linksOf('# T\n```\n[[x]]\n```\nafter [[y]]\n');
80
+ expect(links).toHaveLength(1);
81
+ expect(links[0]!.to).toContain('y');
82
+ });
83
+
84
+ it('a four-backtick fence holding ``` stays open; ``` inside ~~~ too', () => {
85
+ expect(linksOf('# T\n````\n```\n[[x]]\n```\n````\n')).toHaveLength(0);
86
+ expect(linksOf('# T\n~~~\n```\n[[x]]\n```\n~~~\n')).toHaveLength(0);
87
+ });
88
+
89
+ it('an unclosed fence runs to the end', () => {
90
+ expect(linksOf('# T\n```\n[[x]]\n# not a heading\n[[z]]\n')).toHaveLength(0);
91
+ });
92
+
93
+ it('a ~~~ block holding a # line is one section and leaks no link', () => {
94
+ const text = '# T\n~~~bash\n# check\nif [[ -f x ]]; then\n~~~\n';
95
+ expect(markdownParser.parse(srcOf('a.md', text))).toHaveLength(1);
96
+ expect(linksOf(text)).toHaveLength(0);
97
+ });
98
+
99
+ it('a fence inside a list item and a blockquote fence are fences', () => {
100
+ expect(linksOf('# T\n- item\n\n ```\n [[x]]\n ```\n')).toHaveLength(0);
101
+ expect(linksOf('# T\n> ```\n> [[x]]\n> ```\n')).toHaveLength(0);
102
+ });
103
+
104
+ it('a markdown link inside a fence is not an edge', () => {
105
+ expect(linksOf('# T\n```\n[g](guide.md)\n```\n')).toHaveLength(0);
106
+ expect(linksOf('# T\n[g](guide.md)\n')).toHaveLength(1);
107
+ });
108
+
109
+ it('a loose-list continuation keeps its link', () => {
110
+ expect(linksOf('# T\n- item\n\n continues with [[y]]\n')).toHaveLength(1);
111
+ });
112
+
113
+ it('plain text keeps an indented paragraph link', () => {
114
+ expect(linksOf('# T\n\n see [[y]]\n', plainTextParser, 'a.txt')).toHaveLength(1);
115
+ });
116
+ });
117
+
118
+ describe('markdown section text', () => {
119
+ it('keeps a section first-line indentation; a column-0 section is unchanged', () => {
120
+ const indented = markdownParser.parse(srcOf('a.md', '# T\n\n code\n'));
121
+ expect(indented[0]!.text).toBe(' code');
122
+ const plain = markdownParser.parse(srcOf('a.md', '# T\n\nhello\nworld\n\n'));
123
+ expect(plain[0]!.text).toBe('hello\nworld');
124
+ });
125
+ });
@@ -20,7 +20,7 @@ export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
20
20
  * re-extraction (judged sections with unchanged text are re-anchored, not judged again; see
21
21
  * owedFiles.ts for how an unfinished one is carried to the next review).
22
22
  */
23
- export const EXTRACTOR_VERSION = 1;
23
+ export const EXTRACTOR_VERSION = 2;
24
24
  /** Always ignored: VCS internals, installed dependencies, builderforce config. */
25
25
  const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore'];
26
26
 
@@ -52,6 +52,9 @@ const BINARY_EXT = new Set([
52
52
  'ttf', 'otf', 'woff', 'woff2', 'eot', 'sqlite', 'db', 'vsix', 'lock',
53
53
  ]);
54
54
 
55
+ /** Shell and batch scripts are code, never documents (their `[[ … ]]` tests are not links). */
56
+ const SCRIPT_EXT = new Set(['sh', 'bash', 'zsh', 'ps1', 'bat', 'cmd']);
57
+
55
58
  const extOf = (path: string): string => {
56
59
  const m = /\.([A-Za-z0-9]+)$/.exec(path);
57
60
  return m ? m[1]!.toLowerCase() : '';
@@ -113,7 +116,9 @@ const BUILTIN_TEXT_PARSERS: ReadonlySet<KnowledgeParser> = new Set<KnowledgePars
113
116
  * keeps the builtins as they are.
114
117
  */
115
118
  const guardBuiltin = (p: KnowledgeParser): KnowledgeParser =>
116
- BUILTIN_TEXT_PARSERS.has(p) ? { ...p, accepts: (s) => !isBinaryDocumentType(mediaTypeOf(s)) && p.accepts(s) } : p;
119
+ BUILTIN_TEXT_PARSERS.has(p)
120
+ ? { ...p, accepts: (s) => !SCRIPT_EXT.has(extOf(s.id)) && !isBinaryDocumentType(mediaTypeOf(s)) && p.accepts(s) }
121
+ : p;
117
122
 
118
123
  export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
119
124
  const owner = new Map<KnowledgeParser, KnowledgePack>();