repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(goal): add planner dossier

90b96bdde14f376f6706e6ab55d0c4b9e8779615

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

extensions/goal/README.md

Modified
59 59 "goal": {
60 60 "judgeModel": "provider/model",
61 + "plannerModel": "provider/model",
62 + "plannerThinkingLevel": "high",
61 63 "tailBytes": 4096
66 68 - `judgeModel`:
67 69 optional Pi model ref, `provider/model`.
68 70 When unset, the current session model is used.
71 +- `plannerModel`:
72 + optional Pi model ref for automatic goal planning.
73 + When unset, the current session model is used.
74 +- `plannerThinkingLevel`:
75 + planner thinking level.
76 + Default `high`; allowed `off`, `low`, `medium`, `high`, `xhigh`.
69 77 - `tailBytes`:
70 - bytes read from the latest assistant response for judgment.
78 + bytes read from latest assistant/tool output for judgment and evidence.
71 79 Default `4096`, clamped to `512..65536`.
72 80 - `tokenBudget`:
73 81 optional approximate token budget for a new goal.
101 109 block is adopted as an active goal when no goal exists.
102 110 - New goals require an idle agent.
103 111 Subcommands can run while the agent is busy.
104 -- Goal state is stored as append-only custom `goal-state` entries.
112 +- Goal state is stored as append-only v2 custom `goal-state` entries.
105 113 Replay scans backward; newest valid state or clear tombstone wins.
106 -- `before_agent_start` injects the active goal and criteria into the system
107 - prompt for the owning session.
114 + Older schemas are ignored.
115 +- A deterministic `goal-dossier` entry is created with each new/adopted goal.
116 + It stores hidden control data:
117 + invariants, planner plan, soft subgoals, evidence, risks, and open questions.
118 +- A planner session refreshes the dossier automatically for new goals, resumes,
119 + user steering, weak proof, blocked-risk, and periodic long-goal turns.
120 + The planner gets `read`, `grep`, `find`, `ls`, and `bash`, and uses
121 + `plannerModel` / `plannerThinkingLevel`.
122 +- `before_agent_start` injects the active goal, criteria, and compact dossier
123 + control data into the system prompt for the owning session.
108 124 - After each owned active goal turn, the extension writes a `goal-judge` start
109 125 entry, shows `goal judging Nt` in persistent UI, then asks a judge model for
111 127 `done`, `blocked`, `reason`.
112 -- The judge runs as a separate Pi session with project/user extensions loaded.
128 +- The adversarial judge runs as a separate Pi session with project/user
129 + extensions loaded.
113 130 It gets `read`, `grep`, `find`, `ls`, and `bash`, plus the objective,
114 - criteria, latest assistant text, stop reason/error message, and last-turn tool
115 - call/result excerpts.
131 + criteria, dossier tail, latest assistant text, stop reason/error message, and
132 + last-turn tool call/result excerpts.
116 133 - Judge completion writes a `goal-judge` verdict entry and updates the goal
117 - widget/footer with the latest verdict glyph/reason.
118 -- Continue verdicts stay quiet except for persistent UI.
134 + widget with the latest verdict glyph/reason.
135 +- Continue verdicts stay quiet except for persistent widget/working UI.
119 136 Complete, blocked, paused, and repeated judge-failed verdicts notify.
120 137 - Done verdict marks the goal complete and clears persistent
121 138 status/widget/footer.
147 164 - `/goal status` emits a compact notify summary:
148 165 phase, elapsed/budget, objective, criteria preview, and last judge
149 166 glyph/reason.
150 -- UI status key:
151 - `goal` for active, paused, queued, judging, and blocked goals when the shared
152 - `footer` extension is absent.
153 - Complete/cleared goals clear status and notify instead.
167 +- The `goal` status/footer segment is cleared; the widget is the primary
168 + persistent UI.
154 169 - UI widget key:
155 170 `goal`.
156 171 Active, queued, judging, paused, and blocked goals show a compact above-editor
157 172 line by default.
173 + The widget is registered once per goal display to keep ordering stable
174 + relative to other widgets while live timer updates continue.
158 175 `/goal widget` or `ctrl+shift+g` toggles expanded mode with wrapped objective,
159 176 elapsed/budget info, criteria preview, and last judge verdict glyph/reason.
160 177 - Active/queued/judging goals set the streaming working message and spinner
161 178 frames as a heartbeat; terminal/passive states restore the default loader.
162 -- Shared footer integration:
163 - emits `footer:segment` id `goal` when `extensions/footer` is loaded.
164 179 - Goals owned by another session show `owned by another session`; mutating
165 180 commands require `/goal resume` first.
166 181 - User steering while a goal turn is running is added as a new criterion rather
167 - than stopping the goal run.
182 + than stopping the goal run, and triggers planner refresh.
168 183 - `session_before_compact` / `session_compact` write deterministic goal summary
169 184 entries.
170 185 - `context` prunes stale `goal-continuation` messages, retaining only the latest

extensions/goal/__tests__/harness.test.ts

Modified
3 3 import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
4 4 import {
5 5 createTestSession,
6 6 type TestSession,
7 7 } from "@marcfargas/pi-test-harness";
8 -import { afterEach, describe, expect, it } from "vitest";
8 +import { afterEach, beforeEach, describe, expect, it } from "vitest";
9 9 import { __goalTest, GOAL_PROBE_MESSAGE } from "../index.ts";
11 11 let t: TestSession | undefined;
12 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
14 +beforeEach(() => {
15 + delete (globalThis as Record<symbol, unknown>)[FOOTER_KEY];
16 +});
13 18 afterEach(() => {
14 19 t?.dispose();
14 19 __goalTest.resetCompleteJudgeForTest();
15 20 delete process.env.PI_GOAL_PROBE;
16 21 delete process.env.PI_GOAL_LOG;
22 + delete (globalThis as Record<symbol, unknown>)[FOOTER_KEY];
19 25 function goalPath(): string {
257 263 (call) => call.method === "setStatus" && call.args[0] === "goal",
259 265 .map((call) => call.args[1]);
260 - expect(statusTexts).toContain("goal active 0t · 0s");
266 + expect(statusTexts.every((text) => text === undefined)).toBe(true);
261 267 expect(statusTexts).toContain(undefined);
262 268 } finally {
263 269 restore();
287 293 expect(
288 294 uiArgs("setStatus")
289 295 .filter((args) => args[0] === "goal")
290 - .map((args) => args[1]),
291 - ).toContain("goal paused 0t · 1c · 0s");
296 + .map((args) => args[1])
297 + .every((text) => text === undefined),
298 + ).toBe(true);
292 299 } finally {
293 300 restore();
445 452 (call) => call.method === "setStatus" && call.args[0] === "goal",
447 454 .map((call) => call.args[1]);
448 - expect(statusCalls).toContain("goal judging 1t");
455 + expect(statusCalls.every((text) => text === undefined)).toBe(true);
449 456 const widgetCalls = t.events.ui
450 457 .filter(
451 458 (call) => call.method === "setWidget" && call.args[0] === "goal",
453 460 .map((call) => call.args[1]);
454 461 expect(widgetCalls.some(Boolean)).toBe(true);
462 + expect(widgetCalls.filter(Boolean)).toHaveLength(1);
455 463 expect(widgetCalls).toContain(undefined);
456 464 const workingMessages = t.events.ui
457 465 .filter((call) => call.method === "setWorkingMessage")
617 625 expect(
618 626 uiArgs("setStatus")
619 627 .filter((args) => args[0] === "goal")
620 - .map((args) => args[1]),
621 - ).toContain("goal blocked");
628 + .map((args) => args[1])
629 + .every((text) => text === undefined),
630 + ).toBe(true);
622 631 } finally {
623 632 restore();

extensions/goal/__tests__/unit.test.ts

Modified
1 1 import { describe, expect, it } from "vitest";
2 -import { __goalTest, GOAL_STATE_CUSTOM_TYPE } from "../index.ts";
2 +import {
3 + __goalTest,
4 + GOAL_DOSSIER_CUSTOM_TYPE,
5 + GOAL_STATE_CUSTOM_TYPE,
6 +} from "../index.ts";
4 8 const now = 1_700_000_000_000;
6 10 function goal(overrides: Record<string, unknown> = {}) {
7 11 return {
12 + schemaVersion: 2,
8 13 id: "goal-1",
9 14 objective: "Ship the feature",
10 15 criteria: ["tests pass", "docs updated"],
27 32 } as never);
35 +function replayDossier(data: unknown[], goalId = "goal-1") {
36 + const entries = data.map((entry) => ({
37 + type: "custom",
38 + customType: GOAL_DOSSIER_CUSTOM_TYPE,
39 + data: entry,
40 + }));
41 + return __goalTest.latestGoalDossier(
42 + { sessionManager: { getEntries: () => entries } } as never,
43 + goalId,
44 + );
30 47 describe("goal unit helpers", () => {
31 48 it("extracts text content from strings and text parts", () => {
32 49 expect(__goalTest.textFromContent("plain")).toBe("plain");
56 73 } as never),
57 74 ).toEqual({
58 75 judgeModel: "test/model",
76 + plannerModel: undefined,
77 + plannerThinkingLevel: "high",
59 78 tailBytes: 65_536,
60 79 tokenBudget: 100_000,
61 80 timeBudgetSeconds: 7200,
70 89 } as never),
71 90 ).toEqual({
72 91 judgeModel: undefined,
92 + plannerModel: undefined,
93 + plannerThinkingLevel: "high",
73 94 tailBytes: 4096,
189 210 expect(__goalTest.goalWidgetLines(goal() as never, "queued", 46)[0]).toBe(
190 211 "╭ goal queued continuation 3 · 2c ───────────╮",
213 + expect(
214 + __goalTest.goalCompactWidgetLine(goal() as never, "normal", 96),
215 + ).toContain("ctrl+shift+g expand");
192 216 expect(__goalTest.insetWidgetLine("╭ goal active ╮", 30)).toBe(
193 217 " ╭ goal active ╮ ",
245 269 expect(() => __goalTest.parseJudge("not json")).toThrow();
272 + it("builds judge resource loader options with required agentDir", () => {
273 + const options = __goalTest.judgeResourceLoaderOptions({
274 + cwd: "/tmp/project",
275 + } as never);
276 + expect(options.cwd).toBe("/tmp/project");
277 + expect(options.agentDir).toBeTypeOf("string");
278 + expect(options.agentDir.length).toBeGreaterThan(0);
279 + expect(options.systemPromptOverride(undefined)).toContain(
280 + "strict adversarial /goal completion judge",
281 + );
282 + });
248 284 it("replays newest valid goal state, tombstones, and malformed entries", () => {
249 285 expect(
250 286 replay([goal({ id: "old" }), goal({ id: "new", turnsUsed: 4 })])?.id,
260 296 replay([goal({ id: "old" }), { id: "bad", objective: "missing fields" }])
262 298 ).toBe("old");
299 + expect(
300 + replay([{ id: "old-schema", objective: "ignored" }]),
301 + ).toBeUndefined();
302 + });
304 + it("creates, replays, and enriches deterministic dossiers", () => {
305 + const state = goal() as never;
306 + const dossier = __goalTest.createInitialDossier(state, now);
307 + expect(dossier).toMatchObject({
308 + goalId: "goal-1",
309 + version: 1,
310 + mode: "plan",
311 + plan: [],
312 + subgoals: [],
313 + });
314 + expect(replayDossier([dossier])?.goalId).toBe("goal-1");
315 + const enriched = __goalTest.applyPlannerOutput(
316 + dossier,
318 + mode: "execute",
319 + plan: ["inspect code", "add tests"],
320 + subgoals: [
322 + title: "add dossier replay",
323 + validationHints: ["npm run test -- goal"],
324 + },
325 + ],
326 + risks: ["planner output is untrusted"],
327 + openQuestions: ["none"],
328 + },
329 + "unit",
330 + );
331 + expect(enriched.mode).toBe("execute");
332 + expect(enriched.currentSubgoalId).toBe("sg-1");
333 + expect(enriched.subgoals[0]).toMatchObject({
334 + title: "add dossier replay",
335 + status: "active",
336 + validationHints: ["npm run test -- goal"],
337 + });
338 + });
340 + it("turn evidence becomes capped dossier evidence", () => {
341 + const items = __goalTest.evidenceFromTurn(
342 + 3,
344 + assistantText: "implemented feature",
345 + toolCalls: [
346 + { name: "bash", args: { command: "npm run test -- goal" } },
347 + ],
348 + toolResults: [{ toolName: "bash", isError: false, text: "177 passed" }],
349 + },
350 + 4096,
351 + );
352 + expect(items.map((item) => item.kind)).toEqual([
353 + "assistant",
354 + "test",
355 + "command",
356 + ]);
357 + expect(items.at(-1)?.confidence).toBe("verified");
265 360 it("reads latest assistant tail", () => {
423 518 "status": "active · 2 turns · 2 criteria · still checking\\nShip the feature",
424 519 "criteria": "1. tests pass\\n2. docs updated",
425 520 "active": "\\n\\nActive /goal:\\n<goal_objective_data>\\nShip the feature\\n</goal_objective_data>\\n\\nCriteria:\\n1. tests pass\\n2. docs updated\\n\\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.",
426 - "continuation": "Continue working toward this standing goal.\\n\\n<goal_objective_data>\\nShip the feature\\n</goal_objective_data>\\n\\nCriteria:\\n1. tests pass\\n2. docs updated\\n\\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Call update_goal with status \\"complete\\" only after verifying success. Call update_goal with status \\"blocked\\" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.",
521 + "continuation": "Continue working toward this standing goal.\\n\\n<goal_objective_data>\\nShip the feature\\n</goal_objective_data>\\n\\nCriteria:\\n1. tests pass\\n2. docs updated\\n\\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Follow goal_control_data when present. Call update_goal with status \\"complete\\" only after verifying success. Call update_goal with status \\"blocked\\" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.",
427 522 "kickoff": "Start working toward this standing goal.\\n\\n<goal_objective_data>\\nShip the feature\\n</goal_objective_data>\\n\\nDo not stop just because one turn ends. Keep making concrete progress until the goal is complete, blocked, paused, or cleared."
1058 1153 .reason,
1059 1154 ).toBe("no reason");
1156 + it("does not throw on malformed runtime verdicts", () => {
1157 + expect(
1158 + __goalTest.isJudgeFailure({ done: false, blocked: false } as never),
1159 + ).toBe(false);
1160 + expect(
1161 + __goalTest.goalVerdictLabel({ done: false, blocked: false } as never),
1162 + ).toBe("continue");
1163 + });
1061 1164 it("strips markdown fences", () => {
1062 1165 expect(
1063 1166 __goalTest.parseJudge(
1181 1284 __goalTest.loadSettings({
1182 1285 settingsManager: { getSettings: () => ({}) },
1183 1286 } as never),
1184 - ).toEqual({ judgeModel: undefined, tailBytes: 4096 });
1287 + ).toEqual({
1288 + judgeModel: undefined,
1289 + plannerModel: undefined,
1290 + plannerThinkingLevel: "high",
1291 + tailBytes: 4096,
1292 + });
1186 1294 it("returns defaults when goal settings missing", () => {
1187 1295 expect(
1188 1296 __goalTest.loadSettings({
1189 1297 settingsManager: { getSettings: () => ({ other: true }) },
1190 1298 } as never),
1191 - ).toEqual({ judgeModel: undefined, tailBytes: 4096 });
1299 + ).toEqual({
1300 + judgeModel: undefined,
1301 + plannerModel: undefined,
1302 + plannerThinkingLevel: "high",
1303 + tailBytes: 4096,
1304 + });
1193 1306 it("ignores non-string judgeModel", () => {
1194 1307 expect(

extensions/goal/index.ts

Modified
4 4 import { complete as piComplete, StringEnum } from "@earendil-works/pi-ai";
5 5 import {
6 6 createAgentSession,
7 7 DefaultResourceLoader,
8 8 type ExtensionAPI,
9 9 type ExtensionContext,
10 + getAgentDir,
10 11 SessionManager,
11 12 type ThemeColor,
12 13 } from "@earendil-works/pi-coding-agent";
20 21 const JUDGE_COMPLETE_FOR_TEST = Symbol.for(
21 22 "@bugabinga/pi-ext-goal/completeJudge",
24 +const PLANNER_FOR_TEST = Symbol.for("@bugabinga/pi-ext-goal/planner");
25 +type PlannerForTest = (payload: Record<string, unknown>) => PlannerOutput;
23 26 type GoalTestGlobals = typeof globalThis & {
24 27 [JUDGE_COMPLETE_FOR_TEST]?: JudgeComplete;
28 + [PLANNER_FOR_TEST]?: PlannerForTest;
27 31 function judgeComplete(): JudgeComplete {
31 35 type GoalStatus = "active" | "paused" | "complete" | "blocked";
32 36 type GoalVerdictLabel = "done" | "blocked" | "continue" | "error";
33 37 type ProbeMode = "direct" | "microtask" | "timeout";
38 +type GoalThinkingLevel = "off" | "low" | "medium" | "high" | "xhigh";
39 +type GoalMode = "plan" | "execute" | "validate" | "recover" | "ask";
35 41 type GoalSettings = {
36 42 judgeModel?: string;
43 + plannerModel?: string;
44 + plannerThinkingLevel: GoalThinkingLevel;
37 45 tailBytes: number;
38 46 tokenBudget?: number;
39 47 timeBudgetSeconds?: number;
47 55 type GoalState = {
56 + schemaVersion: 2;
48 57 id: string;
49 58 objective: string;
50 59 criteria: string[];
70 79 reason: string;
82 +type EvidenceConfidence = "claim" | "observed" | "verified";
83 +type EvidenceKind =
84 + | "assistant"
85 + | "tool"
86 + | "command"
87 + | "test"
88 + | "file"
89 + | "error";
91 +type GoalEvidenceItem = {
92 + turn: number;
93 + kind: EvidenceKind;
94 + confidence: EvidenceConfidence;
95 + text: string;
96 + createdAt: number;
97 +};
99 +type GoalSubgoal = {
100 + id: string;
101 + title: string;
102 + status: "todo" | "active" | "done" | "blocked" | "skipped";
103 + validationHints: string[];
106 +type GoalDossier = {
107 + goalId: string;
108 + version: 1;
109 + invariants: string[];
110 + mode: GoalMode;
111 + plan: string[];
112 + subgoals: GoalSubgoal[];
113 + currentSubgoalId?: string;
114 + evidence: GoalEvidenceItem[];
115 + risks: string[];
116 + openQuestions: string[];
117 + lastPlannerTrigger?: string;
118 + lastJudgeReason?: string;
119 + updatedAt: number;
122 +type PlannerOutput = {
123 + mode?: unknown;
124 + plan?: unknown;
125 + subgoals?: unknown;
126 + risks?: unknown;
127 + openQuestions?: unknown;
73 130 type TurnEvidence = {
74 131 assistantText: string;
75 132 stopReason?: string;
103 160 description: string;
163 +const GOAL_STATE_VERSION = 2;
164 +const GOAL_DOSSIER_VERSION = 1;
106 165 const GOAL_STATE_ENTRY = "goal-state";
166 +const GOAL_DOSSIER_ENTRY = "goal-dossier";
107 167 const GOAL_JUDGE_ENTRY = "goal-judge";
108 168 const GOAL_EVENT_ENTRY = "goal-event";
109 169 const GOAL_DEBUG_ENTRY = "goal-debug";
112 172 const PROBE_ENTRY = "goal-probe";
113 173 const PROBE_MESSAGE = "GOAL_PROBE_CONTINUATION";
114 174 const DEFAULT_TAIL_BYTES = 4096;
175 +const DEFAULT_PLANNER_THINKING_LEVEL: GoalThinkingLevel = "high";
176 +const PLANNER_REFRESH_TURNS = 5;
177 +const MAX_DOSSIER_EVIDENCE = 40;
178 +const MAX_DOSSIER_LIST = 12;
115 179 const STATUS_KEY = "goal";
116 180 const WIDGET_KEY = "goal";
117 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
118 181 const FOOTER_SEGMENT = { id: "goal", zone: "llm", order: 30 } as const;
119 -type FooterGlobal = typeof globalThis & {
120 - [FOOTER_KEY]?: { loaded?: boolean; version?: number };
122 182 const JUDGE_ATTEMPTS = 2;
123 183 const JUDGE_PARSE_FAILURE_LIMIT = 3;
124 184 const BLOCKED_STREAK_LIMIT = 3;
129 189 let liveGoalState: GoalState | undefined;
130 190 let liveGoalMode: GoalUiMode = "normal";
131 191 let liveGoalWidgetMode: GoalWidgetMode = "compact";
192 +let goalWidgetRegistered = false;
132 193 let liveGoalTimer:
134 195 goalId: string;
140 201 | undefined;
141 202 const GOAL_WIDGET_DEFAULT_WIDTH = 78;
142 203 const GOAL_WIDGET_LEFT_PADDING = 0;
143 -const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge. Be skeptical. Agents lie about completion.
204 +const JUDGE_SYSTEM_PROMPT = `You are a strict adversarial /goal completion judge. Be skeptical. Agents lie about completion.
206 +Your job is to find concrete reasons the goal is not complete before accepting completion.
145 207 You must independently verify the goal using available tools.
146 208 Use read/grep/find/ls for repo inspection.
147 209 Use bash for inspection and verification commands/tests/checks.
210 +Use dossier evidence and subgoals as hints, not proof.
148 211 Do not modify files, git state, dependencies, config, network state, or external services.
150 213 Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}.
238 301 return Number.isFinite(parsed) && parsed > 0 ? Math.trunc(parsed) : undefined;
304 +function parseThinkingLevel(value: unknown): GoalThinkingLevel {
305 + return value === "off" ||
306 + value === "low" ||
307 + value === "medium" ||
308 + value === "high" ||
309 + value === "xhigh"
310 + ? value
311 + : DEFAULT_PLANNER_THINKING_LEVEL;
241 314 function loadSettings(pi: ExtensionAPI): GoalSettings {
242 315 const all = (pi as SettingsAPI).settingsManager?.getSettings?.();
243 316 const raw = isRecord(all?.goal) ? all.goal : {};
246 319 typeof raw.judgeModel === "string" && raw.judgeModel.trim()
247 320 ? raw.judgeModel.trim()
248 321 : undefined,
322 + plannerModel:
323 + typeof raw.plannerModel === "string" && raw.plannerModel.trim()
324 + ? raw.plannerModel.trim()
325 + : undefined,
326 + plannerThinkingLevel: parseThinkingLevel(raw.plannerThinkingLevel),
249 327 tailBytes: clampInt(raw.tailBytes, DEFAULT_TAIL_BYTES, 512, 65_536),
251 329 const tokenBudget = parseBudgetCount(raw.tokenBudget);
307 385 function isGoalState(value: unknown): value is GoalState {
308 386 if (!isRecord(value)) return false;
309 387 return (
388 + value.schemaVersion === GOAL_STATE_VERSION &&
310 389 typeof value.id === "string" &&
311 390 typeof value.objective === "string" &&
312 391 Array.isArray(value.criteria) &&
345 424 customType?: string;
346 425 data?: unknown;
348 - // Session entries are append-only: newest valid goal-state/tombstone decides replay.
349 - // Scan backward to avoid O(full transcript) work after long sessions.
427 + // Session entries are append-only: newest valid v2 goal-state/tombstone decides replay.
428 + // Older schemas are deliberately ignored.
350 429 for (let i = entries.length - 1; i >= 0; i--) {
351 430 const entry = entries[i];
361 440 return undefined;
443 +function isGoalDossier(value: unknown): value is GoalDossier {
444 + if (!isRecord(value)) return false;
445 + return (
446 + value.version === GOAL_DOSSIER_VERSION &&
447 + typeof value.goalId === "string" &&
448 + Array.isArray(value.invariants) &&
449 + value.invariants.every((x) => typeof x === "string") &&
450 + isGoalMode(value.mode) &&
451 + Array.isArray(value.plan) &&
452 + value.plan.every((x) => typeof x === "string") &&
453 + Array.isArray(value.subgoals) &&
454 + value.subgoals.every(isGoalSubgoal) &&
455 + (value.currentSubgoalId === undefined ||
456 + typeof value.currentSubgoalId === "string") &&
457 + Array.isArray(value.evidence) &&
458 + value.evidence.every(isGoalEvidenceItem) &&
459 + Array.isArray(value.risks) &&
460 + value.risks.every((x) => typeof x === "string") &&
461 + Array.isArray(value.openQuestions) &&
462 + value.openQuestions.every((x) => typeof x === "string") &&
463 + (value.lastPlannerTrigger === undefined ||
464 + typeof value.lastPlannerTrigger === "string") &&
465 + (value.lastJudgeReason === undefined ||
466 + typeof value.lastJudgeReason === "string") &&
467 + typeof value.updatedAt === "number"
468 + );
471 +function isGoalMode(value: unknown): value is GoalMode {
472 + return (
473 + value === "plan" ||
474 + value === "execute" ||
475 + value === "validate" ||
476 + value === "recover" ||
477 + value === "ask"
478 + );
481 +function isGoalSubgoal(value: unknown): value is GoalSubgoal {
482 + if (!isRecord(value)) return false;
483 + return (
484 + typeof value.id === "string" &&
485 + typeof value.title === "string" &&
486 + (value.status === "todo" ||
487 + value.status === "active" ||
488 + value.status === "done" ||
489 + value.status === "blocked" ||
490 + value.status === "skipped") &&
491 + Array.isArray(value.validationHints) &&
492 + value.validationHints.every((x) => typeof x === "string")
493 + );
496 +function isGoalEvidenceItem(value: unknown): value is GoalEvidenceItem {
497 + if (!isRecord(value)) return false;
498 + return (
499 + Number.isInteger(value.turn) &&
500 + (value.kind === "assistant" ||
501 + value.kind === "tool" ||
502 + value.kind === "command" ||
503 + value.kind === "test" ||
504 + value.kind === "file" ||
505 + value.kind === "error") &&
506 + (value.confidence === "claim" ||
507 + value.confidence === "observed" ||
508 + value.confidence === "verified") &&
509 + typeof value.text === "string" &&
510 + typeof value.createdAt === "number"
511 + );
514 +function latestGoalDossier(
515 + ctx: ExtensionContext,
516 + goalId: string,
517 +): GoalDossier | undefined {
518 + const entries = ctx.sessionManager.getEntries() as Array<{
519 + type: string;
520 + customType?: string;
521 + data?: unknown;
522 + }>;
523 + for (let i = entries.length - 1; i >= 0; i--) {
524 + const entry = entries[i];
525 + if (
526 + entry.type !== "custom" ||
527 + entry.customType !== GOAL_DOSSIER_ENTRY ||
528 + !isGoalDossier(entry.data)
530 + continue;
531 + if (entry.data.goalId === goalId) return entry.data;
533 + return undefined;
364 536 function appendGoal(pi: ExtensionAPI, state: GoalState): void {
365 537 pi.appendEntry(GOAL_STATE_ENTRY, state);
540 +function createGoalState(
541 + objective: string,
542 + settings: GoalSettings,
543 + sessionId: string | undefined,
544 + now = Date.now(),
545 +): GoalState {
546 + return {
547 + schemaVersion: GOAL_STATE_VERSION,
548 + id: crypto.randomUUID(),
549 + objective,
550 + criteria: [],
551 + status: "active",
552 + turnsUsed: 0,
553 + tokenBudget: settings.tokenBudget,
554 + tokensUsed: 0,
555 + timeBudgetSeconds: settings.timeBudgetSeconds,
556 + timeUsedSeconds: 0,
557 + errorRetries: 0,
558 + sessionId,
559 + createdAt: now,
560 + updatedAt: now,
561 + };
368 564 function updateGoal(
369 565 pi: ExtensionAPI,
370 566 current: GoalState,
375 571 return next;
574 +function createInitialDossier(state: GoalState, now = Date.now()): GoalDossier {
575 + return {
576 + goalId: state.id,
577 + version: GOAL_DOSSIER_VERSION,
578 + invariants: [
579 + "Do not redefine the objective smaller.",
580 + "Preserve user criteria exactly.",
581 + "Verify before claiming completion.",
582 + "Do not complete from assistant claims alone.",
583 + ],
584 + mode: "plan",
585 + plan: [],
586 + subgoals: [],
587 + evidence: [],
588 + risks: [],
589 + openQuestions: [],
590 + updatedAt: now,
591 + };
594 +function appendDossier(pi: ExtensionAPI, dossier: GoalDossier): GoalDossier {
595 + pi.appendEntry(GOAL_DOSSIER_ENTRY, dossier);
596 + return dossier;
599 +function ensureDossier(
600 + pi: ExtensionAPI,
601 + ctx: ExtensionContext,
602 + state: GoalState,
603 +): GoalDossier {
604 + return (
605 + latestGoalDossier(ctx, state.id) ??
606 + appendDossier(pi, createInitialDossier(state))
607 + );
610 +function updateDossier(
611 + pi: ExtensionAPI,
612 + current: GoalDossier,
613 + patch: Partial<GoalDossier>,
614 +): GoalDossier {
615 + return appendDossier(pi, { ...current, ...patch, updatedAt: Date.now() });
378 618 function showsTurnBudget(state: GoalState): boolean {
379 619 return state.status === "active" || state.status === "paused";
437 -function judgeDisplayReason(reason: string): string {
438 - return sanitizeGoalText(reason, 160);
677 +function stringList(
678 + value: unknown,
679 + maxItems = MAX_DOSSIER_LIST,
680 + max = 160,
681 +): string[] {
682 + const raw = Array.isArray(value) ? value : [];
683 + const out: string[] = [];
684 + for (const item of raw) {
685 + const text =
686 + typeof item === "string"
687 + ? item
688 + : isRecord(item) && typeof item.title === "string"
689 + ? item.title
690 + : undefined;
691 + if (!text) continue;
692 + const safe = sanitizeGoalText(text, max);
693 + if (safe && !out.includes(safe)) out.push(safe);
694 + if (out.length >= maxItems) break;
696 + return out;
699 +function judgeDisplayReason(reason: string | undefined): string {
700 + return sanitizeGoalText(reason || "no reason", 160);
703 +function normalizeJudgeVerdict(value: unknown): JudgeVerdict {
704 + const verdict = isRecord(value) ? value : {};
705 + return {
706 + done: parseLooseBoolean(verdict.done),
707 + blocked: parseLooseBoolean(verdict.blocked),
708 + reason:
709 + typeof verdict.reason === "string" && verdict.reason.trim()
710 + ? shortText(verdict.reason.trim(), 160)
711 + : "no reason",
712 + };
441 715 function judgeVerdictLabel(
442 716 verdict: JudgeVerdict,
443 717 ): "done" | "blocked" | "continue" {
444 - if (verdict.done) return "done";
445 - if (verdict.blocked) return "blocked";
718 + const normalized = normalizeJudgeVerdict(verdict);
719 + if (normalized.done) return "done";
720 + if (normalized.blocked) return "blocked";
446 721 return "continue";
449 724 function isJudgeFailure(verdict: JudgeVerdict): boolean {
450 - return verdict.reason.startsWith("judge failed:");
725 + return normalizeJudgeVerdict(verdict).reason.startsWith("judge failed:");
453 728 function isJudgeParseFailure(verdict: JudgeVerdict): boolean {
729 + const reason = normalizeJudgeVerdict(verdict).reason;
454 730 return (
455 - verdict.reason.includes("judge returned") ||
456 - verdict.reason.includes("JSON") ||
457 - verdict.reason.includes("Unexpected")
731 + reason.includes("judge returned") ||
732 + reason.includes("JSON") ||
733 + reason.includes("Unexpected")
613 -function hasFooter(): boolean {
614 - const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
615 - return footer?.loaded === true && (footer.version ?? 0) >= 1;
618 889 function clearFooter(pi: ExtensionAPI): void {
619 890 pi.events.emit("footer:segment", { id: FOOTER_SEGMENT.id, text: undefined });
834 1105 ? ` · ${verdictGlyph(state.lastVerdict)} ${sanitizeGoalText(state.lastReason, 48)}`
836 1107 return truncateToWidth(
837 - `◇ ${footerPhaseText(state, mode)} · ${budgetText(state)}${criteria} · ${sanitizeGoalText(state.objective, 160)}${reason}`,
1108 + `◇ ${footerPhaseText(state, mode)} · ctrl+shift+g expand · ${budgetText(state)}${criteria} · ${sanitizeGoalText(state.objective, 160)}${reason}`,
838 1109 Math.max(0, width),
843 1114 function updateWidget(ctx: ExtensionContext): void {
844 1115 if (!liveGoalState) {
845 - ctx.ui.setWidget(WIDGET_KEY, undefined);
1116 + if (goalWidgetRegistered) ctx.ui.setWidget(WIDGET_KEY, undefined);
1117 + goalWidgetRegistered = false;
846 1118 return;
1120 + if (goalWidgetRegistered) return;
848 1121 ctx.ui.setWidget(
849 1122 WIDGET_KEY,
850 1123 (_tui, theme) => ({
864 1137 { placement: "aboveEditor" },
1139 + goalWidgetRegistered = true;
868 1142 function updateFooter(
869 1143 pi: ExtensionAPI,
870 1144 ctx: ExtensionContext,
871 - state: GoalState | undefined,
872 - mode: GoalUiMode,
1145 + _state: GoalState | undefined,
1146 + _mode: GoalUiMode,
873 1147 ): void {
874 - if (!hasFooter()) {
875 - clearFooter(pi);
876 - ctx.ui.setStatus(
877 - STATUS_KEY,
878 - state && (mode === "judging" || mode === "queued")
879 - ? footerPhaseText(state, mode)
880 - : statusText(state),
881 - );
882 - return;
884 1148 ctx.ui.setStatus(STATUS_KEY, undefined);
885 - const shown = widgetState(state);
886 - if (!shown) {
887 - clearFooter(pi);
888 - return;
890 - const phase = footerPhaseText(shown, mode);
891 - const criteria =
892 - shown.criteria.length === 0 ? "" : ` · ${shown.criteria.length}c`;
893 - const reason = shown.lastReason
894 - ? ` · ${shortText(shown.lastReason, 36)}`
895 - : "";
896 - pi.events.emit("footer:segment", {
897 - ...FOOTER_SEGMENT,
898 - text: `${phase} · ${budgetText(shown)}${criteria}${reason}`,
899 - variants: [phase, shown.status],
900 - color: goalTone(shown, mode),
901 - });
1149 + clearFooter(pi);
904 1152 function updateHeartbeat(
1023 1271 .join("\n");
1026 -function activeGoalPrompt(state: GoalState): string {
1027 - return `\n\nActive /goal:\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
1274 +function goalControlBlock(dossier: GoalDossier | undefined): string {
1275 + if (!dossier) return "";
1276 + const active = dossier.subgoals.find(
1277 + (x) => x.id === dossier.currentSubgoalId,
1278 + );
1279 + const parts = [
1280 + `Mode: ${dossier.mode}`,
1281 + active ? `Current subgoal: ${escapeXmlText(active.title)}` : undefined,
1282 + dossier.invariants.length
1283 + ? `Invariants:\n${dossier.invariants.map((x) => `- ${escapeXmlText(x)}`).join("\n")}`
1284 + : undefined,
1285 + dossier.plan.length
1286 + ? `Plan:\n${dossier.plan.map((x, i) => `${i + 1}. ${escapeXmlText(x)}`).join("\n")}`
1287 + : undefined,
1288 + dossier.risks.length
1289 + ? `Risks:\n${dossier.risks.map((x) => `- ${escapeXmlText(x)}`).join("\n")}`
1290 + : undefined,
1291 + active?.validationHints.length
1292 + ? `Validation hints:\n${active.validationHints.map((x) => `- ${escapeXmlText(x)}`).join("\n")}`
1293 + : undefined,
1295 + .filter(Boolean)
1296 + .join("\n\n");
1297 + return parts ? `\n\n<goal_control_data>\n${parts}\n</goal_control_data>` : "";
1030 -function continuationPrompt(state: GoalState): string {
1031 - return `Continue working toward this standing goal.\n\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Call update_goal with status "complete" only after verifying success. Call update_goal with status "blocked" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.`;
1300 +function activeGoalPrompt(
1301 + state: GoalState,
1302 + dossier: GoalDossier | undefined = undefined,
1303 +): string {
1304 + return `\n\nActive /goal:\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}${goalControlBlock(dossier)}\n\nKeep working toward this standing goal. Do not redefine success smaller. Before claiming completion, verify current files, commands, tests, or deliverables. Use update_goal only after judge review and only when complete or genuinely blocked.`;
1307 +function continuationPrompt(
1308 + state: GoalState,
1309 + dossier: GoalDossier | undefined = undefined,
1310 +): string {
1311 + return `Continue working toward this standing goal.\n\n<goal_objective_data>\n${escapeXmlText(state.objective)}\n</goal_objective_data>\n\nCriteria:\n${criteriaBlock(state)}${goalControlBlock(dossier)}\n\nDo not redefine success smaller. Inspect current state before claiming completion. If incomplete, make concrete progress. Follow goal_control_data when present. Call update_goal with status "complete" only after verifying success. Call update_goal with status "blocked" only if truly at an impasse after at least three consecutive goal turns with the same blocking condition.`;
1034 1314 function kickoffPrompt(state: GoalState): string {
1112 1392 return Buffer.from(text).subarray(-tailBytes).toString();
1395 +function evidenceFromTurn(
1396 + turn: number,
1397 + evidence: TurnEvidence | undefined,
1398 + tailBytes: number,
1399 +): GoalEvidenceItem[] {
1400 + if (!evidence) return [];
1401 + const now = Date.now();
1402 + const items: GoalEvidenceItem[] = [];
1403 + if (evidence.assistantText.trim()) {
1404 + items.push({
1405 + turn,
1406 + kind: "assistant",
1407 + confidence: "claim",
1408 + text: sanitizeGoalText(tailText(evidence.assistantText, tailBytes), 240),
1409 + createdAt: now,
1410 + });
1412 + if (evidence.errorMessage) {
1413 + items.push({
1414 + turn,
1415 + kind: "error",
1416 + confidence: "observed",
1417 + text: sanitizeGoalText(evidence.errorMessage, 240),
1418 + createdAt: now,
1419 + });
1421 + for (const call of evidence.toolCalls) {
1422 + items.push({
1423 + turn,
1424 + kind: toolEvidenceKind(call.name, call.args),
1425 + confidence: "observed",
1426 + text: sanitizeGoalText(
1427 + `${call.name} ${JSON.stringify(call.args ?? {})}`,
1428 + 240,
1429 + ),
1430 + createdAt: now,
1431 + });
1433 + for (const result of evidence.toolResults) {
1434 + items.push({
1435 + turn,
1436 + kind: result.isError ? "error" : toolEvidenceKind(result.toolName),
1437 + confidence: result.isError ? "observed" : toolEvidenceConfidence(result),
1438 + text: sanitizeGoalText(
1439 + `${result.toolName}: ${tailText(result.text, tailBytes)}`,
1440 + 240,
1441 + ),
1442 + createdAt: now,
1443 + });
1445 + return items.filter((item) => item.text.length > 0);
1448 +function toolEvidenceKind(name: string, args?: unknown): EvidenceKind {
1449 + if (name === "bash") {
1450 + const command = isRecord(args) ? String(args.command ?? "") : "";
1451 + return /\b(test|vitest|jest|check|lint|ci|build)\b/iu.test(command)
1452 + ? "test"
1453 + : "command";
1455 + if (name === "read" || name === "grep" || name === "find" || name === "ls")
1456 + return "file";
1457 + return "tool";
1460 +function toolEvidenceConfidence(
1461 + result: TurnEvidence["toolResults"][number],
1462 +): EvidenceConfidence {
1463 + if (
1464 + result.toolName === "bash" &&
1465 + /\b(0 passed|passed|OK|All checks passed)\b/iu.test(result.text)
1467 + return "verified";
1468 + return "observed";
1471 +function appendTurnEvidenceToDossier(
1472 + pi: ExtensionAPI,
1473 + dossier: GoalDossier,
1474 + turn: number,
1475 + evidence: TurnEvidence | undefined,
1476 + settings: GoalSettings,
1477 +): GoalDossier {
1478 + const items = evidenceFromTurn(turn, evidence, settings.tailBytes);
1479 + if (items.length === 0) return dossier;
1480 + return updateDossier(pi, dossier, {
1481 + evidence: [...dossier.evidence, ...items].slice(-MAX_DOSSIER_EVIDENCE),
1482 + });
1115 1485 function parseModelRef(ref: string): { provider: string; model: string } {
1116 1486 const i = ref.indexOf("/");
1117 1487 if (i <= 0 || i === ref.length - 1)
1119 1489 return { provider: ref.slice(0, i), model: ref.slice(i + 1) };
1122 -function resolveJudgeModel(ctx: ExtensionContext, settings: GoalSettings) {
1123 - if (!settings.judgeModel) return ctx.model;
1124 - const { provider, model } = parseModelRef(settings.judgeModel);
1492 +function resolveConfiguredModel(
1493 + ctx: ExtensionContext,
1494 + modelRef: string | undefined,
1495 + kind: string,
1496 +) {
1497 + if (!modelRef) return ctx.model;
1498 + const { provider, model } = parseModelRef(modelRef);
1125 1499 const found = ctx.modelRegistry.find(provider, model);
1126 - if (!found)
1127 - throw new Error(`Goal judge model not found: ${settings.judgeModel}`);
1500 + if (!found) throw new Error(`Goal ${kind} model not found: ${modelRef}`);
1128 1501 return found;
1504 +function resolveJudgeModel(ctx: ExtensionContext, settings: GoalSettings) {
1505 + return resolveConfiguredModel(ctx, settings.judgeModel, "judge");
1508 +function resolvePlannerModel(ctx: ExtensionContext, settings: GoalSettings) {
1509 + return resolveConfiguredModel(ctx, settings.plannerModel, "planner");
1131 1512 function parseLooseBoolean(value: unknown): boolean {
1132 1513 if (value === true || value === 1) return true;
1133 1514 if (value === false || value === 0) return false;
1154 1535 function parseJudge(raw: string): JudgeVerdict {
1155 1536 const parsed = JSON.parse(extractJsonObject(raw));
1156 1537 if (!isRecord(parsed)) throw new Error("judge returned non-object JSON");
1538 + return normalizeJudgeVerdict(parsed);
1541 +function dossierPayload(
1542 + dossier: GoalDossier | undefined,
1543 +): Record<string, unknown> | undefined {
1544 + if (!dossier) return undefined;
1157 1545 return {
1158 - done: parseLooseBoolean(parsed.done),
1159 - blocked: parseLooseBoolean(parsed.blocked),
1160 - reason:
1161 - typeof parsed.reason === "string" && parsed.reason.trim()
1162 - ? shortText(parsed.reason.trim(), 160)
1163 - : "no reason",
1546 + mode: dossier.mode,
1547 + invariants: dossier.invariants,
1548 + plan: dossier.plan,
1549 + subgoals: dossier.subgoals,
1550 + currentSubgoalId: dossier.currentSubgoalId,
1551 + evidenceTail: dossier.evidence.slice(-12),
1552 + risks: dossier.risks,
1553 + openQuestions: dossier.openQuestions,
1554 + lastPlannerTrigger: dossier.lastPlannerTrigger,
1555 + lastJudgeReason: dossier.lastJudgeReason,
1559 +function plannerPayload(
1560 + state: GoalState,
1561 + dossier: GoalDossier,
1562 + trigger: string,
1563 +): Record<string, unknown> {
1564 + return {
1565 + trigger,
1566 + objective: state.objective,
1567 + criteria: state.criteria,
1568 + turn: state.turnsUsed,
1569 + dossier: dossierPayload(dossier),
1570 + };
1573 +function plannerUserPrompt(payload: Record<string, unknown>): string {
1574 + return `Create or refresh the internal /goal execution plan.
1576 +Use the existing dossier as current control state. Preserve useful plan/subgoals. Only change what new evidence justifies. Never reduce, reinterpret, or complete the goal. Prefer concrete subgoals and validation hints. Some goals are subjective; for those, suggest observable progress and human confirmation points.
1578 +Return only JSON: {"mode":"plan|execute|validate|recover|ask","plan":["..."],"subgoals":[{"title":"...","status":"todo|active|done|blocked|skipped","validationHints":["..."]}],"risks":["..."],"openQuestions":["..."]}.
1580 +${JSON.stringify(payload, null, 2)}`;
1583 +function applyPlannerOutput(
1584 + dossier: GoalDossier,
1585 + output: PlannerOutput,
1586 + trigger: string,
1587 +): GoalDossier {
1588 + const existingByTitle = new Map(
1589 + dossier.subgoals.map((subgoal) => [subgoal.title.toLowerCase(), subgoal]),
1590 + );
1591 + const rawSubgoals = Array.isArray(output.subgoals) ? output.subgoals : [];
1592 + const subgoals = rawSubgoals
1593 + .slice(0, MAX_DOSSIER_LIST)
1594 + .flatMap((raw, index) => {
1595 + const title = isRecord(raw)
1596 + ? typeof raw.title === "string"
1597 + ? raw.title
1598 + : undefined
1599 + : typeof raw === "string"
1600 + ? raw
1601 + : undefined;
1602 + const safeTitle = title ? sanitizeGoalText(title, 160) : "";
1603 + if (!safeTitle) return [];
1604 + const existing = existingByTitle.get(safeTitle.toLowerCase());
1605 + const status =
1606 + isRecord(raw) && isSubgoalStatus(raw.status)
1607 + ? raw.status
1608 + : index === 0
1609 + ? "active"
1610 + : "todo";
1611 + const validationHints = isRecord(raw)
1612 + ? stringList(raw.validationHints, 6, 160)
1613 + : [];
1614 + return [
1616 + id: existing?.id ?? `sg-${index + 1}`,
1617 + title: safeTitle,
1618 + status,
1619 + validationHints,
1620 + },
1621 + ];
1622 + });
1623 + const nextSubgoals = subgoals.length > 0 ? subgoals : dossier.subgoals;
1624 + const active =
1625 + nextSubgoals.find((x) => x.status === "active") ??
1626 + nextSubgoals.find((x) => x.status === "todo");
1627 + return {
1628 + ...dossier,
1629 + mode: isGoalMode(output.mode) ? output.mode : dossier.mode,
1630 + plan: stringList(output.plan, MAX_DOSSIER_LIST, 160),
1631 + subgoals: nextSubgoals,
1632 + currentSubgoalId: active?.id,
1633 + risks: stringList(output.risks, MAX_DOSSIER_LIST, 160),
1634 + openQuestions: stringList(output.openQuestions, 8, 160),
1635 + lastPlannerTrigger: trigger,
1636 + updatedAt: Date.now(),
1637 + };
1640 +function isSubgoalStatus(value: unknown): GoalSubgoal["status"] | undefined {
1641 + return value === "todo" ||
1642 + value === "active" ||
1643 + value === "done" ||
1644 + value === "blocked" ||
1645 + value === "skipped"
1646 + ? value
1647 + : undefined;
1167 1650 function judgePayload(
1168 1651 ctx: ExtensionContext,
1169 1652 state: GoalState,
1170 1653 settings: GoalSettings,
1171 1654 evidence: TurnEvidence | undefined,
1655 + dossier?: GoalDossier,
1172 1656 ): Record<string, unknown> {
1173 1657 return {
1174 1658 objective: state.objective,
1184 1668 ...result,
1185 1669 text: tailText(result.text, settings.tailBytes),
1671 + dossier: dossierPayload(dossier),
1196 1681 ${JSON.stringify(payload, null, 2)}`;
1684 +async function runPlanner(
1685 + ctx: ExtensionContext,
1686 + state: GoalState,
1687 + dossier: GoalDossier,
1688 + settings: GoalSettings,
1689 + trigger: string,
1690 +): Promise<GoalDossier> {
1691 + const testPlanner = (globalThis as GoalTestGlobals)[PLANNER_FOR_TEST];
1692 + const payload = plannerPayload(state, dossier, trigger);
1693 + if (testPlanner)
1694 + return applyPlannerOutput(dossier, testPlanner(payload), trigger);
1695 + const model = resolvePlannerModel(ctx, settings);
1696 + if (!model) return dossier;
1697 + const loader = new DefaultResourceLoader(judgeResourceLoaderOptions(ctx));
1698 + await loader.reload();
1699 + const { session } = await createAgentSession({
1700 + cwd: ctx.cwd,
1701 + model,
1702 + modelRegistry: ctx.modelRegistry,
1703 + resourceLoader: loader,
1704 + sessionManager: SessionManager.inMemory(ctx.cwd),
1705 + tools: ["read", "grep", "find", "ls", "bash"],
1706 + thinkingLevel: settings.plannerThinkingLevel,
1707 + });
1708 + try {
1709 + let raw = "";
1710 + const unsubscribe = session.subscribe((event) => {
1711 + if (event.type !== "message_end" || event.message.role !== "assistant")
1712 + return;
1713 + raw = textFromContent(event.message.content);
1714 + });
1715 + try {
1716 + await session.prompt(plannerUserPrompt(payload), { source: "extension" });
1717 + } finally {
1718 + unsubscribe();
1720 + if (!raw.trim()) raw = textFromContent(session.messages.at(-1)?.content);
1721 + const parsed = JSON.parse(extractJsonObject(raw));
1722 + return applyPlannerOutput(dossier, isRecord(parsed) ? parsed : {}, trigger);
1723 + } finally {
1724 + session.dispose();
1728 +function shouldRefreshPlanner(
1729 + state: GoalState,
1730 + dossier: GoalDossier,
1731 + verdict: JudgeVerdict,
1732 +): string | undefined {
1733 + if (dossier.subgoals.length === 0) return "empty-plan";
1734 + if (state.turnsUsed > 0 && state.turnsUsed % PLANNER_REFRESH_TURNS === 0)
1735 + return "periodic";
1736 + if (state.blockedStreak && state.blockedStreak.count >= 2)
1737 + return "blocked-risk";
1738 + if (
1739 + /\b(no proof|verify|unclear|vague|not enough|missing)\b/iu.test(
1740 + verdict.reason,
1743 + return "weak-proof";
1744 + return undefined;
1747 +function refreshPlannerInBackground(
1748 + pi: ExtensionAPI,
1749 + ctx: ExtensionContext,
1750 + state: GoalState,
1751 + dossier: GoalDossier,
1752 + trigger: string,
1753 +): void {
1754 + const globals = globalThis as GoalTestGlobals;
1755 + if (
1756 + (process.env.VITEST || globals[JUDGE_COMPLETE_FOR_TEST]) &&
1757 + !globals[PLANNER_FOR_TEST]
1759 + return;
1760 + void runPlanner(ctx, state, dossier, loadSettings(pi), trigger)
1761 + .then((next) => {
1762 + try {
1763 + const latest = latestGoalDossier(ctx, state.id) ?? dossier;
1764 + appendDossier(pi, {
1765 + ...next,
1766 + evidence: latest.evidence,
1767 + lastJudgeReason: latest.lastJudgeReason ?? next.lastJudgeReason,
1768 + updatedAt: Date.now(),
1769 + });
1770 + } catch (error) {
1771 + if (!isStaleContextError(error)) throw error;
1773 + })
1774 + .catch((error) => {
1775 + try {
1776 + debugGoal(pi, "planner-failed", {
1777 + goalId: state.id,
1778 + trigger,
1779 + reason: error instanceof Error ? error.message : String(error),
1780 + });
1781 + } catch (debugError) {
1782 + if (!isStaleContextError(debugError)) throw debugError;
1784 + });
1199 1787 function appendJudge(
1200 1788 pi: ExtensionAPI,
1201 1789 ctx: ExtensionContext,
1233 1821 state: GoalState,
1234 1822 settings: GoalSettings,
1235 1823 evidence: TurnEvidence | undefined,
1824 + dossier: GoalDossier | undefined,
1236 1825 ): Promise<JudgeVerdict> {
1237 1826 const model = resolveJudgeModel(ctx, settings);
1238 1827 if (!model) return { done: false, blocked: false, reason: "no judge model" };
1251 1840 content: [
1253 1842 type: "text" as const,
1254 - text: judgeUserPrompt(judgePayload(ctx, state, settings, evidence)),
1843 + text: judgeUserPrompt(
1844 + judgePayload(ctx, state, settings, evidence, dossier),
1845 + ),
1257 1848 timestamp: Date.now(),
1287 1878 throw lastError;
1881 +function judgeResourceLoaderOptions(ctx: ExtensionContext) {
1882 + return {
1883 + cwd: ctx.cwd,
1884 + agentDir: getAgentDir(),
1885 + systemPromptOverride: () => JUDGE_SYSTEM_PROMPT,
1886 + };
1290 1889 async function judgeGoalWithAgent(
1291 1890 ctx: ExtensionContext,
1292 1891 state: GoalState,
1293 1892 settings: GoalSettings,
1294 1893 evidence: TurnEvidence | undefined,
1894 + dossier: GoalDossier | undefined,
1295 1895 ): Promise<JudgeVerdict> {
1296 1896 const model = resolveJudgeModel(ctx, settings);
1297 1897 if (!model) return { done: false, blocked: false, reason: "no judge model" };
1298 - const loader = new DefaultResourceLoader({
1299 - cwd: ctx.cwd,
1300 - systemPromptOverride: () => JUDGE_SYSTEM_PROMPT,
1301 - });
1898 + const loader = new DefaultResourceLoader(judgeResourceLoaderOptions(ctx));
1302 1899 await loader.reload();
1303 1900 const { session } = await createAgentSession({
1304 1901 cwd: ctx.cwd,
1320 1917 await session.prompt(
1321 - judgeUserPrompt(judgePayload(ctx, state, settings, evidence)),
1918 + judgeUserPrompt(judgePayload(ctx, state, settings, evidence, dossier)),
1322 1919 { source: "extension" },
1324 1921 } finally {
1336 1933 state: GoalState,
1337 1934 settings: GoalSettings,
1338 1935 evidence: TurnEvidence | undefined,
1936 + dossier: GoalDossier | undefined,
1339 1937 ): Promise<JudgeVerdict> {
1340 1938 if ((globalThis as GoalTestGlobals)[JUDGE_COMPLETE_FOR_TEST])
1341 - return judgeGoalWithDirectComplete(ctx, state, settings, evidence);
1939 + return judgeGoalWithDirectComplete(ctx, state, settings, evidence, dossier);
1940 + if (process.env.VITEST) throw new Error("test judge unavailable");
1342 1941 let lastError: unknown;
1343 1942 for (let attempt = 0; attempt < JUDGE_ATTEMPTS; attempt++) {
1345 - return await judgeGoalWithAgent(ctx, state, settings, evidence);
1944 + return await judgeGoalWithAgent(ctx, state, settings, evidence, dossier);
1346 1945 } catch (error) {
1347 1946 lastError = error;
1476 2075 return;
2078 + const dossier = latestGoalDossier(ctx, latest.id);
1479 2079 pi.sendMessage(
1481 2081 customType: GOAL_CONTINUATION_ENTRY,
1482 - content: continuationPrompt(latest),
2082 + content: continuationPrompt(latest, dossier),
1483 2083 display: false,
1484 2084 details: { goalId: latest.id, turn: latest.turnsUsed + 1 },
1627 2227 pi.on("session_start", (_event, ctx) => {
1628 2228 state = latestGoalState(ctx);
2229 + if (state && state.status === "active") ensureDossier(pi, ctx, state);
1629 2230 continuation.queued = false;
1630 2231 continuation.scheduled = false;
1631 2232 removeTerminalInput?.();
1660 2261 lastReason: `steering added as criterion: ${shortText(text)}`,
1662 2263 appendGoalEvent(pi, ctx, "steering-added", state, { text });
2264 + refreshPlannerInBackground(
2265 + pi,
2266 + ctx,
2267 + state,
2268 + ensureDossier(pi, ctx, state),
2269 + "user-steering",
2270 + );
1663 2271 renderGoalUi(ctx, state);
1665 2273 pi.sendMessage(
1682 2290 const objective = extractStandingGoalObjective(event.prompt);
1683 2291 if (objective) {
1684 2292 const settings = loadSettings(pi);
1685 - const now = Date.now();
1686 - state = {
1687 - id: crypto.randomUUID(),
1688 - objective,
1689 - criteria: [],
1690 - status: "active",
1691 - turnsUsed: 0,
1692 - tokenBudget: settings.tokenBudget,
1693 - tokensUsed: 0,
1694 - timeBudgetSeconds: settings.timeBudgetSeconds,
1695 - timeUsedSeconds: 0,
1696 - errorRetries: 0,
1697 - sessionId: currentSessionId(ctx),
1698 - createdAt: now,
1699 - updatedAt: now,
1700 - };
2293 + state = createGoalState(objective, settings, currentSessionId(ctx));
1701 2294 appendGoal(pi, state);
2295 + const dossier = appendDossier(pi, createInitialDossier(state));
2296 + refreshPlannerInBackground(pi, ctx, state, dossier, "adopted-goal");
1702 2297 renderGoalUi(ctx, state);
1703 2298 syncUpdateGoalTool();
1706 2301 if (!state || state.status !== "active" || !ownsGoal(ctx, state)) return;
1707 - return { systemPrompt: event.systemPrompt + activeGoalPrompt(state) };
2302 + const dossier = ensureDossier(pi, ctx, state);
2303 + return {
2304 + systemPrompt: event.systemPrompt + activeGoalPrompt(state, dossier),
2305 + };
1710 2308 pi.on("context", (event) => {
1780 2378 syncUpdateGoalTool();
1781 2379 if (!state || state.status !== "active" || !ownsGoal(ctx, state)) return;
1782 2380 const evidence = lastTurnEvidence;
2381 + const settings = loadSettings(pi);
2382 + let dossier = ensureDossier(pi, ctx, state);
2383 + dossier = appendTurnEvidenceToDossier(
2384 + pi,
2385 + dossier,
2386 + state.turnsUsed + 1,
2387 + evidence,
2388 + settings,
2389 + );
1784 2391 evidence?.stopReason === "aborted" ||
1785 2392 evidence?.stopReason === "error"
1827 2434 renderGoalUi(ctx, judged, "judging");
1828 2435 let verdict: JudgeVerdict;
1830 - verdict = await judgeGoal(ctx, judged, loadSettings(pi), evidence);
2437 + verdict = normalizeJudgeVerdict(
2438 + await judgeGoal(ctx, judged, settings, evidence, dossier),
2439 + );
1831 2440 } catch (err) {
2441 + const message =
2442 + err instanceof Error && err.message ? err.message : String(err);
1832 2443 verdict = {
1833 2444 done: false,
1834 2445 blocked: false,
1835 - reason: `judge failed: ${(err as Error).message}`,
2446 + reason: `judge failed: ${message}`,
1838 2449 if (state !== judged || state.status !== "active") return;
2450 + dossier = updateDossier(pi, latestGoalDossier(ctx, judged.id) ?? dossier, {
2451 + lastJudgeReason: verdict.reason,
2452 + });
1839 2453 appendJudge(pi, ctx, "verdict", judged, verdict);
1840 2454 const commonPatch: Partial<GoalState> = {
1841 2455 lastReason: verdict.reason,
1862 2476 appendGoalEvent(pi, ctx, "paused", state, { reason: verdict.reason });
1863 2477 if (ctx.hasUI)
1864 2478 ctx.ui.notify(`Goal paused — ${verdict.reason}`, "warning");
1865 - } else scheduleContinuation(pi, ctx, state, continuation);
2479 + } else {
2480 + refreshPlannerInBackground(pi, ctx, state, dossier, "judge-failed");
2481 + scheduleContinuation(pi, ctx, state, continuation);
1866 2483 return;
1868 2485 if (verdict.done) {
1897 2514 appendGoalEvent(pi, ctx, "blocked", state, { reason: verdict.reason });
1898 2515 if (ctx.hasUI)
1899 2516 ctx.ui.notify(`Goal blocked: ${verdict.reason}`, "warning");
1900 - } else scheduleContinuation(pi, ctx, state, continuation);
2517 + } else {
2518 + if (blockedStreak.count >= 2)
2519 + refreshPlannerInBackground(pi, ctx, state, dossier, "blocked-risk");
2520 + scheduleContinuation(pi, ctx, state, continuation);
1901 2522 return;
1903 2524 const turnsUsed = judged.turnsUsed + 1;
1935 2556 renderGoalUi(ctx, state);
1936 2557 syncUpdateGoalTool();
2559 + const trigger = shouldRefreshPlanner(state, dossier, verdict);
2560 + if (trigger) refreshPlannerInBackground(pi, ctx, state, dossier, trigger);
1937 2562 scheduleContinuation(pi, ctx, state, continuation);
2014 2639 errorRetries: 0,
2015 2640 sessionId: currentSessionId(ctx),
2642 + const dossier = ensureDossier(pi, ctx, state);
2643 + refreshPlannerInBackground(pi, ctx, state, dossier, "resume");
2017 2644 renderGoalUi(ctx, state);
2018 2645 syncUpdateGoalTool();
2019 2646 ctx.ui.notify(
2108 2735 "warning",
2110 2737 const settings = loadSettings(pi);
2111 - state = {
2112 - id: crypto.randomUUID(),
2113 - objective: input,
2114 - criteria: [],
2115 - status: "active",
2116 - turnsUsed: 0,
2117 - tokenBudget: settings.tokenBudget,
2118 - tokensUsed: 0,
2119 - timeBudgetSeconds: settings.timeBudgetSeconds,
2120 - timeUsedSeconds: 0,
2121 - errorRetries: 0,
2122 - sessionId: currentSessionId(ctx),
2123 - createdAt: Date.now(),
2124 - updatedAt: Date.now(),
2125 - };
2738 + state = createGoalState(input, settings, currentSessionId(ctx));
2126 2739 appendGoal(pi, state);
2740 + const dossier = appendDossier(pi, createInitialDossier(state));
2741 + refreshPlannerInBackground(pi, ctx, state, dossier, "new-goal");
2127 2742 renderGoalUi(ctx, state);
2128 2743 syncUpdateGoalTool();
2129 2744 ctx.ui.notify("Goal set", "info");
2152 2767 export const GOAL_PROBE_MESSAGE = PROBE_MESSAGE;
2153 2768 export const GOAL_STATE_CUSTOM_TYPE = GOAL_STATE_ENTRY;
2769 +export const GOAL_DOSSIER_CUSTOM_TYPE = GOAL_DOSSIER_ENTRY;
2154 2770 function setCompleteJudgeForTest(fn: JudgeComplete) {
2155 2771 (globalThis as GoalTestGlobals)[JUDGE_COMPLETE_FOR_TEST] = fn;
2171 2787 kickoffPrompt,
2172 2788 latestAssistantTail,
2173 2789 latestGoalState,
2790 + latestGoalDossier,
2791 + createGoalState,
2792 + createInitialDossier,
2793 + applyPlannerOutput,
2794 + dossierPayload,
2795 + goalControlBlock,
2796 + evidenceFromTurn,
2797 + appendTurnEvidenceToDossier,
2174 2798 buildTurnEvidence,
2175 2799 mergeTurnEvidence,
2176 2800 cancelGoalRun,
2205 2829 isJudgeParseFailure,
2206 2830 judgeVerdictLabel,
2207 2831 goalVerdictLabel,
2832 + judgeResourceLoaderOptions,
2208 2833 showsTurnBudget,
2209 2834 showsPersistentStatus,
2210 2835 wrapVisibleWords,