repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(goal): avoid compaction reentrancy

7f609cac0add61b2b73a44914bb6705f22cf9e8b

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

CHANGELOG.md

Modified
4 4 # Changelog
6 6 ## Unreleased
8 8 - Add the `gestalt` skill for visual-organization audits of UIs, diagrams,
9 9 screenshots, dashboards, hierarchy, grouping, and scan-path issues
10 +- Fix goal compaction reentrancy by pausing continuations during session
11 + compaction and avoiding pre-compaction session mutations
11 13 ## 0.0.3

extensions/goal/__tests__/unit.test.ts

Modified
1 -import { describe, expect, it } from "vitest";
1 +import { describe, expect, it, vi } from "vitest";
2 2 import goalExtension, {
3 3 __goalTest,
4 4 GOAL_DOSSIER_CUSTOM_TYPE,
47 +function createCompactionHarness() {
48 + const handlers = new Map<
49 + string,
50 + Array<(event: unknown, ctx: unknown) => unknown>
51 + >();
52 + const entries: Array<Record<string, unknown>> = [];
53 + const sent: Array<Record<string, unknown>> = [];
54 + let activeTools: string[] = [];
55 + const sessionManager = {
56 + getEntries: () => entries,
57 + getSessionId: () => "session-1",
58 + appendCustomMessageEntry: (
59 + customType: string,
60 + content: string,
61 + display: boolean,
62 + details: Record<string, unknown>,
63 + ) => {
64 + entries.push({
65 + type: "custom_message",
66 + customType,
67 + content,
68 + display,
69 + details,
70 + });
71 + },
72 + };
73 + const pi = {
74 + on: (event: string, handler: (event: unknown, ctx: unknown) => unknown) => {
75 + handlers.set(event, [...(handlers.get(event) ?? []), handler]);
76 + },
77 + appendEntry: (customType: string, data: Record<string, unknown>) => {
78 + entries.push({ type: "custom", customType, data });
79 + },
80 + sendMessage: (
81 + message: Record<string, unknown>,
82 + options?: Record<string, unknown>,
83 + ) => {
84 + sent.push({ message, options });
85 + },
86 + registerMessageRenderer: () => {},
87 + registerShortcut: () => {},
88 + registerTool: () => {},
89 + registerCommand: () => {},
90 + getActiveTools: () => activeTools,
91 + setActiveTools: (next: string[]) => {
92 + activeTools = next;
93 + },
94 + settingsManager: { getSettings: () => ({}) },
95 + events: { emit: () => {} },
96 + };
97 + const ctx = {
98 + cwd: process.cwd(),
99 + hasUI: false,
100 + sessionManager,
101 + ui: {
102 + notify: () => {},
103 + setStatus: () => {},
104 + setWidget: () => {},
105 + setWorkingMessage: () => {},
106 + setWorkingIndicator: () => {},
107 + onTerminalInput: () => () => {},
108 + },
109 + isIdle: () => true,
110 + modelRegistry: {},
111 + signal: new AbortController().signal,
112 + };
113 + goalExtension(pi as never);
114 + return { handlers, entries, sent, ctx };
117 +async function emitHarness(
118 + harness: ReturnType<typeof createCompactionHarness>,
119 + event: string,
120 + payload: Record<string, unknown>,
121 +) {
122 + for (const handler of harness.handlers.get(event) ?? []) {
123 + await handler(payload, harness.ctx);
47 127 describe("goal unit helpers", () => {
128 + it("does not mutate session or dispatch continuations during compaction", async () => {
129 + vi.useFakeTimers();
130 + try {
131 + const harness = createCompactionHarness();
132 + await emitHarness(harness, "before_agent_start", {
133 + prompt:
134 + "Start working toward this standing goal.\n\n<objective>ship it</objective>",
135 + systemPrompt: "base",
136 + });
137 + await emitHarness(harness, "agent_end", { messages: [] });
138 + harness.entries.length = 0;
139 + harness.sent.length = 0;
141 + await emitHarness(harness, "session_before_compact", {
142 + preparation: {},
143 + branchEntries: [],
144 + signal: new AbortController().signal,
145 + });
146 + await vi.runAllTimersAsync();
148 + expect(
149 + harness.entries.filter(
150 + (entry) => entry.customType === "goal-compaction",
151 + ),
152 + ).toEqual([]);
153 + expect(
154 + harness.sent.map(
155 + (entry) => (entry.message as Record<string, unknown>).customType,
156 + ),
157 + ).not.toContain("goal-continuation");
158 + expect(
159 + harness.sent.map(
160 + (entry) => (entry.message as Record<string, unknown>).customType,
161 + ),
162 + ).not.toContain("goal-compaction");
163 + } finally {
164 + vi.useRealTimers();
166 + });
48 168 it("extracts text content from strings and text parts", () => {
49 169 expect(__goalTest.textFromContent("plain")).toBe("plain");
50 170 expect(

extensions/goal/index.ts

Modified
155 155 turn?: number;
156 156 queued: boolean;
157 157 scheduled: boolean;
158 + compacting: boolean;
160 161 type ProbeState = {
2439 2440 state: GoalState,
2440 2441 continuation: ContinuationState,
2441 2442 ): void {
2443 + if (continuation.compacting) return;
2442 2444 if (continuation.queued || continuation.scheduled) return;
2443 2445 continuation.goalId = state.id;
2444 2446 continuation.turn = state.turnsUsed + 1;
2456 2458 setTimeout(() => {
2457 2459 continuation.scheduled = false;
2460 + if (continuation.compacting) {
2461 + continuation.queued = false;
2462 + debugGoal(pi, "continuation-skipped-compacting", { goalId: state.id });
2463 + return;
2458 2465 let latest: GoalState | undefined;
2460 2467 latest = latestGoalState(ctx);
2595 2602 let state: GoalState | undefined;
2596 - const continuation: ContinuationState = { queued: false, scheduled: false };
2603 + const continuation: ContinuationState = {
2604 + queued: false,
2605 + scheduled: false,
2606 + compacting: false,
2607 + };
2597 2608 let piRetryDeferrals = 0;
2598 2609 let removeTerminalInput: (() => void) | undefined;
2599 2610 let promptTemplates: GoalPromptTemplate[] = [];
2766 2777 pi.on("session_before_compact", () => {
2767 - const summary = goalSummary(state, continuation);
2768 - pi.appendEntry(GOAL_COMPACTION_ENTRY, {
2769 - event: "before",
2770 - summary,
2771 - timestamp: Date.now(),
2772 - });
2773 - if (!state || state.status === "complete") return;
2774 - pi.sendMessage(
2776 - customType: GOAL_COMPACTION_ENTRY,
2777 - content: `Current /goal summary before compaction:\n${summary}`,
2778 - display: false,
2779 - details: { goalId: state.id },
2780 - },
2781 - { triggerTurn: false, deliverAs: "nextTurn" },
2782 - );
2778 + continuation.compacting = true;
2779 + continuation.queued = false;
2780 + continuation.scheduled = false;
2785 2783 pi.on("session_compact", () => {
2784 + continuation.compacting = false;
2786 2785 pi.appendEntry(GOAL_COMPACTION_ENTRY, {
2787 2786 event: "after",
2788 2787 summary: goalSummary(state, continuation),