From fc4e6347894aba7d162eda941d3e6e1c1f52604f Mon Sep 17 00:00:00 2001 From: Stefan Kaufmann Date: Wed, 1 Apr 2026 00:22:29 +0200 Subject: [PATCH] feat(pi): support phase config files (#446) * allow Plannotator phase configs in pi-extension * fix tool name --- apps/pi-extension/README.md | 81 ++++++++ apps/pi-extension/config.test.ts | 166 +++++++++++++++ apps/pi-extension/config.ts | 318 +++++++++++++++++++++++++++++ apps/pi-extension/index.ts | 241 ++++++++++++++++++---- apps/pi-extension/package.json | 2 + apps/pi-extension/plannotator.json | 12 ++ bun.lock | 7 +- 7 files changed, 785 insertions(+), 42 deletions(-) create mode 100644 apps/pi-extension/config.test.ts create mode 100644 apps/pi-extension/config.ts create mode 100644 apps/pi-extension/plannotator.json diff --git a/apps/pi-extension/README.md b/apps/pi-extension/README.md index 759163e..491722e 100644 --- a/apps/pi-extension/README.md +++ b/apps/pi-extension/README.md @@ -63,6 +63,87 @@ When the agent calls `plannotator_submit_plan`, the Plannotator UI opens in your The agent iterates on the plan until you approve, then executes with full tool access. On resubmission, Plan Diff highlights what changed since the previous version. +### Configuring per-phase behavior + +Plannotator loads configuration in three layers: + +1. Built-in base config shipped with the package: `plannotator.json` +2. Global user config: `~/.pi/agent/plannotator.json` +3. Project-local config: `/.pi/plannotator.json` + +Later layers overwrite earlier ones. If a field is omitted, it inherits the value from lower-precedence layers. If a value is set to `null`, an empty string, or an empty array, it clears the inherited value instead of merging it. You can also set `defaults` or an entire phase object to `null` to clear all inherited settings from lower-precedence layers. + +#### Top-level shape + +```json +{ + "defaults": { + "model": { "provider": "anthropic", "id": "claude-sonnet-4-5" }, + "thinking": "medium", + "activeTools": ["read", "bash"], + "statusLabel": "Ready", + "systemPrompt": "Optional prompt template" + }, + "phases": { + "planning": { + "model": null, + "thinking": null, + "activeTools": ["grep", "find", "ls", "plannotator_submit_plan"], + "statusLabel": "⏸ plan", + "systemPrompt": "[PLANNING]\nPlan file: ${planFilePath}" + }, + "executing": { + "model": { "provider": "anthropic", "id": "claude-sonnet-4-5" }, + "thinking": "high", + "activeTools": [], + "statusLabel": "", + "systemPrompt": "[EXECUTING]\nRemaining steps:\n${todoList}" + }, + "reviewing": { + "systemPrompt": "..." + } + } +} +``` + +#### Option reference + +| Option | Type | Meaning | +|--------|------|---------| +| `defaults` | object | Base values applied to every phase before phase-specific overrides | +| `phases` | object | Phase-specific overrides | +| `phases.planning` | object | Settings for planning mode | +| `phases.executing` | object | Settings for execution mode | +| `phases.reviewing` | object | Reserved for future review-mode customization | +| `model` | `{ provider, id }` \| `null` | Sets the model for the phase; `null` leaves the current model unchanged | +| `thinking` | `minimal` \| `low` \| `medium` \| `high` \| `xhigh` \| `null` | Sets the thinking level; `null` leaves the current level unchanged | +| `activeTools` | string[] \| `null` | Extra tools to enable for the phase; `[]` or `null` means no extra phase tools | +| `statusLabel` | string \| `null` | Optional UI label for the phase; empty/null clears it | +| `systemPrompt` | string \| `null` | Phase system prompt template; empty/null disables prompt injection | + +#### Prompt variables + +Use these inside `systemPrompt` strings: + +- `${planFilePath}` — current plan file path +- `${todoList}` — remaining checklist items as markdown checkboxes +- `${completedCount}` — completed checklist count +- `${totalCount}` — total checklist count +- `${remainingCount}` — remaining checklist count +- `${phase}` — current runtime phase (`planning`, `executing`, `reviewing`, or `idle`) + +#### Behavior notes + +- Unknown template variables trigger a warning in the UI and are rendered as empty strings. +- `activeTools` are additive with the tools currently active in the session, so Plannotator still preserves tools provided by other extensions. +- Execution progress remains dynamic (`[DONE:n]` + checklist tracking), even if `statusLabel` is set. + +#### Example files + +- Built-in base config shipped with the package: `apps/pi-extension/plannotator.json` +- Global user override: `~/.pi/agent/plannotator.json` +- Project-local override: `/.pi/plannotator.json` + ### Code review Run `/plannotator-review` to open your current git changes in the code review UI. Annotate specific lines, switch between diff views (uncommitted, staged, last commit, branch), and submit feedback that gets sent to the agent. diff --git a/apps/pi-extension/config.test.ts b/apps/pi-extension/config.test.ts new file mode 100644 index 0000000..bf3cf3a --- /dev/null +++ b/apps/pi-extension/config.test.ts @@ -0,0 +1,166 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadPlannotatorConfig, formatTodoList, renderTemplate, resolvePhaseProfile } from "./config"; + +const tempDirs: string[] = []; +const originalHome = process.env.HOME; + +function makeTempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + if (originalHome === undefined) { + delete process.env.HOME; + } else { + process.env.HOME = originalHome; + } + + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("plannotator config", () => { + test("loads the shipped internal base config", () => { + const cwdDir = makeTempDir("plannotator-config-base-"); + process.env.HOME = makeTempDir("plannotator-config-home-base-"); + + const loaded = loadPlannotatorConfig(cwdDir); + const planning = resolvePhaseProfile(loaded.config, "planning"); + + expect(loaded.warnings).toEqual([]); + expect(planning.statusLabel).toBe("⏸ plan"); + expect(planning.activeTools).toEqual(["grep", "find", "ls", "plannotator_submit_plan"]); + }); + + test("allows a project config to clear an inherited phase with null", () => { + const homeDir = makeTempDir("plannotator-config-home-null-"); + const cwdDir = makeTempDir("plannotator-config-cwd-null-"); + process.env.HOME = homeDir; + + const globalConfigDir = join(homeDir, ".pi", "agent"); + const projectConfigDir = join(cwdDir, ".pi"); + mkdirSync(globalConfigDir, { recursive: true }); + mkdirSync(projectConfigDir, { recursive: true }); + writeFileSync( + join(globalConfigDir, "plannotator.json"), + JSON.stringify({ + phases: { planning: { statusLabel: "global", activeTools: ["bash"] } }, + }), + "utf-8", + ); + writeFileSync( + join(projectConfigDir, "plannotator.json"), + JSON.stringify({ + phases: { planning: null }, + }), + "utf-8", + ); + + const loaded = loadPlannotatorConfig(cwdDir); + const planning = resolvePhaseProfile(loaded.config, "planning"); + + expect(loaded.warnings).toEqual([]); + expect(planning.statusLabel).toBeUndefined(); + expect(planning.activeTools).toBeUndefined(); + }); + + test("loads global and project configs with project precedence", () => { + const homeDir = makeTempDir("plannotator-config-home-"); + const cwdDir = makeTempDir("plannotator-config-cwd-"); + process.env.HOME = homeDir; + + const globalConfigDir = join(homeDir, ".pi", "agent"); + const projectConfigDir = join(cwdDir, ".pi"); + mkdirSync(globalConfigDir, { recursive: true }); + mkdirSync(projectConfigDir, { recursive: true }); + writeFileSync( + join(globalConfigDir, "plannotator.json"), + JSON.stringify({ + defaults: { + thinking: "low", + model: { provider: "anthropic", id: "claude-sonnet-4-5" }, + }, + phases: { planning: { statusLabel: "global", activeTools: ["bash"] } }, + }), + "utf-8", + ); + writeFileSync( + join(projectConfigDir, "plannotator.json"), + JSON.stringify({ + defaults: { thinking: null, model: null }, + phases: { planning: { statusLabel: "project", activeTools: [] } }, + }), + "utf-8", + ); + + const loaded = loadPlannotatorConfig(cwdDir); + const planning = resolvePhaseProfile(loaded.config, "planning"); + + expect(loaded.warnings).toEqual([]); + expect(planning.thinking).toBeUndefined(); + expect(planning.model).toBeUndefined(); + expect(planning.statusLabel).toBe("project"); + expect(planning.activeTools).toEqual([]); + }); + + test("treats empty strings as clearing values", () => { + const profile = resolvePhaseProfile( + { + defaults: { statusLabel: "base", systemPrompt: "base prompt", activeTools: ["bash"] }, + phases: { planning: { statusLabel: "", systemPrompt: "", activeTools: [] } }, + }, + "planning", + ); + + expect(profile.statusLabel).toBeUndefined(); + expect(profile.systemPrompt).toBeUndefined(); + expect(profile.activeTools).toEqual([]); + }); + + test("allows clearing an entire phase with null", () => { + const profile = resolvePhaseProfile( + { + defaults: { thinking: "low", activeTools: ["bash"], statusLabel: "base" }, + phases: { planning: null }, + }, + "planning", + ); + + expect(profile.thinking).toBe("low"); + expect(profile.activeTools).toEqual(["bash"]); + expect(profile.statusLabel).toBe("base"); + }); + + test("renders prompt templates and reports unknown variables", () => { + const rendered = renderTemplate("Hello ${name} ${missing}", { + planFilePath: "PLAN.md", + todoList: "- [ ] A", + completedCount: 1, + totalCount: 2, + remainingCount: 1, + phase: "planning", + }); + + expect(rendered.text).toBe("Hello "); + expect(rendered.unknownVariables).toEqual(["name", "missing"]); + }); + + test("formats todo lists from checklist items", () => { + const stats = formatTodoList([ + { step: 1, text: "First", completed: true }, + { step: 2, text: "Second", completed: false }, + { step: 3, text: "Third", completed: false }, + ]); + + expect(stats.completedCount).toBe(1); + expect(stats.totalCount).toBe(3); + expect(stats.remainingCount).toBe(2); + expect(stats.todoList).toBe("- [ ] 2. Second\n- [ ] 3. Third"); + }); +}); diff --git a/apps/pi-extension/config.ts b/apps/pi-extension/config.ts new file mode 100644 index 0000000..7419c66 --- /dev/null +++ b/apps/pi-extension/config.ts @@ -0,0 +1,318 @@ +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { homedir } from "node:os"; +import type { ThinkingLevel } from "@mariozechner/pi-agent-core"; + +export type PhaseName = "planning" | "executing" | "reviewing"; +export type RuntimePhase = PhaseName | "idle"; + +export interface PhaseModelRef { + provider: string; + id: string; +} + +/** + * Config values loaded from JSON can intentionally clear inherited values. + * + * - `null` clears a value from a parent config. + * - `[]` clears active tools. + * - `""` clears string values. + */ +export interface PhaseProfile { + model?: PhaseModelRef | null; + thinking?: ThinkingLevel | null; + activeTools?: string[] | null; + statusLabel?: string | null; + systemPrompt?: string | null; +} + +export interface PlannotatorConfig { + defaults?: PhaseProfile | null; + phases?: Partial>; +} + +export interface LoadedPlannotatorConfig { + config: PlannotatorConfig; + warnings: string[]; +} + +export interface ResolvedPhaseProfile { + model?: PhaseModelRef; + thinking?: ThinkingLevel; + activeTools?: string[]; + statusLabel?: string; + systemPrompt?: string; +} + +export interface PromptVariables { + planFilePath: string; + todoList: string; + completedCount: number; + totalCount: number; + remainingCount: number; + phase: RuntimePhase; +} + +export interface PromptRenderResult { + text: string; + unknownVariables: string[]; +} + +const INTERNAL_CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "plannotator.json"); +const PHASES: PhaseName[] = ["planning", "executing", "reviewing"]; +const THINKING_LEVELS = new Set(["minimal", "low", "medium", "high", "xhigh"]); + +function getAgentConfigDir(): string { + const envDir = process.env.PI_CODING_AGENT_DIR; + if (envDir) return envDir; + return join(process.env.HOME || process.env.USERPROFILE || homedir(), ".pi", "agent"); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function readJsonFile(path: string): { data?: unknown; error?: string } { + if (!existsSync(path)) return {}; + + try { + return { data: JSON.parse(readFileSync(path, "utf-8")) }; + } catch (error) { + return { error: `Failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}` }; + } +} + +function normalizeModel(value: unknown): PhaseModelRef | null | undefined { + if (value === null) return null; + if (!isRecord(value)) return undefined; + + const provider = typeof value.provider === "string" ? value.provider.trim() : ""; + const id = typeof value.id === "string" ? value.id.trim() : ""; + if (!provider || !id) return undefined; + return { provider, id }; +} + +function normalizeThinking(value: unknown): ThinkingLevel | null | undefined { + if (value === null) return null; + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + if (!trimmed) return null; + + return THINKING_LEVELS.has(trimmed as ThinkingLevel) ? (trimmed as ThinkingLevel) : undefined; +} + +function normalizeTools(value: unknown): string[] | null | undefined { + if (value === null) return null; + if (!Array.isArray(value)) return undefined; + if (value.length === 0) return []; + + const tools = value.filter((tool): tool is string => typeof tool === "string" && tool.trim().length > 0); + return tools.length > 0 ? tools : undefined; +} + +function normalizeLabel(value: unknown): string | null | undefined { + if (value === null) return null; + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +function normalizePrompt(value: unknown): string | null | undefined { + if (value === null) return null; + if (typeof value !== "string") return undefined; + return value.length > 0 ? value : null; +} + +function normalizeProfile(raw: unknown): PhaseProfile | null | undefined { + if (raw === null) return null; + if (!isRecord(raw)) return undefined; + + const profile: PhaseProfile = {}; + + if ("model" in raw) profile.model = normalizeModel(raw.model); + if ("thinking" in raw) profile.thinking = normalizeThinking(raw.thinking); + if ("thinkingLevel" in raw && profile.thinking === undefined) profile.thinking = normalizeThinking(raw.thinkingLevel); + if ("activeTools" in raw) profile.activeTools = normalizeTools(raw.activeTools); + if ("statusLabel" in raw) profile.statusLabel = normalizeLabel(raw.statusLabel); + if ("systemPrompt" in raw) profile.systemPrompt = normalizePrompt(raw.systemPrompt); + + return profile; +} + +function cloneProfile(profile: PhaseProfile | null | undefined): PhaseProfile | null | undefined { + if (profile === null || profile === undefined) return profile; + return { ...profile, activeTools: profile.activeTools ? [...profile.activeTools] : profile.activeTools }; +} + +function mergeProfile(base: PhaseProfile | null | undefined, override: PhaseProfile | null | undefined): PhaseProfile | null | undefined { + if (override === null) return null; + if (override === undefined) return cloneProfile(base); + if (base === null || base === undefined) return cloneProfile(override); + + const merged: PhaseProfile = { + model: override.model !== undefined ? override.model : base.model, + thinking: override.thinking !== undefined ? override.thinking : base.thinking, + activeTools: override.activeTools !== undefined ? override.activeTools : base.activeTools, + statusLabel: override.statusLabel !== undefined ? override.statusLabel : base.statusLabel, + systemPrompt: override.systemPrompt !== undefined ? override.systemPrompt : base.systemPrompt, + }; + + return merged; +} + +function mergeConfig(base: PlannotatorConfig, override: PlannotatorConfig): PlannotatorConfig { + const phases: Partial> = {}; + for (const phase of PHASES) { + const merged = mergeProfile(base.phases?.[phase], override.phases?.[phase]); + if (merged !== undefined) phases[phase] = merged; + } + + return { + defaults: mergeProfile(base.defaults, override.defaults), + phases: Object.keys(phases).length > 0 ? phases : undefined, + }; +} + +function loadConfigSource(path: string): { config: PlannotatorConfig; warning?: string } { + const parsed = readJsonFile(path); + if (parsed.error) { + return { config: {}, warning: parsed.error }; + } + + const raw = parsed.data; + if (!isRecord(raw)) return { config: {} }; + + const config: PlannotatorConfig = {}; + if ("defaults" in raw) config.defaults = normalizeProfile(raw.defaults); + + if ("phases" in raw && isRecord(raw.phases)) { + const phases: Partial> = {}; + for (const phase of PHASES) { + const normalized = normalizeProfile(raw.phases[phase]); + if (normalized !== undefined) phases[phase] = normalized; + } + if (Object.keys(phases).length > 0) config.phases = phases; + } + + return { config }; +} + +export function loadPlannotatorConfig(cwd: string): LoadedPlannotatorConfig { + const warnings: string[] = []; + + const internal = loadConfigSource(INTERNAL_CONFIG_PATH); + if (internal.warning) warnings.push(internal.warning); + + const globalPath = join(getAgentConfigDir(), "plannotator.json"); + const globalConfig = loadConfigSource(globalPath); + if (globalConfig.warning) warnings.push(globalConfig.warning); + + const projectPath = join(cwd, ".pi", "plannotator.json"); + const projectConfig = loadConfigSource(projectPath); + if (projectConfig.warning) warnings.push(projectConfig.warning); + + const merged = mergeConfig(mergeConfig(internal.config, globalConfig.config), projectConfig.config); + return { config: merged, warnings }; +} + +export function resolvePhaseProfile(config: PlannotatorConfig, phase: PhaseName): ResolvedPhaseProfile { + const defaults = config.defaults ?? {}; + const phaseConfig = config.phases?.[phase] ?? {}; + + return { + model: resolveModel(defaults.model, phaseConfig.model), + thinking: resolveThinking(defaults.thinking, phaseConfig.thinking), + activeTools: resolveTools(defaults.activeTools, phaseConfig.activeTools), + statusLabel: resolveString(defaults.statusLabel, phaseConfig.statusLabel), + systemPrompt: resolveString(defaults.systemPrompt, phaseConfig.systemPrompt), + }; +} + +function resolveModel(base: PhaseModelRef | null | undefined, override: PhaseModelRef | null | undefined): PhaseModelRef | undefined { + if (override !== undefined) { + return override ?? undefined; + } + return base ?? undefined; +} + +function resolveThinking(base: ThinkingLevel | null | undefined, override: ThinkingLevel | null | undefined): ThinkingLevel | undefined { + if (override !== undefined) { + return override ?? undefined; + } + return base ?? undefined; +} + +function resolveTools(base: string[] | null | undefined, override: string[] | null | undefined): string[] | undefined { + if (override !== undefined) { + if (override === null) return []; + return [...override]; + } + if (base === null) return []; + return base ? [...base] : undefined; +} + +function resolveString(base: string | null | undefined, override: string | null | undefined): string | undefined { + if (override !== undefined) { + if (override === null || override === "") return undefined; + return override; + } + return base ?? undefined; +} + +export function buildPromptVariables(options: { + planFilePath: string; + phase: RuntimePhase; + totalCount: number; + completedCount: number; + remainingCount?: number; + todoList?: string; +}): PromptVariables { + const totalCount = options.totalCount; + const completedCount = options.completedCount; + const remainingCount = options.remainingCount ?? Math.max(totalCount - completedCount, 0); + + return { + planFilePath: options.planFilePath, + todoList: options.todoList ?? "", + completedCount, + totalCount, + remainingCount, + phase: options.phase, + }; +} + +export function renderTemplate(template: string, vars: PromptVariables): PromptRenderResult { + const unknownVariables = new Set(); + const text = template.replace(/\$\{([a-zA-Z0-9_]+)\}/g, (_match, key: string) => { + if (key in vars) { + const value = vars[key as keyof PromptVariables]; + return value === undefined || value === null ? "" : String(value); + } + unknownVariables.add(key); + return ""; + }); + + return { text, unknownVariables: [...unknownVariables] }; +} + +export function formatTodoList(items: Array<{ step: number; text: string; completed: boolean }>): { + todoList: string; + completedCount: number; + totalCount: number; + remainingCount: number; +} { + const totalCount = items.length; + const completedCount = items.filter((item) => item.completed).length; + const remainingItems = items.filter((item) => !item.completed); + const todoList = remainingItems.length + ? remainingItems.map((item) => `- [ ] ${item.step}. ${item.text}`).join("\n") + : ""; + + return { + todoList, + completedCount, + totalCount, + remainingCount: remainingItems.length, + }; +} diff --git a/apps/pi-extension/index.ts b/apps/pi-extension/index.ts index db58ef9..dc6583c 100644 --- a/apps/pi-extension/index.ts +++ b/apps/pi-extension/index.ts @@ -21,7 +21,7 @@ import { existsSync, readFileSync, statSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import type { AgentMessage } from "@mariozechner/pi-agent-core"; +import type { AgentMessage, ThinkingLevel } from "@mariozechner/pi-agent-core"; import type { AssistantMessage, TextContent } from "@mariozechner/pi-ai"; import { Type } from "@mariozechner/pi-ai"; import type { @@ -29,6 +29,7 @@ import type { ExtensionContext, } from "@mariozechner/pi-coding-agent"; import { Key } from "@mariozechner/pi-tui"; +import { buildPromptVariables, formatTodoList, loadPlannotatorConfig, renderTemplate, resolvePhaseProfile } from "./config.js"; import { type ChecklistItem, markCompletedSteps, @@ -85,6 +86,20 @@ try { // HTML not built yet — review feature will be unavailable } + + +type SavedPhaseState = { + activeTools: string[]; + model?: { provider: string; id: string }; + thinkingLevel: ThinkingLevel; +}; + +type PersistedPlannotatorState = { + phase: Phase; + planFilePath?: string; + savedState?: SavedPhaseState; +}; + function isAssistantMessage(m: AgentMessage): m is AssistantMessage { return m.role === "assistant" && Array.isArray(m.content); } @@ -122,11 +137,24 @@ function getStartupErrorMessage(err: unknown): string { return err instanceof Error ? err.message : "Unknown error"; } +function getPlanReviewAvailabilityWarning(options: { hasUI: boolean; hasPlanHtml: boolean }): string | null { + const { hasUI, hasPlanHtml } = options; + if (hasUI && hasPlanHtml) return null; + if (!hasUI && !hasPlanHtml) { + return "Plannotator: interactive plan review is unavailable in this session (no UI support and missing built assets). Plans will auto-approve on exit_plan_mode."; + } + if (!hasUI) { + return "Plannotator: interactive plan review is unavailable in this session (no UI support). Plans will auto-approve on exit_plan_mode."; + } + return "Plannotator: interactive plan review assets are missing. Rebuild the extension to restore the browser UI. Plans will auto-approve on exit_plan_mode."; +} + export default function plannotator(pi: ExtensionAPI): void { let phase: Phase = "idle"; let planFilePath = "PLAN.md"; let checklistItems: ChecklistItem[] = []; - let preplanTools: string[] | null = null; + let savedState: SavedPhaseState | null = null; + let plannotatorConfig = {}; // ── Flags ──────────────────────────────────────────────────────────── @@ -148,15 +176,25 @@ export default function plannotator(pi: ExtensionAPI): void { return resolve(cwd, planFilePath); } + function getPhaseProfile(): ReturnType | undefined { + if (phase === "planning" || phase === "executing") { + return resolvePhaseProfile(plannotatorConfig, phase); + } + return undefined; + } + function updateStatus(ctx: ExtensionContext): void { + const profile = getPhaseProfile(); if (phase === "executing" && checklistItems.length > 0) { const completed = checklistItems.filter((t) => t.completed).length; ctx.ui.setStatus( "plannotator", ctx.ui.theme.fg("accent", `📋 ${completed}/${checklistItems.length}`), ); - } else if (phase === "planning") { - ctx.ui.setStatus("plannotator", ctx.ui.theme.fg("warning", "⏸ plan")); + } else if (phase === "planning" && profile?.statusLabel) { + ctx.ui.setStatus("plannotator", ctx.ui.theme.fg("warning", profile.statusLabel)); + } else if (phase === "executing" && profile?.statusLabel) { + ctx.ui.setStatus("plannotator", ctx.ui.theme.fg("accent", profile.statusLabel)); } else { ctx.ui.setStatus("plannotator", undefined); } @@ -179,45 +217,109 @@ export default function plannotator(pi: ExtensionAPI): void { } } + function captureSavedState(ctx: ExtensionContext): void { + savedState = { + activeTools: pi.getActiveTools(), + model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined, + thinkingLevel: pi.getThinkingLevel(), + }; + } + function persistState(): void { - pi.appendEntry("plannotator", { phase, planFilePath, preplanTools }); + + + pi.appendEntry("plannotator", { phase, planFilePath, savedState }); } - /** Apply tool visibility for the current phase, preserving tools from other extensions. */ - function applyToolsForPhase(): void { - const baseTools = stripPlanningOnlyTools(preplanTools ?? pi.getActiveTools()); - pi.setActiveTools(getToolsForPhase(baseTools, phase)); + async function applyModelRef( + ref: { provider: string; id: string }, + ctx: ExtensionContext, + reason: string, + ): Promise { + const model = ctx.modelRegistry.find(ref.provider, ref.id); + if (!model) { + ctx.ui.notify(`Plannotator: ${reason} model ${ref.provider}/${ref.id} not found.`, "warning"); + return; + } + + const success = await pi.setModel(model); + if (!success) { + ctx.ui.notify(`Plannotator: no API key for ${ref.provider}/${ref.id}.`, "warning"); + } } - function enterPlanning(ctx: ExtensionContext): void { - phase = "planning"; - checklistItems = []; - preplanTools = stripPlanningOnlyTools(pi.getActiveTools()); - applyToolsForPhase(); + async function restoreSavedState(ctx: ExtensionContext): Promise { + if (!savedState) return; + + pi.setActiveTools(savedState.activeTools); + if (savedState.model) { + await applyModelRef(savedState.model, ctx, "restore"); + } + pi.setThinkingLevel(savedState.thinkingLevel); + } + + async function applyPhaseConfig(ctx: ExtensionContext, opts: { restoreSavedState?: boolean } = {}): Promise { + const profile = getPhaseProfile(); + if (opts.restoreSavedState !== false && savedState) { + await restoreSavedState(ctx); + } + + if (phase === "planning" || phase === "executing") { + const baseTools = stripPlanningOnlyTools(savedState?.activeTools ?? pi.getActiveTools()); + const toolSet = new Set(baseTools); + for (const tool of profile?.activeTools ?? []) toolSet.add(tool); + if (phase === "planning") { + pi.setActiveTools(getToolsForPhase([...toolSet], phase)); + } else { + pi.setActiveTools([...toolSet]); + } + } + + if (profile?.model) { + await applyModelRef(profile.model, ctx, phase); + } + + if (profile?.thinking) { + pi.setThinkingLevel(profile.thinking); + } + updateStatus(ctx); updateWidget(ctx); + } + + async function enterPlanning(ctx: ExtensionContext): Promise { + phase = "planning"; + checklistItems = []; + captureSavedState(ctx); + await applyPhaseConfig(ctx, { restoreSavedState: false }); persistState(); ctx.ui.notify( `Plannotator: planning mode enabled. Write your plan to ${planFilePath}.`, ); + const warning = getPlanReviewAvailabilityWarning({ hasUI: ctx.hasUI, hasPlanHtml: Boolean(planHtmlContent) }); + if (warning) { + ctx.ui.notify(warning, "warning"); + } } - function exitToIdle(ctx: ExtensionContext): void { + async function exitToIdle(ctx: ExtensionContext): Promise { phase = "idle"; checklistItems = []; - applyToolsForPhase(); - preplanTools = null; + + + await restoreSavedState(ctx); + savedState = null; updateStatus(ctx); updateWidget(ctx); persistState(); ctx.ui.notify("Plannotator: disabled. Full access restored."); } - function togglePlanMode(ctx: ExtensionContext): void { + async function togglePlanMode(ctx: ExtensionContext): Promise { if (phase === "idle") { - enterPlanning(ctx); + await enterPlanning(ctx); } else { - exitToIdle(ctx); + await exitToIdle(ctx); } } @@ -227,7 +329,7 @@ export default function plannotator(pi: ExtensionAPI): void { description: "Toggle plannotator (file-based plan mode)", handler: async (args, ctx) => { if (phase !== "idle") { - exitToIdle(ctx); + await exitToIdle(ctx); return; } @@ -241,7 +343,7 @@ export default function plannotator(pi: ExtensionAPI): void { } if (targetPath) planFilePath = targetPath; - enterPlanning(ctx); + await enterPlanning(ctx); }, }); @@ -540,7 +642,9 @@ export default function plannotator(pi: ExtensionAPI): void { pi.registerShortcut(Key.ctrlAlt("p"), { description: "Toggle plannotator", - handler: async (ctx) => togglePlanMode(ctx), + handler: async (ctx) => { + await togglePlanMode(ctx); + }, }); // ── plannotator_submit_plan Tool ──────────────────────────────────── @@ -610,8 +714,10 @@ export default function plannotator(pi: ExtensionAPI): void { // Non-interactive or no HTML: auto-approve if (!ctx.hasUI || !planHtmlContent) { phase = "executing"; - applyToolsForPhase(); - preplanTools = null; + + + await applyPhaseConfig(ctx, { restoreSavedState: true }); + pi.appendEntry("plannotator-execute", { planFilePath }); persistState(); return { content: [ @@ -648,13 +754,11 @@ export default function plannotator(pi: ExtensionAPI): void { if (result.approved) { phase = "executing"; - applyToolsForPhase(); - preplanTools = null; - updateStatus(ctx); - updateWidget(ctx); - persistState(); + + await applyPhaseConfig(ctx, { restoreSavedState: true }); pi.appendEntry("plannotator-execute", { planFilePath }); + persistState(); const doneMsg = checklistItems.length > 0 @@ -731,6 +835,41 @@ export default function plannotator(pi: ExtensionAPI): void { // Inject phase-specific context pi.on("before_agent_start", async (_event, ctx) => { + const profile = getPhaseProfile(); + if (phase === "executing") { + // Re-read from disk each turn to stay current + const fullPath = resolvePlanPath(ctx.cwd); + try { + const planContent = readFileSync(fullPath, "utf-8"); + checklistItems = parseChecklist(planContent); + } catch { + // File deleted during execution — degrade gracefully + } + } + + const todoStats = phase === "executing" ? formatTodoList(checklistItems) : formatTodoList([]); + if (profile?.systemPrompt) { + const rendered = renderTemplate( + profile.systemPrompt, + buildPromptVariables({ + planFilePath, + phase, + todoList: todoStats.todoList, + completedCount: todoStats.completedCount, + totalCount: todoStats.totalCount, + remainingCount: todoStats.remainingCount, + }), + ); + if (rendered.unknownVariables.length > 0) { + ctx.ui.notify( + "Plannotator: unknown template variables in " + phase + " prompt: " + rendered.unknownVariables.join(", "), + "warning", + ); + } + + return { systemPrompt: rendered.text }; + } + if (phase === "planning") { return { message: { @@ -892,8 +1031,10 @@ Execute each step in order. After completing a step, include [DONE:n] in your re ); phase = "idle"; checklistItems = []; - applyToolsForPhase(); - preplanTools = null; + + + await restoreSavedState(ctx); + savedState = null; updateStatus(ctx); updateWidget(ctx); persistState(); @@ -908,6 +1049,12 @@ Execute each step in order. After completing a step, include [DONE:n] in your re planFilePath = flagPlanFile; } + const loadedConfig = loadPlannotatorConfig(ctx.cwd); + plannotatorConfig = loadedConfig.config; + for (const warning of loadedConfig.warnings) { + ctx.ui.notify(`Plannotator config: ${warning}`, "warning"); + } + // Check --plan flag if (pi.getFlag("plan") === true) { phase = "planning"; @@ -920,14 +1067,16 @@ Execute each step in order. After completing a step, include [DONE:n] in your re (e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "plannotator", ) - .pop() as { - data?: { phase: Phase; planFilePath?: string; preplanTools?: string[] | null }; - } | undefined; + + + .pop() as { data?: PersistedPlannotatorState } | undefined; if (stateEntry?.data) { phase = stateEntry.data.phase ?? phase; planFilePath = stateEntry.data.planFilePath ?? planFilePath; - preplanTools = stateEntry.data.preplanTools ?? preplanTools; + + + savedState = stateEntry.data.savedState ?? savedState; } // Rebuild execution state from disk + session messages @@ -964,11 +1113,25 @@ Execute each step in order. After completing a step, include [DONE:n] in your re } } - // Re-apply tool visibility on startup/resume so planning-only tools stay hidden - // outside planning and pre-plan tool state is restored after approvals. - applyToolsForPhase(); + + + if (phase === "planning") { + checklistItems = []; + const warning = getPlanReviewAvailabilityWarning({ hasUI: ctx.hasUI, hasPlanHtml: Boolean(planHtmlContent) }); + if (warning) { + ctx.ui.notify(warning, "warning"); + } + } + + if (phase === "idle") { + await restoreSavedState(ctx); + savedState = null; + } else if (phase === "planning" || phase === "executing") { + await applyPhaseConfig(ctx, { restoreSavedState: true }); + } updateStatus(ctx); updateWidget(ctx); + persistState(); }); } diff --git a/apps/pi-extension/package.json b/apps/pi-extension/package.json index e5c588c..0eae1bd 100644 --- a/apps/pi-extension/package.json +++ b/apps/pi-extension/package.json @@ -23,6 +23,8 @@ "index.ts", "server.ts", "tool-scope.ts", + "config.ts", + "plannotator.json", "server/", "generated/", "README.md", diff --git a/apps/pi-extension/plannotator.json b/apps/pi-extension/plannotator.json new file mode 100644 index 0000000..fec0f23 --- /dev/null +++ b/apps/pi-extension/plannotator.json @@ -0,0 +1,12 @@ +{ + "phases": { + "planning": { + "activeTools": ["grep", "find", "ls", "plannotator_submit_plan"], + "statusLabel": "⏸ plan", + "systemPrompt": "[PLANNOTATOR - PLANNING PHASE]\nYou are in plan mode. You MUST NOT make any changes to the codebase — no edits, no commits, no installs, no destructive commands. The ONLY file you may write to or edit is the plan file: ${planFilePath}.\n\nAvailable tools: read, bash, grep, find, ls, write (${planFilePath} only), edit (${planFilePath} only), plannotator_submit_plan\n\nDo not run destructive bash commands (rm, git push, npm install, etc.) — focus on reading and exploring the codebase. Web fetching (curl, wget) is fine.\n\n## Iterative Planning Workflow\n\nYou are pair-planning with the user. Explore the code to build context, then write your findings into ${planFilePath} as you go. The plan starts as a rough skeleton and gradually becomes the final plan.\n\n### The Loop\n\nRepeat this cycle until the plan is complete:\n\n1. **Explore** — Use read, grep, find, ls, and bash to understand the codebase. Actively search for existing functions, utilities, and patterns that can be reused — avoid proposing new code when suitable implementations already exist.\n2. **Update the plan file** — After each discovery, immediately capture what you learned in ${planFilePath}. Don't wait until the end. Use write for the initial draft, then edit for all subsequent updates.\n3. **Ask the user** — When you hit an ambiguity or decision you can't resolve from code alone, ask. Then go back to step 1.\n\n### First Turn\n\nStart by quickly scanning key files to form an initial understanding of the task scope. Then write a skeleton plan (headers and rough notes) and ask the user your first round of questions. Don't explore exhaustively before engaging the user.\n\n### Asking Good Questions\n\n- Never ask what you could find out by reading the code.\n- Batch related questions together.\n- Focus on things only the user can answer: requirements, preferences, tradeoffs, edge-case priorities.\n- Scale depth to the task — a vague feature request needs many rounds; a focused bug fix may have one or none.\n\n### Plan File Structure\n\nYour plan file should use markdown with clear sections:\n- **Context** — Why this change is being made: the problem, what prompted it, the intended outcome.\n- **Approach** — Your recommended approach only, not all alternatives considered.\n- **Files to modify** — List the critical file paths that will be changed.\n- **Reuse** — Reference existing functions and utilities you found, with their file paths.\n- **Steps** — Implementation checklist:\n - [ ] Step 1 description\n - [ ] Step 2 description\n- **Verification** — How to test the changes end-to-end (run the code, run tests, manual checks).\n\nKeep the plan concise enough to scan quickly, but detailed enough to execute effectively.\n\n### When to Submit\n\nYour plan is ready when you've addressed all ambiguities and it covers: what to change, which files to modify, what existing code to reuse, and how to verify. Call plannotator_submit_plan to submit for review.\n\n### Revising After Feedback\n\nWhen the user denies a plan with feedback:\n1. Read ${planFilePath} to see the current plan.\n2. Use the edit tool to make targeted changes addressing the feedback — do NOT rewrite the entire file.\n3. Call plannotator_submit_plan again to resubmit.\n\n### Ending Your Turn\n\nYour turn should only end by either:\n- Asking the user a question to gather more information.\n- Calling plannotator_submit_plan when the plan is ready for review.\n\nDo not end your turn without doing one of these two things." + }, + "executing": { + "systemPrompt": "[PLANNOTATOR - EXECUTING PLAN]\nFull tool access is enabled. Execute the plan from ${planFilePath}.\n\nRemaining steps:\n${todoList}\n\nExecute each step in order. After completing a step, include [DONE:n] in your response where n is the step number." + } + } +} diff --git a/bun.lock b/bun.lock index 7dec1fa..ac102d8 100644 --- a/bun.lock +++ b/bun.lock @@ -1,5 +1,6 @@ { "lockfileVersion": 1, + "configVersion": 0, "workspaces": { "": { "name": "plannotator", @@ -61,7 +62,7 @@ }, "apps/opencode-plugin": { "name": "@plannotator/opencode", - "version": "0.15.5", + "version": "0.16.2", "dependencies": { "@opencode-ai/plugin": "^1.1.10", }, @@ -83,7 +84,7 @@ }, "apps/pi-extension": { "name": "@plannotator/pi-extension", - "version": "0.15.5", + "version": "0.16.2", "peerDependencies": { "@mariozechner/pi-coding-agent": ">=0.53.0", }, @@ -169,7 +170,7 @@ }, "packages/server": { "name": "@plannotator/server", - "version": "0.15.5", + "version": "0.16.2", "dependencies": { "@plannotator/ai": "workspace:*", "@plannotator/shared": "workspace:*", -- knotmirror 0.0.1