@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.
- package/dist/knowledge/index.d.ts +1 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/merkle.d.ts +20 -5
- package/dist/knowledge/merkle.d.ts.map +1 -1
- package/dist/knowledge/merkle.js +25 -7
- package/dist/knowledge/merkle.js.map +1 -1
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +3 -5
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/working/fold.d.ts +15 -0
- package/dist/working/fold.d.ts.map +1 -1
- package/dist/working/fold.js +17 -6
- package/dist/working/fold.js.map +1 -1
- package/dist/working/index.d.ts +2 -0
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +1 -0
- package/dist/working/index.js.map +1 -1
- package/dist/working/runElision.d.ts +54 -0
- package/dist/working/runElision.d.ts.map +1 -0
- package/dist/working/runElision.js +137 -0
- package/dist/working/runElision.js.map +1 -0
- package/dist/working/transcript.d.ts +8 -2
- package/dist/working/transcript.d.ts.map +1 -1
- package/dist/working/transcript.js +40 -9
- package/dist/working/transcript.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +3 -0
- package/src/contract/regression.assets.test.ts +1 -1
- package/src/contract/regression.contentHash.test.ts +2 -2
- package/src/contract/regression.inRunWindow.test.ts +175 -0
- package/src/contract/regression.listing.test.ts +1 -1
- package/src/contract/regression.merkleCooperative.test.ts +79 -0
- package/src/contract/types.contract.test.ts +20 -5
- package/src/knowledge/index.ts +1 -1
- package/src/knowledge/merkle.test.ts +84 -47
- package/src/knowledge/merkle.ts +38 -8
- package/src/knowledge/plan.ts +3 -4
- package/src/knowledge/review.readAhead.test.ts +4 -1
- package/src/working/fold.ts +19 -7
- package/src/working/index.ts +2 -0
- package/src/working/runElision.ts +149 -0
- package/src/working/transcript.ts +41 -7
|
@@ -0,0 +1,137 @@
|
|
|
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
|
+
import { contentText, defaultEstimateTokens, messageTokens as handoffMessageTokens } from '../handoff/budget.js';
|
|
24
|
+
import { callsOf, nameOf, stringArgOf } from './fold.js';
|
|
25
|
+
/** A result this small costs less to keep than its stub saves — never elided. */
|
|
26
|
+
export const MIN_ELIDED_RESULT_TOKENS = 200;
|
|
27
|
+
/**
|
|
28
|
+
* Tools whose results the model steers by, never elided: the run's plan or ledger, and the answer to a question the
|
|
29
|
+
* run asked (`ask_user` answered in the run is the person's — or Auto's — direction, a directive like the user turn).
|
|
30
|
+
*/
|
|
31
|
+
const PINNED_RESULT_TOOL = /plan|todo|ledger|ask_?user/i;
|
|
32
|
+
/** The arguments a stub names as the call's target, in order of preference. */
|
|
33
|
+
const TARGET_ARGS = ['path', 'file_path', 'file', 'pattern', 'query', 'url', 'command'];
|
|
34
|
+
/** The longest target a stub quotes. */
|
|
35
|
+
const MAX_TARGET_CHARS = 120;
|
|
36
|
+
/** Every stub starts with this — a stub is never elided again. */
|
|
37
|
+
const STUB_PREFIX = '[result elided:';
|
|
38
|
+
/**
|
|
39
|
+
* The one line an elided tool result becomes: the tool, what it was called on, and how big
|
|
40
|
+
* the result was — so the model knows what it no longer sees and that it can fetch it again.
|
|
41
|
+
*/
|
|
42
|
+
export function elidedResultStub(tool, target, chars) {
|
|
43
|
+
const kb = Math.max(1, Math.round(chars / 1024));
|
|
44
|
+
const on = target ? ` ${target.length > MAX_TARGET_CHARS ? `${target.slice(0, MAX_TARGET_CHARS)}…` : target}` : '';
|
|
45
|
+
return `${STUB_PREFIX} ${tool}${on}, ${kb} KB — re-read if needed]`;
|
|
46
|
+
}
|
|
47
|
+
function messageTokens(m) {
|
|
48
|
+
return handoffMessageTokens(m, defaultEstimateTokens);
|
|
49
|
+
}
|
|
50
|
+
/** The call each tool row answers: by `tool_call_id`, else the next unanswered call of the turn before it. */
|
|
51
|
+
function callsAnswered(msgs) {
|
|
52
|
+
const byId = new Map();
|
|
53
|
+
const answered = new Map();
|
|
54
|
+
let unanswered = [];
|
|
55
|
+
msgs.forEach((m, i) => {
|
|
56
|
+
if (m.role === 'assistant') {
|
|
57
|
+
unanswered = callsOf(m).slice();
|
|
58
|
+
for (const call of unanswered)
|
|
59
|
+
if (typeof call.id === 'string' && call.id.length > 0)
|
|
60
|
+
byId.set(call.id, call);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (m.role !== 'tool')
|
|
64
|
+
return;
|
|
65
|
+
const call = (m.tool_call_id ? byId.get(m.tool_call_id) : undefined) ?? unanswered[0];
|
|
66
|
+
if (!call)
|
|
67
|
+
return;
|
|
68
|
+
unanswered = unanswered.filter((c) => c !== call);
|
|
69
|
+
answered.set(i, call);
|
|
70
|
+
});
|
|
71
|
+
return answered;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Where the verbatim tail begins: `runStart` while the run's own messages fit the tail, else
|
|
75
|
+
* the first fixed cut point (the message after which the run's running total crosses a
|
|
76
|
+
* multiple of `chunkTokens`) that leaves at most `tailTokens` after it — never inside the
|
|
77
|
+
* last `minTailMessages`.
|
|
78
|
+
*/
|
|
79
|
+
function runCut(sizes, runStart, budget) {
|
|
80
|
+
let tail = 0;
|
|
81
|
+
for (let i = runStart; i < sizes.length; i++)
|
|
82
|
+
tail += sizes[i];
|
|
83
|
+
let cut = runStart;
|
|
84
|
+
if (tail > budget.tailTokens) {
|
|
85
|
+
let crossed = 0;
|
|
86
|
+
let nextCut = budget.chunkTokens;
|
|
87
|
+
for (let i = runStart; i < sizes.length; i++) {
|
|
88
|
+
crossed += sizes[i];
|
|
89
|
+
tail -= sizes[i];
|
|
90
|
+
if (crossed < nextCut)
|
|
91
|
+
continue;
|
|
92
|
+
while (crossed >= nextCut)
|
|
93
|
+
nextCut += budget.chunkTokens;
|
|
94
|
+
cut = i + 1;
|
|
95
|
+
// The first cut POINT that leaves the tail within budget — the tail may drop under it between two points.
|
|
96
|
+
if (tail <= budget.tailTokens)
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return Math.min(cut, Math.max(runStart, sizes.length - budget.minTailMessages));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Elide the content of the current run's older tool results so `msgs` fits the budget.
|
|
104
|
+
* Returns the input itself (same reference) when it already fits or nothing could be elided;
|
|
105
|
+
* otherwise a new list whose elided rows are shallow copies with only `content` changed.
|
|
106
|
+
*
|
|
107
|
+
* The run is everything after the LAST user turn (all of `msgs` when there is none). Rows
|
|
108
|
+
* before it, the user turn itself, every assistant turn, results under
|
|
109
|
+
* {@link MIN_ELIDED_RESULT_TOKENS}, plan/ledger results and the verbatim tail are kept as sent.
|
|
110
|
+
*/
|
|
111
|
+
export function elideRunResults(msgs, budget) {
|
|
112
|
+
const sizes = msgs.map(messageTokens);
|
|
113
|
+
const total = sizes.reduce((sum, n) => sum + n, 0) + (budget.extraTokens ?? 0);
|
|
114
|
+
if (total <= budget.budgetTokens)
|
|
115
|
+
return msgs;
|
|
116
|
+
const runStart = msgs.map((m) => m.role).lastIndexOf('user') + 1;
|
|
117
|
+
const cut = runCut(sizes, runStart, budget);
|
|
118
|
+
if (cut <= runStart)
|
|
119
|
+
return msgs;
|
|
120
|
+
const answered = callsAnswered(msgs);
|
|
121
|
+
let changed = false;
|
|
122
|
+
const out = msgs.map((m, i) => {
|
|
123
|
+
if (i < runStart || i >= cut || m.role !== 'tool' || sizes[i] < MIN_ELIDED_RESULT_TOKENS)
|
|
124
|
+
return m;
|
|
125
|
+
const text = contentText(m.content);
|
|
126
|
+
if (text.startsWith(STUB_PREFIX))
|
|
127
|
+
return m;
|
|
128
|
+
const call = answered.get(i);
|
|
129
|
+
const tool = (call && nameOf(call)) ?? 'tool';
|
|
130
|
+
if (PINNED_RESULT_TOOL.test(tool))
|
|
131
|
+
return m;
|
|
132
|
+
changed = true;
|
|
133
|
+
return { ...m, content: elidedResultStub(tool, call ? stringArgOf(call, TARGET_ARGS) : null, text.length) };
|
|
134
|
+
});
|
|
135
|
+
return changed ? out : msgs;
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=runElision.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runElision.js","sourceRoot":"","sources":["../../src/working/runElision.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,aAAa,IAAI,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEjH,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAsB,MAAM,WAAW,CAAC;AAgB7E,iFAAiF;AACjF,MA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|
* begin with a user turn (the cascade `[googleai] 400 INVALID_ARGUMENT` after a long
|
|
87
87
|
* tool loop crossed the window boundary). The most recent user turn is never dropped:
|
|
88
|
-
* correctness over the size cap, when a
|
|
89
|
-
*
|
|
88
|
+
* correctness over the size cap, when a single turn is itself oversized.
|
|
89
|
+
*
|
|
90
|
+
* A RUN that outgrows the budget after that user turn is cut inside ({@link elideRunResults}):
|
|
91
|
+
* its older tool results become one-line stubs, keeping the user turn, every assistant turn
|
|
92
|
+
* and a ~{@link COMPACT_TAIL_TOKEN_BUDGET}-token verbatim tail. Without it one long run grew
|
|
93
|
+
* the prompt by every result it produced (chat #128305: 31k → 191k tokens).
|
|
90
94
|
*
|
|
91
95
|
* A consolidation marker that LEADS the transcript (a reloaded chat's seed begins with its saved
|
|
92
96
|
* fold note) is never dropped: it is the note that stands for everything before the rest, and
|
|
@@ -101,6 +105,8 @@ export declare function windowed<M extends TranscriptMessage>(convo: M[]): M[];
|
|
|
101
105
|
* front. Deliberately conservative: it judges against the CURRENT transcript (which has
|
|
102
106
|
* grown since the last working set was built), so it can only ever call a message gone a
|
|
103
107
|
* turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
|
|
108
|
+
* A result the in-run cut elided ({@link elideRunResults}) is gone too: the model sees its
|
|
109
|
+
* stub, not the row.
|
|
104
110
|
*/
|
|
105
111
|
export declare function stillInWorkingContext<M extends TranscriptMessage>(state: WorkingTranscriptState<M>, anchor: unknown): boolean;
|
|
106
112
|
/** The fewest recent messages the verbatim tail keeps, however large they are. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;G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AE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE/F;AAED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAY3G;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAGnG;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,iBAAiB,EAC3D,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,CAAC,EAAE,EACV,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,GACjB,CAAC,EAAE,CAQL;AAaD;4EAC4E;AAC5E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,SAAS,iBAAiB,EAAE,GAAG,MAAM,CAE3E;AAQD;kEACkE;AAClE,MAAM,WAAW,cAAc;IAC7B,eAAe,EAAE,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,SAAS,iBAAiB,EACtE,KAAK,EAAE,sBAAsB,CAAC,CAAC,CAAC,EAChC,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,EAChD,QAAQ,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,GACvC,OAAO,CAAC,CAAC,EAAE,CAAC,CA4Bd"}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { defaultEstimateTokens, messageTokens as handoffMessageTokens, tokensOf as handoffTokensOf } from '../handoff/budget.js';
|
|
15
15
|
import { CONSOLIDATION_MARKER_PREFIX } from './consolidationMarker.js';
|
|
16
|
+
import { elideRunResults } from './runElision.js';
|
|
16
17
|
/** How much history we send to the model (message-count ceiling). */
|
|
17
18
|
export const HISTORY_WINDOW = 80;
|
|
18
19
|
/**
|
|
@@ -111,8 +112,12 @@ function tokenWindowStart(convo) {
|
|
|
111
112
|
* invalid for strict vendors — Gemini rejects a request whose conversation does not
|
|
112
113
|
* begin with a user turn (the cascade `[googleai] 400 INVALID_ARGUMENT` after a long
|
|
113
114
|
* tool loop crossed the window boundary). The most recent user turn is never dropped:
|
|
114
|
-
* correctness over the size cap, when a
|
|
115
|
-
*
|
|
115
|
+
* correctness over the size cap, when a single turn is itself oversized.
|
|
116
|
+
*
|
|
117
|
+
* A RUN that outgrows the budget after that user turn is cut inside ({@link elideRunResults}):
|
|
118
|
+
* its older tool results become one-line stubs, keeping the user turn, every assistant turn
|
|
119
|
+
* and a ~{@link COMPACT_TAIL_TOKEN_BUDGET}-token verbatim tail. Without it one long run grew
|
|
120
|
+
* the prompt by every result it produced (chat #128305: 31k → 191k tokens).
|
|
116
121
|
*
|
|
117
122
|
* A consolidation marker that LEADS the transcript (a reloaded chat's seed begins with its saved
|
|
118
123
|
* fold note) is never dropped: it is the note that stands for everything before the rest, and
|
|
@@ -128,9 +133,18 @@ export function windowed(convo) {
|
|
|
128
133
|
while (convo[start].role !== 'user')
|
|
129
134
|
start += 1;
|
|
130
135
|
const lead = convo[0];
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
136
|
+
const window = start > 0 && isLeadingMarker(lead) ? [lead, ...convo.slice(start)] : convo.slice(start);
|
|
137
|
+
return elideRunResults(window, runElisionBudget());
|
|
138
|
+
}
|
|
139
|
+
/** The in-run cut's budget: the history budget, the compacted tail, the token drop chunk. */
|
|
140
|
+
function runElisionBudget(extraTokens = 0) {
|
|
141
|
+
return {
|
|
142
|
+
budgetTokens: HISTORY_TOKEN_BUDGET,
|
|
143
|
+
tailTokens: COMPACT_TAIL_TOKEN_BUDGET,
|
|
144
|
+
chunkTokens: HISTORY_TOKEN_DROP_CHUNK,
|
|
145
|
+
minTailMessages: COMPACT_TAIL_TURNS,
|
|
146
|
+
extraTokens,
|
|
147
|
+
};
|
|
134
148
|
}
|
|
135
149
|
/** Is this row a saved consolidation note (the visible marker the next seed starts from)? */
|
|
136
150
|
function isLeadingMarker(m) {
|
|
@@ -142,14 +156,20 @@ function isLeadingMarker(m) {
|
|
|
142
156
|
* front. Deliberately conservative: it judges against the CURRENT transcript (which has
|
|
143
157
|
* grown since the last working set was built), so it can only ever call a message gone a
|
|
144
158
|
* turn early — a needless replay costs tokens, a stub for a vanished result costs the run.
|
|
159
|
+
* A result the in-run cut elided ({@link elideRunResults}) is gone too: the model sees its
|
|
160
|
+
* stub, not the row.
|
|
145
161
|
*/
|
|
146
162
|
export function stillInWorkingContext(state, anchor) {
|
|
147
163
|
const convo = state.transcript;
|
|
148
164
|
const idx = convo.indexOf(anchor);
|
|
149
165
|
if (idx < 0)
|
|
150
166
|
return false;
|
|
151
|
-
|
|
152
|
-
|
|
167
|
+
const memo = state.compactMemo;
|
|
168
|
+
if (memo) {
|
|
169
|
+
if (idx < verbatimStart(convo, memo.coveredEnd))
|
|
170
|
+
return false;
|
|
171
|
+
return boundedCompacted('', convo, memo.note, memo.coveredEnd).includes(convo[idx]);
|
|
172
|
+
}
|
|
153
173
|
return windowed(convo).includes(convo[idx]);
|
|
154
174
|
}
|
|
155
175
|
// ---------------------------------------------------------------------------
|
|
@@ -236,6 +256,16 @@ export function assembleCompacted(systemPrompt, convo, note, coveredEnd) {
|
|
|
236
256
|
out.push(...convo.slice(tailStart));
|
|
237
257
|
return out;
|
|
238
258
|
}
|
|
259
|
+
/**
|
|
260
|
+
* {@link assembleCompacted}, kept inside the history budget: when the note's verbatim
|
|
261
|
+
* remainder has outgrown it and no new fold was made (the summary failed or timed out),
|
|
262
|
+
* the current run's older tool results are elided ({@link elideRunResults}) — the note and
|
|
263
|
+
* the system prompt are kept, the note charged to the budget as the window charges it.
|
|
264
|
+
*/
|
|
265
|
+
function boundedCompacted(systemPrompt, convo, note, coveredEnd) {
|
|
266
|
+
const [system, noteRow, ...rest] = assembleCompacted(systemPrompt, convo, note, coveredEnd);
|
|
267
|
+
return [system, noteRow, ...elideRunResults(rest, runElisionBudget(transcriptTokens([noteRow])))];
|
|
268
|
+
}
|
|
239
269
|
/** Estimated tokens of a message list — the ONE count compaction budgets by, exported so
|
|
240
270
|
* a run measures what compaction kept out of a call with the same rule. */
|
|
241
271
|
export function transcriptTokens(msgs) {
|
|
@@ -276,9 +306,10 @@ export async function buildWorkingTranscript(state, systemPrompt, summarize, onF
|
|
|
276
306
|
: convo.slice(from, to);
|
|
277
307
|
const summary = to > from ? await summarize(fold) : null;
|
|
278
308
|
if (summary == null) {
|
|
279
|
-
// Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest
|
|
309
|
+
// Nothing new to fold, or no summarizer: keep the note already held, else drop-oldest —
|
|
310
|
+
// either way cut inside the run once it outgrows the budget (`elideRunResults`).
|
|
280
311
|
return memo
|
|
281
|
-
?
|
|
312
|
+
? boundedCompacted(systemPrompt, convo, memo.note, memo.coveredEnd)
|
|
282
313
|
: [{ role: 'system', content: systemPrompt }, ...windowed(convo)];
|
|
283
314
|
}
|
|
284
315
|
const note = `Compressed memory of the earlier part of this conversation:\n${summary}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,qBAAqB,EAAE,aAAa,IAAI,oBAAoB,EAAE,QAAQ,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEjI,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/working/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,qBAAqB,EAAE,aAAa,IAAI,oBAAoB,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C,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAO,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,IAAI,GAAG,gEAAgE,OAAO,EAAE,CAAC;IACvF,KAAK,CAAC,WAAW,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;IAC7C,QAAQ,CAAC,EAAE,eAAe,EAAE,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,CAAC;IAC/D,OAAO,iBAAiB,CAAC,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;AAC1D,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seanhogg/builderforce-memory",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.83",
|
|
4
4
|
"description": "BuilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, persistent agent memory, and token-saving agent-run memory (code maps, a prompt-cache-safe working memory, chunked transcript windowing) for BuilderForce.ai agents.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -747,6 +747,7 @@
|
|
|
747
747
|
"HISTORY_WINDOW",
|
|
748
748
|
"MAX_RECALLED_MAPS",
|
|
749
749
|
"MIN_CONSOLIDATED_FILES",
|
|
750
|
+
"MIN_ELIDED_RESULT_TOKENS",
|
|
750
751
|
"NARRATION_OVERLAP",
|
|
751
752
|
"PROGRESS_NOTE",
|
|
752
753
|
"TRANSCRIPT_SUMMARY_INPUT_TOKENS",
|
|
@@ -767,6 +768,8 @@
|
|
|
767
768
|
"consolidationMarkerContent",
|
|
768
769
|
"consolidationMarkerOf",
|
|
769
770
|
"consolidationMetadata",
|
|
771
|
+
"elideRunResults",
|
|
772
|
+
"elidedResultStub",
|
|
770
773
|
"foldKeepFromId",
|
|
771
774
|
"foldRepeatedNarration",
|
|
772
775
|
"foldSupersededReads",
|
|
@@ -233,7 +233,7 @@ describe('regression: an oversized claimed document stays an asset', () => {
|
|
|
233
233
|
const again = await reviewDirectory(args(source, store, manifest, { packs: [withPdf] }));
|
|
234
234
|
expect(again.extracted).toBe(1);
|
|
235
235
|
expect((await store.getExtracted(hashText('small pdf text')))![0]!.nodes[0]!.badges?.asset).toBeUndefined();
|
|
236
|
-
});
|
|
236
|
+
}, 30_000); // CPU-bound (a 3 MB text hashed by two plans and two reviews): ~2 s alone, 5–6.5 s beside other suites.
|
|
237
237
|
|
|
238
238
|
it('regression: an oversized claimed pdf still owes no calls after an aborted run and a refreshed (Continue) plan', async () => {
|
|
239
239
|
const source = memSource({ 'big.pdf': 'x'.repeat(3 * 1024 * 1024) });
|
|
@@ -21,10 +21,10 @@ const listing = (files: Record<string, string>, eol: (s: string) => string = (s)
|
|
|
21
21
|
Object.entries(files).map(([path, text]) => ({ path, hash: contentHash(utf8(eol(text))) }));
|
|
22
22
|
|
|
23
23
|
describe('regression: cross-OS content identity', () => {
|
|
24
|
-
it('regression: a Windows autocrlf checkout and a Linux checkout hash differently', () => {
|
|
24
|
+
it('regression: a Windows autocrlf checkout and a Linux checkout hash differently', async () => {
|
|
25
25
|
const linux = listing(COMMIT);
|
|
26
26
|
const windows = listing(COMMIT, autocrlf);
|
|
27
27
|
expect(windows).toEqual(linux);
|
|
28
|
-
expect(merkleTree(windows).root).toBe(merkleTree(linux).root);
|
|
28
|
+
expect((await merkleTree(windows)).root).toBe((await merkleTree(linux)).root);
|
|
29
29
|
});
|
|
30
30
|
});
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.inRunWindow.test.ts — the drop-oldest window never cut INSIDE a run.
|
|
3
|
+
*
|
|
4
|
+
* VS Code chat #128305 (VSIX 2026.10.204): one long run's prompt grew from 31k tokens at step 0 by ~4–5k a turn to 191k,
|
|
5
|
+
* with no reduction. The fold's summary kept timing out, so every turn fell back to `windowed`, which clamps its cut at
|
|
6
|
+
* the last user turn — and inside one run that turn is the prompt, so nothing after it was ever dropped and the 64k
|
|
7
|
+
* history budget never applied. The window now elides the run's older tool results (`elideRunResults`): the user turn,
|
|
8
|
+
* every assistant turn and a ~40k verbatim tail stay; a call and its result are never split.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
buildWorkingTranscript,
|
|
13
|
+
COMPACT_TAIL_TOKEN_BUDGET,
|
|
14
|
+
elidedResultStub,
|
|
15
|
+
elideRunResults,
|
|
16
|
+
HISTORY_TOKEN_BUDGET,
|
|
17
|
+
MIN_ELIDED_RESULT_TOKENS,
|
|
18
|
+
stillInWorkingContext,
|
|
19
|
+
transcriptTokens,
|
|
20
|
+
windowed,
|
|
21
|
+
type TranscriptMessage,
|
|
22
|
+
type WorkingTranscriptState,
|
|
23
|
+
} from '../working/index.js';
|
|
24
|
+
|
|
25
|
+
/** ~4.5k tokens: one file window of a coding run. */
|
|
26
|
+
const RESULT = (i: number) => `// file ${i}\n${'x'.repeat(18_000)}`;
|
|
27
|
+
|
|
28
|
+
/** One acting turn: an assistant tool call and the result that answers it. */
|
|
29
|
+
function step(i: number, tool = 'read_file', content = RESULT(i)): TranscriptMessage[] {
|
|
30
|
+
const id = `call_${i}`;
|
|
31
|
+
return [
|
|
32
|
+
{
|
|
33
|
+
role: 'assistant',
|
|
34
|
+
content: `Reading the next file (${i}).`,
|
|
35
|
+
tool_calls: [{ id, type: 'function', function: { name: tool, arguments: JSON.stringify({ path: `src/f${i}.ts` }) } }],
|
|
36
|
+
},
|
|
37
|
+
{ role: 'tool', tool_call_id: id, content },
|
|
38
|
+
];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A single run: the person's request, then `turns` tool steps and nothing else. */
|
|
42
|
+
function run(turns: number): TranscriptMessage[] {
|
|
43
|
+
const out: TranscriptMessage[] = [{ role: 'user', content: 'Review the Visualizer and fix what is broken.' }];
|
|
44
|
+
for (let i = 0; i < turns; i++) out.push(...step(i));
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Every assistant tool call is answered by the row right after it, and every tool row answers the call before it. */
|
|
49
|
+
function pairingIntact(msgs: readonly TranscriptMessage[]): boolean {
|
|
50
|
+
return msgs.every((m, i) => {
|
|
51
|
+
if (m.role !== 'tool') return true;
|
|
52
|
+
const prev = msgs[i - 1] as TranscriptMessage & { tool_calls?: Array<{ id: string }> };
|
|
53
|
+
return prev?.role === 'assistant' && (prev.tool_calls ?? []).some((c) => c.id === m.tool_call_id);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
describe('regression: chat #128305 — the fallback window cuts inside one long run', () => {
|
|
58
|
+
it('regression: a 40-turn run stays inside the history budget, keeps every row, the request and a verbatim tail', () => {
|
|
59
|
+
const convo = run(40);
|
|
60
|
+
expect(transcriptTokens(convo)).toBeGreaterThan(2.5 * HISTORY_TOKEN_BUDGET); // ~182k: what every turn used to send
|
|
61
|
+
const w = windowed(convo);
|
|
62
|
+
expect(transcriptTokens(w)).toBeLessThan(48_000); // ~44k: the ~40k tail, the request, every call and its stub
|
|
63
|
+
expect(transcriptTokens(w)).toBeLessThanOrEqual(HISTORY_TOKEN_BUDGET);
|
|
64
|
+
expect(w).toHaveLength(convo.length); // nothing dropped: rows are elided in place
|
|
65
|
+
expect(w[0]).toBe(convo[0]); // the request, verbatim
|
|
66
|
+
expect(pairingIntact(w)).toBe(true);
|
|
67
|
+
// Every assistant turn is the transcript's own row.
|
|
68
|
+
w.forEach((m, i) => { if (m.role === 'assistant') expect(m).toBe(convo[i]); });
|
|
69
|
+
// The most recent results are verbatim, and together within the tail budget.
|
|
70
|
+
const firstVerbatim = w.findIndex((m, i) => m.role === 'tool' && m === convo[i]);
|
|
71
|
+
expect(firstVerbatim).toBeGreaterThan(1);
|
|
72
|
+
expect(w.slice(firstVerbatim).every((m, i) => m === convo[firstVerbatim + i])).toBe(true);
|
|
73
|
+
expect(transcriptTokens(w.slice(firstVerbatim))).toBeLessThanOrEqual(COMPACT_TAIL_TOKEN_BUDGET);
|
|
74
|
+
// An older result is one line naming the tool, its target and its size.
|
|
75
|
+
expect(w[2]!.content).toBe(elidedResultStub('read_file', 'src/f0.ts', String(convo[2]!.content).length));
|
|
76
|
+
expect(w[2]!.content).toBe('[result elided: read_file src/f0.ts, 18 KB — re-read if needed]');
|
|
77
|
+
expect(w[2]!.tool_call_id).toBe('call_0');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('regression: with the summary failing every turn, buildWorkingTranscript stays bounded across the whole run', async () => {
|
|
81
|
+
const state: WorkingTranscriptState = { transcript: [], compactMemo: null };
|
|
82
|
+
let peak = 0;
|
|
83
|
+
for (let turn = 1; turn <= 40; turn++) {
|
|
84
|
+
state.transcript = run(turn);
|
|
85
|
+
const out = await buildWorkingTranscript(state, 'sys', async () => null, () => undefined);
|
|
86
|
+
expect(pairingIntact(out.slice(1))).toBe(true);
|
|
87
|
+
const sent = transcriptTokens(out.slice(1));
|
|
88
|
+
// Once over the budget, the cut leaves the ~40k tail plus the calls and their stubs — on EVERY turn, not only some.
|
|
89
|
+
if (transcriptTokens(state.transcript) > HISTORY_TOKEN_BUDGET) expect(sent).toBeLessThan(48_000);
|
|
90
|
+
peak = Math.max(peak, sent);
|
|
91
|
+
}
|
|
92
|
+
expect(peak).toBeLessThanOrEqual(HISTORY_TOKEN_BUDGET);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('regression: a memo held from an earlier fold does not let the verbatim remainder grow without bound when the next summary fails', async () => {
|
|
96
|
+
const convo = run(40);
|
|
97
|
+
const state: WorkingTranscriptState = { transcript: convo, compactMemo: { note: 'Compressed memory: the first steps.', coveredEnd: 3 } };
|
|
98
|
+
const out = await buildWorkingTranscript(state, 'sys', async () => null, () => undefined);
|
|
99
|
+
expect(out[0]).toEqual({ role: 'system', content: 'sys' });
|
|
100
|
+
expect(out[1]!.content).toBe('Compressed memory: the first steps.');
|
|
101
|
+
expect(transcriptTokens(out.slice(1))).toBeLessThanOrEqual(HISTORY_TOKEN_BUDGET);
|
|
102
|
+
expect(pairingIntact(out.slice(1).filter((m) => m.role !== 'user'))).toBe(true);
|
|
103
|
+
expect(state.compactMemo!.coveredEnd).toBe(3); // a failed summary keeps the note it had
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('regression: an elided result is out of the working context (the read cache replays it), a tail result is in', () => {
|
|
107
|
+
const convo = run(40);
|
|
108
|
+
const state: WorkingTranscriptState = { transcript: convo, compactMemo: null };
|
|
109
|
+
expect(stillInWorkingContext(state, convo[2])).toBe(false);
|
|
110
|
+
expect(stillInWorkingContext(state, convo[convo.length - 1])).toBe(true);
|
|
111
|
+
const memoState: WorkingTranscriptState = { transcript: convo, compactMemo: { note: 'n', coveredEnd: 3 } };
|
|
112
|
+
expect(stillInWorkingContext(memoState, convo[4])).toBe(false);
|
|
113
|
+
expect(stillInWorkingContext(memoState, convo[convo.length - 1])).toBe(true);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('regression: the elided prefix moves in chunks, not on every turn (prefix-cache stability)', () => {
|
|
117
|
+
let changes = 0;
|
|
118
|
+
let previous = -1;
|
|
119
|
+
for (let turn = 15; turn <= 40; turn++) {
|
|
120
|
+
const w = windowed(run(turn));
|
|
121
|
+
const cut = w.filter((m) => m.role === 'tool' && String(m.content).startsWith('[result elided:')).length;
|
|
122
|
+
if (cut !== previous) changes += 1;
|
|
123
|
+
previous = cut;
|
|
124
|
+
}
|
|
125
|
+
// 26 turns of ~4.5k tokens each, a 16k chunk: the cut moves about once every 3–4 turns.
|
|
126
|
+
expect(changes).toBeLessThan(13);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('keeps plan/ledger results, small results, and everything before the run', () => {
|
|
130
|
+
const big = 'y'.repeat(18_000);
|
|
131
|
+
const convo: TranscriptMessage[] = [
|
|
132
|
+
{ role: 'user', content: 'earlier request' },
|
|
133
|
+
{ role: 'assistant', content: 'earlier answer' },
|
|
134
|
+
{ role: 'user', content: 'the request' },
|
|
135
|
+
...step(0, 'update_plan', big),
|
|
136
|
+
...step(1, 'read_file', 'tiny'),
|
|
137
|
+
];
|
|
138
|
+
for (let i = 2; i < 30; i++) convo.push(...step(i));
|
|
139
|
+
const w = elideRunResults(convo, { budgetTokens: HISTORY_TOKEN_BUDGET, tailTokens: COMPACT_TAIL_TOKEN_BUDGET, chunkTokens: 16_000, minTailMessages: 8 });
|
|
140
|
+
expect(w.slice(0, 3)).toEqual(convo.slice(0, 3));
|
|
141
|
+
expect(w[4]).toBe(convo[4]); // the plan result
|
|
142
|
+
expect(w[6]).toBe(convo[6]); // under MIN_ELIDED_RESULT_TOKENS
|
|
143
|
+
expect(MIN_ELIDED_RESULT_TOKENS).toBeGreaterThan(0);
|
|
144
|
+
expect(String(w[8]!.content)).toMatch(/^\[result elided: read_file src\/f2\.ts, \d+ KB — re-read if needed\]$/);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('regression: an answered ask_user result (the run\'s direction) is never elided, however old or large', () => {
|
|
148
|
+
const answer = `Use the second approach. ${'z'.repeat(4_000)}`; // a detailed answer, well over MIN_ELIDED_RESULT_TOKENS
|
|
149
|
+
const convo: TranscriptMessage[] = [{ role: 'user', content: 'the request' }, ...step(0, 'ask_user', answer)];
|
|
150
|
+
for (let i = 1; i < 30; i++) convo.push(...step(i));
|
|
151
|
+
const w = windowed(convo);
|
|
152
|
+
expect(w[2]).toBe(convo[2]); // the answer, verbatim
|
|
153
|
+
expect(String(w[4]!.content).startsWith('[result elided: read_file')).toBe(true); // an older read beside it IS cut
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('returns the input itself when it fits, and is idempotent once elided', () => {
|
|
157
|
+
const short = run(3);
|
|
158
|
+
expect(windowed(short)).toEqual(short);
|
|
159
|
+
const budget = { budgetTokens: HISTORY_TOKEN_BUDGET, tailTokens: COMPACT_TAIL_TOKEN_BUDGET, chunkTokens: 16_000, minTailMessages: 8 };
|
|
160
|
+
expect(elideRunResults(short, budget)).toBe(short);
|
|
161
|
+
const once = elideRunResults(run(40), budget);
|
|
162
|
+
expect(elideRunResults(once, budget)).toBe(once);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('names a positional result (no tool_call_id) by the call before it, and stubs without a target when none is named', () => {
|
|
166
|
+
const convo: TranscriptMessage[] = [{ role: 'user', content: 'go' }];
|
|
167
|
+
for (let i = 0; i < 30; i++) {
|
|
168
|
+
convo.push({ role: 'assistant', content: '', tool_calls: [{ id: '', type: 'function', function: { name: 'search_code', arguments: '{}' } }] });
|
|
169
|
+
convo.push({ role: 'tool', content: RESULT(i) });
|
|
170
|
+
}
|
|
171
|
+
const w = windowed(convo);
|
|
172
|
+
expect(w[2]!.content).toBe(elidedResultStub('search_code', null, String(convo[2]!.content).length));
|
|
173
|
+
expect(String(w[2]!.content)).toBe('[result elided: search_code, 18 KB — re-read if needed]');
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -22,7 +22,7 @@ describe('regression: a host listing cannot break the plan', () => {
|
|
|
22
22
|
expect(detail.files.map((f) => f.path)).toEqual([NFC, 'ok.md']);
|
|
23
23
|
expect(detail.files[0]!.listedPath).toBe(NFD); // the first by (normalized, listed) bytewise
|
|
24
24
|
expect(detail.plan.skipped).toContainEqual({ path: NFC, reason: 'duplicate-path' });
|
|
25
|
-
expect(detail.plan.merkleRoot).toBe(merkleTree(detail.files).root);
|
|
25
|
+
expect(detail.plan.merkleRoot).toBe((await merkleTree(detail.files)).root);
|
|
26
26
|
});
|
|
27
27
|
|
|
28
28
|
it('regression: a `.`/`..` path or a path listed twice is skipped with a reason, never thrown', async () => {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.merkleCooperative.test.ts — merkleTree, canonicalListing and changedPaths became async and
|
|
3
|
+
* cooperative (they yield to the event loop on a work budget). A yield must never change a result: a run that pauses at
|
|
4
|
+
* every check equals a run that never pauses. The root of a small fixed listing is pinned as a literal, so any future
|
|
5
|
+
* change to hashing or ordering fails loudly here.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { CooperativeBudget } from '../knowledge/cooperative.js';
|
|
9
|
+
import { canonicalListing, changedPaths, merkleTree } from '../knowledge/merkle.js';
|
|
10
|
+
|
|
11
|
+
/** Always due: the loops pause at every check. */
|
|
12
|
+
const forced = (): CooperativeBudget & { pauses: number } => {
|
|
13
|
+
const b = { pauses: 0, due: () => true, pause: async () => { b.pauses++; await Promise.resolve(); } };
|
|
14
|
+
return b;
|
|
15
|
+
};
|
|
16
|
+
/** Never due: the loops run straight through. */
|
|
17
|
+
const unforced = (): CooperativeBudget => ({ due: () => false, pause: async () => { throw new Error('unforced budget paused'); } });
|
|
18
|
+
|
|
19
|
+
const hex = (n: number) => n.toString(16).padStart(64, '0');
|
|
20
|
+
|
|
21
|
+
/** ~8k paths across nested directories, listed out of order, with re-spelled, invalid and duplicate entries mixed in. */
|
|
22
|
+
const LARGE: Array<{ path: string; hash: string }> = (() => {
|
|
23
|
+
const out: Array<{ path: string; hash: string }> = [];
|
|
24
|
+
for (let i = 0; i < 8000; i++) out.push({ path: `d${i % 13}/s${i % 7}/t${i % 5}/f${i}.ts`, hash: hex(i) });
|
|
25
|
+
out.reverse();
|
|
26
|
+
out.push({ path: './d0/dup.ts', hash: hex(1) }, { path: 'd0/dup.ts', hash: hex(2) }, { path: '../up.ts', hash: hex(3) }, { path: 'd1/./x.ts', hash: hex(4) });
|
|
27
|
+
return out;
|
|
28
|
+
})();
|
|
29
|
+
|
|
30
|
+
/** LARGE with some files changed, one removed and one added. */
|
|
31
|
+
const LARGE_AFTER = LARGE.filter((f) => f.path !== 'd3/s3/t3/f3.ts')
|
|
32
|
+
.map((f) => (f.path.endsWith('7.ts') ? { ...f, hash: hex(1_000_000 + Number.parseInt(f.hash, 16)) } : f))
|
|
33
|
+
.concat({ path: 'new/added.ts', hash: hex(42) });
|
|
34
|
+
|
|
35
|
+
describe('regression: cooperative merkle yields never change a result', () => {
|
|
36
|
+
it('regression: a budget that is always due pauses, and canonicalListing / merkleTree / changedPaths equal the unforced run', async () => {
|
|
37
|
+
const budget = forced();
|
|
38
|
+
|
|
39
|
+
const listForced = await canonicalListing(LARGE, { budget });
|
|
40
|
+
const listPlain = await canonicalListing(LARGE, { budget: unforced() });
|
|
41
|
+
expect(listForced).toEqual(listPlain);
|
|
42
|
+
expect(listPlain.skipped.length).toBeGreaterThan(0);
|
|
43
|
+
|
|
44
|
+
const afterForced = await canonicalListing(LARGE_AFTER, { budget });
|
|
45
|
+
const afterPlain = await canonicalListing(LARGE_AFTER, { budget: unforced() });
|
|
46
|
+
expect(afterForced).toEqual(afterPlain);
|
|
47
|
+
|
|
48
|
+
const beforeTreeForced = await merkleTree(listForced.kept, { budget });
|
|
49
|
+
const beforeTreePlain = await merkleTree(listPlain.kept, { budget: unforced() });
|
|
50
|
+
const afterTreeForced = await merkleTree(afterForced.kept, { budget });
|
|
51
|
+
const afterTreePlain = await merkleTree(afterPlain.kept, { budget: unforced() });
|
|
52
|
+
expect(beforeTreeForced.root).toBe(beforeTreePlain.root);
|
|
53
|
+
expect(afterTreeForced.root).toBe(afterTreePlain.root);
|
|
54
|
+
expect(beforeTreeForced.dirs).toEqual(beforeTreePlain.dirs);
|
|
55
|
+
expect(beforeTreeForced.entries).toEqual(beforeTreePlain.entries);
|
|
56
|
+
|
|
57
|
+
const changedForced = await changedPaths(beforeTreeForced, afterTreeForced, { budget });
|
|
58
|
+
const changedPlain = await changedPaths(beforeTreePlain, afterTreePlain, { budget: unforced() });
|
|
59
|
+
expect(changedForced).toEqual(changedPlain);
|
|
60
|
+
expect(changedPlain).toContain('d3/s3/t3/f3.ts');
|
|
61
|
+
expect(changedPlain).toContain('new/added.ts');
|
|
62
|
+
expect(changedPlain).toContain('d7/s0/t2/f7.ts');
|
|
63
|
+
|
|
64
|
+
expect(budget.pauses).toBeGreaterThan(0);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('regression: the root of a small fixed listing is pinned (hashing and ordering are frozen)', async () => {
|
|
68
|
+
const FILES = [
|
|
69
|
+
{ path: 'README.md', hash: hex(1) },
|
|
70
|
+
{ path: 'src/index.ts', hash: hex(2) },
|
|
71
|
+
{ path: 'src/lib/util.ts', hash: hex(3) },
|
|
72
|
+
{ path: 'src/lib/zeta.ts', hash: hex(4) },
|
|
73
|
+
{ path: 'docs/guide.md', hash: hex(5) },
|
|
74
|
+
];
|
|
75
|
+
const root = '0e62f74f5b92a6d4723875995eba326617d27e27b7a55db60a84d1051ab1deb4';
|
|
76
|
+
expect((await merkleTree(FILES)).root).toBe(root);
|
|
77
|
+
expect((await merkleTree([...FILES].reverse(), { budget: forced() })).root).toBe(root);
|
|
78
|
+
});
|
|
79
|
+
});
|