pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Compare Notes Search fix(goal): prune resumed failure context 5111ce5be551dd8bd5e207895ff78b7f40a486e6
Review <review@example.invalid > · 16 Jun 2026
unsigned
Browse files Compare with HEAD
- defer to Pi auto-retry and pause after retry exhaustion
- drop goal transcript rows and persisted assistant failures from active goal context
- keep compact goal widget to one truncated line
Checks:
- mise run test -- extensions/goal
- mise run lint
- mise run check
- pre-commit hook: mise run fmt, lint, test
Changed files (4) 19 19 - Let Pi core handle `context_length_exceeded` auto-compaction/retry; goal records
20 20 context-overflow event/UI state without starting a duplicate `ctx.compact` flow
21 - - Pause the goal loop only on terminal errors: auth (401/403), quota
22 - (insufficient credit/billing), bad_request (400), and `stopReason === "aborted"`
21 + - Defer goal-owned retries while Pi core auto-retry attempts remain, then pause
22 + after Pi retry exhaustion instead of starting another continuation loop
23 + - Prune goal transcript rows and persisted assistant failure messages from active
24 + goal LLM context so reload/resume cannot resurrect failed retry payloads
25 + - Pause the goal loop on terminal errors (auth 401/403, quota,
26 + bad_request 400, `stopReason === "aborted"`) and after Pi core retry exhaustion
23 27 - Derive user-facing `lastReason` and notifications from the classifier instead
24 28 of raw API JSON, while keeping raw errors in `goal-event` entries for debugging
25 29 - Bump TypeScript dev dependency to 6.0.3
47 51 - Update brainstorming companion test coverage for the current arrow-function
48 52 `toggleSelect` output
49 53 - Render TLDR widget as icon-prefixed padded lines instead of a boxed panel
50 - - Render goal widget as compact/expanded icon-prefixed lines that wrap instead
54 + - Render expanded goal widget as icon-prefixed wrapped lines while keeping the
55 + compact/collapsed goal widget to one width-truncated line
52 56 - Preserve goal elapsed time across criteria/mode changes and pause/resume, keep
53 57 retryable errors running, and clear stale errors on resume or successful retry
extensions/goal/__tests__/integration-full.test.ts Modified 8 8 } from
"@marcfargas/pi-test-harness" ;
9 - import { afterEach, beforeEach, describe, expect, it }
from "vitest" ;
9 + import { afterEach, beforeEach, describe, expect, it, vi }
from "vitest" ;
10 10 import goalExtension, { __goalTest, GOAL_PROBE_MESSAGE }
from "../index.ts" ;
12 12 let t
: TestSession | undefined ;
585 585 it (
"retries WebSocket 1006 transport errors instead of pausing" ,
async ()
=> {
586 586 t
= await createGoalSession ();
587 + mkdirSync (
join (t.cwd,
".pi" ), { recursive:
true });
589 + join (t.cwd,
".pi" ,
"settings.json" ),
590 + JSON .
stringify ({ retry: { enabled:
false } }),
587 592 installSaysErrorStream (t,
"WebSocket closed 1006 Connection ended" );
589 594 await t.session.
prompt (
"/goal survive websocket drop" );
597 602 expect (
latestGoal ()?.lastReason).
toContain (
"transport error" );
605 + it (
"does not dispatch goal retry while Pi auto-retry delay is pending" ,
async ()
=> {
606 + process .
env .PI_GOAL_LOG
= "1" ;
607 + vi.
useFakeTimers ();
609 + t
= await createGoalSession ();
610 + mkdirSync (
join (t.cwd,
".pi" ), { recursive:
true });
612 + join (t.cwd,
".pi" ,
"settings.json" ),
613 + JSON .
stringify ({ retry: { enabled:
true , maxRetries:
1 } }),
615 + t.session.settingsManager.
applyOverrides ({
616 + retry: { enabled:
true , maxRetries:
1 , baseDelayMs:
10_000 },
618 + installSaysErrorStream (t,
"500 server error" );
620 + const run
= t.session.
prompt (
"/goal survive transient server error" );
621 + await vi.
waitFor (()
=> {
623 + t?.events.
all .
some ((event)
=> event .
type === "auto_retry_start" ),
627 + await vi.
advanceTimersByTimeAsync (
4_000 );
630 + customEvents (
"goal-debug" ).
map ((entry)
=> entry.
event ),
631 + ).not.
toContain (
"continuation-dispatched" );
633 + t.events.
all .
filter ((event)
=> event .
type === "agent_start" ),
636 + await vi.
advanceTimersByTimeAsync (
6_000 );
639 + expect (
latestGoal ()).
toMatchObject ({
640 + objective:
"survive transient server error" ,
642 + lastVerdict:
"error" ,
643 + lastReason:
"retry exhausted: server error" ,
646 + customEvents (
"goal-debug" ).
map ((entry)
=> entry.
event ),
647 + ).not.
toContain (
"continuation-dispatched" );
649 + vi.
clearAllTimers ();
650 + vi.
useRealTimers ();
600 654 it (
"pauses only on auth errors with human-readable reason" ,
async ()
=> {
601 655 t
= await createGoalSession ();
602 656 installSaysErrorStream (t,
"401 Unauthorized" );
extensions/goal/__tests__/unit.test.ts Modified 132 132 expect (pruned.
at (
1 )).
toBe (messages[
3 ]);
135 + it (
"removes goal transcript rows and persisted assistant failures from active goal context" , ()
=> {
136 + const state
= goal ({ status:
"active" })
as never ;
138 + { role:
"user" , content:
"start" },
141 + content:
"500 unknown error" ,
142 + stopReason:
"error" ,
144 + { role:
"custom" , customType:
"goal-judge" , content:
"judge row" },
145 + { role:
"custom" , customType:
"goal-event" , content:
"event row" },
148 + customType:
"goal-continuation" ,
149 + details: { goalId:
"goal-1" },
153 + customType:
"goal-continuation" ,
154 + details: { goalId:
"goal-1" },
158 + const pruned
= __goalTest.
pruneGoalContextMessages (messages, state);
160 + expect (pruned).
toEqual ([messages[
0 ], messages[
5 ]]);
135 163 it (
"parses model refs and rejects invalid refs" , ()
=> {
136 164 expect (__goalTest.
parseModelRef (
"provider/model/name" )).
toEqual ({
137 165 provider:
"provider" ,
211 239 __goalTest.
goalCompactWidgetLine (
goal ()
as never ,
"normal" ,
96 ),
212 240 ).
toContain (
"alt+g expand" );
241 + const compactLines = (
242 + __goalTest
as typeof __goalTest
& {
243 + goalCompactWidgetLines : (
249 + ).
goalCompactWidgetLines (
251 + objective:
"Ship the feature with enough detail to need truncation" ,
253 + { turn:
1 , label:
"continue" , reason:
"needs tests" },
254 + { turn:
2 , label:
"blocked" , reason:
"needs credentials" },
260 + expect (compactLines).
toHaveLength (
1 );
261 + expect (compactLines[
0 ]).
toContain (
"…" );
213 262 expect (__goalTest.
insetWidgetLine (
"goal active" ,
30 )).
toBe (
extensions/goal/index.ts Modified 6 6 type ExtensionContext ,
10 11 } from
"@earendil-works/pi-coding-agent" ;
258 259 type GoalWidgetMode = "compact" | "expanded" ;
260 261 type SettingsAPI = ExtensionAPI & {
261 - settingsManager
?: {
getSettings ()
: Record <
string ,
unknown >
| undefined };
262 + settingsManager
?: {
getSettings ? ()
: Record <
string ,
unknown >
| undefined };
264 265 function isRecord (value
: unknown )
: value
is Record <
string ,
unknown > {
931 932 return `${classified.short}: ${classified.detail}.${classified.hint ? ` ${classified.hint}.` : ""}` ;
935 + type PiRetryState = "none" | "pending" | "exhausted" ;
937 + function piRetryState (
938 + ctx
: ExtensionContext ,
939 + evidence
: TurnEvidence | undefined ,
940 + deferredRetries
: number ,
942 + if (evidence?.stopReason
!== "error" )
return "none" ;
943 + const retry
= SettingsManager.
create (
946 + ).
getRetrySettings ();
947 + if (
! retry.enabled
|| retry.maxRetries
<= 0 )
return "none" ;
948 + const classified
= classifyError (evidence.errorMessage);
949 + if (
! classified.retryable
|| classified.kind
=== "context_overflow" )
951 + return deferredRetries
< retry.maxRetries
? "pending" : "exhausted" ;
934 954 function recoveredAgentErrorPatch (
935 955 state
: GoalState ,
936 956 evidence
: TurnEvidence | undefined ,
1318 1338 mode : GoalUiMode,
1319 1339 width
= GOAL_WIDGET_DEFAULT_WIDTH,
1321 - return goalCompactWidgetLines (state, mode, width)[
0 ]
?? "" ;
1342 + state.criteria.
length === 0 ? "" : ` · ${state.criteria. length }c` ;
1343 + const reason
= state.lastReason
1344 + ? ` · ${ verdictGlyph (state.lastVerdict)} ${ sanitizeGoalText (state.lastReason, 48)}` 1346 + return truncateToWidth (
1347 + `${GOAL_ICON} ${ footerPhaseText (state, mode)} · alt+g expand · ${ budgetText (state)}${criteria} · ${ sanitizeGoalText (state.objective, 160)}${reason}` ,
1348 + Math .
max (
0 , width),
1324 1353 function goalCompactWidgetLines (
1326 1355 mode : GoalUiMode,
1327 1356 width
= GOAL_WIDGET_DEFAULT_WIDTH,
1330 - state.criteria.
length === 0 ? "" : ` · ${state.criteria. length }c` ;
1332 - state.lastVerdict
=== "error" && state.lastReason
1333 - ? ` · ! ${state.lastReason}` 1335 - return goalIconWrap (
1337 - `${ footerPhaseText (state, mode)} · alt+g expand · ${ budgetText (state)}${criteria} · ${state.objective}${error}` ,
1338 - ... (state.verdicts
?? []).
map (
1339 - (verdict, index)
=> 1340 - `verdict ${index + 1}: ${ verdictGlyph (verdict. label )} ${verdict.reason}` ,
1358 + return [
goalCompactWidgetLine (state, mode, width)];
1347 1361 function updateWidget (ctx
: ExtensionContext )
: void {
2349 + const GOAL_TRANSCRIPT_MESSAGE_TYPES
= new Set ([
2352 + GOAL_COMPACTION_ENTRY,
2355 + function isAssistantErrorMessage (msg
: Record <
string ,
unknown >)
: boolean {
2356 + if (msg.role
!== "assistant" )
return false ;
2357 + const stopReason
= msg.stopReason;
2358 + return stopReason
=== "error" || stopReason
=== "aborted" ;
2361 + function pruneGoalContextMessages (
2362 + messages
: Array <
Record <
string ,
unknown >>,
2363 + state
: GoalState | undefined ,
2364 + )
: Array <
Record <
string ,
unknown >> {
2365 + const goalIsActive
= state?.
status === "active" ;
2366 + return pruneContinuationMessages (
2367 + messages.
filter ((msg)
=> {
2368 + if (goalIsActive
&& isAssistantErrorMessage (msg))
return false ;
2370 + msg.role
=== "custom" && 2371 + typeof msg.customType
=== "string" && 2372 + GOAL_TRANSCRIPT_MESSAGE_TYPES.
has (msg.customType)
2335 2382 function safeUpdateUI (
2336 2383 pi
: ExtensionAPI ,
2337 2384 ctx
: ExtensionContext ,
2527 2574 let state
: GoalState | undefined ;
2528 2575 const continuation
: ContinuationState = { queued:
false , scheduled:
false };
2576 + let piRetryDeferrals
= 0 ;
2529 2577 let removeTerminalInput
: (()
=> void )
| undefined ;
2530 2578 let promptTemplates
: GoalPromptTemplate []
= [];
2531 2579 let probe
: ProbeState | undefined ;
2663 2711 pi.
on (
"context" , (event)
=> {
2665 - messages:
pruneContinuationMessages (
2713 + messages:
pruneGoalContextMessages (
2666 2714 event .messages
as never ,
2732 2780 syncUpdateGoalTool ();
2733 2781 if (
! state
|| state.
status !== "active" || ! ownsGoal (ctx, state))
return ;
2734 2782 const evidence
= lastTurnEvidence;
2783 + const piRetry
= piRetryState (ctx, evidence, piRetryDeferrals);
2784 + if (piRetry
=== "pending" ) {
2785 + piRetryDeferrals
++ ;
2788 + piRetryDeferrals
= 0 ;
2735 2789 const settings
= loadSettings (pi);
2736 2790 let dossier
= ensureDossier (pi, ctx, state);
2737 2791 dossier
= appendTurnEvidenceToDossier (
2838 + if (piRetry
=== "exhausted" ) {
2839 + state
= updateGoal (pi, state, {
2841 + lastVerdict:
"error" ,
2842 + lastReason:
`retry exhausted: ${classified.short}` ,
2843 + timeUsedSeconds:
currentElapsedSeconds (state),
2845 + appendGoalEvent (pi, ctx,
"paused" , state, {
2846 + reason: state.lastReason,
2847 + raw: errorMessage,
2848 + kind: classified.kind,
2850 + renderGoalUi (ctx, state);
2851 + syncUpdateGoalTool ();
2853 + ctx.ui.
notify (
`Goal paused — ${state.lastReason}` ,
"warning" );
2784 2857 if (classified.retryable) {
2785 2858 state
= updateGoal (pi, state, {
2786 2859 errorRetries: retries,
3224 3297 compactStatusLine,
3226 3299 pruneContinuationMessages,
3300 + pruneGoalContextMessages,
3229 3303 textFromContent,
3249 3323 wrapVisibleWords,
3251 3325 goalCompactWidgetLine,
3326 + goalCompactWidgetLines,
3252 3327 liveDisplayState,
3253 3328 syncLiveGoalTimer,