repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(goal): prune resumed failure context

5111ce5be551dd8bd5e207895ff78b7f40a486e6

Review <review@example.invalid> ·

unsigned

Browse filesCompare 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)

CHANGELOG.md

Modified
18 18 retry cap
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
51 - of truncating
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
54 58 turns

extensions/goal/__tests__/integration-full.test.ts

Modified
6 6 createTestSession,
7 7 type TestSession,
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 });
588 + writeFileSync(
589 + join(t.cwd, ".pi", "settings.json"),
590 + JSON.stringify({ retry: { enabled: false } }),
591 + );
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();
608 + try {
609 + t = await createGoalSession();
610 + mkdirSync(join(t.cwd, ".pi"), { recursive: true });
611 + writeFileSync(
612 + join(t.cwd, ".pi", "settings.json"),
613 + JSON.stringify({ retry: { enabled: true, maxRetries: 1 } }),
614 + );
615 + t.session.settingsManager.applyOverrides({
616 + retry: { enabled: true, maxRetries: 1, baseDelayMs: 10_000 },
617 + });
618 + installSaysErrorStream(t, "500 server error");
620 + const run = t.session.prompt("/goal survive transient server error");
621 + await vi.waitFor(() => {
622 + expect(
623 + t?.events.all.some((event) => event.type === "auto_retry_start"),
624 + ).toBe(true);
625 + });
627 + await vi.advanceTimersByTimeAsync(4_000);
629 + expect(
630 + customEvents("goal-debug").map((entry) => entry.event),
631 + ).not.toContain("continuation-dispatched");
632 + expect(
633 + t.events.all.filter((event) => event.type === "agent_start"),
634 + ).toHaveLength(1);
636 + await vi.advanceTimersByTimeAsync(6_000);
637 + await run;
639 + expect(latestGoal()).toMatchObject({
640 + objective: "survive transient server error",
641 + status: "paused",
642 + lastVerdict: "error",
643 + lastReason: "retry exhausted: server error",
644 + });
645 + expect(
646 + customEvents("goal-debug").map((entry) => entry.event),
647 + ).not.toContain("continuation-dispatched");
648 + } finally {
649 + vi.clearAllTimers();
650 + vi.useRealTimers();
652 + });
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;
137 + const messages = [
138 + { role: "user", content: "start" },
140 + role: "assistant",
141 + content: "500 unknown error",
142 + stopReason: "error",
143 + },
144 + { role: "custom", customType: "goal-judge", content: "judge row" },
145 + { role: "custom", customType: "goal-event", content: "event row" },
147 + role: "custom",
148 + customType: "goal-continuation",
149 + details: { goalId: "goal-1" },
150 + },
152 + role: "custom",
153 + customType: "goal-continuation",
154 + details: { goalId: "goal-1" },
155 + },
156 + ];
158 + const pruned = __goalTest.pruneGoalContextMessages(messages, state);
160 + expect(pruned).toEqual([messages[0], messages[5]]);
161 + });
135 163 it("parses model refs and rejects invalid refs", () => {
136 164 expect(__goalTest.parseModelRef("provider/model/name")).toEqual({
137 165 provider: "provider",
210 238 expect(
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: (
244 + state: unknown,
245 + mode: "normal",
246 + width: number,
247 + ) => string[];
249 + ).goalCompactWidgetLines(
250 + goal({
251 + objective: "Ship the feature with enough detail to need truncation",
252 + verdicts: [
253 + { turn: 1, label: "continue", reason: "needs tests" },
254 + { turn: 2, label: "blocked", reason: "needs credentials" },
255 + ],
256 + }) as never,
257 + "normal",
258 + 48,
259 + );
260 + expect(compactLines).toHaveLength(1);
261 + expect(compactLines[0]).toContain("…");
213 262 expect(__goalTest.insetWidgetLine("goal active", 30)).toBe(
214 263 " goal active ",

extensions/goal/index.ts

Modified
6 6 type ExtensionContext,
7 7 getAgentDir,
8 8 SessionManager,
9 + SettingsManager,
9 10 type ThemeColor,
10 11 } from "@earendil-works/pi-coding-agent";
11 12 import {
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,
941 +): PiRetryState {
942 + if (evidence?.stopReason !== "error") return "none";
943 + const retry = SettingsManager.create(
944 + ctx.cwd,
945 + getAgentDir(),
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")
950 + return "none";
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,
1320 1340 ): string {
1321 - return goalCompactWidgetLines(state, mode, width)[0] ?? "";
1341 + const criteria =
1342 + state.criteria.length === 0 ? "" : ` · ${state.criteria.length}c`;
1343 + const reason = state.lastReason
1344 + ? ` · ${verdictGlyph(state.lastVerdict)} ${sanitizeGoalText(state.lastReason, 48)}`
1345 + : "";
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),
1349 + "…",
1350 + );
1324 1353 function goalCompactWidgetLines(
1326 1355 mode: GoalUiMode,
1327 1356 width = GOAL_WIDGET_DEFAULT_WIDTH,
1328 1357 ): string[] {
1329 - const criteria =
1330 - state.criteria.length === 0 ? "" : ` · ${state.criteria.length}c`;
1331 - const error =
1332 - state.lastVerdict === "error" && state.lastReason
1333 - ? ` · ! ${state.lastReason}`
1334 - : "";
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}`,
1341 - ),
1342 - ],
1343 - width,
1344 - );
1358 + return [goalCompactWidgetLine(state, mode, width)];
1347 1361 function updateWidget(ctx: ExtensionContext): void {
2349 +const GOAL_TRANSCRIPT_MESSAGE_TYPES = new Set([
2350 + GOAL_EVENT_ENTRY,
2351 + GOAL_JUDGE_ENTRY,
2352 + GOAL_COMPACTION_ENTRY,
2353 +]);
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;
2369 + if (
2370 + msg.role === "custom" &&
2371 + typeof msg.customType === "string" &&
2372 + GOAL_TRANSCRIPT_MESSAGE_TYPES.has(msg.customType)
2373 + ) {
2374 + return false;
2376 + return true;
2377 + }),
2378 + state,
2379 + );
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) => {
2664 2712 return {
2665 - messages: pruneContinuationMessages(
2713 + messages: pruneGoalContextMessages(
2666 2714 event.messages as never,
2668 2716 ) 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++;
2786 + return;
2788 + piRetryDeferrals = 0;
2735 2789 const settings = loadSettings(pi);
2736 2790 let dossier = ensureDossier(pi, ctx, state);
2737 2791 dossier = appendTurnEvidenceToDossier(
2781 2835 return;
2838 + if (piRetry === "exhausted") {
2839 + state = updateGoal(pi, state, {
2840 + status: "paused",
2841 + lastVerdict: "error",
2842 + lastReason: `retry exhausted: ${classified.short}`,
2843 + timeUsedSeconds: currentElapsedSeconds(state),
2844 + });
2845 + appendGoalEvent(pi, ctx, "paused", state, {
2846 + reason: state.lastReason,
2847 + raw: errorMessage,
2848 + kind: classified.kind,
2849 + });
2850 + renderGoalUi(ctx, state);
2851 + syncUpdateGoalTool();
2852 + if (ctx.hasUI)
2853 + ctx.ui.notify(`Goal paused — ${state.lastReason}`, "warning");
2854 + return;
2784 2857 if (classified.retryable) {
2785 2858 state = updateGoal(pi, state, {
2786 2859 errorRetries: retries,
3224 3297 compactStatusLine,
3225 3298 goalSummary,
3226 3299 pruneContinuationMessages,
3300 + pruneGoalContextMessages,
3227 3301 statusLine,
3228 3302 statusText,
3229 3303 textFromContent,
3249 3323 wrapVisibleWords,
3250 3324 goalWidgetRow,
3251 3325 goalCompactWidgetLine,
3326 + goalCompactWidgetLines,
3252 3327 liveDisplayState,
3253 3328 syncLiveGoalTimer,
3254 3329 shortText,