pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Reviews Compare Notes Search Review guide CI runs fix(goal): harden widget and judge loop
6b826fbab5819a19e5f7ed7f3506c4f6ed7bfff1
Oliver Jan Krylow <oliver@bugabinga.net > · 27 May 2026
unsigned
Browse files Compare with HEAD
Changed files (3) Diff layout Auto Unified Split
extensions/goal/__tests__/harness.test.ts Modified +92 / −1 text lines
49 + function errorEvent (message: string ) {51 + type: "error" as const ,52 + reason: "error" as const ,54 + role: "assistant" as const ,56 + api: "openai-responses" as const ,65 + cost: { input: 0 , output: 0 , cacheRead: 0 , cacheWrite: 0 , total: 0 },67 + stopReason: "error" as const ,68 + errorMessage: message,69 + timestamp: Date .now (),49 74 function installSaysStream (session: TestSession , replies: string []) {function installSaysStream (session: TestSession , replies: string []) {50 75 const queue = [... replies]; const queue = [... replies];51 76 session.session.agent.streamFn = () => { session.session.agent.streamFn = () => {
164 + function installJudgeErrorProvider (message: string ) {165 + const previousProvider = getApiProvider ("openai-responses" );166 + registerApiProvider (168 + api: "openai-responses" ,170 + const stream = createAssistantMessageEventStream ();171 + queueMicrotask (() => stream.push (errorEvent (message)));174 + streamSimple : () => {175 + throw new Error ("not used" );181 + if (previousProvider)182 + registerApiProvider (previousProvider, "goal-test-restore" );139 186 async function runProbe (async function runProbe (140 187 mode: "direct" | "microtask" | "timeout" , mode: "direct" | "microtask" | "timeout" ,141 188 expectedAgentEnds: number , expectedAgentEnds: number ,178 225 expect (result.text ).toContain ("Tool update_goal not found" ); expect (result.text ).toContain ("Tool update_goal not found" );179 226 expect (latestGoal ()).toMatchObject ({ expect (latestGoal ()).toMatchObject ({180 227 objective: "ship it" , objective: "ship it" ,
230 + expect (latestGoal ()?.lastReason).toStartWith ("judge failed:" );185 233 it ("update_goal is unavailable without active judged goal" , async () => { it ("update_goal is unavailable without active judged goal" , async () => {
421 + it ("surfaces judge provider errors instead of reporting empty response" , async () => {422 + const restore = installJudgeErrorProvider ("403 quota exhausted" );424 + t = await createTestSession ({ extensions: [goalPath ()] });425 + installSaysStream (t, ["work done" ]);427 + await t.session.prompt ("/goal quota judge" );428 + await waitFor (() => latestGoal ()?.status === "paused" );430 + expect (latestGoal ()).toMatchObject ({431 + objective: "quota judge" ,433 + lastReason: "judge failed: 403 quota exhausted" ,440 + it ("pauses instead of continuing when judge fails after retries" , async () => {441 + const restore = installJudgeProvider (["" , "" ]);443 + t = await createTestSession ({ extensions: [goalPath ()] });444 + installSaysStream (t, ["work done" ]);446 + await t.session.prompt ("/goal flaky judge" );447 + await waitFor (() => latestGoal ()?.status === "paused" );448 + await new Promise ((resolve) => setTimeout (resolve, 25 ));450 + expect (latestGoal ()).toMatchObject ({451 + objective: "flaky judge" ,454 + lastReason: "judge failed: judge returned empty response" ,457 + t.events.all .filter ((event) => event .type === "agent_start" ),373 464 it ("judge blocked verdict blocks goal" , async () => { it ("judge blocked verdict blocks goal" , async () => {374 465 const restore = installJudgeProvider ([ const restore = installJudgeProvider ([375 466 '{"done":false,"blocked":true,"reason":"needs credentials"}' , '{"done":false,"blocked":true,"reason":"needs credentials"}' ,extensions/goal/__tests__/unit.test.ts Modified +34 / −0 text lines
111 111 it ("formats judge reasons as bounded one-line text" , () => { it ("formats judge reasons as bounded one-line text" , () => {112 112 expect (__goalTest.judgeDisplayReason (" a\n\t b " )).toBe ("a b" ); expect (__goalTest.judgeDisplayReason (" a\n\t b " )).toBe ("a b" );
113 + expect (__goalTest.judgeDisplayReason ("\u001b[31mred\u001b[0m\u0007" )).toBe (113 116 const reason = __goalTest.judgeDisplayReason ("x" .repeat (200 )); const reason = __goalTest.judgeDisplayReason ("x" .repeat (200 ));114 117 expect (reason).toHaveLength (160 ); expect (reason).toHaveLength (160 );115 118 expect (reason.endsWith ("…" )).toBe (true ); expect (reason.endsWith ("…" )).toBe (true );
121 + it ("renders compact goal widget boxes with usage-style progress" , () => {123 + __goalTest.goalBar (goal ({ turnsUsed: 2 , maxTurns: 5 }) as never ),124 + ).toBe ("━━━━──────" );126 + __goalTest.goalWidgetLines (127 + goal ({ lastReason: "needs tests" }) as never ,132 + "╭ goal active 2/5 · 2c ────────────────────────╮" ,133 + "│ objective Ship the feature │" ,134 + "│ turns 2/5 ━━━━────── 40% │" ,135 + "│ judge needs tests │" ,136 + "╰──────────────────────────────────────────────╯" ,138 + expect (__goalTest.goalWidgetLines (goal () as never , "judging" , 40 )).toEqual ([139 + "╭ goal judging 3/5 · 2c ───────────────╮" ,140 + "│ objective Ship the feature │" ,142 + "╰──────────────────────────────────────╯" ,144 + expect (__goalTest.insetWidgetLine ("╭ goal active ╮" , 30 )).toBe (147 + expect (__goalTest.goalJudgeMessageLine ("goal judge done" )).toBe (148 + " ◇ goal judge done" ,118 152 it ("parses judge JSON strictly" , () => { it ("parses judge JSON strictly" , () => {120 154 __goalTest.parseJudge ( __goalTest.parseJudge (extensions/goal/index.ts Modified +162 / −29 text lines
6 6 } from "@earendil-works/pi-coding-agent" ;} from "@earendil-works/pi-coding-agent" ;8 8 type AutocompleteItem, type AutocompleteItem,10 11 truncateToWidth, truncateToWidth,11 13 } from "@earendil-works/pi-tui" ;} from "@earendil-works/pi-tui" ;12 14 import { Type } from "typebox" ;import { Type } from "typebox" ;64 66 const CONTINUATION_RETRY_MS = 250 ;const CONTINUATION_RETRY_MS = 250 ;65 67 const CONTINUATION_MAX_ATTEMPTS = 20 ;const CONTINUATION_MAX_ATTEMPTS = 20 ;66 68 const JUDGE_ATTEMPTS = 2 ;const JUDGE_ATTEMPTS = 2 ;
69 + const ANSI_RE = /\x1b\[[0-?] * [ -/] * [@-~]/ g ;70 + const CONTROL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/ g ;71 + const GOAL_WIDGET_LABEL_WIDTH = 11 ;72 + const GOAL_WIDGET_MAX_WIDTH = 78 ;73 + const GOAL_WIDGET_LEFT_PADDING = 1 ;67 74 const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge. const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge. 68 75 Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}. Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}. 69 76 Mark done only if the latest assistant response explicitly proves the objective and every criterion are complete. Mark done only if the latest assistant response explicitly proves the objective and every criterion are complete. 210 217 return oneLine.length <= max ? oneLine : `${oneLine. slice (0, max - 1)}…` ; return oneLine.length <= max ? oneLine : `${oneLine. slice (0, max - 1)}…` ;
220 + function sanitizeGoalText (text: string , max = 160 ): string {222 + text.replace (ANSI_RE, "" ).replace (CONTROL_RE, " " ).replace (/\s + / g , " " ),213 227 function judgeDisplayReason (reason: string ): string {function judgeDisplayReason (reason: string ): string {214 - return shortText (reason, 160 );228 + return sanitizeGoalText (reason, 160 );217 231 function judgeVerdictLabel (function judgeVerdictLabel (222 236 return "continue" ; return "continue" ;
239 + function isJudgeFailure (verdict: JudgeVerdict ): boolean {240 + return verdict.reason.startsWith ("judge failed:" );225 243 function judgeRunningText (state: GoalState ): string {function judgeRunningText (state: GoalState ): string {226 244 const criteria = const criteria = 227 245 state.criteria.length === 0 ? "" : ` · ${state.criteria. length } criteria` ; state.criteria.length === 0 ? "" : ` · ${state.criteria. length } criteria` ;273 291 return "accent" ; return "accent" ;276 - function goalIcon (state: GoalState , mode: GoalUiMode ): string {277 - if (mode === "judging" ) return "…" ;278 - if (state.status === "complete" ) return "✓" ;279 - if (state.status === "blocked" ) return "!" ;280 - if (state.status === "paused" ) return "‖" ;
284 294 function goalProgress (state: GoalState ): number {function goalProgress (state: GoalState ): number {285 295 return state.maxTurns <= 0 return state.maxTurns <= 0 296 306 Math .min (width, Math .round ((goalProgress (state) / 100 ) * width)), Math .min (width, Math .round ((goalProgress (state) / 100 ) * width)),298 - return "█" .repeat (filled) + "░" .repeat (width - filled);308 + return "━" .repeat (filled) + "─" .repeat (width - filled);311 + function padVisible (text: string , width: number ): string {312 + return text + " " .repeat (Math .max (0 , width - visibleWidth (text)));315 + function fitVisible (text: string , width: number ): string {316 + return padVisible (truncateToWidth (text, width, "…" ), width);319 + function goalWidgetRow (324 + const labelText = fitVisible (label, GOAL_WIDGET_LABEL_WIDTH);325 + const valueWidth = Math .max (0 , innerWidth - GOAL_WIDGET_LABEL_WIDTH);326 + return `│ ${labelText}${ fitVisible (value, valueWidth)} │` ;329 + function insetWidgetLine (line: string , width: number ): string {330 + if (width <= 0 ) return "" ;331 + return ` ${ truncateToWidth (line, Math . max (0, width - GOAL_WIDGET_LEFT_PADDING), "…")}` ;334 + function goalJudgeMessageLine (content: string ): string {335 + return ` ◇ ${content}` ;338 + function goalWidgetLines (341 + width = GOAL_WIDGET_MAX_WIDTH,343 + const boxWidth = Math .max (345 + Math .min (GOAL_WIDGET_MAX_WIDTH, Math .max (0 , width)),347 + const innerWidth = boxWidth - 4 ;349 + state.criteria.length === 0 ? "" : ` · ${state.criteria. length }c` ;350 + const title = truncateToWidth (351 + ` goal ${ goalPhaseText (state, mode)}${criteria} ` ,355 + const top = `╭${title}${"─". repeat ( Math . max (0, boxWidth - visibleWidth (title) - 2))}╮` ;360 + sanitizeGoalText (state.objective, 120 ),364 + if (mode === "judging" ) {368 + `${state.turnsUsed + 1}/${state.maxTurns}` ,372 + } else if (showsTurnBudget (state)) {376 + `${state.turnsUsed}/${state.maxTurns} ${ goalBar (state)} ${ goalProgress (state)}%` ,381 + if (state.lastReason)383 + goalWidgetRow ("judge" , judgeDisplayReason (state.lastReason), innerWidth),385 + lines.push (`╰${"─". repeat (boxWidth - 2)}╯` );301 389 function goalPhaseText (state: GoalState , mode: GoalUiMode ): string {function goalPhaseText (state: GoalState , mode: GoalUiMode ): string {326 414 invalidate () {}, invalidate () {},327 415 render (width: number): string[] { render (width: number): string[] {328 416 const tone = goalTone (shown, mode); const tone = goalTone (shown, mode);330 - shown.criteria.length === 0 ? "" : ` · ${shown.criteria. length }c` ;331 - const turns = showsTurnBudget (shown)332 - ? ` · ${ goalBar (shown)} ${ goalProgress (shown)}%` 334 - const header = `${theme. fg (tone, goalIcon (shown, mode))} ${theme. fg (tone, theme. bold ("goal"))} ${theme. fg (tone, goalPhaseText (shown, mode))}${theme. fg ("dim", criteria)}${theme. fg ("dim", turns)}` ;337 - theme.fg ("dim" , "objective: " ) + shown.objective,339 - if (shown.lastReason)340 - lines.push (theme.fg ("dim" , "judge: " ) + shown.lastReason);341 - return lines.map ((line) => truncateToWidth (line, width, "…" ));417 + const lines = goalWidgetLines (420 + Math .max (0 , width - GOAL_WIDGET_LEFT_PADDING),422 + return lines.map ((rawLine) => 423 + theme.fg (tone, insetWidgetLine (rawLine, width)),344 427 { placement : "aboveEditor" }, { placement : "aboveEditor" },618 701 reasoning : "off" , reasoning : "off" ,619 702 cacheRetention : "none" , cacheRetention : "none" ,
704 + if (response.stopReason === "error" || response.stopReason === "aborted" )706 + response.errorMessage || `judge ${response.stopReason}` ,621 708 const raw = response.content const raw = response.content 623 710 (part): part is { type: "text" ; text: string } => (part): part is { type: "text" ; text: string } =>
729 + function cancelGoalRun (731 + ctx: ExtensionContext ,732 + state: GoalState | undefined ,733 + ): GoalState | undefined {734 + if (! state || state.status !== "active" || ! ownsGoal (ctx, state))736 + const next = updateGoal (pi, state, {738 + lastReason: "cancelled by user" ,740 + updateUI (pi, ctx, next);741 + setToolActive (pi, "update_goal" , false );742 + if (ctx.hasUI) ctx.ui.notify ("Goal cancelled" , "warning" );642 746 function sendWhenIdle (function sendWhenIdle (643 747 pi: ExtensionAPI , pi: ExtensionAPI ,644 748 ctx: ExtensionContext , ctx: ExtensionContext ,740 844 : verdict?.blocked : verdict?.blocked741 845 ? "warning" ? "warning" 742 846 : "accent" ; : "accent" ;743 - return new Text (theme.fg (color, `◇ ${message. content }` ), 0 , 0 );848 + theme.fg (color, goalJudgeMessageLine (message.content )),746 854 let state: GoalState | undefined ; let state: GoalState | undefined ;747 855 const continuationScheduled = { value: false }; const continuationScheduled = { value: false };
856 + let removeTerminalInput: (() => void ) | undefined ;748 857 let probe: ProbeState | undefined ; let probe: ProbeState | undefined ;749 858 const syncUpdateGoalTool = () => const syncUpdateGoalTool = () => 750 859 setToolActive (pi, "update_goal" , canUseUpdateGoal (state)); setToolActive (pi, "update_goal" , canUseUpdateGoal (state));752 861 pi.on ("session_start" , (_event, ctx) => { pi.on ("session_start" , (_event, ctx) => {753 862 state = latestGoalState (ctx); state = latestGoalState (ctx);
863 + removeTerminalInput ?.();864 + removeTerminalInput = ctx.hasUI865 + ? ctx.ui.onTerminalInput ((data) => {866 + if (matchesKey (data, "escape" )) {867 + state = cancelGoalRun (pi, ctx, state);868 + continuationScheduled.value = false ;754 873 updateUI (pi, ctx, state); updateUI (pi, ctx, state);755 874 syncUpdateGoalTool (); syncUpdateGoalTool ();788 907 pi.on ("session_shutdown" , (_event, ctx) => { pi.on ("session_shutdown" , (_event, ctx) => {
908 + removeTerminalInput ?.();909 + removeTerminalInput = undefined ;789 910 updateUI (pi, ctx, undefined ); updateUI (pi, ctx, undefined );790 911 setToolActive (pi, "update_goal" , false ); setToolActive (pi, "update_goal" , false );826 947 if (state !== judged || state.status !== "active" ) return ; if (state !== judged || state.status !== "active" ) return ;827 948 appendJudge (pi, "verdict" , judged, verdict); appendJudge (pi, "verdict" , judged, verdict);828 - if (ctx.hasUI && verdict.reason.startsWith ("judge failed:" ))830 - `Goal judge verdict: continue · ${verdict.reason}` ,949 + if (isJudgeFailure (verdict)) {950 + state = updateGoal (pi, judged, {952 + lastReason: verdict.reason,954 + updateUI (pi, ctx, state);955 + syncUpdateGoalTool ();957 + ctx.ui.notify (`Goal paused — ${verdict.reason}` , "warning" );833 960 if (verdict.done) { if (verdict.done) {834 961 state = updateGoal (pi, judged, { state = updateGoal (pi, judged, {835 962 status: "complete" , status: "complete" ,1082 1209 continuationPrompt, continuationPrompt,1083 1210 criteriaText, criteriaText,1084 1211 goalArgumentCompletions, goalArgumentCompletions,
1213 + goalJudgeMessageLine,1085 1216 kickoffPrompt, kickoffPrompt,1086 1217 latestAssistantTail, latestAssistantTail,1087 1218 latestGoalState, latestGoalState,1088 1220 loadSettings, loadSettings,1089 1221 judgeRunningText, judgeRunningText,1090 1222 judgeDisplayReason, judgeDisplayReason,1091 1224 parseJudge, parseJudge,1092 1225 parseModelRef, parseModelRef,1093 1226 extractStandingGoalObjective, extractStandingGoalObjective,