@animalabs/context-manager 0.5.2 → 0.5.4
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/src/adaptive/index.d.ts +6 -0
- package/dist/src/adaptive/index.d.ts.map +1 -1
- package/dist/src/adaptive/index.js +8 -0
- package/dist/src/adaptive/index.js.map +1 -1
- package/dist/src/adaptive/kv-cache-sim.d.ts +128 -0
- package/dist/src/adaptive/kv-cache-sim.d.ts.map +1 -0
- package/dist/src/adaptive/kv-cache-sim.js +0 -0
- package/dist/src/adaptive/kv-cache-sim.js.map +1 -0
- package/dist/src/adaptive/kv-control.d.ts +152 -0
- package/dist/src/adaptive/kv-control.d.ts.map +1 -0
- package/dist/src/adaptive/kv-control.js +368 -0
- package/dist/src/adaptive/kv-control.js.map +1 -0
- package/dist/src/adaptive/kv-replay.d.ts +76 -0
- package/dist/src/adaptive/kv-replay.d.ts.map +1 -0
- package/dist/src/adaptive/kv-replay.js +175 -0
- package/dist/src/adaptive/kv-replay.js.map +1 -0
- package/dist/src/adaptive/render-offsets.d.ts +61 -0
- package/dist/src/adaptive/render-offsets.d.ts.map +1 -0
- package/dist/src/adaptive/render-offsets.js +88 -0
- package/dist/src/adaptive/render-offsets.js.map +1 -0
- package/dist/src/adaptive/strategies/kv-stable.d.ts +48 -0
- package/dist/src/adaptive/strategies/kv-stable.d.ts.map +1 -0
- package/dist/src/adaptive/strategies/kv-stable.js +102 -0
- package/dist/src/adaptive/strategies/kv-stable.js.map +1 -0
- package/dist/src/adaptive/summary-tree.d.ts +98 -0
- package/dist/src/adaptive/summary-tree.d.ts.map +1 -0
- package/dist/src/adaptive/summary-tree.js +214 -0
- package/dist/src/adaptive/summary-tree.js.map +1 -0
- package/dist/src/context-log.d.ts.map +1 -1
- package/dist/src/context-log.js +7 -2
- package/dist/src/context-log.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/message-store.js +1 -1
- package/dist/src/message-store.js.map +1 -1
- package/dist/src/normalize-tool-messages.d.ts +33 -0
- package/dist/src/normalize-tool-messages.d.ts.map +1 -1
- package/dist/src/normalize-tool-messages.js +59 -0
- package/dist/src/normalize-tool-messages.js.map +1 -1
- package/dist/src/strategies/autobiographical.d.ts +101 -39
- package/dist/src/strategies/autobiographical.d.ts.map +1 -1
- package/dist/src/strategies/autobiographical.js +398 -222
- package/dist/src/strategies/autobiographical.js.map +1 -1
- package/dist/src/types/strategy.d.ts +40 -1
- package/dist/src/types/strategy.d.ts.map +1 -1
- package/dist/src/types/strategy.js +2 -0
- package/dist/src/types/strategy.js.map +1 -1
- package/dist/test/adaptive/kv-cache-sim.test.d.ts +16 -0
- package/dist/test/adaptive/kv-cache-sim.test.d.ts.map +1 -0
- package/dist/test/adaptive/kv-cache-sim.test.js +173 -0
- package/dist/test/adaptive/kv-cache-sim.test.js.map +1 -0
- package/dist/test/adaptive/kv-control.test.d.ts +14 -0
- package/dist/test/adaptive/kv-control.test.d.ts.map +1 -0
- package/dist/test/adaptive/kv-control.test.js +130 -0
- package/dist/test/adaptive/kv-control.test.js.map +1 -0
- package/dist/test/adaptive/kv-replay.test.d.ts +15 -0
- package/dist/test/adaptive/kv-replay.test.d.ts.map +1 -0
- package/dist/test/adaptive/kv-replay.test.js +112 -0
- package/dist/test/adaptive/kv-replay.test.js.map +1 -0
- package/dist/test/adaptive/kv-stable-strategy.test.d.ts +10 -0
- package/dist/test/adaptive/kv-stable-strategy.test.d.ts.map +1 -0
- package/dist/test/adaptive/kv-stable-strategy.test.js +89 -0
- package/dist/test/adaptive/kv-stable-strategy.test.js.map +1 -0
- package/dist/test/adaptive/render-offsets.test.d.ts +11 -0
- package/dist/test/adaptive/render-offsets.test.d.ts.map +1 -0
- package/dist/test/adaptive/render-offsets.test.js +85 -0
- package/dist/test/adaptive/render-offsets.test.js.map +1 -0
- package/dist/test/adaptive/summary-tree.test.d.ts +5 -0
- package/dist/test/adaptive/summary-tree.test.d.ts.map +1 -0
- package/dist/test/adaptive/summary-tree.test.js +72 -0
- package/dist/test/adaptive/summary-tree.test.js.map +1 -0
- package/dist/test/chunker-tool-boundary.test.d.ts +12 -0
- package/dist/test/chunker-tool-boundary.test.d.ts.map +1 -0
- package/dist/test/chunker-tool-boundary.test.js +89 -0
- package/dist/test/chunker-tool-boundary.test.js.map +1 -0
- package/dist/test/compression-shape-invariants.test.d.ts +22 -0
- package/dist/test/compression-shape-invariants.test.d.ts.map +1 -0
- package/dist/test/compression-shape-invariants.test.js +312 -0
- package/dist/test/compression-shape-invariants.test.js.map +1 -0
- package/dist/test/image-strip-render-stats.test.d.ts +2 -0
- package/dist/test/image-strip-render-stats.test.d.ts.map +1 -0
- package/dist/test/image-strip-render-stats.test.js +130 -0
- package/dist/test/image-strip-render-stats.test.js.map +1 -0
- package/dist/test/image-stripping.test.d.ts +13 -0
- package/dist/test/image-stripping.test.d.ts.map +1 -0
- package/dist/test/image-stripping.test.js +104 -0
- package/dist/test/image-stripping.test.js.map +1 -0
- package/dist/test/normalize-tool-messages.test.js +61 -1
- package/dist/test/normalize-tool-messages.test.js.map +1 -1
- package/dist/test/render-stats.test.d.ts +2 -0
- package/dist/test/render-stats.test.d.ts.map +1 -0
- package/dist/test/render-stats.test.js +91 -0
- package/dist/test/render-stats.test.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/src/adaptive/index.ts +48 -0
- package/src/adaptive/kv-cache-sim.ts +0 -0
- package/src/adaptive/kv-control.ts +497 -0
- package/src/adaptive/kv-replay.ts +238 -0
- package/src/adaptive/render-offsets.ts +116 -0
- package/src/adaptive/strategies/kv-stable.ts +123 -0
- package/src/adaptive/summary-tree.ts +252 -0
- package/src/context-log.ts +7 -2
- package/src/index.ts +1 -1
- package/src/message-store.ts +1 -1
- package/src/normalize-tool-messages.ts +61 -0
- package/src/strategies/autobiographical.ts +414 -271
- package/src/types/strategy.ts +40 -1
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session replay for measuring REAL KV-cache stability.
|
|
3
|
+
*
|
|
4
|
+
* `replaySession` is the BASELINE: the production-default `FlatProfileStrategy`
|
|
5
|
+
* (level-equalizing) run through the real `Picker`, replayed over a growing
|
|
6
|
+
* session. Compare it against `replayControlled` (the KV-stable controller) to
|
|
7
|
+
* see what minimizing prefix churn actually buys. (Prior to the half-life/λ
|
|
8
|
+
* solver's removal this line ran `solveStableFrontier`; the λ value model was
|
|
9
|
+
* retired — see docs/kv-stable-context-control.md.)
|
|
10
|
+
*
|
|
11
|
+
* At each step it:
|
|
12
|
+
* 1. exposes only the chunks/summaries that existed by that point
|
|
13
|
+
* (a summary is available once its youngest covered message has happened —
|
|
14
|
+
* `SummaryNode.lastSequence <= now`; compression is bottom-up over time);
|
|
15
|
+
* 2. folds the middle to a FIXED token cap, carrying F_prev forward, with the
|
|
16
|
+
* newest `rawTailTokens` pinned raw (the flat zone);
|
|
17
|
+
* 3. READS a PERSISTENT provider cache (`CacheStore`, Anthropic ≤4
|
|
18
|
+
* breakpoints) for the longest live stored prefix still byte-identical to
|
|
19
|
+
* this render — entries written ANY prior turn — then WRITES this render's
|
|
20
|
+
* breakpoints back. A prefix frozen many turns ago is still a hit today.
|
|
21
|
+
*
|
|
22
|
+
* Pure and deterministic.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import type { ChunkId } from './folding-strategy.js';
|
|
26
|
+
import type { PickerInputs, PickerChunk } from './picker.js';
|
|
27
|
+
import type { SummaryEntry } from '../types/strategy.js';
|
|
28
|
+
import { SummaryTree } from './summary-tree.js';
|
|
29
|
+
import { Picker } from './picker.js';
|
|
30
|
+
import { FlatProfileStrategy } from './strategies/flat-profile.js';
|
|
31
|
+
import { renderLayout, type RenderLayout, type Frontier } from './render-offsets.js';
|
|
32
|
+
import { placeMarkers, CacheStore } from './kv-cache-sim.js';
|
|
33
|
+
|
|
34
|
+
export interface ReplayOptions {
|
|
35
|
+
/** Fixed context-window cap each step folds against (tokens). */
|
|
36
|
+
budgetTokens: number;
|
|
37
|
+
/** Cache breakpoints to place per step (1…4). Default 4. */
|
|
38
|
+
markerCount?: number;
|
|
39
|
+
/** Newest-N tokens kept raw (the protected flat zone). */
|
|
40
|
+
rawTailTokens?: number;
|
|
41
|
+
/** Approximate number of replay steps (history is down-sampled to this).
|
|
42
|
+
* Default 120. */
|
|
43
|
+
targetSteps?: number;
|
|
44
|
+
/** Cache entries older than this many steps are evicted (provider TTL).
|
|
45
|
+
* Default Infinity (keep all — the faithful upper bound on reuse). */
|
|
46
|
+
cacheTtlSteps?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ReplayStep {
|
|
50
|
+
/** Newest visible source sequence at this step. */
|
|
51
|
+
now: number;
|
|
52
|
+
/** Visible chunk count. */
|
|
53
|
+
numChunks: number;
|
|
54
|
+
/** Rendered tokens of this step's frontier. */
|
|
55
|
+
renderedTokens: number;
|
|
56
|
+
/** Tokens served from the simulated provider cache this step. */
|
|
57
|
+
cachedTokens: number;
|
|
58
|
+
/** Tokens recomputed this step (cache miss). */
|
|
59
|
+
recomputedTokens: number;
|
|
60
|
+
/** cachedTokens / renderedTokens, in [0, 1]. */
|
|
61
|
+
hitRate: number;
|
|
62
|
+
/** Source sequence at/after which the frontier was re-optimized. */
|
|
63
|
+
boundarySequence: number;
|
|
64
|
+
/** Solver could not fit under the cap this step. */
|
|
65
|
+
overBudget: boolean;
|
|
66
|
+
/** Deepest fold level present in the rendered frontier (0 = all raw). */
|
|
67
|
+
deepestLevel: number;
|
|
68
|
+
/** Age (in steps) of the cache entry that served this step's hit — evidence
|
|
69
|
+
* the hit came from an older write, not just the previous turn. −1 = miss. */
|
|
70
|
+
cacheAgeSteps: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface ReplayResult {
|
|
74
|
+
steps: ReplayStep[];
|
|
75
|
+
/** Σ renderedTokens over all steps. */
|
|
76
|
+
totalRendered: number;
|
|
77
|
+
/** Σ recomputedTokens over all steps (the cache-miss bill). */
|
|
78
|
+
totalRecomputed: number;
|
|
79
|
+
/** (totalRendered − totalRecomputed) / totalRendered, in [0, 1]. */
|
|
80
|
+
overallHitRate: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Replay a full session (the exported PickerInputs snapshot) as growing
|
|
85
|
+
* history, measuring per-step provider-cache hit under a fixed budget.
|
|
86
|
+
*/
|
|
87
|
+
export function replaySession(fullInputs: PickerInputs, opts: ReplayOptions): ReplayResult {
|
|
88
|
+
const markerCount = opts.markerCount ?? 4;
|
|
89
|
+
const targetSteps = Math.max(1, opts.targetSteps ?? 120);
|
|
90
|
+
|
|
91
|
+
// Availability threshold per summary: youngest covered leaf sequence.
|
|
92
|
+
// Built once over the full tree; a summary is usable at `now` iff <= now.
|
|
93
|
+
const fullTree = new SummaryTree(fullInputs);
|
|
94
|
+
const availableAt = new Map<string, number>();
|
|
95
|
+
for (const s of fullTree.allSummaries()) availableAt.set(s.id, s.lastSequence);
|
|
96
|
+
|
|
97
|
+
const allChunks = [...fullInputs.chunks].sort((a, b) => a.sequence - b.sequence);
|
|
98
|
+
const seqValues = allChunks.map((c) => c.sequence);
|
|
99
|
+
|
|
100
|
+
// Down-sample to ~targetSteps growth points (always include the final state).
|
|
101
|
+
const stride = Math.max(1, Math.ceil(seqValues.length / targetSteps));
|
|
102
|
+
const stepSeqs: number[] = [];
|
|
103
|
+
for (let i = 0; i < seqValues.length; i += stride) stepSeqs.push(seqValues[i]);
|
|
104
|
+
const last = seqValues[seqValues.length - 1];
|
|
105
|
+
if (stepSeqs[stepSeqs.length - 1] !== last) stepSeqs.push(last);
|
|
106
|
+
|
|
107
|
+
const steps: ReplayStep[] = [];
|
|
108
|
+
let fprev: Frontier = new Map<ChunkId, number>();
|
|
109
|
+
const cache = new CacheStore({ ttlSteps: opts.cacheTtlSteps });
|
|
110
|
+
let totalRendered = 0;
|
|
111
|
+
let totalRecomputed = 0;
|
|
112
|
+
|
|
113
|
+
for (const now of stepSeqs) {
|
|
114
|
+
const visiblePlain = allChunks.filter((c) => c.sequence <= now);
|
|
115
|
+
const tailIds = rawTailSet(visiblePlain, opts.rawTailTokens ?? 0);
|
|
116
|
+
// Pin the flat zone so flat-profile won't fold it AND it renders as
|
|
117
|
+
// individual raw units — not collapsed into one fixed-key 'tail' unit,
|
|
118
|
+
// which would falsely match across turns in the cache.
|
|
119
|
+
const visible = visiblePlain.map((c) => (tailIds.has(c.id) ? { ...c, pinned: true } : c));
|
|
120
|
+
const summaries = new Map<string, SummaryEntry>();
|
|
121
|
+
const recallPairTokens = new Map<string, number>();
|
|
122
|
+
for (const [id, s] of fullInputs.summaries) {
|
|
123
|
+
const lastSeq = availableAt.get(id);
|
|
124
|
+
if (lastSeq !== undefined && lastSeq >= 0 && lastSeq <= now) {
|
|
125
|
+
summaries.set(id, s);
|
|
126
|
+
const rp = fullInputs.recallPairTokens?.get(id);
|
|
127
|
+
if (rp !== undefined) recallPairTokens.set(id, rp);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const inputs: PickerInputs = {
|
|
132
|
+
chunks: visible,
|
|
133
|
+
summaries,
|
|
134
|
+
recallPairTokens,
|
|
135
|
+
headTokens: 0,
|
|
136
|
+
tailTokens: 0,
|
|
137
|
+
headChunkIds: new Set(),
|
|
138
|
+
tailChunkIds: new Set(),
|
|
139
|
+
};
|
|
140
|
+
const tree = new SummaryTree(inputs);
|
|
141
|
+
|
|
142
|
+
// Baseline policy: the production default, FlatProfileStrategy, via the real
|
|
143
|
+
// Picker — folds the middle to the budget, leaving the pinned flat zone raw.
|
|
144
|
+
const result = new Picker(new FlatProfileStrategy()).run(inputs, {
|
|
145
|
+
totalBudget: opts.budgetTokens,
|
|
146
|
+
targetBudget: opts.budgetTokens,
|
|
147
|
+
slack: 0,
|
|
148
|
+
});
|
|
149
|
+
const resolutions = result.finalResolutions;
|
|
150
|
+
|
|
151
|
+
const layout = renderLayout(inputs, tree, resolutions);
|
|
152
|
+
// READ the persistent cache: longest live stored prefix that still matches.
|
|
153
|
+
const hit = cache.read(layout);
|
|
154
|
+
const recomputedTokens = layout.totalTokens - hit.cachedTokens;
|
|
155
|
+
// WRITE this render's breakpoints back (hinting at the earliest change vs
|
|
156
|
+
// F_prev), then advance the turn clock so future reads see this write.
|
|
157
|
+
const boundarySeq = earliestChangedSequence(fprev, resolutions, visible);
|
|
158
|
+
const boundaryUnitIndex = unitsBeforeSequence(layout, tree, boundarySeq);
|
|
159
|
+
cache.write(layout, placeMarkers(layout, markerCount, { boundaryUnitIndex }));
|
|
160
|
+
cache.tick();
|
|
161
|
+
|
|
162
|
+
let deepestLevel = 0;
|
|
163
|
+
for (const lvl of resolutions.values()) if (lvl > deepestLevel) deepestLevel = lvl;
|
|
164
|
+
|
|
165
|
+
steps.push({
|
|
166
|
+
now,
|
|
167
|
+
numChunks: visible.length,
|
|
168
|
+
renderedTokens: layout.totalTokens,
|
|
169
|
+
cachedTokens: hit.cachedTokens,
|
|
170
|
+
recomputedTokens,
|
|
171
|
+
hitRate: layout.totalTokens > 0 ? hit.cachedTokens / layout.totalTokens : 0,
|
|
172
|
+
boundarySequence: boundarySeq,
|
|
173
|
+
overBudget: result.finalTokens > opts.budgetTokens,
|
|
174
|
+
deepestLevel,
|
|
175
|
+
cacheAgeSteps: hit.ageSteps,
|
|
176
|
+
});
|
|
177
|
+
totalRendered += layout.totalTokens;
|
|
178
|
+
totalRecomputed += recomputedTokens;
|
|
179
|
+
|
|
180
|
+
fprev = resolutions;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
steps,
|
|
185
|
+
totalRendered,
|
|
186
|
+
totalRecomputed,
|
|
187
|
+
overallHitRate: totalRendered > 0 ? (totalRendered - totalRecomputed) / totalRendered : 0,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
/** Earliest source sequence whose resolution changed `prev → next` (the marker
|
|
194
|
+
* hint / churn boundary). MAX_SAFE_INTEGER when nothing changed. */
|
|
195
|
+
function earliestChangedSequence(
|
|
196
|
+
prev: Frontier,
|
|
197
|
+
next: ReadonlyMap<ChunkId, number>,
|
|
198
|
+
ordered: PickerChunk[],
|
|
199
|
+
): number {
|
|
200
|
+
for (const c of ordered) {
|
|
201
|
+
if ((prev.get(c.id) ?? 0) !== (next.get(c.id) ?? 0)) return c.sequence;
|
|
202
|
+
}
|
|
203
|
+
return Number.MAX_SAFE_INTEGER;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Chunk ids within the newest `tailTokens` of raw content (kept non-foldable). */
|
|
207
|
+
function rawTailSet(orderedChunks: PickerChunk[], tailTokens: number): Set<ChunkId> {
|
|
208
|
+
const s = new Set<ChunkId>();
|
|
209
|
+
if (tailTokens <= 0) return s;
|
|
210
|
+
let used = 0;
|
|
211
|
+
for (let i = orderedChunks.length - 1; i >= 0; i--) {
|
|
212
|
+
s.add(orderedChunks[i].id);
|
|
213
|
+
used += orderedChunks[i].rawTokens;
|
|
214
|
+
if (used >= tailTokens) break;
|
|
215
|
+
}
|
|
216
|
+
return s;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Number of leading rendered units whose start sequence is < `boundary` (the
|
|
220
|
+
* frozen-prefix length → a natural cache breakpoint). */
|
|
221
|
+
function unitsBeforeSequence(layout: RenderLayout, tree: SummaryTree, boundary: number): number {
|
|
222
|
+
let count = 0;
|
|
223
|
+
for (const u of layout.units) {
|
|
224
|
+
if (unitStartSeq(u, tree) < boundary) count++;
|
|
225
|
+
else break;
|
|
226
|
+
}
|
|
227
|
+
return count;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function unitStartSeq(
|
|
231
|
+
u: RenderLayout['units'][number],
|
|
232
|
+
tree: SummaryTree,
|
|
233
|
+
): number {
|
|
234
|
+
if (u.kind === 'raw') return tree.leaf(u.key)?.sequence ?? 0;
|
|
235
|
+
if (u.kind === 'recall') return tree.summary(u.key)?.firstSequence ?? 0;
|
|
236
|
+
if (u.kind === 'head') return -1;
|
|
237
|
+
return Number.MAX_SAFE_INTEGER; // tail
|
|
238
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rendered-unit / offset accounting for the adaptive compiled context.
|
|
3
|
+
*
|
|
4
|
+
* `render.ts` reconstructs content byte-faithfully but exposes no token
|
|
5
|
+
* positions. The V2 best-fit KV term needs them: KV cost is governed by the
|
|
6
|
+
* EARLIEST position at which a new frontier diverges from the previous one —
|
|
7
|
+
* the provider caches the longest byte-identical prefix, so every token after
|
|
8
|
+
* the first divergence is recomputed (`docs/best-fit-frontier-resolution.md`
|
|
9
|
+
* §4, §4.1).
|
|
10
|
+
*
|
|
11
|
+
* `renderLayout` produces the ordered sequence of rendered units (head,
|
|
12
|
+
* per-chunk raw/recall in source order, tail) with cumulative token offsets,
|
|
13
|
+
* matching `MutableFoldingState.computeTokens` exactly:
|
|
14
|
+
* - head/tail are fixed blocks;
|
|
15
|
+
* - pinned chunks render raw (L0) regardless of resolution;
|
|
16
|
+
* - a folded chunk emits its L_k ancestor's recall pair, once per distinct
|
|
17
|
+
* ancestor (siblings share one recall pair);
|
|
18
|
+
* - a resolution whose ancestor summary is missing falls back to raw.
|
|
19
|
+
*
|
|
20
|
+
* Pure and deterministic.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { ChunkId, SummaryId } from './folding-strategy.js';
|
|
24
|
+
import type { PickerInputs } from './picker.js';
|
|
25
|
+
import type { SummaryTree } from './summary-tree.js';
|
|
26
|
+
|
|
27
|
+
/** Resolution map: chunkId → display level (0 = raw). */
|
|
28
|
+
export type Frontier = ReadonlyMap<ChunkId, number>;
|
|
29
|
+
|
|
30
|
+
export interface RenderedUnit {
|
|
31
|
+
kind: 'head' | 'raw' | 'recall' | 'tail';
|
|
32
|
+
/**
|
|
33
|
+
* Stable identity for prefix comparison. Two units are byte-identical iff
|
|
34
|
+
* they share (kind, key): 'head'/'tail' for the fixed blocks, the chunk id
|
|
35
|
+
* for a raw shard, the summary id for a recall pair.
|
|
36
|
+
*/
|
|
37
|
+
key: string;
|
|
38
|
+
tokens: number;
|
|
39
|
+
/** Cumulative tokens BEFORE this unit (its start offset in the prefix). */
|
|
40
|
+
offset: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface RenderLayout {
|
|
44
|
+
units: RenderedUnit[];
|
|
45
|
+
totalTokens: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Build the ordered rendered-unit layout for a frontier. `totalTokens` equals
|
|
50
|
+
* `MutableFoldingState.computeTokens` for the same resolutions.
|
|
51
|
+
*/
|
|
52
|
+
export function renderLayout(
|
|
53
|
+
inputs: PickerInputs,
|
|
54
|
+
tree: SummaryTree,
|
|
55
|
+
frontier: Frontier,
|
|
56
|
+
): RenderLayout {
|
|
57
|
+
const units: RenderedUnit[] = [];
|
|
58
|
+
let offset = 0;
|
|
59
|
+
const push = (kind: RenderedUnit['kind'], key: string, tokens: number): void => {
|
|
60
|
+
units.push({ kind, key, tokens, offset });
|
|
61
|
+
offset += tokens;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
if (inputs.headTokens > 0) push('head', 'head', inputs.headTokens);
|
|
65
|
+
|
|
66
|
+
const ordered = [...inputs.chunks].sort((a, b) => a.sequence - b.sequence);
|
|
67
|
+
const renderedSummaries = new Set<SummaryId>();
|
|
68
|
+
for (const c of ordered) {
|
|
69
|
+
if (inputs.headChunkIds.has(c.id) || inputs.tailChunkIds.has(c.id)) continue;
|
|
70
|
+
const effective = c.pinned ? 0 : frontier.get(c.id) ?? 0;
|
|
71
|
+
if (effective === 0) {
|
|
72
|
+
push('raw', c.id, c.rawTokens);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const ancestor = tree.ancestorAt(c.id, effective);
|
|
76
|
+
if (!ancestor) {
|
|
77
|
+
// Resolution set but summary missing — render raw (renderer makes the
|
|
78
|
+
// same call). Matches computeTokens' fallback.
|
|
79
|
+
push('raw', c.id, c.rawTokens);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (renderedSummaries.has(ancestor.id)) continue; // sibling shares the pair
|
|
83
|
+
renderedSummaries.add(ancestor.id);
|
|
84
|
+
push('recall', ancestor.id, ancestor.recallTokens);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (inputs.tailTokens > 0) push('tail', 'tail', inputs.tailTokens);
|
|
88
|
+
|
|
89
|
+
return { units, totalTokens: offset };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Earliest index at which two unit sequences differ (by kind+key).
|
|
94
|
+
* Returns -1 when the sequences are identical; otherwise the first differing
|
|
95
|
+
* index (which may be `min(len)` when one is a strict prefix of the other).
|
|
96
|
+
*/
|
|
97
|
+
export function earliestDivergenceIndex(a: RenderedUnit[], b: RenderedUnit[]): number {
|
|
98
|
+
const n = Math.min(a.length, b.length);
|
|
99
|
+
for (let i = 0; i < n; i++) {
|
|
100
|
+
if (a[i].kind !== b[i].kind || a[i].key !== b[i].key) return i;
|
|
101
|
+
}
|
|
102
|
+
return a.length === b.length ? -1 : n;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* KV cost of moving from `prev` to `next`: the number of tokens in `next` that
|
|
107
|
+
* must be recomputed — everything from the earliest divergence onward. 0 when
|
|
108
|
+
* `next`'s units are an exact prefix of (or identical to) `prev`'s, since the
|
|
109
|
+
* whole of `next` is then a cached prefix.
|
|
110
|
+
*/
|
|
111
|
+
export function kvCost(prev: RenderLayout, next: RenderLayout): number {
|
|
112
|
+
const d = earliestDivergenceIndex(prev.units, next.units);
|
|
113
|
+
if (d === -1) return 0; // identical
|
|
114
|
+
if (d >= next.units.length) return 0; // next is a prefix of prev → fully cached
|
|
115
|
+
return next.totalTokens - next.units[d].offset;
|
|
116
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* KvStableStrategy — the KV-stable context controller plugged into the existing
|
|
3
|
+
* picker (see `docs/kv-stable-context-control.md`).
|
|
4
|
+
*
|
|
5
|
+
* Same "solve-once-then-walk" bridge as `BestFitStrategy`: on the first
|
|
6
|
+
* `selectNextFold` it computes a target frontier with `planControlledFrontier`
|
|
7
|
+
* (the *same* policy the replay harness measures), memoizes it, then emits one
|
|
8
|
+
* `raise`/`lower` op per call to walk the live state toward it, returning `null`
|
|
9
|
+
* once reached. The picker already applies raise/lower — no picker change.
|
|
10
|
+
*
|
|
11
|
+
* Unlike `BestFitStrategy` (which maximizes value − λ·KVcost over a half-life
|
|
12
|
+
* recency model), this minimizes real prefix churn directly: it holds the flat
|
|
13
|
+
* zone (head/tail/pinned) raw, never folds locked chunks, and sheds the foldable
|
|
14
|
+
* middle oldest-first/leveled under a per-turn divergence **reach cap** (the
|
|
15
|
+
* perturbation cap P), bounded by per-chunk log-age saliency caps, yielding the
|
|
16
|
+
* reach cap only as far as needed to stay under the hard wall (`totalBudget`).
|
|
17
|
+
* No λ, no recency half-life.
|
|
18
|
+
*
|
|
19
|
+
* Like `BestFitStrategy`, it does not emit `produce` ops — deeper folding than
|
|
20
|
+
* has been produced is the speculative pre-producer's job; the controller only
|
|
21
|
+
* targets levels whose summaries already exist. Deterministic.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type {
|
|
25
|
+
FoldingStrategy,
|
|
26
|
+
FoldingState,
|
|
27
|
+
FoldingBudget,
|
|
28
|
+
FoldOp,
|
|
29
|
+
ChunkId,
|
|
30
|
+
} from '../folding-strategy.js';
|
|
31
|
+
import type { PickerInputs } from '../picker.js';
|
|
32
|
+
import { SummaryTree } from '../summary-tree.js';
|
|
33
|
+
import { planControlledFrontier } from '../kv-control.js';
|
|
34
|
+
|
|
35
|
+
export interface KvStableOptions {
|
|
36
|
+
/** Per-turn divergence reach — the structural perturbation cap P, in tokens.
|
|
37
|
+
* Smaller = gentler per-turn KV churn (shallow divergence) but less efficient
|
|
38
|
+
* compression. Exceeded only to stay under the hard wall. Default: the hard
|
|
39
|
+
* budget (effectively unbounded within the window). */
|
|
40
|
+
reachTokens?: number;
|
|
41
|
+
/** Base-k summary grouping (matches the strategy's mergeThreshold). Default 6. */
|
|
42
|
+
mergeThreshold?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class KvStableStrategy implements FoldingStrategy {
|
|
46
|
+
readonly name = 'kv-stable';
|
|
47
|
+
|
|
48
|
+
private readonly inputs: PickerInputs;
|
|
49
|
+
private readonly opts: KvStableOptions;
|
|
50
|
+
private readonly fPrev: Map<ChunkId, number>;
|
|
51
|
+
private target: Map<ChunkId, number> | null = null;
|
|
52
|
+
|
|
53
|
+
constructor(inputs: PickerInputs, opts: KvStableOptions = {}) {
|
|
54
|
+
this.inputs = inputs;
|
|
55
|
+
this.opts = opts;
|
|
56
|
+
this.fPrev = new Map(inputs.chunks.map((c) => [c.id, c.currentResolution]));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
selectNextFold(state: FoldingState, budget: FoldingBudget): FoldOp | null {
|
|
60
|
+
if (!this.target) this.target = this.solve(budget);
|
|
61
|
+
return this.nextOp(state);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Target frontier this run is walking toward (null before the first call). */
|
|
65
|
+
targetFrontier(): ReadonlyMap<ChunkId, number> | null {
|
|
66
|
+
return this.target;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private solve(budget: FoldingBudget): Map<ChunkId, number> {
|
|
70
|
+
const tree = new SummaryTree(this.inputs);
|
|
71
|
+
|
|
72
|
+
// Flat zone (forced raw, never folded): head, tail, pinned. Frozen (kept at
|
|
73
|
+
// their carried resolution, never folded): locked.
|
|
74
|
+
const rawZone = new Set<ChunkId>();
|
|
75
|
+
const frozen = new Set<ChunkId>();
|
|
76
|
+
let now = 0;
|
|
77
|
+
for (const c of this.inputs.chunks) {
|
|
78
|
+
if (c.sequence > now) now = c.sequence;
|
|
79
|
+
if (this.inputs.headChunkIds.has(c.id) || this.inputs.tailChunkIds.has(c.id) || c.pinned) {
|
|
80
|
+
rawZone.add(c.id);
|
|
81
|
+
} else if (c.lockedByAgent) {
|
|
82
|
+
frozen.add(c.id);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return planControlledFrontier(this.inputs, tree, {
|
|
87
|
+
previous: this.fPrev,
|
|
88
|
+
// Bidirectional within the slack band: fold when over the hard budget,
|
|
89
|
+
// un-fold to use headroom when under the soft target. Both reach-bounded;
|
|
90
|
+
// [targetBudget, totalBudget] is the quiet dead band.
|
|
91
|
+
foldAtTokens: budget.totalBudget,
|
|
92
|
+
expandAtTokens: budget.targetBudget,
|
|
93
|
+
targetTokens: budget.targetBudget,
|
|
94
|
+
windowTokens: budget.totalBudget,
|
|
95
|
+
reachTokens: this.opts.reachTokens,
|
|
96
|
+
rawZone,
|
|
97
|
+
frozen,
|
|
98
|
+
now,
|
|
99
|
+
mergeThreshold: this.opts.mergeThreshold,
|
|
100
|
+
}).resolutions;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Emit one op moving the live state toward the target frontier. */
|
|
104
|
+
private nextOp(state: FoldingState): FoldOp | null {
|
|
105
|
+
const target = this.target!;
|
|
106
|
+
for (const c of state.chunks()) {
|
|
107
|
+
if (c.inHead || c.inTail || c.pinned || c.lockedByAgent) continue;
|
|
108
|
+
const cur = c.currentResolution;
|
|
109
|
+
const tgt = target.get(c.id) ?? 0;
|
|
110
|
+
if (cur === tgt) continue;
|
|
111
|
+
|
|
112
|
+
if (cur < tgt) {
|
|
113
|
+
const summary = c.ancestorAt(tgt);
|
|
114
|
+
if (!summary) continue; // unrealizable target (summary not produced) — skip
|
|
115
|
+
return { kind: 'raise', groupRoot: summary.id };
|
|
116
|
+
}
|
|
117
|
+
const summary = c.ancestorAt(cur);
|
|
118
|
+
if (!summary) continue;
|
|
119
|
+
return { kind: 'lower', groupRoot: summary.id };
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|