/** * Session-scoped state and tool gating for plan mode. * * Enabling plan mode removes every tool the policy does not consider read-only * from the active set, and keeps the one `plan` tool active in both modes: its * actions are what ask to enter, save the artifact under the plans directory, * present it, tick it, and leave. Disabling restores exactly what it hid. The * enabled flag is persisted as a custom session entry so `/resume` and `/tree` * follow the branch, and it is also mirrored into the footer status. The review * baseline travels the same way, as one digest per heading section, so the * changed-section markers survive a resume too. * * The `plan` tool's `write` action is the one sanctioned write while planning. The * read-only guard in `index.ts` permits that tool only when the registered one is * this extension's (matched by source path), so a same-named tool from another * extension cannot borrow the exemption, and each action refuses outside its mode. */ import { basename, resolve } from "node:path"; import { truncateToWidth } from "@earendil-works/pi-tui"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; import { sanitizeLine } from "../../lib/format.ts"; import { mayEnterFrom, PLAN_MODE_ENTRY_TYPE } from "../../lib/mode-state.ts"; import { realPathOfNearest } from "../../lib/path.ts"; import type { ReadOnlyPolicy } from "../../lib/policy.ts"; import { toolResultDetails } from "../../lib/tool-result.ts"; import { PLAN_TOOL as PLAN_TOOL_NAME } from "../../lib/tool-names.ts"; import { createToolSetFilter } from "../../lib/tool-set.ts"; import { GLYPHS, STATUS_KEYS } from "../../lib/tui/glyphs.ts"; import { createPlanStore, type PlanStore } from "./plans.ts"; import { sameSections, sectionDigests, type SectionDigest } from "./plan-text.ts"; import type { PlanModeEntry, ReviewBaselineEntry, SeededStepsEntry } from "./types.ts"; /** The one model-facing tool: every planning verb is one of its actions. */ export const PLAN_TOOL = PLAN_TOOL_NAME; /** * The verbs of the one `plan` tool, in the order the schema offers them. * * One action tool rather than five tools, so every verb shares a name and a * registration; the order is the one the description walks them in. */ export const PLAN_ACTIONS = ["enter", "write", "exit", "steps", "cancel"] as const; /** One verb of the `plan` tool. */ export type PlanAction = (typeof PLAN_ACTIONS)[number]; /** * The fields each action reads. * * The parameters are one flat object, so every field is published to every action at once and * only this table stops one reaching an action that would drop it — a `title` on `enter`, an * `updates` batch on `write`. It lives beside the action list so a new verb adds its row where the * verb is declared; `lib/stray-fields.ts` words the refusal, and `stray-field.test.ts` holds the * other direction, so a published field cannot go unclaimed. * * `enter` and `cancel` read none: their executors are handed no params. */ export const PLAN_FIELDS: Record = { enter: [], write: ["title", "content", "plan_path"], exit: ["plan_path"], steps: ["plan_path", "updates"], cancel: [], }; /** Custom-entry type used for plan-mode state. */ export const STATE_TYPE = PLAN_MODE_ENTRY_TYPE; /** Custom-entry type used for a plan's review baseline. */ export const BASELINE_TYPE = "plan-baseline"; /** Custom-entry type used for the steps one approval seeded, so a re-approval can replace them. */ export const SEEDED_TYPE = "plan-seeded"; /** Longest plan-file basename shown in the footer chip. */ const STATUS_NAME_LENGTH = 28; /** * The one tool plan mode keeps in the active set in both modes. Every other tool * follows the policy, which is about writing files and cannot answer for a tool * whose actions are the mode's own verbs: hiding it while planning would hide the * way to write the plan and the way out. */ const MODE_TOOLS = [PLAN_TOOL]; export interface PlanRuntime { /** Whether plan mode is currently on. */ isEnabled(): boolean; /** * Turn plan mode on, or hand back the sentence that refused it. * * The sentence rather than a boolean, because a door that enters has to say what happened: a tool * answering "entered" over a mode that is off, or a `/plan ` sending work into one it never * got, is a green result over a refusal. The gate words it once — `mayEnterFrom`'s own line — so no * caller derives a second copy, and `undefined` is the answer when the mode is on. */ enable(ctx: ExtensionContext): string | undefined; disable(ctx: ExtensionContext): void; /** Flip the mode, and answer the state it left: `true` only when plan mode is on afterwards. */ toggle(ctx: ExtensionContext): boolean; /** Restore state from the branch and the `--plan` flag. */ restore(ctx: ExtensionContext): void; /** Plan-file storage for the `write` and `exit` actions. */ plans: PlanStore; /** Whether `toolName` is the `plan` tool (not a same-named impostor) the read-only guard exempts. */ isOwnTool(toolName: string): boolean; /** Path of the most recently written plan, for the footer chip. */ lastPlanPath(): string | undefined; /** Remember a written plan and repaint the footer. */ setLastPlan(ctx: ExtensionContext, path: string): void; /** The sections the last review of `path` showed, restored with the branch. */ reviewed(path: string): SectionDigest[] | undefined; /** Remember what a review just showed, as a session entry on this branch. */ markReviewed(path: string, content: string): void; /** The todo items this plan's approvals seeded and still own, or undefined. */ seeded(path: string): string[] | undefined; /** Record the items those approvals own now, so a re-approval can replace them. */ markSeeded(path: string, steps: readonly string[]): void; } /** What the branch carries: the last plan-mode state, a baseline per plan, and the plan it last wrote. */ interface BranchState { mode: PlanModeEntry | undefined; /** The plan the branch last wrote, which is the name the footer chip shows. */ lastPlan: string | undefined; baselines: Map; /** The step texts each approval appended, per plan path. */ seeded: Map; } /** Well-formed `{ title, digest }` pairs from untrusted branch data, or undefined. */ function readSections(value: unknown): SectionDigest[] | undefined { if (!Array.isArray(value)) return undefined; const sections: SectionDigest[] = []; for (const raw of value) { const section = raw as { title?: unknown; digest?: unknown; blocks?: unknown } | null | undefined; if (typeof section?.title !== "string" || typeof section.digest !== "string") return undefined; // Branch data is untrusted, so the block digests are kept only when they are a list // of strings: a baseline written before block marks simply has none, and one that // holds something else is read at section depth rather than repaired. const blocks = Array.isArray(section.blocks) ? section.blocks.filter((entry): entry is string => typeof entry === "string") : undefined; sections.push( blocks === undefined ? { title: section.title, digest: section.digest } : { title: section.title, digest: section.digest, blocks }, ); } return sections; } /** * The last plan-mode state, the last review baseline per plan, and the plan last * written. One pass, because reading the branch walks the whole session. */ function readBranchState(ctx: ExtensionContext): BranchState { let mode: PlanModeEntry | undefined; let lastPlan: string | undefined; const baselines = new Map(); const seeded = new Map(); for (const raw of ctx.sessionManager.getBranch()) { // A `write` result is where "the plan this branch last wrote" lives, so replaying it // is what keeps the chip naming that plan after `/resume` or a `/tree` hop. Only the // write: a baseline also names a plan, and a view opened from `/plan list` names one // the session may never have written, which is not a plan it is holding. const write = toolResultDetails(raw, PLAN_TOOL); if (write) { if (write.action === "write" && typeof write.path === "string") lastPlan = resolve(write.path); continue; } const entry = raw as { type?: string; customType?: string; data?: unknown }; if (entry.type !== "custom") continue; if (entry.customType === STATE_TYPE) { const data = entry.data as { enabled?: unknown; removed?: unknown } | null | undefined; if (typeof data?.enabled !== "boolean") continue; // Branch data is untrusted; keep only string tool names. const removed = Array.isArray(data.removed) ? data.removed.filter((name): name is string => typeof name === "string") : undefined; mode = removed ? { enabled: data.enabled, removed } : { enabled: data.enabled }; continue; } if (entry.customType === SEEDED_TYPE) { const data = entry.data as { path?: unknown; steps?: unknown } | null | undefined; if (typeof data?.path !== "string" || !Array.isArray(data.steps)) continue; // Branch data is untrusted: keep only the strings a step can be. seeded.set( resolve(data.path), data.steps.filter((text): text is string => typeof text === "string"), ); continue; } if (entry.customType !== BASELINE_TYPE) continue; const data = entry.data as { path?: unknown; sections?: unknown } | null | undefined; if (typeof data?.path !== "string") continue; const sections = readSections(data.sections); // Last entry per path wins, the same rule the mode entry follows. The key is // canonical, so a path recorded on another platform or relative to another cwd // still answers a lookup for the plan it names. if (sections) baselines.set(resolve(data.path), sections); } return { mode, lastPlan, baselines, seeded }; } /** One terminal-safe line for the footer chip. */ function statusName(path: string): string { const name = sanitizeLine(basename(path).replace(/\.md$/i, "")); if (!name) return "plan"; return truncateToWidth(name, STATUS_NAME_LENGTH, "…"); } export function createPlanRuntime( pi: ExtensionAPI, policy: ReadOnlyPolicy, options: { entryPath?: string } = {}, ): PlanRuntime { let enabled = false; let lastPlanPath: string | undefined; // The section digests each plan path last showed in a review, so the next review // can mark what changed. Persisted with the branch, so `/resume` and `/tree` // compare against the review this branch actually showed. const reviewedPlans = new Map(); /** The steps each approval appended, so the next approval can replace its own leftovers. */ const seededPlans = new Map(); // Tools plan mode deactivated, so disabling restores exactly those and does // not re-activate a tool another extension intentionally hid. The tools it had // to *activate* are `createToolSetFilter`'s own memory. let removedForPlan: string[] = []; const plans = createPlanStore(pi); const tools = createToolSetFilter(pi, policy, MODE_TOOLS); /** * Whether `toolName` is plan's own registration, matched by the entry path the * host recorded. Older hosts may not record a source; only a recorded mismatch * is rejected. */ const isOwnTool = (toolName: string): boolean => { if (toolName !== PLAN_TOOL) return false; const info = pi.getAllTools().find((tool) => tool.name === toolName); const source = info?.sourceInfo?.path; return ( source === undefined || options.entryPath === undefined || realPathOfNearest(source) === realPathOfNearest(options.entryPath) ); }; /** * Apply the enabled mode to the active set. `addHidden` re-adds the tools a * user disable hid; a branch restore passes false, because the host has * already put the target branch's base tools back. */ const applyMode = (addHidden: boolean): void => { if (enabled) { tools.enter(); return; } tools.leave(removedForPlan, { reAdd: addHidden }); removedForPlan = []; }; const statusText = (): string => lastPlanPath ? `${GLYPHS.plan} plan · ${statusName(lastPlanPath)}` : `${GLYPHS.plan} plan`; const setStatus = (ctx: ExtensionContext): void => { // Published unstyled: the chip's text is what a footer without bytefly shows, and // bytefly's mode segment paints the mode by role instead of reading this pill. ctx.ui.setStatus(STATUS_KEYS.planMode, enabled ? statusText() : undefined); }; const setEnabled = (next: boolean, ctx: ExtensionContext | undefined, persist: boolean): void => { const changed = next !== enabled; // Capture what we hide only when entering plan mode from a non-plan set. // A redundant enable (for example a `session_tree` restore while already // enabled) must not recompute this from the already-filtered active set, or // disabling would lose them. if (changed && next) removedForPlan = tools.capture(); enabled = next; applyMode(!next); if (persist && changed) { pi.appendEntry(STATE_TYPE, (next ? { enabled, removed: removedForPlan } : { enabled }) satisfies PlanModeEntry); } if (ctx) setStatus(ctx); }; /** * Turn plan mode on, or say why the branch will not have it. * * The one gate every entering door goes through: the tool's `enter`, the request another extension * sends, and Shift+Tab's toggle. The mode is read from the branch rather than from this closure's * flag, because a resume or a `/tree` hop is what moved it — and a refusal names the hatch and * leaves the mode off, so two entries cannot both replay as on. The refusal is handed back as the * sentence it already notified, which is what lets a door put the same words in its own result * rather than describing the refusal a second way. */ const enterPlan = (ctx: ExtensionContext): string | undefined => { const refused = mayEnterFrom("plan", ctx.sessionManager.getBranch()); if (refused !== undefined) { ctx.ui.notify(refused, "warning"); return refused; } setEnabled(true, ctx, true); return undefined; }; return { isEnabled: () => enabled, enable: (ctx) => enterPlan(ctx), disable: (ctx) => setEnabled(false, ctx, true), toggle: (ctx) => { // The state it left, not the sentence: a toggle has no one to explain a refusal to, and the // key that pressed it shows the mode off. A door that must word the refusal calls `enable`. if (!enabled) return enterPlan(ctx) === undefined; setEnabled(false, ctx, true); return false; }, restore: (ctx) => { const branch = readBranchState(ctx); lastPlanPath = branch.lastPlan; // The baseline belongs to the branch that was reviewed: a plan this branch // never showed has no digest here, so nothing looks changed until it does. reviewedPlans.clear(); for (const [path, sections] of branch.baselines) reviewedPlans.set(path, sections); seededPlans.clear(); for (const [path, steps] of branch.seeded) seededPlans.set(path, steps); const persisted = branch.mode; // `--plan` starts a fresh session in plan mode; an explicit persisted // choice (including a later disable) wins over the launch flag. const fromFlag = persisted === undefined && pi.getFlag("plan") === true; const next = fromFlag || persisted?.enabled === true; // A branch carries the tools it hid, so adopt them for a later disable; // a fresh `--plan` captures the current set instead. if (next && persisted?.removed !== undefined) removedForPlan = [...persisted.removed]; else if (next) removedForPlan = tools.capture(); else removedForPlan = []; enabled = next; // Never re-add hidden tools on restore: the host has already restored the // target branch's base set, and only a user disable should undo our hide. applyMode(false); if (ctx) setStatus(ctx); }, plans, isOwnTool, lastPlanPath: () => lastPlanPath, setLastPlan: (ctx, path) => { lastPlanPath = path; setStatus(ctx); }, reviewed: (path) => reviewedPlans.get(resolve(path)), seeded: (path) => seededPlans.get(resolve(path)), markSeeded: (path, steps) => { const key = resolve(path); const previous = seededPlans.get(key); seededPlans.set(key, [...steps]); // Approving the same text again must not grow the branch, the rule `markReviewed` // follows below. if (previous?.length === steps.length && previous.every((text, index) => text === steps[index])) return; pi.appendEntry(SEEDED_TYPE, { path: key, steps: [...steps] } satisfies SeededStepsEntry); }, markReviewed: (path, content) => { const key = resolve(path); const sections = sectionDigests(content); const previous = reviewedPlans.get(key); // A screen shown again over the same content must not grow the branch. if (previous && sameSections(previous, sections)) return; reviewedPlans.set(key, sections); pi.appendEntry(BASELINE_TYPE, { path: key, sections } satisfies ReviewBaselineEntry); }, }; }