@narumitw/pi-plan-mode 0.46.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,8 @@ Pi core intentionally does not ship a built-in plan mode; this package provides
15
15
  - Blocks `update_plan`, mutating built-in tools, and unsafe `bash` forms such as writes, substitutions, background jobs, dependency installs, and mutating Git commands.
16
16
  - Injects Codex-like Plan mode instructions: explore first, ask decision questions for high-impact ambiguity, do not mutate files, and finalize only when decision-complete.
17
17
  - Adds required `plan_mode_question` and `plan_mode_complete` tools for structured questions and completion.
18
- - Presents the complete plan and prompts you to implement, save it for later, stay in Plan mode, or exit and discard it.
18
+ - Presents the complete plan and prompts you to implement, export it to a chosen Markdown file, save it for later, stay in Plan mode, or exit and discard it.
19
+ - Exports ready, saved, or active implementation plans with `/plan export [path]` without overwriting existing paths; exporting a ready plan completes and exits Plan mode.
19
20
  - Keeps legacy `<proposed_plan>` responses compatible without advertising XML as the primary workflow.
20
21
  - Shows Plan mode state in Pi's statusline as `plan active`, `plan ready`, `plan saved`, or `plan implementing`; `@narumitw/pi-statusline` adds the default `📝` icon unless configured otherwise.
21
22
  - Persists Plan mode, one session-local saved plan, and active implementation state so resume and compaction retain the exact accepted plan.
@@ -50,6 +51,7 @@ pi -e ./extensions/pi-plan-mode
50
51
  /plan finalize
51
52
  /plan implement
52
53
  /plan save
54
+ /plan export [path]
53
55
  /plan exit
