From fc655beb0ea69c2b738749f31d334affd6cfcc98 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Mon, 16 Mar 2026 16:13:57 -0700 Subject: [PATCH] feat: Pi-style iterative planning for OpenCode plugin (#318) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: extract checklist utilities to shared package Move ChecklistItem, parseChecklist, extractDoneSteps, and markCompletedSteps from Pi extension to @plannotator/shared for reuse by the OpenCode plugin. Co-Authored-By: Claude Opus 4.6 (1M context) * feat: Pi-style iterative planning for OpenCode plugin Rewrite the OpenCode plugin to match Pi's planning methodology: - Inject rich iterative planning prompt when agent is "plan" (explore → update plan → ask user loop, structured plan format) - File-based submit_plan: reads plan from disk instead of requiring it as a string arg. Resolves path from OpenCode's system prompt, falls back to PLAN.md - Suppress plan_exit via tool.definition hook (directs to submit_plan) - Add PLANNOTATOR_ALLOW_SUBAGENTS env var for #289 - Pass planFilePath to denial feedback template - Keep existing subagent/build/title guards intact Co-Authored-By: Claude Opus 4.6 (1M context) * fix: address review findings in OpenCode plugin - Cache agents list (static per session, was fetched every LLM call) - Remove TOCTOU: drop redundant file.exists() before file.text() - Eliminate duplicate system.join() by reusing joined string - Resolve getSharingEnabled() once in submit_plan instead of twice - Use path.join() instead of string concatenation for file paths Co-Authored-By: Claude Opus 4.6 (1M context) * feat: session-scoped plan files and tool-neutral prompt Replace plugin-global resolvedPlanFilePath and prompt-path parsing with per-session plan files at ~/.plannotator/session-plans/opencode/{id}/plan.md. Remove resolvePlanFilePath() regex (fixes spaces-in-path and cross-session race). Make planning prompt tool-neutral (no write/edit references) so it works with apply_patch models. Strip OpenCode's native read-only and experimental-mode prompt lines before injecting Plannotator's planning prompt. Co-Authored-By: Claude Opus 4.6 (1M context) * feat: directory-based plan storage with path validation Replace session-scoped plan files with a shared plan directory at ~/.plannotator/session-plans/opencode/. Agent picks the filename, submit_plan takes a path arg and validates it (absolute, inside plan dir, exists, readable, non-empty) with canonical path checks to defeat traversal and symlink escapes. Remove summary and plan string args. Planning prompt is now tool-neutral and directs the agent to reuse the same file on feedback, not create new ones. Co-Authored-By: Claude Opus 4.6 (1M context) * fix: use OpenCode's native plans directory for permission compatibility OpenCode's plan mode permission ruleset only allows edits to .opencode/plans/*.md and $XDG_DATA_HOME/opencode/plans/*.md. Our custom ~/.plannotator/session-plans/opencode/ path was blocked by PermissionDeniedError at the tool level regardless of prompt stripping. Switch to the XDG path that OpenCode already allows. Co-Authored-By: Claude Opus 4.6 (1M context) * feat: exploration-first planning prompt Restructure the planning prompt as a phased workflow: Explore → Ask → Write → Submit. The agent now explores the codebase before creating a plan file or asking questions, producing better-researched plans for existing codebases. Greenfield tasks can skip straight to questions. Co-Authored-By: Claude Opus 4.6 (1M context) * chore: fix stale path in JSDoc header comment Co-Authored-By: Claude Opus 4.6 (1M context) --------- Co-authored-by: Claude Opus 4.6 (1M context) --- apps/opencode-plugin/index.ts | 211 +++++++++++++++++-------- apps/opencode-plugin/plan-mode.test.ts | 178 +++++++++++++++++++++ apps/opencode-plugin/plan-mode.ts | 120 ++++++++++++++ bun.lock | 6 +- packages/shared/checklist.ts | 52 ++++++ packages/shared/package.json | 1 + 6 files changed, 497 insertions(+), 71 deletions(-) create mode 100644 apps/opencode-plugin/plan-mode.test.ts create mode 100644 apps/opencode-plugin/plan-mode.ts create mode 100644 packages/shared/checklist.ts diff --git a/apps/opencode-plugin/index.ts b/apps/opencode-plugin/index.ts index ab31af4..bd58dab 100644 --- a/apps/opencode-plugin/index.ts +++ b/apps/opencode-plugin/index.ts @@ -1,14 +1,19 @@ /** * Plannotator Plugin for OpenCode * - * Provides a Claude Code-style planning experience with interactive plan review. - * When the agent calls submit_plan, the Plannotator UI opens for the user to - * annotate, approve, or request changes to the plan. + * Provides iterative planning with interactive browser-based plan review. + * + * When the agent is in plan mode: + * - Injects planning prompt directing the agent to write plans in $XDG_DATA_HOME/opencode/plans/ + * - Agent creates a uniquely-named plan file, revises it on feedback + * - submit_plan(path) reads the plan from disk and opens browser UI + * - plan_exit suppressed in favor of submit_plan (experimental mode compatibility) * * Environment variables: * PLANNOTATOR_REMOTE - Set to "1" or "true" for remote mode (devcontainer, SSH) * PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote) * PLANNOTATOR_PLAN_TIMEOUT_SECONDS - Max wait for submit_plan approval (default: 345600, set 0 to disable) + * PLANNOTATOR_ALLOW_SUBAGENTS - Set to "1" to allow subagents to see submit_plan tool * * @packageDocumentation */ @@ -30,6 +35,11 @@ import { getGitContext, runGitDiff } from "@plannotator/server/git"; import { writeRemoteShareLink } from "@plannotator/server/share-url"; import { resolveMarkdownFile } from "@plannotator/server/resolve-file"; import { planDenyFeedback } from "@plannotator/shared/feedback-templates"; +import { + getPlanDirectory, + validatePlanPath, + stripConflictingPlanModeRules, +} from "./plan-mode"; // @ts-ignore - Bun import attribute for text import indexHtml from "./plannotator.html" with { type: "text" }; @@ -41,13 +51,81 @@ const reviewHtmlContent = reviewHtml as unknown as string; const DEFAULT_PLAN_TIMEOUT_SECONDS = 345_600; // 96 hours +// ── Planning prompt ─────────────────────────────────────────────────────── + +function getPlanningPrompt(planDir: string): string { + return `## Plannotator — Iterative Planning + +Your plan files must live in this directory: + +${planDir} + +You must not edit the codebase during planning. The only files you may create or edit are plan markdown files inside that directory. Do not run destructive shell commands (rm, git push, npm install, etc.). + +### Step 1 — Explore + +Before writing anything, understand the task and the code it touches. + +- Read the relevant source files. Trace call paths, data flow, and dependencies. +- Look at existing patterns, utilities, and conventions in the codebase — your plan should reuse them. +- Check related tests to understand expected behavior and edge cases. +- Scale depth to the task: a vague feature request needs deep exploration; a focused bug fix may only need a few files. + +Do not jump to writing a plan or asking questions until you have the context you need. If the conversation already provided sufficient context, or the task is greenfield with no code to explore, move on to the next step. + +### Step 2 — Ask (if needed) + +If there are things only the user can answer — requirements, preferences, tradeoffs, edge-case priorities — use the \`question\` tool. Do not ask via plain text output. + +- Never ask what you could find out by reading the code. +- Batch related questions into a single \`question\` call. +- For greenfield tasks, this may be your first step. + +### Step 3 — Write the plan + +Once you understand the task, create exactly one markdown plan file in the directory above with a unique, descriptive filename (e.g. \`auth-refactor.md\`, \`fix-upload-timeout.md\`). Do not overwrite or reuse filenames from existing plans. + +Structure the plan with: +- **Context** — Why this change is being made. +- **Approach** — Your recommended approach only, not all alternatives considered. +- **Files to modify** — List the critical file paths that will be changed. +- **Reuse** — Reference existing functions and utilities you found, with their file paths. +- **Steps** — Implementation checklist with \`- [ ]\` items. +- **Verification** — How to test the changes end-to-end. + +Keep it concise enough to scan quickly, but detailed enough to execute effectively. + +### Step 4 — Submit + +Call \`submit_plan(path: "/absolute/path/to/your-plan.md")\` to open the plan in a visual review UI. Do not submit plan text directly — submit the file path. + +### If the user requests changes + +1. Read the same plan file you previously submitted. +2. Edit that same file to address the feedback. +3. Call \`submit_plan\` again with the same \`path\`. +4. Never create a new file in response to feedback — always revise the existing one. + +### Ending your turn + +Your turn should only end by either: +- Using the question tool to ask the user for information. +- Calling submit_plan when the plan is ready for review. + +Do not end your turn without doing one of these two things.`; +} + +// ── Plugin ──────────────────────────────────────────────────────────────── + export const PlannotatorPlugin: Plugin = async (ctx) => { + // Agents list is static for the session lifetime — fetch once and cache + let cachedAgents: any[] | null = null; + // Helper to determine if sharing is enabled (lazy evaluation) // Priority: OpenCode config > env var > default (enabled) async function getSharingEnabled(): Promise { try { const response = await ctx.client.config.get({ query: { directory: ctx.directory } }); - // Config is wrapped in response.data // @ts-ignore - share config may exist const share = response?.data?.share; if (share !== undefined) { @@ -56,21 +134,13 @@ export const PlannotatorPlugin: Plugin = async (ctx) => { } catch { // Config read failed, fall through to env var } - // Fall back to env var return process.env.PLANNOTATOR_SHARE !== "disabled"; } - // Custom share portal URL for self-hosting function getShareBaseUrl(): string | undefined { return process.env.PLANNOTATOR_SHARE_URL || undefined; } - /** - * submit_plan wait timeout in seconds. - * - unset: default to 96h - * - 0: disable timeout - * - invalid/negative: fall back to default - */ function getPlanTimeoutSeconds(): number | null { const raw = process.env.PLANNOTATOR_PLAN_TIMEOUT_SECONDS?.trim(); if (!raw) return DEFAULT_PLAN_TIMEOUT_SECONDS; @@ -87,9 +157,16 @@ export const PlannotatorPlugin: Plugin = async (ctx) => { return parsed; } + function allowSubagents(): boolean { + const val = process.env.PLANNOTATOR_ALLOW_SUBAGENTS?.trim(); + return val === "1" || val === "true"; + } + return { - // Register submit_plan as primary-only tool (hidden from sub-agents) + // Register submit_plan as primary-only tool (hidden from sub-agents by default) config: async (opencodeConfig) => { + if (allowSubagents()) return; + const existingPrimaryTools = opencodeConfig.experimental?.primary_tools ?? []; if (!existingPrimaryTools.includes("submit_plan")) { opencodeConfig.experimental = { @@ -99,23 +176,32 @@ export const PlannotatorPlugin: Plugin = async (ctx) => { } }, + // Suppress plan_exit in favor of submit_plan + "tool.definition": async (input, output) => { + if (input.toolID === "plan_exit") { + output.description = + "Do not call this tool. Use submit_plan instead — it opens a visual review UI for plan approval."; + } + }, + // Inject planning instructions into system prompt "experimental.chat.system.transform": async (input, output) => { // Skip for title generation requests - const existingSystem = output.system.join("\n").toLowerCase(); - if (existingSystem.includes("title generator") || existingSystem.includes("generate a title")) { + const systemText = output.system.join("\n"); + if (systemText.toLowerCase().includes("title generator") || systemText.toLowerCase().includes("generate a title")) { return; } + let lastUserAgent: string | undefined; try { // Fetch session messages to determine current agent const messagesResponse = await ctx.client.session.messages({ + // @ts-ignore - sessionID exists on input path: { id: input.sessionID } }); const messages = messagesResponse.data; // Find last user message (reverse iteration) - let lastUserAgent: string | undefined; if (messages) { for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i]; @@ -133,12 +219,14 @@ export const PlannotatorPlugin: Plugin = async (ctx) => { // Hardcoded exclusion: build agent if (lastUserAgent === "build") return; - // Dynamic exclusion: check agent mode via API - const agentsResponse = await ctx.client.app.agents({ - query: { directory: ctx.directory } - }); - const agents = agentsResponse.data; - const agent = agents?.find((a: { name: string }) => a.name === lastUserAgent); + // Agents list is static — cache after first fetch + if (!cachedAgents) { + const agentsResponse = await ctx.client.app.agents({ + query: { directory: ctx.directory } + }); + cachedAgents = agentsResponse.data ?? []; + } + const agent = cachedAgents.find((a: { name: string }) => a.name === lastUserAgent); // Skip if agent is a sub-agent // @ts-ignore - Agent has mode field @@ -149,6 +237,15 @@ export const PlannotatorPlugin: Plugin = async (ctx) => { return; } + // Plan agent: inject full iterative planning prompt + if (lastUserAgent === "plan") { + const planDir = getPlanDirectory(); + output.system = stripConflictingPlanModeRules(output.system); + output.system.push(getPlanningPrompt(planDir)); + return; + } + + // Other primary agents: inject minimal submission reminder output.system.push(` ## Plan Submission @@ -166,14 +263,13 @@ Do NOT proceed with implementation until your plan is approved. `); }, - // Listen for /plannotator-review command + // Listen for slash commands event: async ({ event }) => { - // Check for command execution event const isCommandEvent = event.type === "command.executed" || event.type === "tui.command.execute"; - // @ts-ignore - Event structure: event.properties.name for command.executed + // @ts-ignore - Event structure varies const commandName = event.properties?.name || event.command || event.payload?.name; const isReviewCommand = commandName === "plannotator-review"; @@ -183,16 +279,12 @@ Do NOT proceed with implementation until your plan is approved. message: "Opening code review UI...", }); - // Get git context (branches, available diff options) const gitContext = await getGitContext(); - - // Run git diff HEAD (uncommitted changes - default) const { patch: rawPatch, label: gitRef, error: diffError } = await runGitDiff( "uncommitted", gitContext.defaultBranch ); - // Start server even if empty - user can switch diff types const server = await startReviewServer({ rawPatch, gitRef, @@ -211,14 +303,11 @@ Do NOT proceed with implementation until your plan is approved. await Bun.sleep(1500); server.stop(); - // Send feedback back to the session if provided if (result.feedback) { - // @ts-ignore - Event properties contain sessionID for command.executed events + // @ts-ignore - Event properties contain sessionID const sessionId = event.properties?.sessionID; - // Only try to send feedback if we have a valid session ID if (sessionId) { - // Check agent switch setting (defaults to 'build' if not set) const shouldSwitchAgent = result.agentSwitch && result.agentSwitch !== 'disabled'; const targetAgent = result.agentSwitch || 'build'; @@ -226,18 +315,12 @@ Do NOT proceed with implementation until your plan is approved. ? `# Code Review\n\nCode review completed — no changes requested.` : `# Code Review Feedback\n\n${result.feedback}\n\nPlease address this feedback.`; - // Send feedback to agent try { await ctx.client.session.prompt({ path: { id: sessionId }, body: { ...(shouldSwitchAgent && { agent: targetAgent }), - parts: [ - { - type: "text", - text: message, - }, - ], + parts: [{ type: "text", text: message }], }, }); } catch { @@ -267,7 +350,6 @@ Do NOT proceed with implementation until your plan is approved. message: `Opening annotation UI for ${filePath}...`, }); - // Smart file resolution: exact path, case-insensitive relative, or bare filename const projectRoot = process.cwd(); const resolved = await resolveMarkdownFile(filePath, projectRoot); @@ -293,7 +375,6 @@ Do NOT proceed with implementation until your plan is approved. }); const markdown = await Bun.file(absolutePath).text(); - // Start annotate server (reuses plan editor HTML) const server = await startAnnotateServer({ markdown, filePath: absolutePath, @@ -308,9 +389,8 @@ Do NOT proceed with implementation until your plan is approved. await Bun.sleep(1500); server.stop(); - // Send feedback back to the session if provided if (result.feedback) { - // @ts-ignore - Event properties contain sessionID for command.executed events + // @ts-ignore - Event properties contain sessionID const sessionId = event.properties?.sessionID; if (sessionId) { @@ -337,28 +417,34 @@ Do NOT proceed with implementation until your plan is approved. tool: { submit_plan: tool({ description: - "Submit your completed plan for interactive user review. The user can annotate, approve, or request changes. Call this when you have finished creating your implementation plan.", + "Submit your plan file for interactive user review. The user can annotate, approve, or request changes in a visual browser UI. Pass the absolute path to your plan file.", args: { - plan: tool.schema + path: tool.schema .string() - .describe("The complete implementation plan in markdown format"), - summary: tool.schema - .string() - .describe("A brief 1-2 sentence summary of what the plan accomplishes"), + .describe("Absolute path to the plan markdown file on disk."), }, async execute(args, context) { + const planDir = getPlanDirectory(); + const validation = validatePlanPath(args.path, planDir); + + if (!validation.ok) { + return `Error: ${validation.error}`; + } + + const planContent = validation.content; + const sharingEnabled = await getSharingEnabled(); const server = await startPlannotatorServer({ - plan: args.plan, + plan: planContent, origin: "opencode", - sharingEnabled: await getSharingEnabled(), + sharingEnabled, shareBaseUrl: getShareBaseUrl(), htmlContent, opencodeClient: ctx.client, onReady: async (url, isRemote, port) => { handleServerReady(url, isRemote, port); - if (isRemote && await getSharingEnabled()) { - await writeRemoteShareLink(args.plan, getShareBaseUrl(), "review the plan", "plan only").catch(() => {}); + if (isRemote && sharingEnabled) { + await writeRemoteShareLink(planContent, getShareBaseUrl(), "review the plan", "plan only").catch(() => {}); } }, }); @@ -387,12 +473,11 @@ Do NOT proceed with implementation until your plan is approved. server.stop(); if (result.approved) { - // Check agent switch setting (defaults to 'build' if not set) + // Check agent switch setting const shouldSwitchAgent = result.agentSwitch && result.agentSwitch !== 'disabled'; const targetAgent = result.agentSwitch || 'build'; if (shouldSwitchAgent) { - // Switch TUI display to target agent try { await ctx.client.tui.executeCommand({ body: { command: "agent_cycle" }, @@ -401,10 +486,6 @@ Do NOT proceed with implementation until your plan is approved. // Silently fail } - // Create a user message with target agent using noReply: true - // This ensures the message is created BEFORE we return from the tool, - // so the current loop's next iteration will see it. - // noReply: true means we don't wait for a new loop to complete. try { await ctx.client.session.prompt({ path: { id: context.sessionID }, @@ -419,11 +500,8 @@ Do NOT proceed with implementation until your plan is approved. } } - // If user approved with annotations, include them as notes for implementation if (result.feedback) { return `Plan approved with notes! - -Plan Summary: ${args.summary} ${result.savedPath ? `Saved to: ${result.savedPath}` : ""} ## Implementation Notes @@ -435,12 +513,9 @@ ${result.feedback} Proceed with implementation, incorporating these notes where applicable.`; } - return `Plan approved! - -Plan Summary: ${args.summary} -${result.savedPath ? `Saved to: ${result.savedPath}` : ""}`; + return `Plan approved!${result.savedPath ? ` Saved to: ${result.savedPath}` : ""}`; } else { - return planDenyFeedback(result.feedback || "", "submit_plan"); + return planDenyFeedback(result.feedback || "", "submit_plan", { planFilePath: args.path }); } }, }), diff --git a/apps/opencode-plugin/plan-mode.test.ts b/apps/opencode-plugin/plan-mode.test.ts new file mode 100644 index 0000000..3e2d142 --- /dev/null +++ b/apps/opencode-plugin/plan-mode.test.ts @@ -0,0 +1,178 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import path from "path"; +import { + getPlanDirectory, + validatePlanPath, + stripConflictingPlanModeRules, +} from "./plan-mode"; + +const tempDirs: string[] = []; + +function makeTempDir(): string { + const dir = mkdtempSync(path.join(tmpdir(), "plannotator-test-")); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("getPlanDirectory", () => { + test("returns XDG-based opencode plans path", () => { + const planDir = getPlanDirectory(); + const expectedDataHome = process.env.XDG_DATA_HOME || path.join(require("os").homedir(), ".local", "share"); + expect(planDir).toBe(path.join(expectedDataHome, "opencode", "plans")); + }); +}); + +describe("validatePlanPath", () => { + test("rejects non-absolute paths", () => { + const planDir = makeTempDir(); + const result = validatePlanPath("relative/plan.md", planDir); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("Path must be absolute"); + expect(result.error).toContain("relative/plan.md"); + } + }); + + test("rejects paths outside the plan directory", () => { + const planDir = makeTempDir(); + const outsidePath = path.join(makeTempDir(), "evil-plan.md"); + writeFileSync(outsidePath, "# Evil plan"); + + const result = validatePlanPath(outsidePath, planDir); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("must be inside"); + expect(result.error).toContain(planDir); + } + }); + + test("rejects .. traversal attempts", () => { + const planDir = makeTempDir(); + const traversalPath = path.join(planDir, "..", "escaped.md"); + + const result = validatePlanPath(traversalPath, planDir); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("must be inside"); + } + }); + + test("rejects symlink escapes", () => { + const planDir = makeTempDir(); + const outsideDir = makeTempDir(); + const outsideFile = path.join(outsideDir, "secret.md"); + writeFileSync(outsideFile, "# Secret"); + + const linkPath = path.join(planDir, "link-to-outside"); + symlinkSync(outsideDir, linkPath); + const symlinkPlanPath = path.join(linkPath, "secret.md"); + + const result = validatePlanPath(symlinkPlanPath, planDir); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("must be inside"); + } + }); + + test("rejects missing files", () => { + const planDir = makeTempDir(); + const missingPath = path.join(planDir, "nonexistent.md"); + + const result = validatePlanPath(missingPath, planDir); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("No plan file found"); + expect(result.error).toContain(missingPath); + } + }); + + test("rejects whitespace-only files", () => { + const planDir = makeTempDir(); + const emptyPath = path.join(planDir, "empty.md"); + writeFileSync(emptyPath, " \n\n \t "); + + const result = validatePlanPath(emptyPath, planDir); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toContain("is empty"); + } + }); + + test("accepts a valid plan file inside the directory", () => { + const planDir = makeTempDir(); + const validPath = path.join(planDir, "auth-refactor.md"); + writeFileSync(validPath, "# Auth Refactor\n\nRewrite the auth layer."); + + const result = validatePlanPath(validPath, planDir); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.content).toBe("# Auth Refactor\n\nRewrite the auth layer."); + } + }); + + test("deny and resubmit reads updated content from the same path", () => { + const planDir = makeTempDir(); + const planPath = path.join(planDir, "my-plan.md"); + writeFileSync(planPath, "# Plan v1"); + + const result1 = validatePlanPath(planPath, planDir); + expect(result1.ok).toBe(true); + if (result1.ok) expect(result1.content).toBe("# Plan v1"); + + // Simulate agent revising the file after denial + writeFileSync(planPath, "# Plan v2 — addressed feedback"); + + const result2 = validatePlanPath(planPath, planDir); + expect(result2.ok).toBe(true); + if (result2.ok) expect(result2.content).toBe("# Plan v2 — addressed feedback"); + }); +}); + +describe("stripConflictingPlanModeRules", () => { + test("removes OpenCode's blanket file-edit prohibition", () => { + expect( + stripConflictingPlanModeRules([ + "Read-only mode\nSTRICTLY FORBIDDEN: ANY file edits.\nUse the tools carefully.", + ]), + ).toEqual(["Read-only mode\nUse the tools carefully."]); + }); + + test("drops conversation-only plan storage lines and keeps unrelated instructions", () => { + expect( + stripConflictingPlanModeRules([ + "The plan lives only in the agent's conversation, not on disk.\nKeep the plan concise.", + ]), + ).toEqual(["Keep the plan concise."]); + }); + + test("drops experimental plan path lines", () => { + expect( + stripConflictingPlanModeRules([ + "Create your plan at /tmp/.opencode/plans/1234-test.md\nKeep the plan concise.", + ]), + ).toEqual(["Keep the plan concise."]); + }); + + test("drops experimental plan_exit instructions", () => { + expect( + stripConflictingPlanModeRules([ + "Call plan_exit when the plan is ready.\nKeep the plan concise.", + ]), + ).toEqual(["Keep the plan concise."]); + }); +}); diff --git a/apps/opencode-plugin/plan-mode.ts b/apps/opencode-plugin/plan-mode.ts new file mode 100644 index 0000000..b5b171b --- /dev/null +++ b/apps/opencode-plugin/plan-mode.ts @@ -0,0 +1,120 @@ +import { existsSync, readFileSync, realpathSync } from "fs"; +import { homedir } from "os"; +import path from "path"; + +// ── Directory ───────────────────────────────────────────────────────────── + +/** + * Returns the OpenCode plans directory path. + * Matches OpenCode's own resolution: $XDG_DATA_HOME/opencode/plans + * (defaults to ~/.local/share/opencode/plans on all platforms). + * + * We use this path because OpenCode's plan mode permission ruleset + * only allows edits to .opencode/plans/*.md and this XDG path. + */ +export function getPlanDirectory(): string { + const dataHome = process.env.XDG_DATA_HOME || path.join(homedir(), ".local", "share"); + return path.join(dataHome, "opencode", "plans"); +} + +// ── Path validation ─────────────────────────────────────────────────────── + +export type ValidatePlanPathResult = + | { ok: true; content: string } + | { ok: false; error: string }; + +export function validatePlanPath( + filePath: string, + planDir: string, +): ValidatePlanPathResult { + // 1. Must be absolute + if (!path.isAbsolute(filePath)) { + return { ok: false, error: `Path must be absolute. Got: ${filePath}` }; + } + + // 2. Must be inside the plan directory (canonical comparison) + try { + const canonicalDir = realpathSync(planDir); + const canonicalFile = realpathSync(path.dirname(filePath)) + path.sep + path.basename(filePath); + if (!canonicalFile.startsWith(canonicalDir + path.sep) && canonicalFile !== canonicalDir) { + return { + ok: false, + error: `Plan file must be inside ${planDir}. Got: ${filePath}`, + }; + } + } catch { + // If the file's parent dir doesn't exist, realpath will throw. + // Check if it's at least structurally inside the plan dir. + const normalizedFile = path.normalize(filePath); + const normalizedDir = path.normalize(planDir); + if (!normalizedFile.startsWith(normalizedDir + path.sep)) { + return { + ok: false, + error: `Plan file must be inside ${planDir}. Got: ${filePath}`, + }; + } + } + + // 3. Must exist + if (!existsSync(filePath)) { + return { + ok: false, + error: `No plan file found at ${filePath}. Create the file first, then call submit_plan.`, + }; + } + + // 4. Must be readable + let content: string; + try { + content = readFileSync(filePath, "utf-8"); + } catch (err) { + return { + ok: false, + error: `Could not read plan file at ${filePath}: ${err instanceof Error ? err.message : String(err)}`, + }; + } + + // 5. Must have non-whitespace content + if (!content.trim()) { + return { + ok: false, + error: `Plan file at ${filePath} is empty. Write your plan content first, then call submit_plan.`, + }; + } + + return { ok: true, content }; +} + +// ── Prompt stripping ────────────────────────────────────────────────────── + +function shouldStripPlanModeLine(line: string): boolean { + const normalized = line.trim().toLowerCase(); + return normalized.includes("strictly forbidden: any file edits") + || normalized.includes("your plan at ") + || normalized.includes("plan file already exists at ") + || normalized.includes(".opencode/plans/") + || normalized.includes("plan_exit") + || (normalized.includes("agent's conversation") && normalized.includes("not on disk")); +} + +function cleanupSystemEntry(entry: string): string { + return entry + .split("\n") + .map((line) => line.replace(/[ \t]+$/g, "")) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +export function stripConflictingPlanModeRules(systemEntries: string[]): string[] { + return systemEntries + .map((entry) => + cleanupSystemEntry( + entry + .split("\n") + .filter((line) => !shouldStripPlanModeLine(line)) + .join("\n"), + ), + ) + .filter(Boolean); +} diff --git a/bun.lock b/bun.lock index e7c6880..fc89390 100644 --- a/bun.lock +++ b/bun.lock @@ -51,7 +51,7 @@ }, "apps/opencode-plugin": { "name": "@plannotator/opencode", - "version": "0.12.0", + "version": "0.13.0", "dependencies": { "@opencode-ai/plugin": "^1.1.10", }, @@ -73,7 +73,7 @@ }, "apps/pi-extension": { "name": "@plannotator/pi-extension", - "version": "0.12.0", + "version": "0.13.0", "peerDependencies": { "@mariozechner/pi-coding-agent": ">=0.53.0", }, @@ -153,7 +153,7 @@ }, "packages/server": { "name": "@plannotator/server", - "version": "0.12.0", + "version": "0.13.0", "dependencies": { "@plannotator/shared": "workspace:*", }, diff --git a/packages/shared/checklist.ts b/packages/shared/checklist.ts new file mode 100644 index 0000000..8d372f7 --- /dev/null +++ b/packages/shared/checklist.ts @@ -0,0 +1,52 @@ +/** + * Checklist parsing and progress tracking utilities. + * + * Shared between Pi extension and OpenCode plugin for plan execution tracking. + */ + +export interface ChecklistItem { + /** 1-based step number, compatible with markCompletedSteps/extractDoneSteps. */ + step: number; + text: string; + completed: boolean; +} + +/** + * Parse standard markdown checkboxes from file content. + * + * Matches lines like: + * - [ ] Step description + * - [x] Completed step + * * [ ] Alternative bullet + */ +export function parseChecklist(content: string): ChecklistItem[] { + const items: ChecklistItem[] = []; + const pattern = /^[-*]\s*\[([ xX])\]\s+(.+)$/gm; + + for (const match of content.matchAll(pattern)) { + const completed = match[1] !== " "; + const text = match[2].trim(); + if (text.length > 0) { + items.push({ step: items.length + 1, text, completed }); + } + } + return items; +} + +export function extractDoneSteps(message: string): number[] { + const steps: number[] = []; + for (const match of message.matchAll(/\[DONE:(\d+)\]/gi)) { + const step = Number(match[1]); + if (Number.isFinite(step)) steps.push(step); + } + return steps; +} + +export function markCompletedSteps(text: string, items: ChecklistItem[]): number { + const doneSteps = extractDoneSteps(text); + for (const step of doneSteps) { + const item = items.find((t) => t.step === step); + if (item) item.completed = true; + } + return doneSteps.length; +} diff --git a/packages/shared/package.json b/packages/shared/package.json index 1308fd4..243b075 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -7,6 +7,7 @@ "./crypto": "./crypto.ts", "./feedback-templates": "./feedback-templates.ts", "./review-core": "./review-core.ts", + "./checklist": "./checklist.ts", "./types": "./types.ts" } } -- knotmirror 0.0.1