@seanhogg/builderforce-memory 2026.10.81 → 2026.10.83

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 (42) hide show
  1. package/dist/knowledge/index.d.ts +1 -1
  2. package/dist/knowledge/index.d.ts.map +1 -1
  3. package/dist/knowledge/merkle.d.ts +20 -5
  4. package/dist/knowledge/merkle.d.ts.map +1 -1
  5. package/dist/knowledge/merkle.js +25 -7
  6. package/dist/knowledge/merkle.js.map +1 -1
  7. package/dist/knowledge/plan.d.ts.map +1 -1
  8. package/dist/knowledge/plan.js +3 -5
  9. package/dist/knowledge/plan.js.map +1 -1
  10. package/dist/working/fold.d.ts +15 -0
  11. package/dist/working/fold.d.ts.map +1 -1
  12. package/dist/working/fold.js +17 -6
  13. package/dist/working/fold.js.map +1 -1
  14. package/dist/working/index.d.ts +2 -0
  15. package/dist/working/index.d.ts.map +1 -1
  16. package/dist/working/index.js +1 -0
  17. package/dist/working/index.js.map +1 -1
  18. package/dist/working/runElision.d.ts +54 -0
  19. package/dist/working/runElision.d.ts.map +1 -0
  20. package/dist/working/runElision.js +137 -0
  21. package/dist/working/runElision.js.map +1 -0
  22. package/dist/working/transcript.d.ts +8 -2
  23. package/dist/working/transcript.d.ts.map +1 -1
  24. package/dist/working/transcript.js +40 -9
  25. package/dist/working/transcript.js.map +1 -1
  26. package/package.json +1 -1
  27. package/src/contract/exports.snapshot.json +3 -0
  28. package/src/contract/regression.assets.test.ts +1 -1
  29. package/src/contract/regression.contentHash.test.ts +2 -2
  30. package/src/contract/regression.inRunWindow.test.ts +175 -0
  31. package/src/contract/regression.listing.test.ts +1 -1
  32. package/src/contract/regression.merkleCooperative.test.ts +79 -0
  33. package/src/contract/types.contract.test.ts +20 -5
  34. package/src/knowledge/index.ts +1 -1
  35. package/src/knowledge/merkle.test.ts +84 -47
  36. package/src/knowledge/merkle.ts +38 -8
  37. package/src/knowledge/plan.ts +3 -4
  38. package/src/knowledge/review.readAhead.test.ts +4 -1
  39. package/src/working/fold.ts +19 -7
  40. package/src/working/index.ts +2 -0
  41. package/src/working/runElision.ts +149 -0
  42. package/src/working/transcript.ts +41 -7
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import type { ParsedSection, SourceDocument } from '../ingest/types.js';
15
- import type { changedPaths, contentHash, CONTENT_HASH_RULE, merkleTree, MerkleEntry, MerkleTree, PlanDetail, ReviewPlan } from '../knowledge/index.js';
15
+ import type { changedPaths, contentHash, CONTENT_HASH_RULE, merkleTree, MerkleEntry, MerkleOptions, MerkleTree, PlanDetail, ReviewPlan } from '../knowledge/index.js';
16
16
  import type { BASELINE_CONTENT_HASH_RULE, canonicalListing, contentHashRuleOf, ListingSkipReason } from '../knowledge/index.js';