54
56
  ```
55
57
 
@@ -63,9 +65,29 @@ the query to restore the stable tool cursor. RPC keeps the complete unfiltered t
63
65
  model-requested planning interaction, not command-menu navigation. `/plan show` displays the stored
64
66
  plan without starting a model turn, including the accepted plan while implementation is active.
65
67
  `/plan finalize` explicitly asks the agent to complete the plan or ask one remaining material
66
- question, `/plan save` stores a completed ready plan for later and leaves Plan mode, and `/plan
67
- implement` hands a ready or saved plan to a normal implementation turn. `show`, `save`, and
68
- `implement` fail closed when no applicable plan is stored; `finalize` requires active Plan mode.
68
+ question, `/plan save` stores a completed ready plan for later and leaves Plan mode, `/plan
69
+ export [path]` writes a ready, saved, or active implementation plan to Markdown, and `/plan
70
+ implement` hands a ready or saved plan to a normal implementation turn. A successful ready-plan
71
+ export also leaves Plan mode; saved and active implementation exports retain their existing state.
72
+ `show`, `save`, `export`, and `implement` fail closed when no applicable plan is stored; `finalize`
73
+ requires active Plan mode.
74
+
75
+ `/plan export` creates `PLAN.md` in Pi's current working directory. Supply a path to choose another
76
+ location; relative paths resolve from that directory, absolute paths remain absolute, and missing
77
+ parent directories are created. Export never overwrites an existing file, directory, or symbolic
78
+ link: choose another path or remove the existing target first. A successful export adds one trailing
79
+ newline but otherwise preserves the accepted Markdown exactly. After a ready plan is written, Plan
80
+ mode ends, its tools and thinking level are restored, and the ready state is cleared without starting
81
+ a model turn. Exporting a saved or active implementation plan leaves that state unchanged. Failed or
82
+ cancelled exports leave every Plan-mode state unchanged. The resulting file is available to the agent
83
+ through its normal file-reading tools. Export is an explicit user-requested file mutation;
84
+ model-initiated Plan-mode writes remain blocked.
85
+
86
+ In TUI and RPC, **Export plan…** opens a single-line path input from every ready, saved, or active
87
+ plan menu. Submit an empty value to use `PLAN.md`, or enter a relative or absolute custom path. A
88
+ failed TUI export retains the draft for correction; RPC reopens its input dialog. Escape returns to
89
+ the owning menu without writing a file. A successful ready-plan export closes the menu and ends Plan
90
+ mode; saved and active implementation menus close without changing their stored state.
69
91
 
70
92
  When Plan mode is active, ask the agent to design the change. The agent may inspect files and run read-only commands, but it should not edit files or execute the implementation. It should explore first, then use structured questions when your preference or a tradeoff materially changes the plan.
71
93
 
@@ -85,20 +107,20 @@ A complete Plan mode answer should appear only after the agent has resolved disc
85
107
 
86
108
  Legacy sessions and models may still submit one non-empty `<proposed_plan>` block with tags on their own lines. That compatibility path remains accepted, but it is not the primary workflow. Empty, malformed, unclosed, or multiple legacy blocks keep Plan mode active and produce a warning.
87
109
 
88
- After completion, `/plan` opens the ready actions when interactive UI is available. Choosing implementation—or running `/plan implement`—disables Plan mode, restores full tool access, and starts an implementation turn with the stored plan. Choosing **Save for later**—or running `/plan save`—instead stores one plan in the current Pi session, restores normal tools and thinking, and leaves Plan mode without starting a model turn.
110
+ After completion, `/plan` opens the ready actions when interactive UI is available. Choosing implementation—or running `/plan implement`—disables Plan mode, restores full tool access, and starts an implementation turn with the stored plan. Choosing **Export plan…** asks for a destination, writes the plan, restores normal tools and thinking, and leaves Plan mode without starting a model turn. Choosing **Save for later**—or running `/plan save`—instead stores one plan in the current Pi session before leaving Plan mode.
89
111
 
90
- A saved plan appears as `plan saved` and remains available after reload, resume, branch-local fork, and compaction in that session. It does not expire automatically, cross into a new session, or participate in ordinary model context. Open `/plan` to Show, Implement, or Clear it; `/plan show`, `/plan implement`, and `/plan exit`/`off` provide the same direct routes in TUI and RPC. Implementation checks the selected model and authentication before consuming the saved plan. Starting another workflow with `/plan <prompt>` or `/plan tools` is blocked until the saved plan is implemented or cleared, so the single saved slot is never silently overwritten. Resuming that session with `--plan` moves the saved plan back to ready Plan mode. Cancellation or failed implementation preflight leaves it unchanged.
112
+ A saved plan appears as `plan saved` and remains available after reload, resume, branch-local fork, and compaction in that session. It does not expire automatically, cross into a new session, or participate in ordinary model context. Open `/plan` to Show, Implement, Export, or Clear it; `/plan show`, `/plan implement`, `/plan export [path]`, and `/plan exit`/`off` provide the same direct routes in TUI and RPC. Implementation checks the selected model and authentication before consuming the saved plan. Starting another workflow with `/plan <prompt>` or `/plan tools` is blocked until the saved plan is implemented or cleared, so the single saved slot is never silently overwritten. Resuming that session with `--plan` moves the saved plan back to ready Plan mode. Cancellation or failed implementation preflight leaves it unchanged.
91
113
 
92
- Text print and JSON modes can save a ready plan with `/plan save` and clear it with `/plan exit` or `/plan off`. They reject saved-plan display and implementation before changing state because Pi provides neither printable custom-message output nor acknowledged extension-triggered turns in those modes; resume the session in TUI or RPC to show or implement it.
114
+ Text print and JSON modes can export any stored plan with `/plan export [path]`, save a ready plan with `/plan save`, and clear it with `/plan exit` or `/plan off`. Successful export is observable through the created file; exporting a ready plan also leaves Plan mode, while saved and active implementation state remains unchanged. An existing target or missing plan fails the command without changing state. These modes reject saved-plan display and implementation before changing state because Pi provides neither printable custom-message output nor acknowledged extension-triggered turns; resume the session in TUI or RPC to show or implement it.
93
115
 
94
116
  Once implemented, the exact accepted plan remains active across later turns, session resume, and manual or automatic compaction without depending on the compaction summary. Plan mode avoids a duplicate context block while the original implementation handoff remains available and injects one hidden canonical copy after that handoff is compacted away. This can consume up to the existing 50,000-character plan limit in model context when reinjection is needed.
95
117
 
96
- While implementation is active, `/plan show` displays the accepted plan. Interactive `/plan` offers Show, Start a new plan, and Clear; `/plan exit` and `/plan off` are the direct clear routes. Starting a new Plan-mode workflow or implementing a replacement plan supersedes the previous active plan. The extension deliberately does not infer completion from assistant prose or agent settlement, so clear the active plan when the implementation no longer applies. Choosing Stay before implementation keeps the plan ready. Revision feedback starts another Plan-mode turn and clears the previous implementable plan until an updated completion arrives. For clarification-only follow-ups, the agent answers and resubmits the complete unchanged plan so it remains implementable. Before saving or implementation, exit/off discards the ready plan and removes its completion result from later non-Plan model context.
118
+ While implementation is active, `/plan show` displays the accepted plan. Interactive `/plan` offers Show, Export plan…, Start a new plan, and Clear; `/plan exit` and `/plan off` are the direct clear routes. Starting a new Plan-mode workflow or implementing a replacement plan supersedes the previous active plan. The extension deliberately does not infer completion from assistant prose or agent settlement, so clear the active plan when the implementation no longer applies. Choosing Stay before implementation keeps the plan ready. Revision feedback starts another Plan-mode turn and clears the previous implementable plan until an updated completion arrives. For clarification-only follow-ups, the agent answers and resubmits the complete unchanged plan so it remains implementable. Before saving or implementation, exit/off discards the ready plan and removes its completion result from later non-Plan model context.
97
119
 
98
120
  While Plan mode is enabled, the extension also publishes a compact status for Pi statuslines. With `@narumitw/pi-statusline`, this appears in the extension status area:
99
121
 
100
122
  - `plan active`: Plan mode is enabled and still gathering context or drafting a plan.
101
- - `plan ready`: A completed plan is stored until you implement it, save it, continue planning, or exit Plan mode.
123
+ - `plan ready`: A completed plan is stored until you implement it, export it, save it, continue planning, or exit Plan mode.
102
124
  - `plan saved`: One completed plan is stored outside model context in the current session until you implement or clear it.
103
125
  - `plan implementing`: The exact accepted plan remains active until you clear or supersede it.
104
126
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.46.0",
3
+ "version": "0.47.0",
4
4
  "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,6 +43,6 @@
43
43
  "directory": "extensions/pi-plan-mode"
44
44
  },
45
45
  "dependencies": {
46
- "@narumitw/pi-tui-kit": "^0.40.0"
46
+ "@narumitw/pi-tui-kit": "^0.41.0"
47
47
  }
48
48
  }
@@ -6,6 +6,7 @@ interface ActiveImplementationMenuOptions {
6
6
  signal: AbortSignal;
7
7
  isCurrent(): boolean;
8
8
  show(): void;
9
+ exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
9
10
  startNew(): void;
10
11
  clear(): void;
11
12
  }
@@ -14,8 +15,9 @@ export async function showActiveImplementationMenu(
14
15
  ctx: ExtensionContext,
15
16
  options: ActiveImplementationMenuOptions,
16
17
  ) {
17
- type Action = "show" | "start-new" | "clear";
18
- const menu = defineMenu<undefined, "active", Action, ExtensionContext>({
18
+ type Screen = "active" | "export";
19
+ type Action = "show" | "export" | "start-new" | "clear";
20
+ const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
19
21
  start: "active",
20
22
  screens: {
21
23
  active: () => ({
@@ -24,17 +26,28 @@ export async function showActiveImplementationMenu(
24
26
  lines: [options.statusText],
25
27
  items: [
26
28
  { id: "show", label: "Show active implementation plan", action: "show" },
29
+ { id: "export", label: "Export plan…", to: "export" },
27
30
  { id: "start-new", label: "Start a new plan", action: "start-new" },
28
31
  { id: "clear", label: "Clear active implementation plan", action: "clear" },
29
32
  ],
30
33
  hint: "close",
31
34
  }),
35
+ export: () => ({
36
+ kind: "input",
37
+ title: "Export plan",
38
+ lines: ["Existing paths are never overwritten."],
39
+ placeholder: "PLAN.md",
40
+ action: "export",
41
+ hint: "back",
42
+ }),
32
43
  },
33
44
  actions: {
34
45
  show: async () => {
35
46
  options.show();
36
47
  return { kind: "close" };
37
48
  },
49
+ export: async ({ value, signal }) =>
50
+ (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
38
51
  "start-new": async () => {
39
52
  options.startNew();
40
53
  return { kind: "close" };
package/src/command.ts CHANGED
@@ -9,6 +9,7 @@ const PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [
9
9
  { value: "finalize", label: "finalize", description: "Request a completed plan" },
10
10
  { value: "implement", label: "implement", description: "Implement the completed or saved plan" },
11
11
  { value: "save", label: "save", description: "Save the completed plan for later" },
12
+ { value: "export", label: "export", description: "Export the stored plan to a Markdown file" },
12
13
  { value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
13
14
  { value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
14
15
  { value: "tools", label: "tools", description: "Select tools allowed in Plan mode" },
@@ -12,6 +12,7 @@ interface PlanMenuOptions extends MenuLifecycle {
12
12
  show(): void;
13
13
  finalize(): void;
14
14
  implement(): void | Promise<void>;
15
+ exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
15
16
  save(): void;
16
17
  tools(): Promise<void>;
17
18
  stay(): void;
@@ -19,8 +20,9 @@ interface PlanMenuOptions extends MenuLifecycle {
19
20
  }
20
21
 
21
22
  export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuOptions) {
22
- type Action = "show" | "finalize" | "implement" | "save" | "tools" | "stay" | "exit";
23
- const menu = defineMenu<undefined, "main", Action, ExtensionContext>({
23
+ type Screen = "main" | "export";
24
+ type Action = "show" | "finalize" | "implement" | "export" | "save" | "tools" | "stay" | "exit";
25
+ const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
24
26
  start: "main",
25
27
  screens: {
26
28
  main: () => ({
@@ -31,6 +33,7 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
31
33
  ? [
32
34
  { id: "show", label: "Show latest proposed plan", action: "show" },
33
35
  { id: "implement", label: "Implement this plan", action: "implement" },
36
+ { id: "export", label: "Export plan…", to: "export" },
34
37
  { id: "save", label: "Save for later", action: "save" },
35
38
  { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
36
39
  { id: "stay", label: "Stay in Plan mode", action: "stay" },
@@ -44,6 +47,14 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
44
47
  ],
45
48
  hint: "close",
46
49
  }),
50
+ export: () => ({
51
+ kind: "input",
52
+ title: "Export plan",
53
+ lines: ["Existing paths are never overwritten."],
54
+ placeholder: "PLAN.md",
55
+ action: "export",
56
+ hint: "back",
57
+ }),
47
58
  },
48
59
  actions: {
49
60
  show: async () => {
@@ -58,6 +69,8 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
58
69
  await options.implement();
59
70
  return { kind: "close" };
60
71
  },
72
+ export: async ({ value, signal }) =>
73
+ (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
61
74
  save: async () => {
62
75
  options.save();
63
76
  return { kind: "close" };
@@ -85,14 +98,16 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
85
98
 
86
99
  interface ReadyPlanMenuOptions extends MenuLifecycle {
87
100
  implement(): void | Promise<void>;
101
+ exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
88
102
  save(): void;
89
103
  stay(): void;
90
104
  exit(): void;
91
105
  }
92
106
 
93
107
  export async function showReadyPlanMenu(ctx: ExtensionContext, options: ReadyPlanMenuOptions) {
94
- type Action = "implement" | "save" | "stay" | "exit";
95
- const menu = defineMenu<undefined, "ready", Action, ExtensionContext>({
108
+ type Screen = "ready" | "export";
109
+ type Action = "implement" | "export" | "save" | "stay" | "exit";
110
+ const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
96
111
  start: "ready",
97
112
  screens: {
98
113
  ready: () => ({
@@ -100,18 +115,29 @@ export async function showReadyPlanMenu(ctx: ExtensionContext, options: ReadyPla
100
115
  title: "Proposed plan ready. What next?",
101
116
  items: [
102
117
  { id: "implement", label: "Implement this plan", action: "implement" },
118
+ { id: "export", label: "Export plan…", to: "export" },
103
119
  { id: "save", label: "Save for later", action: "save" },
104
120
  { id: "stay", label: "Stay in Plan mode", action: "stay" },
105
121
  { id: "exit", label: "Exit Plan mode", action: "exit" },
106
122
  ],
107
123
  hint: "close",
108
124
  }),
125
+ export: () => ({
126
+ kind: "input",
127
+ title: "Export plan",
128
+ lines: ["Existing paths are never overwritten."],
129
+ placeholder: "PLAN.md",
130
+ action: "export",
131
+ hint: "back",
132
+ }),
109
133
  },
110
134
  actions: {
111
135
  implement: async () => {
112
136
  await options.implement();
113
137
  return { kind: "close" };
114
138
  },
139
+ export: async ({ value, signal }) =>
140
+ (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
115
141
  save: async () => {
116
142
  options.save();
117
143
  return { kind: "close" };
@@ -0,0 +1,119 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { stripVTControlCharacters } from "node:util";
4
+ import { type ExtensionContext, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
+ import type { PlanModeState } from "./state.js";
6
+
7
+ export const DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
8
+
9
+ export interface PlanExportResult {
10
+ path: string;
11
+ }
12
+
13
+ export interface PlanExportLifecycle {
14
+ signal: AbortSignal;
15
+ isCurrent(): boolean;
16
+ getState?(): PlanModeState;
17
+ finishReady?(): void;
18
+ }
19
+
20
+ export async function exportStoredPlan(
21
+ state: PlanModeState,
22
+ requestedPath: string | undefined,
23
+ ctx: ExtensionContext,
24
+ lifecycle?: PlanExportLifecycle,
25
+ ) {
26
+ const plan =
27
+ (state.enabled ? state.latestPlan : undefined)?.trim() ??
28
+ state.savedPlan?.plan.trim() ??
29
+ state.activeImplementation?.plan.trim();
30
+ if (!plan) {
31
+ const error = new Error(
32
+ "No completed plan is available to export. Use /plan finalize when planning is complete.",
33
+ );
34
+ if (!ctx.hasUI) throw error;
35
+ ctx.ui.notify(error.message, "warning");
36
+ return false;
37
+ }
38
+
39
+ const isCurrent = () =>
40
+ !lifecycle ||
41
+ (lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state));
42
+ let result: PlanExportResult;
43
+ try {
44
+ result = await exportPlanToFile(plan, requestedPath, ctx.cwd, lifecycle?.signal, isCurrent);
45
+ } catch (error: unknown) {
46
+ if (lifecycle?.signal.aborted || !isCurrent()) return false;
47
+ if (!ctx.hasUI) throw error;
48
+ const detail = error instanceof Error ? error.message : String(error);
49
+ ctx.ui.notify(safeNotification(`Unable to export plan: ${detail}`), "error");
50
+ return false;
51
+ }
52
+
53
+ if (!isCurrent()) return false;
54
+ const finishedReady =
55
+ state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== undefined;
56
+ if (finishedReady) lifecycle.finishReady?.();
57
+ const detail = finishedReady ? " Plan mode disabled." : "";
58
+ ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), "info");
59
+ return true;
60
+ }
61
+
62
+ export async function exportPlanToFile(
63
+ plan: string,
64
+ requestedPath: string | undefined,
65
+ cwd: string,
66
+ signal?: AbortSignal,
67
+ isCurrent: () => boolean = () => true,
68
+ ): Promise<PlanExportResult> {
69
+ const path = resolvePlanExportPath(requestedPath, cwd);
70
+ await withFileMutationQueue(path, async () => {
71
+ throwIfCancelled(signal, isCurrent);
72
+ await mkdir(dirname(path), { recursive: true });
73
+ throwIfCancelled(signal, isCurrent);
74
+ try {
75
+ await writeFile(path, `${plan}\n`, { encoding: "utf8", flag: "wx" });
76
+ } catch (error: unknown) {
77
+ if (isNodeError(error) && error.code === "EEXIST") {
78
+ throw new Error(
79
+ `Plan export target already exists: ${path}. Choose another path or remove it first.`,
80
+ );
81
+ }
82
+ throw error;
83
+ }
84
+ });
85
+ return { path };
86
+ }
87
+
88
+ export function resolvePlanExportPath(requestedPath: string | undefined, cwd: string) {
89
+ const rawPath = requestedPath?.trim() || DEFAULT_PLAN_EXPORT_PATH;
90
+ const normalizedPath = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
91
+ if (!normalizedPath.trim()) throw new Error("Plan export path must not be empty.");
92
+ if (normalizedPath.includes("\0")) {
93
+ throw new Error("Plan export path must not contain NUL bytes.");
94
+ }
95
+ return resolve(cwd, normalizedPath);
96
+ }
97
+
98
+ function safeNotification(value: string) {
99
+ let sanitized = "";
100
+ for (const character of stripVTControlCharacters(value)) {
101
+ const codePoint = character.codePointAt(0);
102
+ sanitized +=
103
+ codePoint !== undefined && codePoint > 0x1f && !(codePoint >= 0x7f && codePoint <= 0x9f)
104
+ ? character
105
+ : " ";
106
+ }
107
+ return sanitized;
108
+ }
109
+
110
+ function throwIfCancelled(signal: AbortSignal | undefined, isCurrent: () => boolean) {
111
+ if (!signal?.aborted && isCurrent()) return;
112
+ throw signal?.reason instanceof Error
113
+ ? signal.reason
114
+ : new DOMException("Plan export cancelled", "AbortError");
115
+ }
116
+
117
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
118
+ return error instanceof Error && "code" in error;
119
+ }
package/src/plan-mode.ts CHANGED
@@ -29,10 +29,11 @@ import {
29
29
  stripProposedPlanBlocksFromMessage,
30
30
  } from "./message-transform.js";
31
31
  import { showPlanModeMenu, showReadyPlanMenu } from "./plan-action-menus.js";
32
+ import { exportStoredPlan } from "./plan-export.js";
32
33
  import {
33
34
  clearPlanModeUi,
34
35
  planModeStatusText as formatPlanModeStatusText,
35
- showPlanModePlan,
36
+ showStoredPlan,
36
37
  updatePlanModeUi,
37
38
  } from "./presentation.js";
38
39
  import { buildPlanModePrompt } from "./prompt.js";
@@ -168,7 +169,7 @@ export default function planMode(
168
169
  const prompt = args.trim();
169
170
  const command = prompt.toLowerCase();
170
171
  if (command === "show") {
171
- showStoredPlan(ctx);
172
+ showStoredPlan(pi, ctx, state);
172
173
  return;
173
174
  }
174
175
  if (command === "finalize") {
@@ -187,6 +188,17 @@ export default function planMode(
187
188
  savePlanForLater(ctx);
188
189
  return;
189
190
  }
191
+ const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
192
+ if (exportMatch) {
193
+ const lifecycle = captureMenuLifecycle();
194
+ await exportStoredPlan(
195
+ state,
196
+ exportMatch[1],
197
+ ctx,
198
+ exportOwner(ctx, lifecycle.signal, lifecycle.isCurrent),
199
+ );
200
+ return;
201
+ }
190
202
  if (command === "exit" || command === "off") {
191
203
  const notification = state.activeImplementation
192
204
  ? "Active implementation plan cleared."
@@ -526,29 +538,6 @@ export default function planMode(
526
538
  return completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;
527
539
  }
528
540
 
529
- function showStoredPlan(ctx: ExtensionContext) {
530
- const readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;
531
- const savedPlan = state.savedPlan?.plan.trim();
532
- if (savedPlan && (ctx.mode === "print" || ctx.mode === "json")) {
533
- throw new Error("Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.");
534
- }
535
- const activePlan = state.activeImplementation?.plan.trim();
536
- const plan = readyPlan ?? savedPlan ?? activePlan;
537
- if (!plan) {
538
- ctx.ui.notify(
539
- "No completed plan is available. Use /plan finalize when planning is complete.",
540
- "info",
541
- );
542
- return;
543
- }
544
- const title = readyPlan
545
- ? "Proposed Plan"
546
- : savedPlan
547
- ? "Saved Plan"
548
- : "Active Implementation Plan";
549
- showPlanModePlan(pi, ctx, title, plan);
550
- }
551
-
552
541
  function requestFinalPlan(ctx: ExtensionContext) {
553
542
  if (!state.enabled) {
554
543
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
@@ -665,7 +654,9 @@ export default function planMode(
665
654
  statusText: planStatusText(),
666
655
  signal: lifecycle.signal,
667
656
  isCurrent: lifecycle.isCurrent,
668
- show: () => showStoredPlan(ctx),
657
+ show: () => showStoredPlan(pi, ctx, state),
658
+ exportPlan: (path, signal) =>
659
+ exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
669
660
  startNew: () => {
670
661
  enterPlanMode(ctx);
671
662
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
@@ -683,8 +674,10 @@ export default function planMode(
683
674
  statusText: planStatusText(),
684
675
  signal: lifecycle.signal,
685
676
  isCurrent: lifecycle.isCurrent,
686
- show: () => showStoredPlan(ctx),
677
+ show: () => showStoredPlan(pi, ctx, state),
687
678
  implement: () => startImplementation(ctx),
679
+ exportPlan: (path, signal) =>
680
+ exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
688
681
  clear: () => {
689
682
  exitPlanMode(ctx);
690
683
  ctx.ui.notify("Saved plan cleared.", "info");
@@ -702,9 +695,11 @@ export default function planMode(
702
695
  statusText: planStatusText(),
703
696
  hasReadyPlan: state.latestPlan !== undefined,
704
697
  ...lifecycle,
705
- show: () => showStoredPlan(ctx),
698
+ show: () => showStoredPlan(pi, ctx, state),
706
699
  finalize: () => requestFinalPlan(ctx),
707
700
  implement: () => startImplementation(ctx),
701
+ exportPlan: (path, signal) =>
702
+ exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
708
703
  save: () => savePlanForLater(ctx),
709
704
  tools: () => showToolSelector(ctx),
710
705
  stay: () => updateUi(ctx),
@@ -720,6 +715,8 @@ export default function planMode(
720
715
  await showReadyPlanMenu(ctx, {
721
716
  ...lifecycle,
722
717
  implement: () => startImplementation(ctx),
718
+ exportPlan: (path, signal) =>
719
+ exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
723
720
  save: () => savePlanForLater(ctx),
724
721
  stay: () => undefined,
725
722
  exit: () => {
@@ -794,6 +791,10 @@ export default function planMode(
794
791
  updateUi(ctx);
795
792
  }
796
793
 
794
+ function exportOwner(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean) {
795
+ return { signal, isCurrent, getState: () => state, finishReady: () => exitPlanMode(ctx) };
796
+ }
797
+
797
798
  function captureMenuLifecycle() {
798
799
  const sessionGeneration = menuGeneration;
799
800
  const planWorkflowGeneration = workflowGeneration;
@@ -41,6 +41,29 @@ export function clearPlanModeUi(ctx: ExtensionContext) {
41
41
  ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
42
42
  }
43
43
 
44
+ export function showStoredPlan(pi: ExtensionAPI, ctx: ExtensionContext, state: PlanModeState) {
45
+ const readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;
46
+ const savedPlan = state.savedPlan?.plan.trim();
47
+ if (savedPlan && (ctx.mode === "print" || ctx.mode === "json")) {
48
+ throw new Error("Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.");
49
+ }
50
+ const activePlan = state.activeImplementation?.plan.trim();
51
+ const plan = readyPlan ?? savedPlan ?? activePlan;
52
+ if (!plan) {
53
+ ctx.ui.notify(
54
+ "No completed plan is available. Use /plan finalize when planning is complete.",
55
+ "info",
56
+ );
57
+ return;
58
+ }
59
+ const title = readyPlan
60
+ ? "Proposed Plan"
61
+ : savedPlan
62
+ ? "Saved Plan"
63
+ : "Active Implementation Plan";
64
+ showPlanModePlan(pi, ctx, title, plan);
65
+ }
66
+
44
67
  export function showPlanModePlan(
45
68
  pi: ExtensionAPI,
46
69
  ctx: ExtensionContext,
@@ -7,15 +7,19 @@ interface SavedPlanMenuOptions {
7
7
  isCurrent(): boolean;
8
8
  show(): void;
9
9
  implement(): void | Promise<void>;
10
+ exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
10
11
  clear(): void;
11
12
  }
12
13
 
13
14
  export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPlanMenuOptions) {
14
15
  if (!ctx.hasUI) {
15
- throw new Error(`${options.statusText} Use /plan show, /plan implement, or /plan exit.`);
16
+ throw new Error(
17
+ `${options.statusText} Use /plan show, /plan implement, /plan export, or /plan exit.`,
18
+ );
16
19
  }
17
- type Action = "show" | "implement" | "clear";
18
- const menu = defineMenu<undefined, "saved", Action, ExtensionContext>({
20
+ type Screen = "saved" | "export";
21
+ type Action = "show" | "implement" | "export" | "clear";
22
+ const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
19
23
  start: "saved",
20
24
  screens: {
21
25
  saved: () => ({
@@ -25,10 +29,19 @@ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPla
25
29
  items: [
26
30
  { id: "show", label: "Show saved plan", action: "show" },
27
31
  { id: "implement", label: "Implement saved plan", action: "implement" },
32
+ { id: "export", label: "Export plan…", to: "export" },
28
33
  { id: "clear", label: "Clear saved plan", action: "clear" },
29
34
  ],
30
35
  hint: "close",
31
36
  }),
37
+ export: () => ({
38
+ kind: "input",
39
+ title: "Export plan",
40
+ lines: ["Existing paths are never overwritten."],
41
+ placeholder: "PLAN.md",
42
+ action: "export",
43
+ hint: "back",
44
+ }),
32
45
  },
33
46
  actions: {
34
47
  show: async () => {
@@ -39,6 +52,8 @@ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPla
39
52
  await options.implement();
40
53
  return { kind: "close" };
41
54
  },
55
+ export: async ({ value, signal }) =>
56
+ (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
42
57
  clear: async () => {
43
58
  options.clear();
44
59
  return { kind: "close" };