repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(decay): measure retained history and improve merge progress

669a82014109c7094e3b96f5fa0ed88190fd8cea

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (7)

extensions/decay/README.md

Modified
24 24 Repeated compactions provide the classifier a bounded prior-atom identity catalog so paraphrased facts can reuse exact recurrence keys without counting catalog entries as new occurrences.
26 26 Interactive progress uses a passive fixed-height widget above Pi's editor, preserving native steering submission and Escape cancellation during compaction.
27 +History and the retained tail share one row, with contrasting labels over the block cells.
28 +Pending history is neutral; accepted records acquire source-age colors, and recurring keys are marked only after recurrence is observed across records.
29 +During merge, a looping summary blend indicates activity, not percentage complete.
30 +The widget reports the allocated atom count and an estimated output-token count driven by streamed summary text.
28 -The binding behavior and visual artifacts live in the [Decay plan](../../docs/super/plans/2026-08-22-decay-compaction.md).
32 +`keepRecentTokens` is Pi's configured target, not an exact count or minimum guarantee.
33 +Pi chooses whole-entry boundaries, which can retain more or fewer tokens than the target.
34 +Decay preserves `firstKeptEntryId` unchanged and does not send the retained suffix to its classifier.
35 +The displayed retained count and `estimatedKeptTokens` details field use Pi's message-token estimator over the actual retained suffix, including older summaries when present.
36 +`~` marks estimates; unavailable boundaries display `?`, never the configured target as a measured count.
38 +The [original Decay plan](../../docs/super/plans/2026-08-22-decay-compaction.md) contains earlier visual artifacts.
39 +The current widget uses seven normal lines or four short-terminal lines; the single-row history and evidence-driven rendering replace that plan's eight-line design.

extensions/decay/__tests__/integration.test.ts