17
17
  import type {
18
18
  DirectorySource, Extracted, ExtractJob, ExtractJobResult, GraphApp, GraphOutline, GraphReadSkip, GraphSystem, KEdge, KNode, KnowledgeGraph, KnowledgeStore,
@@ -49,6 +49,7 @@ import type {
49
49
  effectiveGuards, factStoreDump, loadFactGraph, memoryFactStore, rootRouters, saveFactGraph, sweepFactStore,
50
50
  } from '../knowledge/index.js';
51
51
  import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
52
+ import type { elidedResultStub, elideRunResults, RunElisionBudget, TranscriptMessage, windowed } from '../working/index.js';
52
53
 
53
54
  type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
54
55
  type Expect<T extends true> = T;
@@ -158,8 +159,8 @@ export type MerkleEntry_shape = Expect<Equal<MerkleEntry, { name: string; kind:
158
159
  export type MerkleTree_shape = Expect<Equal<MerkleTree, {
159
160
  root: string; dirs: ReadonlyMap<string, string>; entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
160
161
  }>>;
161
- export type merkleTree_signature = Expect<Equal<typeof merkleTree, (files: ReadonlyArray<{ path: string; hash: string }>) => MerkleTree>>;
162
- export type changedPaths_signature = Expect<Equal<typeof changedPaths, (before: MerkleTree, after: MerkleTree) => string[]>>;
162
+ export type merkleTree_signature = Expect<Equal<typeof merkleTree, (files: ReadonlyArray<{ path: string; hash: string }>, opts?: MerkleOptions) => Promise<MerkleTree>>>;
163
+ export type changedPaths_signature = Expect<Equal<typeof changedPaths, (before: MerkleTree, after: MerkleTree, opts?: MerkleOptions) => Promise<string[]>>>;
163
164
  export type ReviewPlan_merkleRoot = Expect<Equal<ReviewPlan['merkleRoot'], string | undefined>>;
164
165
  export type PlanDetail_merkle = Expect<Equal<PlanDetail['merkle'], MerkleTree | undefined>>;
165
166
  export type BASELINE_CONTENT_HASH_RULE_type = Expect<Equal<typeof BASELINE_CONTENT_HASH_RULE, 'eol-lf@1'>>;
@@ -170,9 +171,13 @@ export type ReviewPlan_skipped_reason = Expect<Equal<
170
171
  >>;
171
172
  export type PlannedFile_listedPath = Expect<Equal<PlannedFile['listedPath'], string | undefined>>;
172
173
  export type canonicalListing_skipped = Expect<Equal<
173
- ReturnType<typeof canonicalListing<{ path: string }>>['skipped'], Array<{ path: string; reason: ListingSkipReason }>
174
+ Awaited<ReturnType<typeof canonicalListing<{ path: string }>>>['skipped'], Array<{ path: string; reason: ListingSkipReason }>
174
175
  >>;
175
- export type ListingSkipReason_values = Expect<Equal<ListingSkipReason, 'invalid-path' | 'duplicate-path'>>;
176
+ export type canonicalListing_signature = Expect<Equal<typeof canonicalListing, <T extends { path: string }>(entries: readonly T[], opts?: MerkleOptions) => Promise<{
177
+ kept: Array<T & { listedPath?: string }>;
178
+ skipped: Array<{ path: string; reason: ListingSkipReason }>;
179
+ }>>>;
180
+ export type ListingSkipReason_values =Expect<Equal<ListingSkipReason, 'invalid-path' | 'duplicate-path'>>;
176
181
 
177
182
  /* ── DirectorySource: optional per-path hooks ──────────────────────────────────────────────────────────────── */
178
183
  // hashOf takes the path (a host whose read() transforms bytes returns the listing hash for it); a one-argument hashOf still satisfies it.
@@ -475,6 +480,16 @@ export type ResolvedMount_shape = Expect<Equal<ResolvedMount, {
475
480
  }>>;
476
481
  export type EffectiveEntryPoint_extra_keys = Expect<Equal<Exclude<keyof EffectiveEntryPoint, keyof EntryPointFact>, 'file' | 'via' | 'guardsInferred'>>;
477
482
 
483
+ /* ── working transcript: the in-run cut (chat #128305) ──────────────────────────────────────────────────────── */
484
+ // `windowed` keeps its signature (brain-embedded's fallback window and read-cache check call it); the cut is inside it.
485
+ export type windowed_signature = Expect<Equal<typeof windowed, <M extends TranscriptMessage>(convo: M[]) => M[]>>;
486
+ export type elideRunResults_signature = Expect<Equal<
487
+ typeof elideRunResults, <M extends TranscriptMessage>(msgs: readonly M[], budget: RunElisionBudget) => M[]
488
+ >>;
489
+ export type RunElisionBudget_keys = Expect<Equal<keyof RunElisionBudget, 'budgetTokens' | 'tailTokens' | 'chunkTokens' | 'minTailMessages' | 'extraTokens'>>;
490
+ export type RunElisionBudget_extraTokens_is_optional = Expect<Equal<IsOptional<RunElisionBudget, 'extraTokens'>, true>>;
491
+ export type elidedResultStub_signature = Expect<Equal<typeof elidedResultStub, (tool: string, target: string | null, chars: number) => string>>;
492
+
478
493
  describe('type contract', () => {
479
494
  it('is enforced by `npm run check:contract-types` (tsc over tsconfig.contract.json), not at run time', () => {
480
495
  // The values above only exist so the `satisfies` / `@ts-expect-error` lines are real code; this proves the file loads.
@@ -108,7 +108,7 @@ export type { PlanOptions, PlannedFile, PlanDetail } from './plan.js';
108
108
  export type { ExtractorState } from './owedFiles.js';
109
109
  export { contentHash, CONTENT_HASH_RULE, BASELINE_CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
110
110
  export { merkleTree, changedPaths, canonicalListing } from './merkle.js';
111
- export type { MerkleTree, MerkleEntry, MerkleKind, ListingSkipReason } from './merkle.js';
111
+ export type { MerkleTree, MerkleEntry, MerkleKind, ListingSkipReason, MerkleOptions } from './merkle.js';
112
112
  // PRD 41 §B2 steps 1–2: the stat prefilter (size + mtimeNs + fileId, BigInt) with git's racy-file rule.
113
113
  export {
114
114
  RACY_WINDOW_MS, statManifestKey, statMatches, isRacy, prefilterStats, createStatPrefilter, loadStatManifest, saveStatManifest,
@@ -18,28 +18,28 @@ const FILES = [
18
18
  const edited = (files: typeof FILES, path: string, hash: string) => files.map((f) => (f.path === path ? { path, hash } : f));
19
19
 
20
20
  describe('merkleTree', () => {
21
- it('gives the same root and dirs for any input order', () => {
22
- const a = merkleTree(FILES);
23
- const b = merkleTree([...FILES].reverse());
21
+ it('gives the same root and dirs for any input order', async () => {
22
+ const a = await merkleTree(FILES);
23
+ const b = await merkleTree([...FILES].reverse());
24
24
  expect(b.root).toBe(a.root);
25
25
  expect([...b.dirs]).toEqual([...a.dirs]);
26
26
  expect(a.dirs.get('')).toBe(a.root);
27
27
  expect([...a.dirs.keys()].sort()).toEqual(['', 'docs', 'docs/guide', 'docs/guide/deep', 'src', 'src/lib']);
28
28
  });
29
29
 
30
- it('normalizes paths: backslashes, a leading ./, NFC', () => {
31
- const a = merkleTree([{ path: 'src/café.ts', hash: 'h' }]);
32
- expect(merkleTree([{ path: '.\\src\\café.ts', hash: 'h' }]).root).toBe(a.root);
30
+ it('normalizes paths: backslashes, a leading ./, NFC', async () => {
31
+ const a = await merkleTree([{ path: 'src/café.ts', hash: 'h' }]);
32
+ expect((await merkleTree([{ path: '.\\src\\café.ts', hash: 'h' }])).root).toBe(a.root);
33
33
  });
34
34
 
35
- it('sorts entries bytewise (code-point order), not by UTF-16 unit', () => {
36
- const tree = merkleTree([{ path: '\u{1F600}.md', hash: 'h1' }, { path: '~.md', hash: 'h2' }, { path: 'Z.md', hash: 'h3' }]);
35
+ it('sorts entries bytewise (code-point order), not by UTF-16 unit', async () => {
36
+ const tree = await merkleTree([{ path: '\u{1F600}.md', hash: 'h1' }, { path: '~.md', hash: 'h2' }, { path: 'Z.md', hash: 'h3' }]);
37
37
  expect(tree.entries.get('')!.map((e) => e.name)).toEqual(['Z.md', '~.md', '\u{1F600}.md']);
38
38
  });
39
39
 
40
- it('a file change changes only its ancestors', () => {
41
- const before = merkleTree(FILES);
42
- const after = merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2'));
40
+ it('a file change changes only its ancestors', async () => {
41
+ const before = await merkleTree(FILES);
42
+ const after = await merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2'));
43
43
  expect(after.root).not.toBe(before.root);
44
44
  for (const dir of before.dirs.keys()) {
45
45
  const ancestor = dir === '' || dir === 'src' || dir === 'src/lib';
@@ -47,42 +47,45 @@ describe('merkleTree', () => {
47
47
  }
48
48
  });
49
49
 
50
- it('a file and a directory of one name differ in kind, so they never hash alike', () => {
51
- expect(merkleTree([{ path: 'x', hash: 'h' }]).root).not.toBe(merkleTree([{ path: 'x/y', hash: 'h' }]).root);
50
+ it('a file and a directory of one name differ in kind, so they never hash alike', async () => {
51
+ expect((await merkleTree([{ path: 'x', hash: 'h' }])).root).not.toBe((await merkleTree([{ path: 'x/y', hash: 'h' }])).root);
52
52
  });
53
53
 
54
- it('refuses a path listed twice at different hashes, or as both a file and a directory', () => {
55
- expect(() => merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '2' }])).toThrow(/listed twice/);
56
- expect(() => merkleTree([{ path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }])).toThrow(/file and a directory/);
57
- expect(() => merkleTree([{ path: 'a/b', hash: '2' }, { path: 'a', hash: '1' }])).toThrow(/file and a directory/);
58
- expect(() => merkleTree([{ path: 'a//b', hash: '1' }])).toThrow(/not a file path/);
59
- expect(() => merkleTree([{ path: 'a/./b', hash: '1' }])).toThrow(/not a file path/);
60
- expect(() => merkleTree([{ path: 'a/../b', hash: '1' }])).toThrow(/not a file path/);
61
- expect(() => merkleTree([{ path: '..', hash: '1' }])).toThrow(/not a file path/);
62
- expect(merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '1' }]).root).toBe(merkleTree([{ path: 'a', hash: '1' }]).root);
54
+ it('refuses a path listed twice at different hashes, or as both a file and a directory', async () => {
55
+ await expect(merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '2' }])).rejects.toThrow(/listed twice/);
56
+ await expect(merkleTree([{ path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }])).rejects.toThrow(/file and a directory/);
57
+ await expect(merkleTree([{ path: 'a/b', hash: '2' }, { path: 'a', hash: '1' }])).rejects.toThrow(/file and a directory/);
58
+ await expect(merkleTree([{ path: 'a//b', hash: '1' }])).rejects.toThrow(/not a file path/);
59
+ await expect(merkleTree([{ path: 'a/./b', hash: '1' }])).rejects.toThrow(/not a file path/);
60
+ await expect(merkleTree([{ path: 'a/../b', hash: '1' }])).rejects.toThrow(/not a file path/);
61
+ await expect(merkleTree([{ path: '..', hash: '1' }])).rejects.toThrow(/not a file path/);
62
+ expect((await merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '1' }])).root).toBe((await merkleTree([{ path: 'a', hash: '1' }])).root);
63
63
  });
64
64
 
65
- it('an empty listing has a root', () => {
66
- expect(merkleTree([]).root).toMatch(/^[0-9a-f]{64}$/);
65
+ it('an empty listing has a root', async () => {
66
+ expect((await merkleTree([])).root).toMatch(/^[0-9a-f]{64}$/);
67
67
  });
68
68
  });
69
69
 
70
70
  describe('canonicalListing', () => {
71
- const NFC = 'café.md', NFD = 'café.md';
71
+ // Written with escapes so the two spellings are guaranteed: NFC 'é' (U+00E9) vs NFD 'e' + combining acute (U+0065 U+0301).
72
+ const NFC = 'caf\u00e9.md', NFD = 'cafe\u0301.md';
72
73
 
73
- it('keeps the first of a colliding pair by (normalized, listed) bytewise, in any input order, and never makes merkleTree throw', () => {
74
+ it('keeps the first of a colliding pair by (normalized, listed) bytewise, in any input order, and never makes merkleTree throw', async () => {
74
75
  const pair = [{ path: NFC, hash: 'h1' }, { path: NFD, hash: 'h2' }];
75
76
  for (const input of [pair, [...pair].reverse()]) {
76
- const { kept, skipped } = canonicalListing(input);
77
- // NFD's 'e' (U+0065) sorts before NFC's 'é' (U+00E9): the NFD spelling is kept, under its NFC path.
77
+ const { kept, skipped } = await canonicalListing(input);
78
+ // Both normalize to the same NFC path; the tie-break is the listed spelling, bytewise —
79
+ // NFD's 'e' (U+0065) before NFC's 'é' (U+00E9) — so the NFD spelling is kept, stored under
80
+ // its NFC path with `listedPath` carrying the source spelling. The NFC spelling is skipped.
78
81
  expect(kept).toEqual([{ path: NFC, hash: 'h2', listedPath: NFD }]);
79
82
  expect(skipped).toEqual([{ path: NFC, reason: 'duplicate-path' }]);
80
- expect(() => merkleTree(kept)).not.toThrow();
83
+ await expect(merkleTree(kept)).resolves.toBeDefined();
81
84
  }
82
85
  });
83
86
 
84
- it('skips invalid paths, a path listed twice, and a path below a kept file', () => {
85
- const { kept, skipped } = canonicalListing([
87
+ it('skips invalid paths, a path listed twice, and a path below a kept file', async () => {
88
+ const { kept, skipped } = await canonicalListing([
86
89
  { path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }, { path: 'x.md', hash: '3' }, { path: './x.md', hash: '4' },
87
90
  { path: '../up.md', hash: '5' }, { path: 'p/./q', hash: '6' }, { path: 'p//q', hash: '7' }, { path: '', hash: '8' }, { path: 'src\\k.ts', hash: '9' },
88
91
  ]);
@@ -102,36 +105,70 @@ function spied(tree: MerkleTree) {
102
105
  }
103
106
 
104
107
  describe('changedPaths', () => {
105
- it('returns exactly the changed, added and removed files', () => {
108
+ it('returns exactly the changed, added and removed files', async () => {
106
109
  const next = [
107
110
  ...edited(FILES, 'src/lib/b.ts', 'h-b2').filter((f) => f.path !== 'docs/guide/deep/more.md'),
108
111
  { path: 'src/lib/new.ts', hash: 'h-new' },
109
112
  ];
110
- expect(changedPaths(merkleTree(FILES), merkleTree(next))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
111
- expect(changedPaths(merkleTree(next), merkleTree(FILES))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
113
+ expect(await changedPaths(await merkleTree(FILES), await merkleTree(next))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
114
+ expect(await changedPaths(await merkleTree(next), await merkleTree(FILES))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
112
115
  });
113
116
 
114
- it('is empty for equal trees and opens no directory', () => {
115
- const after = spied(merkleTree(FILES));
116
- expect(changedPaths(merkleTree(FILES), after.tree)).toEqual([]);
117
+ it('is empty for equal trees and opens no directory', async () => {
118
+ const after = spied(await merkleTree(FILES));
119
+ expect(await changedPaths(await merkleTree(FILES), after.tree)).toEqual([]);
117
120
  expect(after.opened().size).toBe(0);
118
121
  });
119
122
 
120
- it('never descends into a subtree whose hash is equal', () => {
121
- const before = spied(merkleTree(FILES));
122
- const after = spied(merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2')));
123
- expect(changedPaths(before.tree, after.tree)).toEqual(['src/lib/b.ts']);
123
+ it('never descends into a subtree whose hash is equal', async () => {
124
+ const before = spied(await merkleTree(FILES));
125
+ const after = spied(await merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2')));
126
+ expect(await changedPaths(before.tree, after.tree)).toEqual(['src/lib/b.ts']);
124
127
  expect([...after.opened()].sort()).toEqual(['', 'src', 'src/lib']);
125
128
  expect([...before.opened()].sort()).toEqual(['', 'src', 'src/lib']);
126
129
  });
127
130
 
128
- it('a file replaced by a directory reports both sides', () => {
129
- const before = merkleTree([{ path: 'x', hash: 'h' }, { path: 'keep.md', hash: 'k' }]);
130
- const after = merkleTree([{ path: 'x/y', hash: 'h' }, { path: 'x/z/w', hash: 'h2' }, { path: 'keep.md', hash: 'k' }]);
131
- expect(changedPaths(before, after)).toEqual(['x', 'x/y', 'x/z/w']);
131
+ it('a file replaced by a directory reports both sides', async () => {
132
+ const before = await merkleTree([{ path: 'x', hash: 'h' }, { path: 'keep.md', hash: 'k' }]);
133
+ const after = await merkleTree([{ path: 'x/y', hash: 'h' }, { path: 'x/z/w', hash: 'h2' }, { path: 'keep.md', hash: 'k' }]);
134
+ expect(await changedPaths(before, after)).toEqual(['x', 'x/y', 'x/z/w']);
132
135
  });
133
136
 
134
- it('from an empty tree, every file is added', () => {
135
- expect(changedPaths(merkleTree([]), merkleTree(FILES))).toEqual(FILES.map((f) => f.path).sort());
137
+ it('from an empty tree, every file is added', async () => {
138
+ expect(await changedPaths(await merkleTree([]), await merkleTree(FILES))).toEqual(FILES.map((f) => f.path).sort());
139
+ });
140
+ });
141
+
142
+ describe('cooperative yields', () => {
143
+ /** A budget that is always due and counts its pauses, so a test sees the yields without real timers. */
144
+ const countingBudget = () => {
145
+ let pauses = 0;
146
+ return { budget: { due: () => true, pause: async () => { pauses += 1; } }, pauses: () => pauses };
147
+ };
148
+
149
+ it('merkleTree yields on an injected budget while hashing a large listing', async () => {
150
+ const { budget, pauses } = countingBudget();
151
+ const files = Array.from({ length: 500 }, (_, i) => ({ path: `f${String(i).padStart(4, '0')}.ts`, hash: `h${i}` }));
152
+ const tree = await merkleTree(files, { budget });
153
+ expect(pauses()).toBeGreaterThan(0);
154
+ expect(tree.root).toMatch(/^[0-9a-f]{64}$/);
155
+ // The yields did not change the result.
156
+ expect(tree.root).toBe((await merkleTree(files)).root);
157
+ });
158
+
159
+ it('canonicalListing yields on an injected budget', async () => {
160
+ const { budget, pauses } = countingBudget();
161
+ const entries = Array.from({ length: 200 }, (_, i) => ({ path: `f${i}.ts` }));
162
+ const { kept } = await canonicalListing(entries, { budget });
163
+ expect(pauses()).toBeGreaterThan(0);
164
+ expect(kept).toHaveLength(200);
165
+ });
166
+
167
+ it('changedPaths yields on an injected budget', async () => {
168
+ const { budget, pauses } = countingBudget();
169
+ const before = await merkleTree(FILES);
170
+ const after = await merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2'));
171
+ expect(await changedPaths(before, after, { budget })).toEqual(['src/lib/b.ts']);
172
+ expect(pauses()).toBeGreaterThan(0);
136
173
  });
137
174
  });
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
14
+ import { cooperativeBudget, type CooperativeBudget } from './cooperative.js';
14
15
  import { canonicalJson, isRootFilePath, normalizePath } from './refs.js';
15
16
 
16
17
  export type MerkleKind = 'file' | 'dir';
@@ -31,6 +32,17 @@ export interface MerkleTree {
31
32
  entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
32
33
  }
33
34
 
35
+ /**
36
+ * Options for the cooperative Merkle helpers. A host that plans on its UI thread over tens of
37
+ * thousands of files passes its own {@link CooperativeBudget} (the plan shares its walk's budget,
38
+ * so the yields are one budget across the whole plan); the default yields to the event loop
39
+ * every ~12 ms ({@link cooperativeBudget}).
40
+ */
41
+ export interface MerkleOptions {
42
+ /** The work budget the long loops hand back to the event loop on. Default {@link cooperativeBudget}. */
43
+ budget?: CooperativeBudget;
44
+ }
45
+
34
46
  /** Bytewise UTF-8 order (code-point order), which UTF-16 `<` is not for astral characters. */
35
47
  export function compareBytewise(a: string, b: string): number {
36
48
  const n = Math.min(a.length, b.length);
@@ -61,13 +73,18 @@ export type ListingSkipReason = 'invalid-path' | 'duplicate-path';
61
73
  * bytewise, is kept and the rest are skipped as `duplicate-path`; so is a path below a kept FILE (`a` and `a/b`).
62
74
  * Skipped entries carry the listed spelling. `kept` is sorted bytewise by normalized path.
63
75
  */
64
- export function canonicalListing<T extends { path: string }>(entries: readonly T[]): {
76
+ export async function canonicalListing<T extends { path: string }>(
77
+ entries: readonly T[],
78
+ opts: MerkleOptions = {},
79
+ ): Promise<{
65
80
  kept: Array<T & { listedPath?: string }>;
66
81
  skipped: Array<{ path: string; reason: ListingSkipReason }>;
67
- } {
82
+ }> {
83
+ const budget = opts.budget ?? cooperativeBudget();
68
84
  const skipped: Array<{ path: string; reason: ListingSkipReason }> = [];
69
85
  const candidates: Array<{ entry: T; path: string }> = [];
70
86
  for (const entry of entries) {
87
+ if (budget.due()) await budget.pause();
71
88
  const path = normalizePath(entry.path);
72
89
  if (isRootFilePath(path)) candidates.push({ entry, path });
73
90
  else skipped.push({ path: entry.path, reason: 'invalid-path' });
@@ -76,6 +93,7 @@ export function canonicalListing<T extends { path: string }>(entries: readonly T
76
93
  const files = new Set<string>();
77
94
  const kept: Array<T & { listedPath?: string }> = [];
78
95
  for (const { entry, path } of candidates) {
96
+ if (budget.due()) await budget.pause();
79
97
  let clash = files.has(path);
80
98
  for (let dir = dirOf(path); !clash && dir !== ''; dir = dirOf(dir)) clash = files.has(dir);
81
99
  if (clash) { skipped.push({ path: entry.path, reason: 'duplicate-path' }); continue; }
@@ -89,8 +107,15 @@ export function canonicalListing<T extends { path: string }>(entries: readonly T
89
107
  * The Merkle tree of a file listing. Throws on an invalid path, a path listed twice with different hashes, or a path
90
108
  * that is both a file and a directory — each would make the root depend on input order. {@link canonicalListing}
91
109
  * first makes a host listing safe.
110
+ *
111
+ * Async and cooperative: over a large listing the loop yields to the event loop every ~12 ms (or on the
112
+ * caller's {@link MerkleOptions.budget}), so a UI-thread host stays responsive. Callers `await` the tree.
92
113
  */
93
- export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>): MerkleTree {
114
+ export async function merkleTree(
115
+ files: ReadonlyArray<{ path: string; hash: string }>,
116
+ opts: MerkleOptions = {},
117
+ ): Promise<MerkleTree> {
118
+ const budget = opts.budget ?? cooperativeBudget();
94
119
  const children = new Map<string, Map<string, { kind: MerkleKind; hash?: string }>>([['', new Map()]]);
95
120
  const childrenOf = (dir: string) => {
96
121
  let c = children.get(dir);
@@ -98,6 +123,7 @@ export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>)
98
123
  return c;
99
124
  };
100
125
  for (const f of files) {
126
+ if (budget.due()) await budget.pause();
101
127
  const path = normalizePath(f.path);
102
128
  if (!isRootFilePath(path)) throw new Error(`merkleTree: not a file path: ${JSON.stringify(f.path)}`);
103
129
  const own = childrenOf(dirOf(path)).get(nameOf(path));
@@ -117,6 +143,7 @@ export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>)
117
143
  // Deepest first, so every child directory is hashed before its parent.
118
144
  const order = [...children.keys()].sort((a, b) => depth(b) - depth(a) || compareBytewise(a, b));
119
145
  for (const dir of order) {
146
+ if (budget.due()) await budget.pause();
120
147
  const list = [...children.get(dir)!].map(([name, c]): MerkleEntry => ({
121
148
  name, kind: c.kind, hash: c.kind === 'file' ? c.hash! : dirs.get(joinPath(dir, name))!,
122
149
  })).sort((a, b) => compareBytewise(a.name, b.name));
@@ -139,18 +166,21 @@ function filesUnder(tree: MerkleTree, dir: string, out: string[]): void {
139
166
 
140
167
  /**
141
168
  * 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.
169
+ * and never descends into a directory whose hash is equal on both sides. Async and cooperative:
170
+ * the walk yields to the event loop on the caller's budget (default every ~12 ms).
143
171
  */
144
- export function changedPaths(before: MerkleTree, after: MerkleTree): string[] {
172
+ export async function changedPaths(before: MerkleTree, after: MerkleTree, opts: MerkleOptions = {}): Promise<string[]> {
173
+ const budget = opts.budget ?? cooperativeBudget();
145
174
  const out: string[] = [];
146
- const walk = (dir: string): void => {
175
+ const walk = async (dir: string): Promise<void> => {
147
176
  if (before.dirs.get(dir) === after.dirs.get(dir)) return;
177
+ if (budget.due()) await budget.pause();
148
178
  const was = new Map((before.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
149
179
  const is = new Map((after.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
150
180
  for (const name of new Set([...was.keys(), ...is.keys()])) {
151
181
  const a = was.get(name), b = is.get(name);
152
182
  const path = joinPath(dir, name);
153
- if (a?.kind === 'dir' && b?.kind === 'dir') { if (a.hash !== b.hash) walk(path); continue; }
183
+ if (a?.kind === 'dir' && b?.kind === 'dir') { if (a.hash !== b.hash) await walk(path); continue; }
154
184
  if (a && b && a.kind === 'file' && b.kind === 'file') { if (a.hash !== b.hash) out.push(path); continue; }
155
185
  // Added, removed, or a file replaced by a directory (or back): every file on either side.
156
186
  for (const [side, e] of [[before, a], [after, b]] as const) {
@@ -159,6 +189,6 @@ export function changedPaths(before: MerkleTree, after: MerkleTree): string[] {
159
189
  }
160
190
  }
161
191
  };
162
- walk('');
192
+ await walk('');
163
193
  return [...new Set(out)].sort(compareBytewise);
164
194
  }
@@ -134,9 +134,8 @@ export async function planDetail(
134
134
  if (budget.due()) await budget.pause();
135
135
  }
136
136
  // The ONE normalization (POSIX, NFC) — so plan paths are Merkle paths — and a listing that cannot break the plan: invalid and
137
- // colliding paths are skipped with a reason (merkle.ts canonicalListing), never thrown.
138
- const listing = canonicalListing(listed);
139
- if (budget.due()) await budget.pause();
137
+ // colliding paths are skipped with a reason (merkle.ts canonicalListing), never thrown. One budget across the whole plan.
138
+ const listing = await canonicalListing(listed, { budget });
140
139
  const entries = sortBy(listing.kept, (e) => e.path);
141
140
  const listedOf = new Map(entries.filter((e) => e.listedPath !== undefined).map((e) => [e.path, e.listedPath!] as const));
142
141
 
@@ -211,7 +210,7 @@ export async function planDetail(
211
210
  const compareCalls = compares ? Math.ceil((compareSections + awaiting) / SECTIONS_PER_COMPARE) : 0;
212
211
  const sortedByPack = Object.fromEntries(Object.keys(byPack).sort(compareStr).map((k) => [k, byPack[k]!]));
213
212
  if (budget.due()) await budget.pause();
214
- const merkle = merkleTree(files);
213
+ const merkle = await merkleTree(files, { budget });
215
214
  const planShapeVersion = 2; // 2 (2026-11-14, PRD 41 B2): the plan gained the stat-manifest identity; bump on any PlanDetail/manifest-shape change
216
215
  return {
217
216
  plan: {
@@ -87,7 +87,10 @@ describe('read-ahead with a pool that reads', () => {
87
87
  const run = reviewDirectory(args(source, new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
88
88
  judgement: fakeJudge(), mechanical: true, extractPool: pool, deferRead: true, concurrency: 8, signal: ctl.signal,
89
89
  }));
90
- await jest.advanceTimersByTimeAsync(50);
90
+ // The cooperative plan (async merkleTree/canonicalListing, 2026-11-14) yields to the event loop over several real
91
+ // macrotasks before the pool opens; each advanceTimersByTimeAsync drains one round, and the count varies with the
92
+ // runner's load. Poll-advance until the pool has opened (bounded, so a real stall still fails the test).
93
+ for (let i = 0; started() === 0 && i < 20; i++) await jest.advanceTimersByTimeAsync(50);
91
94
  expect(started()).toBe(8);
92
95
  ctl.abort();
93
96
  // No timer is advanced past the 10 s extract deadline: the stop alone settles every in-flight and queued job.
@@ -33,7 +33,8 @@ export function supersededReadMarker(path: string, step: number): string {
33
33
  /** B7's replacement for a tool-call turn's narration that merely repeats the previous one. */
34
34
  export const PROGRESS_NOTE = '(progress note)';
35
35
 
36
- interface NamedToolCall {
36
+ /** An OpenAI-style tool call, read defensively (a host's shape is not trusted). Shared with `runElision.ts`. */
37
+ export interface NamedToolCall {
37
38
  id?: unknown;
38
39
  function?: { name?: unknown; arguments?: unknown };
39
40
  }
@@ -43,17 +44,20 @@ interface ToolResult {
43
44
  error?: unknown;
44
45
  }
45
46
 
46
- function callsOf(m: TranscriptMessage): NamedToolCall[] {
47
+ export function callsOf(m: TranscriptMessage): NamedToolCall[] {
47
48
  return Array.isArray(m.tool_calls) ? (m.tool_calls as NamedToolCall[]) : [];
48
49
  }
49
50
 
50
- function nameOf(call: NamedToolCall): string | null {
51
+ export function nameOf(call: NamedToolCall): string | null {
51
52
  const name = call.function?.name;
52
53
  return typeof name === 'string' && name.length > 0 ? name : null;
53
54
  }
54
55
 
55
- /** The `path` argument of a tool call — from the object form or parsed out of a JSON string. */
56
- function pathOf(call: NamedToolCall): string | null {
56
+ /**
57
+ * The first non-empty string argument of a tool call among `keys`, in that order — from the object form or parsed out of
58
+ * a JSON string. Null when none is present or the arguments are not JSON (a malformed call names no target).
59
+ */
60
+ export function stringArgOf(call: NamedToolCall, keys: readonly string[]): string | null {
57
61
  const raw = call.function?.arguments;
58
62
  let parsed: unknown = raw;
59
63
  if (typeof raw === 'string') {
@@ -64,8 +68,16 @@ function pathOf(call: NamedToolCall): string | null {
64
68
  }
65
69
  }
66
70
  if (!parsed || typeof parsed !== 'object') return null;
67
- const path = (parsed as { path?: unknown }).path;
68
- return typeof path === 'string' && path.length > 0 ? path : null;
71
+ for (const key of keys) {
72
+ const value = (parsed as Record<string, unknown>)[key];
73
+ if (typeof value === 'string' && value.length > 0) return value;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /** The `path` argument of a tool call. */
79
+ function pathOf(call: NamedToolCall): string | null {
80
+ return stringArgOf(call, ['path']);
69
81
  }
70
82
 
71
83
  /** The tool result answering `call`: by `tool_call_id` when present, else positionally. */
@@ -54,6 +54,8 @@ export {
54
54
  buildWorkingTranscript,
55
55
  } from './transcript.js';
56
56
  export type { TranscriptMessage, CompactMemo, WorkingTranscriptState, TranscriptFold } from './transcript.js';
57
+ export { MIN_ELIDED_RESULT_TOKENS, elideRunResults, elidedResultStub } from './runElision.js';
58
+ export type { RunElisionBudget } from './runElision.js';
57
59
  export {
58
60
  NARRATION_OVERLAP,
59
61
  PROGRESS_NOTE,
@@ -0,0 +1,149 @@
1
+ /**
2
+ * In-run elision — how the drop-oldest window keeps ONE long run inside the history budget.
3
+ *
4
+ * The window ({@link windowed}) drops whole turns from the front, but never past the most
5
+ * recent user turn: a request must open on a user turn, and that turn is the run's task. So
6
+ * inside a single long run nothing after the prompt was ever dropped, and with the summary
7
+ * unavailable (timed out, failed) the prompt grew by every tool result the run produced —
8
+ * VS Code chat #128305 went from 31k to 191k tokens over one run, the 64k budget never
9
+ * applying.
10
+ *
11
+ * This is the cut INSIDE the run. Everything stays — the user turn, every assistant turn (its
12
+ * narration, a plan, the tool calls it made), and every tool result's ROW — but a tool result
13
+ * older than the recent tail has its CONTENT replaced by one line naming the tool, its target
14
+ * and its size ({@link elidedResultStub}). A call and its result are never split (the row
15
+ * stays, only its content shrinks), so strict vendors accept the request; and the model is
16
+ * told what it no longer sees and how to get it back.
17
+ *
18
+ * The cut moves in fixed chunks counted from the run's own start, so the elided prefix — what
19
+ * a provider prefix cache hashes — changes once per chunk of new work, not on every turn.
20
+ *
21
+ * Pure: no `node:*`, no I/O.
22
+ */
23
+
24
+ import { contentText, defaultEstimateTokens, messageTokens as handoffMessageTokens } from '../handoff/budget.js';
25
+ import type { HandoffMessage } from '../handoff/types.js';
26
+ import { callsOf, nameOf, stringArgOf, type NamedToolCall } from './fold.js';
27
+
28
+ /** The budget an in-run cut works to — the transcript module supplies its own constants. */
29
+ export interface RunElisionBudget {
30
+ /** The history budget: below it (counting `extraTokens`) nothing is elided. */
31
+ budgetTokens: number;
32
+ /** How much of the run's most recent work stays verbatim once it is over. */
33
+ tailTokens: number;
34
+ /** The step the cut moves in, counted from the run's start (prefix-cache hysteresis). */
35
+ chunkTokens: number;
36
+ /** The fewest most-recent messages kept verbatim, however large. */
37
+ minTailMessages: number;
38
+ /** Tokens the caller sends in front of these messages (a memo note) — charged to the budget. */
39
+ extraTokens?: number;
40
+ }
41
+
42
+ /** A result this small costs less to keep than its stub saves — never elided. */
43
+ export const MIN_ELIDED_RESULT_TOKENS = 200;
44
+
45
+ /**
46
+ * Tools whose results the model steers by, never elided: the run's plan or ledger, and the answer to a question the
47
+ * run asked (`ask_user` answered in the run is the person's — or Auto's — direction, a directive like the user turn).
48
+ */
49
+ const PINNED_RESULT_TOOL = /plan|todo|ledger|ask_?user/i;
50
+
51
+ /** The arguments a stub names as the call's target, in order of preference. */
52
+ const TARGET_ARGS = ['path', 'file_path', 'file', 'pattern', 'query', 'url', 'command'] as const;
53
+
54
+ /** The longest target a stub quotes. */
55
+ const MAX_TARGET_CHARS = 120;
56
+
57
+ /** Every stub starts with this — a stub is never elided again. */
58
+ const STUB_PREFIX = '[result elided:';
59
+
60
+ /**
61
+ * The one line an elided tool result becomes: the tool, what it was called on, and how big
62
+ * the result was — so the model knows what it no longer sees and that it can fetch it again.
63
+ */
64
+ export function elidedResultStub(tool: string, target: string | null, chars: number): string {
65
+ const kb = Math.max(1, Math.round(chars / 1024));
66
+ const on = target ? ` ${target.length > MAX_TARGET_CHARS ? `${target.slice(0, MAX_TARGET_CHARS)}…` : target}` : '';
67
+ return `${STUB_PREFIX} ${tool}${on}, ${kb} KB — re-read if needed]`;
68
+ }
69
+
70
+ function messageTokens(m: HandoffMessage): number {
71
+ return handoffMessageTokens(m, defaultEstimateTokens);
72
+ }
73
+
74
+ /** The call each tool row answers: by `tool_call_id`, else the next unanswered call of the turn before it. */
75
+ function callsAnswered(msgs: readonly HandoffMessage[]): Map<number, NamedToolCall> {
76
+ const byId = new Map<string, NamedToolCall>();
77
+ const answered = new Map<number, NamedToolCall>();
78
+ let unanswered: NamedToolCall[] = [];
79
+ msgs.forEach((m, i) => {
80
+ if (m.role === 'assistant') {
81
+ unanswered = callsOf(m).slice();
82
+ for (const call of unanswered) if (typeof call.id === 'string' && call.id.length > 0) byId.set(call.id, call);
83
+ return;
84
+ }
85
+ if (m.role !== 'tool') return;
86
+ const call = (m.tool_call_id ? byId.get(m.tool_call_id) : undefined) ?? unanswered[0];
87
+ if (!call) return;
88
+ unanswered = unanswered.filter((c) => c !== call);
89
+ answered.set(i, call);
90
+ });
91
+ return answered;
92
+ }
93
+
94
+ /**
95
+ * Where the verbatim tail begins: `runStart` while the run's own messages fit the tail, else
96
+ * the first fixed cut point (the message after which the run's running total crosses a
97
+ * multiple of `chunkTokens`) that leaves at most `tailTokens` after it — never inside the
98
+ * last `minTailMessages`.
99
+ */
100
+ function runCut(sizes: readonly number[], runStart: number, budget: RunElisionBudget): number {
101
+ let tail = 0;
102
+ for (let i = runStart; i < sizes.length; i++) tail += sizes[i]!;
103
+ let cut = runStart;
104
+ if (tail > budget.tailTokens) {
105
+ let crossed = 0;
106
+ let nextCut = budget.chunkTokens;
107
+ for (let i = runStart; i < sizes.length; i++) {
108
+ crossed += sizes[i]!;
109
+ tail -= sizes[i]!;
110
+ if (crossed < nextCut) continue;
111
+ while (crossed >= nextCut) nextCut += budget.chunkTokens;
112
+ cut = i + 1;
113
+ // The first cut POINT that leaves the tail within budget — the tail may drop under it between two points.
114
+ if (tail <= budget.tailTokens) break;
115
+ }
116
+ }
117
+ return Math.min(cut, Math.max(runStart, sizes.length - budget.minTailMessages));
118
+ }
119
+
120
+ /**
121
+ * Elide the content of the current run's older tool results so `msgs` fits the budget.
122
+ * Returns the input itself (same reference) when it already fits or nothing could be elided;
123
+ * otherwise a new list whose elided rows are shallow copies with only `content` changed.
124
+ *
125
+ * The run is everything after the LAST user turn (all of `msgs` when there is none). Rows
126
+ * before it, the user turn itself, every assistant turn, results under
127
+ * {@link MIN_ELIDED_RESULT_TOKENS}, plan/ledger results and the verbatim tail are kept as sent.
128
+ */
129
+ export function elideRunResults<M extends HandoffMessage>(msgs: readonly M[], budget: RunElisionBudget): M[] {
130
+ const sizes = msgs.map(messageTokens);
131
+ const total = sizes.reduce((sum, n) => sum + n, 0) + (budget.extraTokens ?? 0);
132
+ if (total <= budget.budgetTokens) return msgs as M[];
133
+ const runStart = msgs.map((m) => m.role).lastIndexOf('user') + 1;
134
+ const cut = runCut(sizes, runStart, budget);
135
+ if (cut <= runStart) return msgs as M[];
136
+ const answered = callsAnswered(msgs);
137
+ let changed = false;
138
+ const out = msgs.map((m, i) => {
139
+ if (i < runStart || i >= cut || m.role !== 'tool' || sizes[i]! < MIN_ELIDED_RESULT_TOKENS) return m;
140
+ const text = contentText(m.content);
141
+ if (text.startsWith(STUB_PREFIX)) return m;
142
+ const call = answered.get(i);
143
+ const tool = (call && nameOf(call)) ?? 'tool';
144
+ if (PINNED_RESULT_TOOL.test(tool)) return m;
145
+ changed = true;
146
+ return { ...m, content: elidedResultStub(tool, call ? stringArgOf(call, TARGET_ARGS) : null, text.length) } as M;
147
+ });
148
+ return changed ? out : (msgs as M[]);
149
+ }