repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(goal): harden widget and judge loop

6b826fbab5819a19e5f7ed7f3506c4f6ed7bfff1

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

+288 / −30 text lines

Diff layout

extensions/goal/__tests__/harness.test.ts

Modified

+92 / −1 text lines

4646 };
49function errorEvent(message: string) {
50 return {
51 type: "error" as const,
52 reason: "error" as const,
53 error: {
54 role: "assistant" as const,
55 content: [],
56 api: "openai-responses" as const,
57 provider: "test",
58 model: "playbook",
59 usage: {
60 input: 0,
61 output: 0,
62 cacheRead: 0,
63 cacheWrite: 0,
64 totalTokens: 0,
65 cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
66 },
67 stopReason: "error" as const,
68 errorMessage: message,
69 timestamp: Date.now(),
70 },
71 };
72}
4974function installSaysStream(session: TestSession, replies: string[]) {
5075 const queue = [...replies];
5176 session.session.agent.streamFn = () => {
136161 };
164function installJudgeErrorProvider(message: string) {
165 const previousProvider = getApiProvider("openai-responses");
166 registerApiProvider(
167 {
168 api: "openai-responses",
169 stream: () => {
170 const stream = createAssistantMessageEventStream();
171 queueMicrotask(() => stream.push(errorEvent(message)));
172 return stream;
173 },
174 streamSimple: () => {
175 throw new Error("not used");
176 },
177 },
178 "goal-test",
179 );
180 return () => {
181 if (previousProvider)
182 registerApiProvider(previousProvider, "goal-test-restore");
183 };
184}
139186async function runProbe(
140187 mode: "direct" | "microtask" | "timeout",
141188 expectedAgentEnds: number,
178225 expect(result.text).toContain("Tool update_goal not found");
179226 expect(latestGoal()).toMatchObject({
180227 objective: "ship it",
181 status: "active",
228 status: "paused",
182229 });
230 expect(latestGoal()?.lastReason).toStartWith("judge failed:");
183231 });
185233 it("update_goal is unavailable without active judged goal", async () => {
370418 }
371419 });
421 it("surfaces judge provider errors instead of reporting empty response", async () => {
422 const restore = installJudgeErrorProvider("403 quota exhausted");
423 try {
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",
432 status: "paused",
433 lastReason: "judge failed: 403 quota exhausted",
434 });
435 } finally {
436 restore();
437 }
438 });
440 it("pauses instead of continuing when judge fails after retries", async () => {
441 const restore = installJudgeProvider(["", ""]);
442 try {
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",
452 status: "paused",
453 turnsUsed: 0,
454 lastReason: "judge failed: judge returned empty response",
455 });
456 expect(
457 t.events.all.filter((event) => event.type === "agent_start"),
458 ).toHaveLength(1);
459 } finally {
460 restore();
461 }
462 });
373464 it("judge blocked verdict blocks goal", async () => {
374465 const restore = installJudgeProvider([
375466 '{"done":false,"blocked":true,"reason":"needs credentials"}',

extensions/goal/__tests__/unit.test.ts

Modified

+34 / −0 text lines

111111 it("formats judge reasons as bounded one-line text", () => {
112112 expect(__goalTest.judgeDisplayReason(" a\n\t b ")).toBe("a b");
113 expect(__goalTest.judgeDisplayReason("\u001b[31mred\u001b[0m\u0007")).toBe(
114 "red",
115 );
113116 const reason = __goalTest.judgeDisplayReason("x".repeat(200));
114117 expect(reason).toHaveLength(160);
115118 expect(reason.endsWith("…")).toBe(true);
116119 });
121 it("renders compact goal widget boxes with usage-style progress", () => {
122 expect(
123 __goalTest.goalBar(goal({ turnsUsed: 2, maxTurns: 5 }) as never),
124 ).toBe("━━━━──────");
125 expect(
126 __goalTest.goalWidgetLines(
127 goal({ lastReason: "needs tests" }) as never,
128 "normal",
129 48,
130 ),
131 ).toEqual([
132 "╭ goal active 2/5 · 2c ────────────────────────╮",
133 "│ objective Ship the feature │",
134 "│ turns 2/5 ━━━━────── 40% │",
135 "│ judge needs tests │",
136 "╰──────────────────────────────────────────────╯",
137 ]);
138 expect(__goalTest.goalWidgetLines(goal() as never, "judging", 40)).toEqual([
139 "╭ goal judging 3/5 · 2c ───────────────╮",
140 "│ objective Ship the feature │",
141 "│ turn 3/5 │",
142 "╰──────────────────────────────────────╯",
143 ]);
144 expect(__goalTest.insetWidgetLine("╭ goal active ╮", 30)).toBe(
145 " ╭ goal active ╮",
146 );
147 expect(__goalTest.goalJudgeMessageLine("goal judge done")).toBe(
148 " ◇ goal judge done",
149 );
150 });
118152 it("parses judge JSON strictly", () => {
119153 expect(
120154 __goalTest.parseJudge(

extensions/goal/index.ts

Modified

+162 / −29 text lines

66} from "@earendil-works/pi-coding-agent";
77import {
88 type AutocompleteItem,
9 matchesKey,
910 Text,
1011 truncateToWidth,
12 visibleWidth,
1113} from "@earendil-works/pi-tui";
1214import { Type } from "typebox";
6466const CONTINUATION_RETRY_MS = 250;
6567const CONTINUATION_MAX_ATTEMPTS = 20;
6668const JUDGE_ATTEMPTS = 2;
69const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
70const CONTROL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
71const GOAL_WIDGET_LABEL_WIDTH = 11;
72const GOAL_WIDGET_MAX_WIDTH = 78;
73const GOAL_WIDGET_LEFT_PADDING = 1;
6774const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge.
6875Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}.
6976Mark done only if the latest assistant response explicitly proves the objective and every criterion are complete.
210217 return oneLine.length <= max ? oneLine : `${oneLine.slice(0, max - 1)}…`;
220function sanitizeGoalText(text: string, max = 160): string {
221 return shortText(
222 text.replace(ANSI_RE, "").replace(CONTROL_RE, " ").replace(/\s+/g, " "),
223 max,
224 );
225}
213227function judgeDisplayReason(reason: string): string {
214 return shortText(reason, 160);
228 return sanitizeGoalText(reason, 160);
217231function judgeVerdictLabel(
222236 return "continue";
239function isJudgeFailure(verdict: JudgeVerdict): boolean {
240 return verdict.reason.startsWith("judge failed:");
241}
225243function judgeRunningText(state: GoalState): string {
226244 const criteria =
227245 state.criteria.length === 0 ? "" : ` · ${state.criteria.length} criteria`;
273291 return "accent";
276function 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 "‖";
281 return "●";
282}
284294function goalProgress(state: GoalState): number {
285295 return state.maxTurns <= 0
286296 ? 0
295305 0,
296306 Math.min(width, Math.round((goalProgress(state) / 100) * width)),
297307 );
298 return "█".repeat(filled) + "░".repeat(width - filled);
308 return "━".repeat(filled) + "─".repeat(width - filled);
309}
311function padVisible(text: string, width: number): string {
312 return text + " ".repeat(Math.max(0, width - visibleWidth(text)));
313}
315function fitVisible(text: string, width: number): string {
316 return padVisible(truncateToWidth(text, width, "…"), width);
317}
319function goalWidgetRow(
320 label: string,
321 value: string,
322 innerWidth: number,
323): string {
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)} │`;
327}
329function insetWidgetLine(line: string, width: number): string {
330 if (width <= 0) return "";
331 return ` ${truncateToWidth(line, Math.max(0, width - GOAL_WIDGET_LEFT_PADDING), "…")}`;
332}
334function goalJudgeMessageLine(content: string): string {
335 return ` ◇ ${content}`;
336}
338function goalWidgetLines(
339 state: GoalState,
340 mode: GoalUiMode,
341 width = GOAL_WIDGET_MAX_WIDTH,
342): string[] {
343 const boxWidth = Math.max(
344 28,
345 Math.min(GOAL_WIDGET_MAX_WIDTH, Math.max(0, width)),
346 );
347 const innerWidth = boxWidth - 4;
348 const criteria =
349 state.criteria.length === 0 ? "" : ` · ${state.criteria.length}c`;
350 const title = truncateToWidth(
351 ` goal ${goalPhaseText(state, mode)}${criteria} `,
352 boxWidth - 2,
353 "…",
354 );
355 const top = `╭${title}${"─".repeat(Math.max(0, boxWidth - visibleWidth(title) - 2))}╮`;
356 const lines = [
357 top,
358 goalWidgetRow(
359 "objective",
360 sanitizeGoalText(state.objective, 120),
361 innerWidth,
362 ),
363 ];
364 if (mode === "judging") {
365 lines.push(
366 goalWidgetRow(
367 "turn",
368 `${state.turnsUsed + 1}/${state.maxTurns}`,
369 innerWidth,
370 ),
371 );
372 } else if (showsTurnBudget(state)) {
373 lines.push(
374 goalWidgetRow(
375 "turns",
376 `${state.turnsUsed}/${state.maxTurns} ${goalBar(state)} ${goalProgress(state)}%`,
377 innerWidth,
378 ),
379 );
380 }
381 if (state.lastReason)
382 lines.push(
383 goalWidgetRow("judge", judgeDisplayReason(state.lastReason), innerWidth),
384 );
385 lines.push(`╰${"─".repeat(boxWidth - 2)}╯`);
386 return lines;
301389function goalPhaseText(state: GoalState, mode: GoalUiMode): string {
326414 invalidate() {},
327415 render(width: number): string[] {
328416 const tone = goalTone(shown, mode);
329 const criteria =
330 shown.criteria.length === 0 ? "" : ` · ${shown.criteria.length}c`;
331 const turns = showsTurnBudget(shown)
332 ? ` · ${goalBar(shown)} ${goalProgress(shown)}%`
333 : "";
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)}`;
335 const lines = [
336 header,
337 theme.fg("dim", "objective: ") + shown.objective,
338 ];
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(
418 shown,
419 mode,
420 Math.max(0, width - GOAL_WIDGET_LEFT_PADDING),
421 );
422 return lines.map((rawLine) =>
423 theme.fg(tone, insetWidgetLine(rawLine, width)),
424 );
342425 },
343426 }),
344427 { placement: "aboveEditor" },
618701 reasoning: "off",
619702 cacheRetention: "none",
620703 });
704 if (response.stopReason === "error" || response.stopReason === "aborted")
705 throw new Error(
706 response.errorMessage || `judge ${response.stopReason}`,
707 );
621708 const raw = response.content
622709 .filter(
623710 (part): part is { type: "text"; text: string } =>
639726 );
729function cancelGoalRun(
730 pi: ExtensionAPI,
731 ctx: ExtensionContext,
732 state: GoalState | undefined,
733): GoalState | undefined {
734 if (!state || state.status !== "active" || !ownsGoal(ctx, state))
735 return state;
736 const next = updateGoal(pi, state, {
737 status: "paused",
738 lastReason: "cancelled by user",
739 });
740 updateUI(pi, ctx, next);
741 setToolActive(pi, "update_goal", false);
742 if (ctx.hasUI) ctx.ui.notify("Goal cancelled", "warning");
743 return next;
744}
642746function sendWhenIdle(
643747 pi: ExtensionAPI,
644748 ctx: ExtensionContext,
740844 : verdict?.blocked
741845 ? "warning"
742846 : "accent";
743 return new Text(theme.fg(color, `◇ ${message.content}`), 0, 0);
847 return new Text(
848 theme.fg(color, goalJudgeMessageLine(message.content)),
849 0,
850 0,
851 );
744852 });
746854 let state: GoalState | undefined;
747855 const continuationScheduled = { value: false };
856 let removeTerminalInput: (() => void) | undefined;
748857 let probe: ProbeState | undefined;
749858 const syncUpdateGoalTool = () =>
750859 setToolActive(pi, "update_goal", canUseUpdateGoal(state));
752861 pi.on("session_start", (_event, ctx) => {
753862 state = latestGoalState(ctx);
863 removeTerminalInput?.();
864 removeTerminalInput = ctx.hasUI
865 ? ctx.ui.onTerminalInput((data) => {
866 if (matchesKey(data, "escape")) {
867 state = cancelGoalRun(pi, ctx, state);
868 continuationScheduled.value = false;
869 }
870 return undefined;
871 })
872 : undefined;
754873 updateUI(pi, ctx, state);
755874 syncUpdateGoalTool();
756875 });
786905 });
788907 pi.on("session_shutdown", (_event, ctx) => {
908 removeTerminalInput?.();
909 removeTerminalInput = undefined;
789910 updateUI(pi, ctx, undefined);
790911 setToolActive(pi, "update_goal", false);
791912 });
825946 }
826947 if (state !== judged || state.status !== "active") return;
827948 appendJudge(pi, "verdict", judged, verdict);
828 if (ctx.hasUI && verdict.reason.startsWith("judge failed:"))
829 ctx.ui.notify(
830 `Goal judge verdict: continue · ${verdict.reason}`,
831 "warning",
832 );
949 if (isJudgeFailure(verdict)) {
950 state = updateGoal(pi, judged, {
951 status: "paused",
952 lastReason: verdict.reason,
953 });
954 updateUI(pi, ctx, state);
955 syncUpdateGoalTool();
956 if (ctx.hasUI)
957 ctx.ui.notify(`Goal paused — ${verdict.reason}`, "warning");
958 return;
959 }
833960 if (verdict.done) {
834961 state = updateGoal(pi, judged, {
835962 status: "complete",
10821209 continuationPrompt,
10831210 criteriaText,
10841211 goalArgumentCompletions,
1212 goalBar,
1213 goalJudgeMessageLine,
1214 goalWidgetLines,
1215 insetWidgetLine,
10851216 kickoffPrompt,
10861217 latestAssistantTail,
10871218 latestGoalState,
1219 cancelGoalRun,
10881220 loadSettings,
10891221 judgeRunningText,
10901222 judgeDisplayReason,
1223 isJudgeFailure,
10911224 parseJudge,
10921225 parseModelRef,
10931226 extractStandingGoalObjective,