Modified
43 43 return {
44 44 type: "session_before_compact" as const,
45 45 preparation: preparation(),
46 - branchEntries: [],
46 + branchEntries: [
47 + {
48 + type: "message" as const,
49 + id: "kept-entry",
50 + parentId: null,
51 + timestamp: new Date(1).toISOString(),
52 + message: {
53 + role: "user" as const,
54 + content: "k".repeat(96_000),
55 + timestamp: 1,
56 + },
57 + },
58 + ],
47 59 customInstructions: "focus on exact paths",
48 60 reason: "manual" as const,
49 61 willRetry: false,
139 151 version: 1,
140 152 chunkCount: 1,
141 153 keepRecentTokens: 20_000,
154 + estimatedKeptTokens: 24_000,
142 155 atoms: [expect.objectContaining({ key: "path:src/main.ts" })],
163 176 willRetry: false,
165 178 expect(testSession.events.uiCallsFor("notify").at(-1)?.args.at(0)).toMatch(
166 - /Decay · gpt-4o · 1\/1 classified · 20,000 kept/,
179 + /Decay · gpt-4o · 1\/1 classified · ~24,000 kept \(target 20,000\)/,
183 + it("preserves real prepared messages through the Decay hook and context rebuild", async () => {
184 + const { testSession, faux } = await setup();
185 + const manager = testSession.session.sessionManager;
186 + const old = { role: "user", content: "old ".repeat(12_000), timestamp: 1 };
187 + const kept = [
188 + { role: "user", content: "keep-a ".repeat(7_000), timestamp: 2 },
189 + { role: "user", content: "keep-b ".repeat(7_000), timestamp: 3 },
190 + ];
191 + manager.appendMessage(old);
192 + for (const message of kept) manager.appendMessage(message);
193 + let classifierContext: Context | undefined;
194 + faux.setResponses([
195 + (context) => {
196 + classifierContext = context;
197 + return classifierMessage();
198 + },
199 + fauxAssistantMessage("New summary."),
200 + ]);
201 + await testSession.session.compact();
202 + const messages = manager.buildSessionContext().messages;
203 + expect(messages.slice(1)).toEqual(kept);
204 + expect(JSON.stringify(classifierContext)).not.toContain("keep-a");
205 + expect(JSON.stringify(classifierContext)).not.toContain("keep-b");
206 + const checkpoint = manager.getBranch().at(-1);
207 + expect(checkpoint.details.decay.estimatedKeptTokens).toBe(24_500);
208 + expect(checkpoint.details.decay.keepRecentTokens).toBe(20_000);
209 + });
170 211 it("uses a separately configured summarizer model", async () => {
171 212 const { testSession, faux } = await setup();
172 213 vi.spyOn(SettingsManager, "create").mockReturnValue(
209 250 let widgetOptions: unknown;
210 251 let widgetCleared = false;
211 252 let component:
212 - | { render(width: number): string[]; dispose?(): void }
253 + | {
254 + render(width: number): string[];
255 + dispose?(): void;
256 + state: { mergeAtoms: number; summaryTokens: number };
213 258 | undefined;
214 259 runner.createContext = () => ({
215 260 ...baseContext,
239 284 fg: (_color: string, text: string) => text,
285 + bg: (_color: string, text: string) => text,
240 286 bold: (text: string) => text,
250 296 expect(result.compaction.summary).toContain("Widget path");
251 297 expect(widgetOptions).toEqual({ placement: "aboveEditor" });
252 298 expect(widgetCleared).toBe(true);
253 - expect(rendered).toHaveLength(8);
299 + expect(rendered).toHaveLength(7);
300 + expect(component?.state.mergeAtoms).toBe(1);
301 + expect(component?.state.summaryTokens).toBeGreaterThan(0);
254 302 expect(rendered.join("\n")).toContain("DECAY.EXE");
255 303 expect(rendered.join("\n")).toContain("Enter queues steer");
256 304 expect(custom).not.toHaveBeenCalled();

extensions/decay/__tests__/retention.test.ts

Added
new file mode 100644
1 +import {
2 + fauxProvider,
3 + InMemoryCredentialStore,
4 + InMemoryModelsStore,
5 +} from "@earendil-works/pi-ai";
6 +import {
7 + createAgentSession,
8 + DefaultResourceLoader,
9 + estimateTokens,
10 + ModelRuntime,
11 + type SessionBeforeCompactEvent,
12 + SessionManager,
13 + SettingsManager,
14 + sessionEntryToContextMessages,
15 +} from "@earendil-works/pi-coding-agent";
16 +import { describe, expect, it } from "vitest";
17 +import {
18 + type DecayDetails,
19 + estimateKeptTokens,
20 + parseDecayDetails,
21 +} from "../core";
23 +const settings = {
24 + enabled: true,
25 + reserveTokens: 16_384,
26 + keepRecentTokens: 20_000,
27 +};
29 +function user(tokens: number, marker: string) {
30 + return {
31 + role: "user" as const,
32 + content: [
33 + {
34 + type: "text" as const,
35 + text: marker + "x".repeat(tokens * 4 - marker.length),
36 + },
37 + ],
38 + timestamp: 1,
39 + };
42 +function assistant(tokens: number, marker: string) {
43 + return {
44 + role: "assistant" as const,
45 + content: [
46 + {
47 + type: "text" as const,
48 + text: marker + "x".repeat(tokens * 4 - marker.length),
49 + },
50 + ],
51 + api: "test",
52 + provider: "test",
53 + model: "test",
54 + usage: {
55 + input: 0,
56 + output: 0,
57 + cacheRead: 0,
58 + cacheWrite: 0,
59 + totalTokens: 0,
60 + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
61 + },
62 + stopReason: "stop" as const,
63 + timestamp: 1,
64 + };
67 +async function prepare(manager: SessionManager) {
68 + const settingsManager = SettingsManager.inMemory({ compaction: settings });
69 + const faux = fauxProvider({
70 + models: [{ id: "retention", contextWindow: 128_000, maxTokens: 16_384 }],
71 + });
72 + const modelRuntime = await ModelRuntime.create({
73 + credentials: new InMemoryCredentialStore(),
74 + modelsPath: null,
75 + modelsStore: new InMemoryModelsStore(),
76 + refreshOnCreate: false,
77 + });
78 + modelRuntime.registerNativeProvider(faux.provider);
80 + let captured: SessionBeforeCompactEvent | undefined;
81 + const resourceLoader = new DefaultResourceLoader({
82 + cwd: process.cwd(),
83 + agentDir: process.cwd(),
84 + settingsManager,
85 + noExtensions: true,
86 + noSkills: true,
87 + noPromptTemplates: true,
88 + noThemes: true,
89 + noContextFiles: true,
90 + extensionFactories: [
91 + (pi) => {
92 + pi.on("session_before_compact", (event) => {
93 + captured = event;
94 + return { cancel: true };
95 + });
96 + },
97 + ],
98 + });
99 + await resourceLoader.reload();
100 + const { session } = await createAgentSession({
101 + model: faux.getModel("retention"),
102 + modelRuntime,
103 + noTools: "all",
104 + resourceLoader,
105 + sessionManager: manager,
106 + settingsManager,
107 + });
108 + try {
109 + await expect(session.compact()).rejects.toThrow("Compaction cancelled");
110 + } finally {
111 + session.dispose();
114 + expect(faux.state.callCount).toBe(0);
115 + if (!captured) throw new Error("session_before_compact was not captured");
116 + return captured;
119 +function projectedSuffix(event: SessionBeforeCompactEvent) {
120 + const boundary = event.branchEntries.findIndex(
121 + (entry) => entry.id === event.preparation.firstKeptEntryId,
122 + );
123 + return event.branchEntries
124 + .slice(boundary)
125 + .flatMap(sessionEntryToContextMessages);
128 +function settleAndCompare(
129 + manager: SessionManager,
130 + event: SessionBeforeCompactEvent,
131 + summary = "new summary",
132 +) {
133 + const suffix = projectedSuffix(event);
134 + const estimated = estimateKeptTokens(event);
135 + expect(estimated).toBe(
136 + suffix.reduce((total, message) => total + estimateTokens(message), 0),
137 + );
138 + manager.appendCompaction(
139 + summary,
140 + event.preparation.firstKeptEntryId,
141 + event.preparation.tokensBefore,
142 + );
143 + const rebuilt = manager.buildSessionContext().messages;
144 + expect(rebuilt[0]).toMatchObject({ role: "compactionSummary", summary });
145 + expect(rebuilt.slice(1)).toEqual(suffix);
146 + return { estimated, suffix, rebuilt };
149 +describe("settled Decay retention accounting", () => {
150 + it("keeps normal-boundary message objects verbatim and may exceed the 20k target", async () => {
151 + const manager = SessionManager.inMemory();
152 + manager.appendMessage(user(12_000, "old"));
153 + const firstKept = user(12_000, "kept-a");
154 + const newest = user(12_000, "kept-b");
155 + manager.appendMessage(firstKept);
156 + manager.appendMessage(newest);
157 + const event = await prepare(manager);
158 + expect(event.preparation.isSplitTurn).toBe(false);
160 + const result = settleAndCompare(manager, event);
161 + expect(result.estimated).toBe(24_000);
162 + expect(result.estimated).toBeGreaterThan(settings.keepRecentTokens);
163 + expect(result.suffix).toHaveLength(2);
164 + expect(result.suffix[0]).toBe(firstKept);
165 + expect(result.suffix[1]).toBe(newest);
166 + });
168 + it("keeps split-turn suffix message objects verbatim", async () => {
169 + const manager = SessionManager.inMemory();
170 + manager.appendMessage(user(100, "request"));
171 + const firstKept = assistant(12_000, "kept-a");
172 + const newest = assistant(12_000, "kept-b");
173 + manager.appendMessage(firstKept);
174 + manager.appendMessage(newest);
175 + const event = await prepare(manager);
176 + expect(event.preparation.isSplitTurn).toBe(true);
178 + const result = settleAndCompare(manager, event);
179 + expect(result.estimated).toBe(24_000);
180 + expect(result.suffix[0]).toBe(firstKept);
181 + expect(result.suffix[1]).toBe(newest);
182 + });
184 + it("can stay below 20k at a tool-result cut and excludes metadata", async () => {
185 + const manager = SessionManager.inMemory();
186 + manager.appendMessage(user(1_000, "old"));
187 + manager.appendMessage({
188 + ...assistant(1, "a"),
189 + content: [
190 + { type: "toolCall", id: "call-1", name: "read", arguments: {} },
191 + ],
192 + } as never);
193 + manager.appendMessage({
194 + role: "toolResult",
195 + toolCallId: "call-1",
196 + toolName: "read",
197 + content: [{ type: "text", text: "x".repeat(21_000 * 4) }],
198 + isError: false,
199 + timestamp: 1,
200 + });
201 + const metadataId = manager.appendCustomEntry("retention-test", {
202 + notContext: "x".repeat(40_000),
203 + });
204 + const newest = user(100, "new");
205 + manager.appendMessage(newest);
206 + const event = await prepare(manager);
207 + expect(event.preparation.firstKeptEntryId).toBe(metadataId);
209 + const result = settleAndCompare(manager, event);
210 + expect(result.estimated).toBe(100);
211 + expect(result.estimated).toBeLessThan(settings.keepRecentTokens);
212 + expect(result.suffix).toEqual([newest]);
213 + });
215 + it("includes an older compaction summary when the later boundary precedes it", async () => {
216 + const manager = SessionManager.inMemory();
217 + for (let index = 1; index <= 4; index++)
218 + manager.appendMessage(user(8_000, `turn-${index}`));
219 + const first = (await prepare(manager)).preparation;
220 + manager.appendCompaction(
221 + "s".repeat(4_000),
222 + first.firstKeptEntryId,
223 + first.tokensBefore,
224 + );
225 + manager.appendMessage(user(4_000, "later"));
226 + const secondEvent = await prepare(manager);
227 + const boundaryIndex = secondEvent.branchEntries.findIndex(
228 + (entry) => entry.id === secondEvent.preparation.firstKeptEntryId,
229 + );
230 + const olderCompactionIndex = secondEvent.branchEntries.findIndex(
231 + (entry) => entry.type === "compaction",
232 + );
233 + expect(boundaryIndex).toBeLessThan(olderCompactionIndex);
235 + const result = settleAndCompare(manager, secondEvent);
236 + expect(
237 + result.suffix.some((message) => message.role === "compactionSummary"),
238 + ).toBe(true);
239 + });
241 + it("moves a repeated-compaction boundary across the previous checkpoint", async () => {
242 + const manager = SessionManager.inMemory();
243 + for (let index = 1; index <= 4; index++)
244 + manager.appendMessage(user(8_000, `turn-${index}`));
245 + const first = (await prepare(manager)).preparation;
246 + manager.appendCompaction(
247 + "older checkpoint",
248 + first.firstKeptEntryId,
249 + first.tokensBefore,
250 + );
251 + manager.appendMessage(user(12_000, "later-a"));
252 + manager.appendMessage(user(12_000, "later-b"));
253 + const secondEvent = await prepare(manager);
254 + const boundaryIndex = secondEvent.branchEntries.findIndex(
255 + (entry) => entry.id === secondEvent.preparation.firstKeptEntryId,
256 + );
257 + const olderCompactionIndex = secondEvent.branchEntries.findIndex(
258 + (entry) => entry.type === "compaction",
259 + );
260 + expect(boundaryIndex).toBeGreaterThan(olderCompactionIndex);
262 + const result = settleAndCompare(manager, secondEvent);
263 + expect(result.estimated).toBe(24_000);
264 + expect(
265 + result.suffix.some((message) => message.role === "compactionSummary"),
266 + ).toBe(false);
267 + });
269 + it("returns undefined when the prepared boundary is absent", async () => {
270 + const manager = SessionManager.inMemory();
271 + manager.appendMessage(user(12_000, "old"));
272 + manager.appendMessage(user(12_000, "kept-a"));
273 + manager.appendMessage(user(12_000, "kept-b"));
274 + const preparedEvent = await prepare(manager);
275 + const event = {
276 + ...preparedEvent,
277 + preparation: {
278 + ...preparedEvent.preparation,
279 + firstKeptEntryId: "missing",
280 + },
281 + };
282 + expect(estimateKeptTokens(event)).toBeUndefined();
283 + });
285 + it("parses an optional valid estimate and rejects invalid present values", () => {
286 + const legacy: DecayDetails = {
287 + decay: {
288 + version: 1,
289 + model: "p/m",
290 + elapsedMs: 1,
291 + chunkCount: 1,
292 + keepRecentTokens: 20_000,
293 + atoms: [],
294 + readFiles: [],
295 + modifiedFiles: [],
296 + },
297 + };
298 + expect(parseDecayDetails(legacy)).toEqual(legacy);
299 + const withEstimate: DecayDetails = {
300 + decay: { ...legacy.decay, estimatedKeptTokens: 24_000 },
301 + };
302 + expect(parseDecayDetails(withEstimate)).toEqual(withEstimate);
303 + for (const invalid of [-1, 1.5, Number.NaN, "20000", null]) {
304 + expect(
305 + parseDecayDetails({
306 + decay: { ...legacy.decay, estimatedKeptTokens: invalid },
307 + }),
308 + ).toBeUndefined();
310 + });
311 +});
313 +// These are pure accounting tests. They exercise Pi's real preparation and session
314 +// rebuilding APIs, but intentionally do not invoke Decay's extension hook or any model.

extensions/decay/__tests__/ui.test.ts

Modified
10 10 return {
11 11 model: "openai-codex/gpt-5.6-luna",
12 12 inputTokens: 118_420,
13 - keptTokens: 20_000,
13 + keptTokens: 24_000,
14 14 totalChunks: 8,
15 15 phase: "classify",
16 16 transfers: [],
22 -const completedTransfers: DecayDisplayState["transfers"] = [
23 - { chunk: 1, kind: "old", recurring: false, acceptedAt: 1_000 },
24 - { chunk: 2, kind: "old", recurring: true, acceptedAt: 1_000 },
25 - { chunk: 3, kind: "established", recurring: false, acceptedAt: 1_000 },
26 - { chunk: 4, kind: "established", recurring: false, acceptedAt: 1_000 },
27 - { chunk: 5, kind: "recent", recurring: false, acceptedAt: 1_000 },
28 - { chunk: 6, kind: "recent", recurring: true, acceptedAt: 1_000 },
29 - { chunk: 7, kind: "newest", recurring: false, acceptedAt: 1_000 },
30 - { chunk: 8, kind: "newest", recurring: true, acceptedAt: 1_000 },
31 -];
22 +const completedTransfers: DecayDisplayState["transfers"] = Array.from(
23 + { length: 8 },
24 + (_, index) => ({
25 + chunk: index + 1,
26 + kind: (["old", "established", "recent", "newest"] as const)[
27 + Math.floor(index / 2)
28 + ],
29 + recurring: index === 5,
30 + acceptedAt: 1_000,
31 + }),
32 +);
34 +const theme = {
35 + fg: (_color: string, text: string) => text,
36 + bg: vi.fn((_color: string, text: string) => text),
37 + bold: (text: string) => text,
38 +};
40 +function component(displayState = state()) {
41 + return new DecayComponent(
42 + {
43 + terminal: { rows: 30 },
44 + requestRender: vi.fn(),
45 + } as never,
46 + theme as never,
47 + displayState,
48 + () => 1_000,
49 + );
33 52 describe("Decay terminal rendering", () => {
34 53 it.each([
54 + [1, 15, 4],
55 + [20, 24, 7],
35 56 [40, 15, 4],
36 - [40, 24, 8],
57 + [40, 24, 7],
37 58 [59, 23, 4],
38 - [80, 30, 8],
39 - [120, 40, 8],
40 - [140, 45, 8],
59 + [80, 30, 7],
60 + [120, 40, 7],
61 + [140, 45, 7],
42 - "renders a fixed responsive %ix%i widget with %i lines",
43 - (width, viewportHeight, widgetHeight) => {
44 - const lines = plainFrame(
45 - renderDecayFrame(width, viewportHeight, state(), 5_000),
46 - );
47 - expect(lines).toHaveLength(widgetHeight);
48 - for (const line of lines) expect([...line]).toHaveLength(width);
49 - expect(lines.join("\n")).toContain("DECAY");
50 - expect(lines.join("\n")).toContain("CLASSIFY 0/8");
51 - expect(lines.join("\n")).not.toMatch(/TRIGGER|CAUSE/);
52 - if (widgetHeight === 8) {
53 - expect(lines.join("\n")).toContain("TRANSFER");
54 - expect(lines.join("\n")).toContain("SUMMARY");
55 - expect(lines.join("\n")).toContain("KEPT");
56 - } else {
57 - expect(lines.join("\n")).toContain("↵ queue");
63 + "keeps %ix%i frames bounded at %i lines across phases",
64 + (width, height, lines) => {
65 + for (const phase of ["classify", "merge"] as const) {
66 + const frame = plainFrame(
67 + renderDecayFrame(width, height, state({ phase }), 5_000),
68 + );
69 + expect(frame).toHaveLength(lines);
70 + for (const line of frame) expect([...line]).toHaveLength(width);
71 + if (width >= 40) {
72 + expect(frame.join("\n")).toContain("DECAY");
73 + expect(frame[0]).toContain(
74 + phase === "merge" ? "MERGE" : "CLASSIFY 0/8",
75 + );
76 + expect(frame[1]).toContain("KEPT");
77 + }
62 - it("keeps widget height stable across progress and phase changes", () => {
63 - for (const viewportHeight of [15, 30]) {
64 - const initial = renderDecayFrame(80, viewportHeight, state(), 1_000);
65 - const active = renderDecayFrame(
66 - 80,
67 - viewportHeight,
68 - state({ transfers: completedTransfers }),
69 - 2_000,
82 + it("starts with neutral history, no inferred age or fake recurrence", () => {
83 + const frame = renderDecayFrame(80, 30, state(), 2_000);
84 + const separator = frame[1].findIndex((cell) => cell.char === "║");
85 + const history = frame[1].slice(2, separator);
86 + expect(history.filter((cell) => cell.char === "░").length).toBeGreaterThan(
87 + 10,
88 + );
89 + expect(history.every((cell) => ["dim", "label"].includes(cell.color))).toBe(
90 + true,
91 + );
92 + expect(history.some((cell) => cell.color === "recurring")).toBe(false);
93 + expect(plainFrame(frame)[1]).toContain("HISTORY ~94K");
94 + expect(plainFrame(frame)[1]).toContain("~24K KEPT");
95 + });
97 + it("vacates source-order history and lands only completed records, preserving the tail", () => {
98 + const initial = renderDecayFrame(80, 30, state(), 2_000);
99 + const completed = renderDecayFrame(
100 + 80,
101 + 30,
102 + state({ transfers: completedTransfers }),
103 + 2_000,
104 + );
105 + const separator = initial[1].findIndex((cell) => cell.char === "║");
106 + expect(
107 + completed[1].slice(2, separator).some((cell) => cell.char === "░"),
108 + ).toBe(false);
109 + expect(completed[1].slice(separator)).toEqual(initial[1].slice(separator));
110 + expect(completed[3].filter((cell) => cell.color === "recurring")).toEqual([
111 + { char: "◆", color: "recurring" },
112 + ]);
113 + expect(plainFrame(completed)[3]).toContain("SUMMARY");
114 + });
116 + it("shows every in-flight record, not only the newest transfer", () => {
117 + const frame = renderDecayFrame(
118 + 80,
119 + 30,
120 + state({
121 + transfers: [
122 + { ...completedTransfers[0], acceptedAt: 1_000 },
123 + { ...completedTransfers[1], acceptedAt: 1_200 },
124 + ],
125 + }),
126 + 1_400,
127 + );
128 + expect(frame[2].filter((cell) => /[▖▘▝▗]/.test(cell.char))).toHaveLength(2);
129 + });
131 + it.each([15, 30])(
132 + "keeps summary blending animated long after the last transfer at height %i",
133 + (height) => {
134 + const display = state({
135 + phase: "merge",
136 + transfers: completedTransfers,
137 + mergeAtoms: 72,
138 + summaryTokens: 1_200,
139 + });
140 + const summaryRow = height < 24 ? 2 : 3;
141 + const first = renderDecayFrame(80, height, display, 20_000);
142 + const second = renderDecayFrame(80, height, display, 20_110);
143 + expect(second[summaryRow]).not.toEqual(first[summaryRow]);
144 + expect(second[1]).toEqual(first[1]);
145 + expect(plainFrame(second).join("\n")).not.toContain("%");
146 + if (height >= 24) {
147 + expect(plainFrame(second)[2]).toContain("72 atoms");
148 + expect(plainFrame(second)[2]).toContain("tokens emitted");
150 + },
151 + );
153 + it("does not label an unknown retained count as the configured 20k target", () => {
154 + const frame = plainFrame(
155 + renderDecayFrame(80, 30, state({ keptTokens: undefined }), 2_000),
156 + );
157 + expect(frame[1]).toContain("? KEPT");
158 + expect(frame[1]).not.toContain("20K");
159 + });
161 + it("overlays readable labels on block rows and remains passive", () => {
162 + const widget = component();
163 + try {
164 + expect("handleInput" in widget).toBe(false);
165 + expect(widget.render(80)).toHaveLength(7);
166 + expect(theme.bg).toHaveBeenCalledWith(
167 + "selectedBg",
168 + expect.stringContaining("HISTORY"),
71 - const merge = renderDecayFrame(
72 - 80,
73 - viewportHeight,
74 - state({ phase: "merge", transfers: completedTransfers }),
75 - 3_000,
76 - );
77 - expect(active).toHaveLength(initial.length);
78 - expect(merge).toHaveLength(initial.length);
170 + } finally {
171 + widget.dispose();
82 - it("vacates classified history cells and lands an old-to-new summary", () => {
83 - const initial = plainFrame(renderDecayFrame(80, 30, state(), 2_000));
84 - const completed = plainFrame(
85 - renderDecayFrame(80, 30, state({ transfers: completedTransfers }), 2_000),
86 - );
87 - const initialHistory = initial.slice(1, 3).join("");
88 - const completedHistory = completed.slice(1, 3).join("");
89 - expect(completedHistory).not.toBe(initialHistory);
90 - expect(completedHistory.split(" ").length).toBeGreaterThan(
91 - initialHistory.split(" ").length,
92 - );
93 - const summary = completed.find((line) => line.includes("SUMMARY ["));
94 - expect(summary).toBeDefined();
95 - expect(
96 - summary
97 - ?.slice(summary.indexOf("[") + 1, summary.lastIndexOf("]"))
98 - .replaceAll("·", "")
99 - .trim(),
100 - ).toBe("░░▒▒▓▓██");
101 - });
103 - it("shows transfer motion and indeterminate merge without fake percentage", () => {
104 - const moving = plainFrame(
105 - renderDecayFrame(
106 - 80,
107 - 30,
108 - state({
109 - transfers: [
110 - {
111 - chunk: 1,
112 - kind: "old",
113 - recurring: false,
114 - acceptedAt: 1_000,
115 - },
116 - ],
117 - }),
118 - 1_330,
119 - ),
120 - );
121 - expect(moving.find((line) => line.includes("TRANSFER"))).toMatch(/[▖▘▝▗]/);
122 - const merging = plainFrame(
123 - renderDecayFrame(80, 30, state({ phase: "merge" }), 2_000),
124 - );
125 - expect(merging.join("\n")).toContain("MERGE");
126 - expect(merging.join("\n")).not.toContain("MERGE 0%");
127 - });
129 - it("is passive and never implements focused keyboard handling", () => {
130 - const tui = {
131 - terminal: { rows: 30 },
132 - requestRender: vi.fn(),
133 - } as never;
134 - const component = new DecayComponent(
135 - tui,
136 - {
137 - fg: (_color: string, text: string) => text,
138 - bold: (text: string) => text,
139 - } as never,
140 - state(),
141 - );
175 + it("counts recurrence across records, not duplicate keys in one record", () => {
176 + const widget = component();
177 + const atom = {
178 + key: " Same Key ",
179 + text: "fact",
180 + kind: "context" as const,
181 + status: "active" as const,
182 + };
143 - expect("handleInput" in component).toBe(false);
144 - expect(component.render(80)).toHaveLength(8);
184 + widget.record({ chunk: 1, of: 8, atoms: [atom, atom] });
185 + widget.record({ chunk: 2, of: 8, atoms: [{ ...atom, key: "same key" }] });
186 + expect(
187 + widget.state.transfers.map((transfer) => transfer.recurring),
188 + ).toEqual([false, true]);
145 189 } finally {
146 - component.dispose();
190 + widget.dispose();
192 + });
194 + it("stops its render timer when disposed", () => {
195 + vi.useFakeTimers();
196 + try {
197 + const requestRender = vi.fn();
198 + const widget = new DecayComponent(
199 + { terminal: { rows: 30 }, requestRender } as never,
200 + theme as never,
201 + state(),
202 + );
203 + vi.advanceTimersByTime(110);
204 + expect(requestRender).toHaveBeenCalledTimes(2);
205 + widget.dispose();
206 + widget.dispose();
207 + vi.advanceTimersByTime(110);
208 + expect(requestRender).toHaveBeenCalledTimes(2);
209 + } finally {
210 + vi.useRealTimers();

extensions/decay/core.ts

Modified
7 7 convertToLlm,
8 8 estimateTokens,
9 9 serializeConversation,
10 + sessionEntryToContextMessages,
10 11 } from "@earendil-works/pi-coding-agent";
11 12 import { type Static, Type } from "typebox";
12 13 import { Value } from "typebox/value";
94 95 elapsedMs: number;
95 96 chunkCount: number;
96 97 keepRecentTokens: number;
98 + estimatedKeptTokens?: number;
97 99 atoms: MemoryAtom[];
98 100 readFiles: string[];
99 101 modifiedFiles: string[];
284 286 return [...byChunk.values()].sort((left, right) => left.chunk - right.chunk);
289 +export function estimateKeptTokens(
290 + event: SessionBeforeCompactEvent,
291 +): number | undefined {
292 + const boundaryIndex = event.branchEntries.findIndex(
293 + (entry) => entry.id === event.preparation.firstKeptEntryId,
294 + );
295 + if (boundaryIndex < 0) return undefined;
296 + return event.branchEntries
297 + .slice(boundaryIndex)
298 + .flatMap(sessionEntryToContextMessages)
299 + .reduce((total, message) => total + estimateTokens(message), 0);
287 302 export function findPreviousDecayDetails(
288 303 entries: readonly SessionEntry[],
289 304 ): DecayDetails["decay"] | undefined {
304 319 !Number.isFinite(decay.elapsedMs) ||
305 320 !Number.isInteger(decay.chunkCount) ||
306 321 !Number.isInteger(decay.keepRecentTokens) ||
322 + ("estimatedKeptTokens" in decay &&
323 + (!Number.isInteger(decay.estimatedKeptTokens) ||
324 + (decay.estimatedKeptTokens as number) < 0)) ||
307 325 !Array.isArray(decay.atoms) ||
308 326 !Array.isArray(decay.readFiles) ||
309 327 !Array.isArray(decay.modifiedFiles)
323 341 elapsedMs: decay.elapsedMs as number,
324 342 chunkCount: decay.chunkCount as number,
325 343 keepRecentTokens: decay.keepRecentTokens as number,
344 + ...(decay.estimatedKeptTokens === undefined
345 + ? {}
346 + : { estimatedKeptTokens: decay.estimatedKeptTokens as number }),
326 347 atoms,
327 348 readFiles: [...(decay.readFiles as string[])],
328 349 modifiedFiles: [...(decay.modifiedFiles as string[])],

extensions/decay/index.ts

Modified
18 18 createSourceChunks,
19 19 DECAY_DETAILS_VERSION,
20 20 type DecayDetails,
21 + estimateKeptTokens,
21 22 findPreviousDecayDetails,
22 23 formatFileAppendix,
23 24 type MemoryAtom,
48 49 summary: string;
49 50 usage: Usage;
50 51 details: DecayDetails;
51 - estimatedTokensAfter: number;
52 + estimatedTokensAfter?: number;
54 55 type RunOutcome =
58 59 interface RunCallbacks {
59 60 onRecord(record: RecordChunk): void;
60 - onMerge(): void;
61 + onMerge(atomCount: number): void;
62 + onSummary?(tokens: number): void;
63 65 type DecayFailureStage =
193 195 const details = parseDecayDetails(event.compactionEntry.details)?.decay;
194 196 if (!details) return;
195 197 ctx.ui.notify(
196 - `Decay · ${modelLabel(details.model)} · ${details.chunkCount}/${details.chunkCount} classified · ${details.keepRecentTokens.toLocaleString("en-US")} kept · ${(details.elapsedMs / 1_000).toFixed(1)}s`,
198 + `Decay · ${modelLabel(details.model)} · ${details.chunkCount}/${details.chunkCount} classified · ${details.estimatedKeptTokens === undefined ? "unknown" : `~${details.estimatedKeptTokens.toLocaleString("en-US")}`} kept (target ${details.keepRecentTokens.toLocaleString("en-US")}) · ${(details.elapsedMs / 1_000).toFixed(1)}s`,
197 199 "info",
225 227 const state: DecayDisplayState = {
226 228 model: modelReference,
227 229 inputTokens: event.preparation.tokensBefore,
228 - keptTokens: event.preparation.settings.keepRecentTokens,
230 + keptTokens: estimateKeptTokens(event),
229 231 totalChunks: previewChunkCount(event),
230 232 phase: "classify",
231 233 transfers: [],
250 252 signal,
252 254 onRecord: (record) => component?.record(record),
253 - onMerge: () => component?.setPhase("merge"),
255 + onMerge: (atomCount) => {
256 + state.mergeAtoms = atomCount;
257 + state.model = `${summarizerModel.provider}/${summarizerModel.id}`;
258 + component?.setPhase("merge");
259 + },
260 + onSummary: (tokens) => {
261 + state.summaryTokens = tokens;
262 + },
256 265 return { type: "success", result };
319 328 event.preparation.settings.reserveTokens,
321 330 const allocated = allocateAtoms(atoms, outputBudget);
322 - callbacks.onMerge();
331 + callbacks.onMerge(allocated.length);
323 332 stage = "summarizer";
324 333 const auth = await ctx.modelRegistry.getApiKeyAndHeaders(summarizerModel);
325 334 if (!auth.ok)
327 336 const provider = ctx.modelRegistry.getProvider(summarizerModel.provider);
328 337 if (!provider)
329 338 throw new Error(`Decay provider not found: ${summarizerModel.provider}`);
330 - const response = await provider
331 - .streamSimple(
332 - summarizerModel,
333 - buildSummarizerContext(allocated, event.customInstructions),
334 - {
335 - apiKey: auth.apiKey,
336 - headers: auth.headers,
337 - env: auth.env,
338 - maxTokens: outputBudget,
339 - signal,
340 - cacheRetention: "none",
341 - sessionId: uuidv7(),
342 - reasoning: summarizerModel.reasoning ? "low" : undefined,
343 - },
344 - )
345 - .result();
339 + const stream = provider.streamSimple(
340 + summarizerModel,
341 + buildSummarizerContext(allocated, event.customInstructions),
343 + apiKey: auth.apiKey,
344 + headers: auth.headers,
345 + env: auth.env,
346 + maxTokens: outputBudget,
347 + signal,
348 + cacheRetention: "none",
349 + sessionId: uuidv7(),
350 + reasoning: summarizerModel.reasoning ? "low" : undefined,
351 + },
352 + );
353 + for await (const item of stream) {
354 + if (item.type === "text_delta") {
355 + callbacks.onSummary?.(
356 + Math.ceil(contentText(item.partial.content).length / 4),
357 + );
360 + const response = await stream.result();
346 361 if (response.stopReason !== "stop")
347 362 throw new Error(
348 363 `Decay summarizer stopped with ${response.stopReason}: ${response.errorMessage ?? "no detail"}`,
355 370 const summary =
356 371 prose + formatFileAppendix(files.readFiles, files.modifiedFiles);
357 372 const elapsedMs = Date.now() - startedAt;
373 + const estimatedKeptTokens = estimateKeptTokens(event);
358 374 result = {
359 375 summary,
360 376 usage: combineUsage(classifierUsage, response.usage),
361 377 estimatedTokensAfter:
362 - Math.ceil(summary.length / 4) +
363 - event.preparation.settings.keepRecentTokens,
378 + estimatedKeptTokens === undefined
379 + ? undefined
380 + : Math.ceil(summary.length / 4) + estimatedKeptTokens,
364 381 details: {
365 382 decay: {
366 383 version: DECAY_DETAILS_VERSION,
368 385 elapsedMs,
369 386 chunkCount: chunks.length,
370 387 keepRecentTokens: event.preparation.settings.keepRecentTokens,
388 + ...(estimatedKeptTokens === undefined ? {} : { estimatedKeptTokens }),
371 389 atoms,
372 390 readFiles: files.readFiles,
373 391 modifiedFiles: files.modifiedFiles,

extensions/decay/ui.ts

Modified
4 4 import type { Theme } from "@earendil-works/pi-coding-agent";
5 5 import type { Component, TUI } from "@earendil-works/pi-tui";
6 6 import type { RecordChunk } from "./core.js";
8 8 const FRAME_MS = 55;
9 9 const TRANSFER_MS = 660;
10 -const NORMAL_HEIGHT = 8;
10 +const NORMAL_HEIGHT = 7;
11 11 const SHORT_HEIGHT = 4;
12 12 const SPIN = ["▖", "▘", "▝", "▗"] as const;
14 14 type Recency = "old" | "established" | "recent" | "newest";
15 -type CellColor = Recency | "recurring" | "title" | "text" | "dim";
15 +type CellColor = Recency | "recurring" | "title" | "text" | "dim" | "label";
17 17 interface Cell {
18 18 char: string;
26 26 export interface DecayDisplayState {
27 27 model: string;
28 28 inputTokens: number;
29 - keptTokens: number;
29 + keptTokens: number | undefined;
30 30 totalChunks: number;
31 31 phase: "classify" | "merge";
32 32 transfers: DisplayTransfer[];
33 33 startedAt: number;
34 + mergeAtoms?: number;
35 + summaryTokens?: number;
36 38 export class DecayComponent implements Component {
51 53 record(record: RecordChunk): void {
52 - let recurring = false;
53 - for (const atom of record.atoms) {
54 - const key = atom.key.trim().toLowerCase();
55 - if (this.seenKeys.has(key)) recurring = true;
56 - this.seenKeys.add(key);
57 - }
54 + const keys = new Set(
55 + record.atoms.map((atom) =>
56 + atom.key.trim().toLowerCase().replace(/\s+/g, " "),
57 + ),
58 + );
59 + const recurring = [...keys].some((key) => this.seenKeys.has(key));
60 + for (const key of keys) this.seenKeys.add(key);
58 61 this.state.transfers.push({
59 62 chunk: record.chunk,
60 63 kind: recencyFor(record.chunk, record.of),
96 99 const width = Math.max(1, viewportWidth);
97 100 const height = viewportHeight < 24 ? SHORT_HEIGHT : NORMAL_HEIGHT;
98 101 const canvas = blankCanvas(width, height);
99 - if (height === SHORT_HEIGHT) renderShort(canvas, state, now);
100 - else renderNormal(canvas, state, now);
102 + const elapsedMs = Math.max(0, now - state.startedAt);
103 + const frame = Math.floor(elapsedMs / FRAME_MS);
104 + const short = height === SHORT_HEIGHT;
105 + const phase =
106 + state.phase === "classify"
107 + ? `CLASSIFY ${state.transfers.length}/${state.totalChunks}`
108 + : "MERGE";
109 + const header = `${short ? "DECAY" : "DECAY.EXE"} ${SPIN[frame % SPIN.length]} · ${phase} · ${(elapsedMs / 1_000).toFixed(1)}s · ${modelLabel(state.model)}`;
110 + put(canvas, 0, 0, "─".repeat(width), "dim");
111 + put(canvas, 2, 0, header.slice(0, Math.max(0, width - 4)), "title");
112 + renderHistory(canvas, state);
113 + if (short) {
114 + const controls = width >= 48 ? " ↵ queue · Esc cancel" : " ↵ queue";
115 + renderSummary(canvas, 2, width - controls.length - 2, state, now);
116 + put(canvas, width - controls.length - 1, 2, controls, "dim");
117 + } else {
118 + renderTransfer(canvas, 2, state, now);
119 + renderSummary(canvas, 3, width - 2, state, now);
120 + renderLegend(canvas, 4);
121 + const controls = "Enter queues steer · Esc cancels";
122 + const leftWidth = Math.max(0, width - controls.length - 5);
123 + put(
124 + canvas,
125 + 2,
126 + 5,
127 + `INPUT ${state.inputTokens.toLocaleString("en-US")}`.slice(0, leftWidth),
128 + "text",
129 + );
130 + put(canvas, Math.max(2, width - controls.length - 2), 5, controls, "dim");
132 + // Draw borders last so even tiny viewports cannot overwrite them.
133 + for (let y = 1; y < height - 1; y++) {
134 + put(canvas, 0, y, "│", "dim");
135 + put(canvas, width - 1, y, "│", "dim");
137 + for (let x = 0; x < width; x++) {
138 + put(canvas, x, height - 1, "─", "dim");
140 + put(canvas, 0, 0, "╭", "dim");
141 + put(canvas, width - 1, 0, "╮", "dim");
142 + put(canvas, 0, height - 1, "╰", "dim");
143 + put(canvas, width - 1, height - 1, "╯", "dim");
101 144 return canvas;
104 -function renderNormal(
105 - canvas: Cell[][],
106 - state: DecayDisplayState,
107 - now: number,
108 -): void {
147 +function renderHistory(canvas: Cell[][], state: DecayDisplayState): void {
109 148 const width = canvas[0].length;
110 - const elapsedMs = Math.max(0, now - state.startedAt);
111 - const frame = Math.floor(elapsedMs / FRAME_MS);
112 - renderBorder(canvas, 0, "╭", "─", "╮");
113 - renderBorder(canvas, NORMAL_HEIGHT - 1, "╰", "─", "╯");
114 - for (let row = 1; row < NORMAL_HEIGHT - 1; row++) {
115 - put(canvas, 0, row, "│", "dim");
116 - put(canvas, width - 1, row, "│", "dim");
117 - }
119 - const phase = phaseLabel(state);
120 - const header = `DECAY.EXE ${frame % 12 < 6 ? "█" : " "} · ${phase} · ${(elapsedMs / 1_000).toFixed(1)}s · ${modelLabel(state.model)}`;
121 - put(canvas, 2, 0, header.slice(0, Math.max(0, width - 4)), "title");
123 - const tailWidth = clamp(Math.round(width * 0.28), 14, 28);
124 - const separatorX = Math.max(18, width - tailWidth - 1);
125 - const historyEnd = Math.max(3, separatorX - 1);
126 - for (const row of [1, 2]) put(canvas, separatorX, row, "║", "recent");
128 - const decayedTokens = Math.max(0, state.inputTokens - state.keptTokens);
129 - put(canvas, 2, 1, `HISTORY ${compactTokens(decayedTokens)}`, "dim");
130 - fillHistory(canvas, 14, historyEnd, 1, 0);
131 - fillHistory(canvas, 2, historyEnd, 2, 1);
132 - for (const transfer of state.transfers) {
133 - const source = sourcePosition(separatorX, transfer.chunk);
134 - put(canvas, source.x, source.y, " ", "dim");
135 - }
137 - put(
138 - canvas,
139 - separatorX + 2,
140 - 1,
141 - `${compactTokens(state.keptTokens)} KEPT`,
142 - "recent",
149 + const tailWidth = Math.min(
150 + Math.max(12, Math.round(width * 0.25)),
151 + Math.max(0, width - 6),
144 - fillTail(canvas, separatorX + 2, width - 2, 2);
146 - put(canvas, 2, 3, "TRANSFER", "dim");
147 - const laneStart = Math.min(width - 3, 11);
148 - const laneEnd = Math.max(laneStart, width - 3);
149 - put(
150 - canvas,
151 - laneStart,
152 - 3,
153 - "·".repeat(Math.max(0, laneEnd - laneStart)),
154 - "dim",
155 - );
156 - put(canvas, laneEnd, 3, "▶", "recent");
157 - const latest = state.transfers.at(-1);
158 - if (latest) {
159 - const progress = clamp((now - latest.acceptedAt) / TRANSFER_MS, 0, 1);
160 - if (progress < 1) {
161 - const x = Math.round(laneStart + (laneEnd - laneStart) * progress);
162 - put(
163 - canvas,
164 - x,
165 - 3,
166 - SPIN[frame % SPIN.length],
167 - latest.recurring ? "recurring" : latest.kind,
168 - );
169 - }
170 - } else if (state.phase === "merge") {
171 - const span = Math.max(1, laneEnd - laneStart);
172 - put(
173 - canvas,
174 - laneStart + (frame % span),
175 - 3,
176 - SPIN[frame % SPIN.length],
177 - "recent",
153 + const separator = width - tailWidth - 3;
154 + const historyStart = 2;
155 + const historyEnd = Math.max(historyStart, separator - 1);
156 + const capacity = historyEnd - historyStart;
157 + const accepted = new Set(state.transfers.map((transfer) => transfer.chunk));
158 + for (let x = historyStart; x < historyEnd; x++) {
159 + // Contiguous source-order bins, never decorative pseudo-random classifications.
160 + const first =
161 + Math.floor(
162 + ((x - historyStart) * state.totalChunks) / Math.max(1, capacity),
163 + ) + 1;
164 + const last = Math.max(
165 + first,
166 + Math.ceil(
167 + ((x - historyStart + 1) * state.totalChunks) / Math.max(1, capacity),
168 + ),
170 + let complete = state.totalChunks > 0;
171 + for (let chunk = first; chunk <= last; chunk++)
172 + complete &&= accepted.has(chunk);
173 + put(canvas, x, 1, complete ? " " : "░", "dim");
181 - renderSummary(canvas, 4, state, now);
182 - renderLegend(canvas, 5);
183 - renderStatus(canvas, 6, state);
175 + put(canvas, separator, 1, "║", "dim");
176 + for (let x = separator + 2; x < width - 2; x++)
177 + put(canvas, x, 1, "▓", "recent");
178 + const history =
179 + state.keptTokens === undefined
180 + ? "?"
181 + : compactTokens(Math.max(0, state.inputTokens - state.keptTokens));
182 + put(
183 + canvas,
184 + historyStart,
185 + 1,
186 + ` HISTORY ${history} `.slice(0, capacity),
187 + "label",
188 + );
189 + put(
190 + canvas,
191 + separator + 2,
192 + 1,
193 + ` ${compactTokens(state.keptTokens)} KEPT `.slice(0, tailWidth - 1),
194 + "label",
195 + );
186 -function renderShort(
198 +function renderTransfer(
187 199 canvas: Cell[][],
200 + y: number,
188 201 state: DecayDisplayState,
189 202 now: number,
190 203 ): void {
191 - const width = canvas[0].length;
192 - const elapsedMs = Math.max(0, now - state.startedAt);
193 - const frame = Math.floor(elapsedMs / FRAME_MS);
194 - renderBorder(canvas, 0, "╭", "─", "╮");
195 - renderBorder(canvas, SHORT_HEIGHT - 1, "╰", "─", "╯");
196 - for (const row of [1, 2]) {
197 - put(canvas, 0, row, "│", "dim");
198 - put(canvas, width - 1, row, "│", "dim");
204 + const end = canvas[0].length - 3;
205 + if (state.phase === "merge") {
206 + const output = state.summaryTokens
207 + ? `${compactTokens(state.summaryTokens)} tokens emitted`
208 + : "awaiting summary text";
209 + put(
210 + canvas,
211 + 2,
212 + y,
213 + `MERGING ${state.mergeAtoms ?? 0} atoms → summary · ${output}`,
214 + "text",
215 + );
216 + return;
200 - const header = `DECAY · ${phaseLabel(state)} · ${(elapsedMs / 1_000).toFixed(1)}s · ${modelLabel(state.model)}`;
201 - put(canvas, 2, 0, header.slice(0, Math.max(0, width - 4)), "title");
203 - const decayed = compactTokens(
204 - Math.max(0, state.inputTokens - state.keptTokens),
205 - );
206 - const kept = compactTokens(state.keptTokens);
207 - const prefix = `H${decayed} `;
208 - const suffix = ` → K${kept}`;
209 - const historyStart = 2 + prefix.length;
210 - const historyEnd = Math.max(historyStart, width - suffix.length - 3);
211 - put(canvas, 2, 1, prefix, "dim");
212 - fillHistory(canvas, historyStart, historyEnd, 1, 0);
213 - put(canvas, historyEnd, 1, suffix, "recent");
214 - const latest = state.transfers.at(-1);
215 - if (latest) {
216 - const progress = clamp((now - latest.acceptedAt) / TRANSFER_MS, 0, 1);
217 - if (progress < 1) {
218 - const x = Math.round(
219 - historyStart + (historyEnd - historyStart) * progress,
220 - );
221 - put(
222 - canvas,
223 - x,
224 - 1,
225 - SPIN[frame % SPIN.length],
226 - latest.recurring ? "recurring" : latest.kind,
227 - );
228 - }
218 + for (let x = 2; x < end; x++) put(canvas, x, y, "·", "dim");
219 + put(canvas, end, y, "▶", "recent");
220 + const frame = Math.floor(Math.max(0, now - state.startedAt) / FRAME_MS);
221 + for (const transfer of state.transfers) {
222 + const progress = Math.max(0, (now - transfer.acceptedAt) / TRANSFER_MS);
223 + if (progress >= 1) continue;
224 + const x = Math.round(2 + (end - 2) * progress);
225 + put(
226 + canvas,
227 + x,
228 + y,
229 + SPIN[frame % SPIN.length],
230 + transfer.recurring ? "recurring" : transfer.kind,
231 + );
231 - put(canvas, 2, 2, "S [", "dim");
232 - const controls = width >= 48 ? " ↵ queue · Esc cancel" : " ↵ queue";
233 - const summaryStart = 5;
234 - const summaryCapacity = Math.max(
235 - 1,
236 - width - summaryStart - controls.length - 2,
237 - );
238 - put(canvas, summaryStart, 2, "·".repeat(summaryCapacity), "dim");
239 - put(canvas, summaryStart + summaryCapacity, 2, "]", "dim");
240 - put(canvas, summaryStart + summaryCapacity + 1, 2, controls, "dim");
241 - landTransfers(canvas, summaryStart, summaryCapacity, 2, state, now);
233 + put(canvas, 2, y, " TRANSFER ", "label");
244 236 function renderSummary(
245 237 canvas: Cell[][],
246 238 y: number,
239 + end: number,
247 240 state: DecayDisplayState,
248 241 now: number,
249 242 ): void {
250 - const width = canvas[0].length;
251 - put(canvas, 2, y, "SUMMARY [", "dim");
252 - const start = 11;
253 - const capacity = Math.max(1, width - start - 3);
254 - put(canvas, start, y, "·".repeat(capacity), "dim");
255 - put(canvas, start + capacity, y, "]", "dim");
256 - landTransfers(canvas, start, capacity, y, state, now);
259 -function landTransfers(
260 - canvas: Cell[][],
261 - start: number,
262 - capacity: number,
263 - y: number,
264 - state: DecayDisplayState,
265 - now: number,
266 -): void {
267 - const latest = state.transfers.at(-1);
243 + const start = 2;
244 + const capacity = Math.max(0, end - start);
245 + for (let x = start; x < end; x++) put(canvas, x, y, "·", "dim");
268 246 for (const transfer of state.transfers) {
269 - const moving =
270 - transfer === latest && (now - transfer.acceptedAt) / TRANSFER_MS < 1;
271 - if (moving) continue;
272 - const index = Math.floor(
273 - ((transfer.chunk - 1) / Math.max(1, state.totalChunks)) * capacity,
274 - );
247 + if (state.phase !== "merge" && now - transfer.acceptedAt < TRANSFER_MS)
248 + continue;
249 + const x =
250 + start +
251 + Math.floor(
252 + ((transfer.chunk - 1) / Math.max(1, state.totalChunks)) * capacity,
253 + );
276 255 canvas,
277 - start + clamp(index, 0, capacity - 1),
256 + x,
279 - historyGlyph(transfer.kind),
258 + transfer.recurring ? "◆" : historyGlyph(transfer.kind),
280 259 transfer.recurring ? "recurring" : transfer.kind,
262 + const short = canvas.length === SHORT_HEIGHT;
263 + const label = short
264 + ? " S "
265 + : state.phase === "merge"
266 + ? " SUMMARY · blending "
267 + : " SUMMARY ";
268 + const blendStart = start + label.length;
269 + const blendWidth = end - blendStart;
270 + if (state.phase === "merge" && blendWidth > 0) {
271 + // A looping blend indicates synthesis activity, not progress toward an unknown total.
272 + const frame = Math.floor(Math.max(0, now - state.startedAt) / 110);
273 + for (let offset = 0; offset < Math.min(5, blendWidth); offset++) {
274 + put(
275 + canvas,
276 + blendStart + ((frame + offset) % blendWidth),
277 + y,
278 + ["░", "▒", "▓", "▒", "░"][offset],
279 + "recent",
280 + );
283 + put(canvas, start, y, label.slice(0, capacity), "label");
285 286 function renderLegend(canvas: Cell[][], y: number): void {
286 287 const width = canvas[0].length;
287 288 const legend =
288 289 width < 68
289 - ? "░ old ▒ established ▓ recent █ newest ◆ recurring"
290 - : "LEGEND ░ old ▒ established ▓ recent █ newest ◆ recurring";
291 - put(canvas, 2, y, legend.slice(0, Math.max(0, width - 4)), "dim");
292 - for (const [glyph, color] of [
293 - ["░", "old"],
294 - ["▒", "established"],
295 - ["▓", "recent"],
296 - ["█", "newest"],
297 - ["◆", "recurring"],
298 - ] as const) {
299 - const index = legend.indexOf(glyph);
300 - if (index >= 0) put(canvas, 2 + index, y, glyph, color);
301 - }
304 -function renderStatus(
305 - canvas: Cell[][],
306 - y: number,
307 - state: DecayDisplayState,
308 -): void {
309 - const width = canvas[0].length;
310 - const left = `INPUT ${state.inputTokens.toLocaleString("en-US")} · ${modelLabel(state.model)}`;
311 - const controls = "Enter queues steer · Esc cancels";
312 - put(canvas, 2, y, left.slice(0, Math.max(0, width - 4)), "text");
313 - if (width >= controls.length + 4) {
314 - put(canvas, width - controls.length - 2, y, controls, "dim");
315 - }
318 -function fillHistory(
319 - canvas: Cell[][],
320 - start: number,
321 - end: number,
322 - y: number,
323 - row: number,
324 -): void {
325 - for (let x = start; x < end; x++) {
326 - const kind = historyCellKind(x - start, Math.max(1, end - start), row);
327 - const recurring = (x * 17 + row * 31) % 43 === 0;
328 - put(canvas, x, y, historyGlyph(kind), recurring ? "recurring" : kind);
329 - }
332 -function fillTail(
333 - canvas: Cell[][],
334 - start: number,
335 - end: number,
336 - y: number,
337 -): void {
338 - for (let x = start; x < end; x++) {
339 - put(canvas, x, y, x % 7 === 0 ? "█" : "▓", "recent");
340 - }
343 -function sourcePosition(
344 - separatorX: number,
345 - chunk: number,
346 -): { x: number; y: number } {
347 - const firstStart = 14;
348 - const firstWidth = Math.max(1, separatorX - 1 - firstStart);
349 - const secondStart = 2;
350 - const secondWidth = Math.max(1, separatorX - 1 - secondStart);
351 - const capacity = firstWidth + secondWidth;
352 - const index = (chunk * 37) % capacity;
353 - return index < firstWidth
354 - ? { x: firstStart + index, y: 1 }
355 - : { x: secondStart + index - firstWidth, y: 2 };
358 -function phaseLabel(state: DecayDisplayState): string {
359 - return state.phase === "classify"
360 - ? `CLASSIFY ${state.transfers.length}/${state.totalChunks}`
361 - : "MERGE";
290 + ? "░ pending · age: old → new · ◆ repeat"
291 + : "░ pending · colors: source age, old → new · ◆ recurring";
292 + put(canvas, 2, y, legend, "dim");
293 + const index = legend.indexOf("◆");
294 + put(canvas, 2 + index, y, "◆", "recurring");
364 297 function recencyFor(chunk: number, total: number): Recency {
378 -function renderBorder(
379 - canvas: Cell[][],
380 - y: number,
381 - left: string,
382 - fill: string,
383 - right: string,
384 -): void {
385 - const width = canvas[0].length;
386 - put(canvas, 0, y, left, "dim");
387 - put(canvas, 1, y, fill.repeat(Math.max(0, width - 2)), "dim");
388 - put(canvas, width - 1, y, right, "dim");
391 311 function put(
392 312 canvas: Cell[][],
393 313 x: number,
407 -function historyCellKind(x: number, width: number, row: number): Recency {
408 - const ratio = x / Math.max(1, width - 1);
409 - const hash = (x * 37 + row * 61 + x * row * 11) % 101;
410 - const recency = clamp(ratio + (hash / 100 - 0.5) * 0.54, 0, 1);
411 - if (recency < 0.25) return "old";
412 - if (recency < 0.5) return "established";
413 - if (recency < 0.75) return "recent";
414 - return "newest";
417 327 function historyGlyph(kind: Recency): string {
418 328 return { old: "░", established: "▒", recent: "▓", newest: "█" }[kind];
423 333 return separator >= 0 ? reference.slice(separator + 1) : reference;
426 -function compactTokens(tokens: number): string {
427 - return tokens >= 1_000 ? `${Math.round(tokens / 1_000)}K` : String(tokens);
430 -function clamp(value: number, minimum: number, maximum: number): number {
431 - return Math.max(minimum, Math.min(maximum, value));
336 +function compactTokens(tokens: number | undefined): string {
337 + if (tokens === undefined) return "?";
338 + return tokens >= 1_000 ? `~${Math.round(tokens / 1_000)}K` : `~${tokens}`;
434 341 function styleFrame(frame: Cell[][], theme: Theme): string[] {
436 343 switch (name) {
437 344 case "title":
438 345 return theme.bold(theme.fg("success", text));
346 + case "label":
347 + return theme.bg("selectedBg", theme.bold(theme.fg("text", text)));
439 348 case "text":
440 349 case "newest":
441 350 return theme.fg("text", text);
446 355 case "established":
447 356 return theme.fg("borderAccent", text);
448 357 case "old":
358 + return theme.fg("muted", text);
449 359 case "dim":
450 360 return theme.fg("dim", text);