pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Compare Notes Search fix(decay): measure retained history and improve merge progress
669a82014109c7094e3b96f5fa0ed88190fd8cea
Oliver Jan Krylow <oliver@bugabinga.net > · 7 Sep 2026
SSH signature · not checked
Browse files Compare 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 44 44 type:
"session_before_compact" as const ,
45 45 preparation:
preparation (),
48 + type:
"message" as const ,
51 + timestamp:
new Date (
1 ).
toISOString (),
53 + role:
"user" as const ,
54 + content:
"k" .
repeat (
96_000 ),
47 59 customInstructions:
"focus on exact paths" ,
48 60 reason:
"manual" as const ,
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 };
188 + { role:
"user" , content:
"keep-a " .
repeat (
7_000 ), timestamp:
2 },
189 + { role:
"user" , content:
"keep-b " .
repeat (
7_000 ), timestamp:
3 },
191 + manager.
appendMessage (old);
192 + for (
const message
of kept) manager.
appendMessage (message);
193 + let classifierContext
: Context | undefined ;
194 + faux.
setResponses ([
196 + classifierContext
= context;
197 + return classifierMessage ();
199 + fauxAssistantMessage (
"New summary." ),
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 );
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 ;
212 - | {
render (width
: number )
: string [];
dispose ? ()
: void }
254 + render (width
: number )
: string [];
256 + state
: { mergeAtoms
: number ; summaryTokens
: number };
214 259 runner.
createContext = ()
=> ({
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 3 + InMemoryCredentialStore,
5 + }
from "@earendil-works/pi-ai" ;
8 + DefaultResourceLoader,
11 + type SessionBeforeCompactEvent,
14 + sessionEntryToContextMessages,
15 + }
from "@earendil-works/pi-coding-agent" ;
16 + import { describe, expect, it }
from "vitest" ;
25 + reserveTokens:
16_384 ,
26 + keepRecentTokens:
20_000 ,
29 + function user (tokens
: number , marker
: string ) {
31 + role:
"user" as const ,
34 + type:
"text" as const ,
35 + text: marker
+ "x" .
repeat (tokens
* 4 - marker.
length ),
42 + function assistant (tokens
: number , marker
: string ) {
44 + role:
"assistant" as const ,
47 + type:
"text" as const ,
48 + text: marker
+ "x" .
repeat (tokens
* 4 - marker.
length ),
60 + cost: { input:
0 , output:
0 , cacheRead:
0 , cacheWrite:
0 , total:
0 },
62 + stopReason:
"stop" as const ,
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 }],
72 + const modelRuntime
= await ModelRuntime.
create ({
73 + credentials:
new InMemoryCredentialStore (),
75 + modelsStore:
new InMemoryModelsStore (),
76 + refreshOnCreate:
false ,
78 + modelRuntime.
registerNativeProvider (faux.provider);
80 + let captured
: SessionBeforeCompactEvent | undefined ;
81 + const resourceLoader
= new DefaultResourceLoader ({
83 + agentDir:
process .
cwd (),
87 + noPromptTemplates:
true ,
89 + noContextFiles:
true ,
90 + extensionFactories: [
92 + pi.
on (
"session_before_compact" , (event)
=> {
94 + return { cancel:
true };
99 + await resourceLoader.
reload ();
100 + const { session }
= await createAgentSession ({
101 + model: faux.
getModel (
"retention" ),
105 + sessionManager: manager,
109 + await expect (session.
compact ()).rejects.
toThrow (
"Compaction cancelled" );
114 + expect (faux.state.callCount).
toBe (
0 );
115 + if (
! captured)
throw new Error (
"session_before_compact was not captured" );
119 + function projectedSuffix (event
: SessionBeforeCompactEvent ) {
120 + const boundary
= event .branchEntries.
findIndex (
121 + (entry)
=> entry.
id === event .preparation.firstKeptEntryId,
123 + return event .branchEntries
125 + .
flatMap (sessionEntryToContextMessages);
128 + function settleAndCompare (
129 + manager
: SessionManager ,
130 + event
: SessionBeforeCompactEvent ,
131 + summary
= "new summary" ,
133 + const suffix
= projectedSuffix (
event );
134 + const estimated
= estimateKeptTokens (
event );
135 + expect (estimated).
toBe (
136 + suffix.
reduce ((total, message)
=> total
+ estimateTokens (message),
0 ),
138 + manager.
appendCompaction (
140 + event .preparation.firstKeptEntryId,
141 + event .preparation.tokensBefore,
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);
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);
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" ),
190 + { type:
"toolCall" , id:
"call-1" , name:
"read" , arguments: {} },
193 + manager.
appendMessage ({
194 + role:
"toolResult" ,
195 + toolCallId:
"call-1" ,
197 + content: [{ type:
"text" , text:
"x" .
repeat (
21_000 * 4 ) }],
201 + const metadataId
= manager.
appendCustomEntry (
"retention-test" , {
202 + notContext:
"x" .
repeat (
40_000 ),
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]);
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 (
222 + first.firstKeptEntryId,
223 + first.tokensBefore,
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,
230 + const olderCompactionIndex
= secondEvent.branchEntries.
findIndex (
231 + (entry)
=> entry.
type === "compaction" ,
233 + expect (boundaryIndex).
toBeLessThan (olderCompactionIndex);
235 + const result
= settleAndCompare (manager, secondEvent);
237 + result.suffix.
some ((message)
=> message.role
=== "compactionSummary" ),
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,
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,
257 + const olderCompactionIndex
= secondEvent.branchEntries.
findIndex (
258 + (entry)
=> entry.
type === "compaction" ,
260 + expect (boundaryIndex).
toBeGreaterThan (olderCompactionIndex);
262 + const result
= settleAndCompare (manager, secondEvent);
263 + expect (result.estimated).
toBe (
24_000 );
265 + result.suffix.
some ((message)
=> message.role
=== "compactionSummary" ),
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);
278 + ... preparedEvent.preparation,
279 + firstKeptEntryId:
"missing" ,
282 + expect (
estimateKeptTokens (
event )).
toBeUndefined ();
285 + it (
"parses an optional valid estimate and rejects invalid present values" , ()
=> {
286 + const legacy
: DecayDetails = {
292 + keepRecentTokens:
20_000 ,
298 + expect (
parseDecayDetails (legacy)).
toEqual (legacy);
299 + const withEstimate
: DecayDetails = {
300 + decay: {
... legacy.decay, estimatedKeptTokens:
24_000 },
302 + expect (
parseDecayDetails (withEstimate)).
toEqual (withEstimate);
303 + for (
const invalid
of [
- 1 ,
1.5 ,
Number .NaN,
"20000" ,
null ]) {
305 + parseDecayDetails ({
306 + decay: {
... legacy.decay, estimatedKeptTokens: invalid },
extensions/decay/__tests__/ui.test.ts Modified 11 11 model:
"openai-codex/gpt-5.6-luna" ,
12 12 inputTokens:
118_420 ,
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 },
22 + const completedTransfers
: DecayDisplayState [
"transfers" ]
= Array .
from (
26 + kind: ([
"old" ,
"established" ,
"recent" ,
"newest" ]
as const )[
27 + Math .
floor (index
/ 2 )
29 + recurring: index
=== 5 ,
35 + fg : (_color
: string , text
: string )
=> text,
36 + bg: vi.
fn ((_color
: string , text
: string )
=> text),
37 + bold : (text
: string )
=> text,
40 + function component (displayState
= state ()) {
41 + return new DecayComponent (
43 + terminal: { rows:
30 },
44 + requestRender: vi.
fn (),
33 52 describe (
"Decay terminal rendering" , ()
=> {
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 ),
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" );
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 ),
69 + expect (frame).
toHaveLength (lines);
70 + for (
const line
of frame)
expect ([
... line]).
toHaveLength (width);
72 + expect (frame.
join (
"\n" )).
toContain (
"DECAY" );
73 + expect (frame[
0 ]).
toContain (
74 + phase
=== "merge" ? "MERGE" : "CLASSIFY 0/8" ,
76 + expect (frame[
1 ]).
toContain (
"KEPT" );
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 (
68 - state ({ transfers: completedTransfers }),
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 (
89 + expect (history.
every ((cell)
=> [
"dim" ,
"label" ].
includes (cell.
color ))).
toBe (
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" );
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 (
102 + state ({ transfers: completedTransfers }),
105 + const separator
= initial[
1 ].
findIndex ((cell)
=> cell.char
=== "║" );
107 + completed[
1 ].
slice (
2 , separator).
some ((cell)
=> cell.char
=== "░" ),
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" },
113 + expect (
plainFrame (completed)[
3 ]).
toContain (
"SUMMARY" );
116 + it (
"shows every in-flight record, not only the newest transfer" , ()
=> {
117 + const frame
= renderDecayFrame (
122 + {
... completedTransfers[
0 ], acceptedAt:
1_000 },
123 + {
... completedTransfers[
1 ], acceptedAt:
1_200 },
128 + expect (frame[
2 ].
filter ((cell)
=> /[▖▘▝▗]/ .
test (cell.char))).
toHaveLength (
2 );
132 + "keeps summary blending animated long after the last transfer at height %i" ,
134 + const display
= state ({
136 + transfers: completedTransfers,
138 + summaryTokens:
1_200 ,
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" );
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 ),
157 + expect (frame[
1 ]).
toContain (
"? KEPT" );
158 + expect (frame[
1 ]).not.
toContain (
"20K" );
161 + it (
"overlays readable labels on block rows and remains passive" , ()
=> {
162 + const widget
= component ();
164 + expect (
"handleInput" in widget).
toBe (
false );
165 + expect (widget.
render (
80 )).
toHaveLength (
7 );
166 + expect (theme.bg).
toHaveBeenCalledWith (
168 + expect.
stringContaining (
"HISTORY" ),
71 - const merge
= renderDecayFrame (
74 - state ({ phase:
"merge" , transfers: completedTransfers }),
77 - expect (active).
toHaveLength (initial.
length );
78 - expect (merge).
toHaveLength (initial.
length );
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 ),
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 ,
93 - const summary
= completed.
find ((line)
=> line.
includes (
"SUMMARY [" ));
94 - expect (summary).
toBeDefined ();
97 - ?.
slice (summary.
indexOf (
"[" )
+ 1 , summary.
lastIndexOf (
"]" ))
98 - .
replaceAll (
"·" ,
"" )
100 - ).
toBe (
"░░▒▒▓▓██" );
103 - it (
"shows transfer motion and indeterminate merge without fake percentage" , ()
=> {
104 - const moving
= plainFrame (
121 - expect (moving.
find ((line)
=> line.
includes (
"TRANSFER" ))).
toMatch (
/[▖▘▝▗]/ );
122 - const merging
= plainFrame (
123 - renderDecayFrame (
80 ,
30 ,
state ({ phase:
"merge" }),
2_000 ),
125 - expect (merging.
join (
"\n" )).
toContain (
"MERGE" );
126 - expect (merging.
join (
"\n" )).not.
toContain (
"MERGE 0%" );
129 - it (
"is passive and never implements focused keyboard handling" , ()
=> {
131 - terminal: { rows:
30 },
132 - requestRender: vi.
fn (),
134 - const component
= new DecayComponent (
137 - fg : (_color
: string , text
: string )
=> text,
138 - bold : (text
: string )
=> text,
175 + it (
"counts recurrence across records, not duplicate keys in one record" , ()
=> {
176 + const widget
= component ();
180 + kind:
"context" as const ,
181 + status:
"active" as const ,
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" }] });
187 + widget.state.transfers.
map ((transfer)
=> transfer.recurring),
188 + ).
toEqual ([
false ,
true ]);
146 - component.
dispose ();
194 + it (
"stops its render timer when disposed" , ()
=> {
195 + vi.
useFakeTimers ();
197 + const requestRender
= vi.
fn ();
198 + const widget
= new DecayComponent (
199 + { terminal: { rows:
30 }, requestRender }
as never ,
203 + vi.
advanceTimersByTime (
110 );
204 + expect (requestRender).
toHaveBeenCalledTimes (
2 );
207 + vi.
advanceTimersByTime (
110 );
208 + expect (requestRender).
toHaveBeenCalledTimes (
2 );
210 + vi.
useRealTimers ();
extensions/decay/core.ts Modified 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" ;
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,
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 346 + : { estimatedKeptTokens: decay.estimatedKeptTokens
as number }),
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,
21 22 findPreviousDecayDetails,
22 23 formatFileAppendix,
50 51 details : DecayDetails;
51 - estimatedTokensAfter : number;
52 + estimatedTokensAfter
?: number;
58 59 interface RunCallbacks {
59 60 onRecord (record
: RecordChunk )
: 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 ;
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` ,
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" ,
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" );
260 + onSummary : (tokens)
=> {
261 + state.summaryTokens
= tokens;
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);
327 336 const provider
= ctx.modelRegistry.
getProvider (summarizerModel.provider);
329 338 throw new Error (
`Decay provider not found: ${summarizerModel.provider}` );
330 - const response
= await provider
333 - buildSummarizerContext (allocated,
event .customInstructions),
335 - apiKey: auth.apiKey,
336 - headers: auth.
headers ,
338 - maxTokens: outputBudget,
340 - cacheRetention:
"none" ,
341 - sessionId:
uuidv7 (),
342 - reasoning: summarizerModel.reasoning
? "low" : undefined ,
339 + const stream
= provider.
streamSimple (
341 + buildSummarizerContext (allocated,
event .customInstructions),
343 + apiKey: auth.apiKey,
344 + headers: auth.
headers ,
346 + maxTokens: outputBudget,
348 + cacheRetention:
"none" ,
349 + sessionId:
uuidv7 (),
350 + reasoning: summarizerModel.reasoning
? "low" : undefined ,
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 ),
360 + const response
= await stream.
result ();
346 361 if (response.stopReason
!== "stop" )
348 363 `Decay summarizer stopped with ${response.stopReason}: ${response.errorMessage ?? "no detail"}` ,
356 371 prose
+ formatFileAppendix (files.readFiles, files.modifiedFiles);
357 372 const elapsedMs
= Date .
now ()
- startedAt;
373 + const estimatedKeptTokens
= estimateKeptTokens (
event );
360 376 usage:
combineUsage (classifierUsage, response.usage),
361 377 estimatedTokensAfter:
362 - Math .
ceil (summary.
length / 4 )
+ 363 - event .preparation.settings.keepRecentTokens,
378 + estimatedKeptTokens
=== undefined 380 + : Math .
ceil (summary.
length / 4 )
+ estimatedKeptTokens,
366 383 version: DECAY_DETAILS_VERSION,
369 386 chunkCount : chunks.
length ,
370 387 keepRecentTokens :
event .preparation.settings.keepRecentTokens,
388 + ... (estimatedKeptTokens
=== undefined ? {}
: { estimatedKeptTokens }),
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" ;
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" ;
26 26 export interface DecayDisplayState {
28 28 inputTokens
: number ;
29 + keptTokens
: number | undefined ;
30 30 totalChunks
: number ;
31 31 phase
: "classify" | "merge" ;
32 32 transfers
: DisplayTransfer [];
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);
54 + const keys
= new Set (
55 + record.atoms.
map ((atom)
=> 56 + atom.key.
trim ().
toLowerCase ().
replace (
/\s + / g ,
" " ),
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;
106 + state.phase
=== "classify" 107 + ? `CLASSIFY ${state.transfers. length }/${state.totalChunks}` 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);
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" );
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 );
127 + `INPUT ${state.inputTokens. toLocaleString ("en-US")}` .
slice (
0 , leftWidth),
130 + put (canvas,
Math .
max (
2 , width
- controls.
length - 2 ),
5 , controls,
"dim" );
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" );
104 - function renderNormal (
106 - state
: DecayDisplayState ,
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" );
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" );
141 - `${ compactTokens (state.keptTokens)} KEPT` ,
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 );
153 - "·" .
repeat (
Math .
max (
0 , laneEnd
- laneStart)),
156 - put (canvas, laneEnd,
3 ,
"▶" ,
"recent" );
157 - const latest
= state.transfers.
at (
- 1 );
159 - const progress
= clamp ((now
- latest.acceptedAt)
/ TRANSFER_MS,
0 ,
1 );
160 - if (progress
< 1 ) {
161 - const x
= Math .
round (laneStart
+ (laneEnd
- laneStart)
* progress);
166 - SPIN[frame
% SPIN.
length ],
167 - latest.recurring
? "recurring" : latest.kind,
170 - }
else if (state.phase
=== "merge" ) {
171 - const span
= Math .
max (
1 , laneEnd
- laneStart);
174 - laneStart
+ (frame
% span),
176 - SPIN[frame
% SPIN.
length ],
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
++ ) {
162 + ((x
- historyStart)
* state.totalChunks)
/ Math .
max (
1 , capacity),
164 + const last
= Math .
max (
167 + ((x
- historyStart
+ 1 )
* state.totalChunks)
/ Math .
max (
1 , capacity),
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" );
179 + state.keptTokens
=== undefined 181 + : compactTokens (
Math .
max (
0 , state.inputTokens
- state.keptTokens));
186 + ` HISTORY ${history} ` .
slice (
0 , capacity),
193 + ` ${ compactTokens (state.keptTokens)} KEPT ` .
slice (
0 , tailWidth
- 1 ),
186 - function renderShort (
198 + function renderTransfer (
187 199 canvas
: Cell [][],
188 201 state
: DecayDisplayState ,
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" ;
213 + `MERGING ${state.mergeAtoms ?? 0} atoms → summary · ${output}` ,
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),
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 );
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,
225 - SPIN[frame
% SPIN.
length ],
226 - latest.recurring
? "recurring" : latest.kind,
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);
229 + SPIN[frame
% SPIN.
length ],
230 + transfer.recurring
? "recurring" : transfer.kind,
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 (
236 - width
- summaryStart
- controls.
length - 2 ,
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 [][],
247 240 state
: DecayDisplayState ,
250 - const width
= canvas[
0 ].
length ;
251 - put (canvas,
2 , y,
"SUMMARY [" ,
"dim" );
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 (
264 - state
: DecayDisplayState ,
267 - const latest
= state.transfers.
at (
- 1 );
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) {
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,
247 + if (state.phase
!== "merge" && now
- transfer.acceptedAt
< TRANSFER_MS)
252 + ((transfer.chunk
- 1 )
/ Math .
max (
1 , state.totalChunks))
* capacity,
277 - start
+ clamp (index,
0 , capacity
- 1 ),
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
265 + : state.phase
=== "merge" 266 + ? " SUMMARY · blending " 268 + const blendStart
= start
+ label.
length ;
269 + const blendWidth
= end
- blendStart;
270 + if (state.phase
=== "merge" && blendWidth
> 0 ) {
272 + const frame
= Math .
floor (
Math .
max (
0 , now
- state.startedAt)
/ 110 );
273 + for (
let offset
= 0 ; offset
< Math .
min (
5 , blendWidth); offset
++ ) {
276 + blendStart
+ ((frame
+ offset)
% blendWidth),
278 + [
"░" ,
"▒" ,
"▓" ,
"▒" ,
"░" ][offset],
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 ;
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 [
294 - [
"▒" ,
"established" ],
297 - [
"◆" ,
"recurring" ],
299 - const index
= legend.
indexOf (glyph);
300 - if (index
>= 0 )
put (canvas,
2 + index, y, glyph, color);
304 - function renderStatus (
307 - state
: DecayDisplayState ,
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" );
318 - function fillHistory (
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);
338 - for (
let x
= start; x
< end; x
++ ) {
339 - put (canvas, x, y, x
% 7 === 0 ? "█" : "▓" ,
"recent" );
343 - function sourcePosition (
344 - separatorX
: 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}` 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 (
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" );
392 312 canvas
: Cell [][],
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" ;
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 [] {
438 345 return theme.
bold (theme.
fg (
"success" , text));
347 + return theme.
bg (
"selectedBg" , theme.
bold (theme.
fg (
"text" , text)));
441 350 return theme.
fg (
"text" , text);
446 355 case "established" :
447 356 return theme.
fg (
"borderAccent" , text);
358 + return theme.
fg (
"muted" , text);
450 360 return theme.
fg (
"dim" , text);