@deathbeam/pi-plan 0.0.5 → 0.0.7

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/index.ts CHANGED
@@ -1,448 +1,310 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
- import {
3
- getMarkdownTheme,
4
- type ExtensionAPI,
5
- type ExtensionContext,
6
- type KeybindingHints,
7
- type SessionEntry,
8
- type Theme,
9
- } from "@earendil-works/pi-coding-agent";
10
- import { Markdown, type Component, Text, truncateToWidth } from "@earendil-works/pi-tui";
2
+ import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
11
3
  import { Type } from "typebox";
12
- import { hardBreaks, openPlans } from "./src/inspector.ts";
13
4
  import {
14
- doneCount,
5
+ argText,
6
+ blocks,
7
+ callRenderer,
8
+ changeView,
9
+ listView,
10
+ markdownView,
11
+ planTarget,
12
+ statusArg,
13
+ taskTarget,
14
+ type PlanDetails,
15
+ } from "./src/format.ts";
16
+ import { openPlans } from "./src/inspector.ts";
17
+ import {
15
18
  excludePlans,
16
- fact,
17
- hanging,
18
19
  listPlans,
19
20
  listText,
20
- moreLines,
21
- planStatus,
22
- planSummary,
21
+ planCount,
22
+ planOverview,
23
23
  planText,
24
24
  plansDir,
25
25
  readPlan,
26
26
  repoRoot,
27
- STATUS,
28
- statusText,
29
27
  STATUSES,
30
- taskFacts,
31
28
  taskLine,
32
- taskRow,
33
29
  taskText,
34
- widgetLines,
30
+ tasksText,
35
31
  writePlan,
36
32
  type Plan,
37
- type PlanList,
38
33
  type PlanStatus,
34
+ type PlanTask,
39
35
  } from "./src/store.ts";
40
36
 
41
- type Action = (typeof ACTIONS)[number];
42
-
43
- type PlanDetails = {
44
- action: Action;
45
- active?: string;
46
- /** create, get and update: the plan as it stands after the call. */
47
- plan?: Plan;
48
- /** get and update: the task the call is about. */
49
- id?: string;
50
- /** update: the note this call appended. */
51
- note?: string;
52
- /** list: every plan the call found. */
53
- list?: PlanList;
54
- };
37
+ /** Strict models inject literal "null" for optional params they omit; drop it from those only. */
38
+ function withoutNulls<T extends Record<string, unknown>>(params: T, optionals: readonly (keyof T & string)[]): T {
39
+ const copy: Record<string, unknown> = { ...params };
40
+ for (const key of optionals) if (copy[key] === null || copy[key] === "null") delete copy[key];
41
+ return copy as T;
42
+ }
55
43
 
56
- const ACTIONS = ["create", "update", "get", "list"] as const;
44
+ function taskList(value: unknown, field: string): string[] {
45
+ if (value === undefined) return [];
46
+ if (!Array.isArray(value)) throw new Error(`${field} must be an array.`);
47
+ // pi coerces a bare "null" for an array param into ["null"] before execute runs.
48
+ return value.length === 1 && value[0] === "null" ? [] : (value as string[]);
49
+ }
57
50
 
58
- const PlanParams = Type.Object({
59
- action: StringEnum(ACTIONS),
60
- plan: Type.Optional(
61
- Type.String({ description: "Plan id in kebab-case; get and update default to the active plan." }),
62
- ),
63
- title: Type.Optional(
64
- Type.String({
65
- description: "create: a three to eight word summary of the outcome, shown in the widget and list.",
66
- }),
67
- ),
68
- goal: Type.Optional(Type.String({ description: "create: the observable outcome and the check that proves it." })),
69
- detail: Type.Optional(
70
- Type.String({
71
- description:
72
- "create: markdown sections: current behaviour with path:line, problem, chosen design and rejected alternatives, accepted behaviour changes, out of scope, open questions.",
73
- }),
74
- ),
75
- tasks: Type.Optional(
76
- Type.Array(
77
- Type.Object({
78
- title: Type.String({
79
- description: "The deliverable or behaviour in one line; the widget and get show it beside the id.",
80
- }),
81
- goal: Type.String({
82
- description: "Observable result, with the command to run and its expected output.",
83
- }),
84
- detail: Type.String({
85
- description: "Approach, interfaces to match, pitfalls, and a Where: line citing path:line.",
86
- }),
87
- dependsOn: Type.Optional(
88
- Type.Array(Type.String(), { description: "Task ids this task waits on, such as t1." }),
89
- ),
90
- status: Type.Optional(StringEnum(STATUSES, { description: "Defaults to todo." })),
91
- notes: Type.Optional(
92
- Type.Array(Type.String(), { description: "Existing notes or log lines for this task." }),
93
- ),
51
+ export default function (pi: ExtensionAPI) {
52
+ pi.registerTool({
53
+ name: "plan",
54
+ label: "Plan",
55
+ description:
56
+ "Create a plan for multi-step work at .pi/plans/<id>.json: the goal and the detail a cold reader needs. Add tasks with plan_task.",
57
+ promptSnippet:
58
+ "Create a plan for multi-step work in this project: its goal and detail, then plan_task for each verifiable step",
59
+ promptGuidelines: [
60
+ "When another agent works a task, run `plan_get` with the plan and task and open its brief with that output, unchanged; update the plan here from the agent's result, since a second writer would overwrite plan state.",
61
+ "`plan_update` a task to `doing` when work starts, to `done` only after its goal's check passed and with the result in the note (for example `npm test -- packages/x: 42 passed`), and to `blocked` with what remains while its outcome is unproven.",
62
+ "When the last task is `done`, run the plan `goal`'s check and record the result as a plan note.",
63
+ 'When the user refers to a plan by a loose name ("continue the npc draft"), run `plan_list`, then `plan_get` with the matching `plan` id.',
64
+ ],
65
+ parameters: Type.Object({
66
+ plan: Type.String({ description: "Plan id in kebab-case, for example my-plan." }),
67
+ title: Type.String({
68
+ description: "A three to eight word summary of the outcome, shown in plan_list and the inspector.",
69
+ }),
70
+ goal: Type.String({ description: "The observable outcome and the check that proves it." }),
71
+ detail: Type.String({
72
+ description:
73
+ "Markdown sections: current behaviour with path:line, problem, chosen design and rejected alternatives, accepted behaviour changes, out of scope, open questions.",
94
74
  }),
95
- { description: "create: tasks in execution order; ids t1..tn follow this order." },
96
- ),
97
- ),
98
- task: Type.Optional(
99
- Type.String({
100
- description: "update: task id to change. get: this task alone, with the plan's goal and detail.",
101
- }),
102
- ),
103
- status: Type.Optional(StringEnum(STATUSES, { description: "update: the task's new state." })),
104
- note: Type.Optional(
105
- Type.String({
106
- description:
107
- "update: a note appended to the task's notes; without task, to the plan's notes (use for cross-task rulings).",
108
75
  }),
109
- ),
110
- });
111
-
112
- const WIDGET_KEY = "plan";
113
- const ACTIVE_ENTRY = "plan";
114
- /** pi caps a collapsed tool result at ten rows; the expansion shows all of them. */
115
- const COLLAPSED_LINES = 10;
76
+ executionMode: "sequential",
116
77
 
117
- function lastActive(entries: SessionEntry[]): string | undefined {
118
- let active: string | undefined;
119
- for (const entry of entries) {
120
- // A /plan selection is a custom entry; a tool call carries the plan it touched in its details.
121
- if (entry.type === "custom" && entry.customType === ACTIVE_ENTRY && typeof entry.data === "string")
122
- active = entry.data;
123
- else if (entry.type === "message" && entry.message.role === "toolResult") {
124
- if (entry.message.toolName !== "plan") continue;
125
- const details = entry.message.details as PlanDetails | undefined;
126
- if (typeof details?.active === "string") active = details.active;
127
- }
128
- }
129
- return active;
130
- }
78
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
79
+ const { plan: id, title, goal, detail } = rawParams;
80
+ if (!argText(id) || !argText(title) || !argText(goal) || !argText(detail))
81
+ throw new Error("plan needs plan, title, goal and detail.");
82
+ const root = repoRoot(ctx.cwd);
83
+ if (readPlan(root, id)) throw new Error(`Plan ${id} already exists; use plan_update or plan_get.`);
84
+ const plan: Plan = { id, title, goal, detail, notes: [], tasks: [] };
85
+ excludePlans(root);
86
+ writePlan(root, plan);
87
+ const text = `${plan.id} ${plan.title} ${planCount(plan)}`;
88
+ return { content: [{ type: "text" as const, text }], details: { plan } };
89
+ },
131
90
 
132
- /** Strict models send literal "null" for optional params they omit; a renderer treats it as absent. */
133
- function argText(value: unknown): string {
134
- const text = typeof value === "string" ? value.trim() : "";
135
- return text === "null" ? "" : text;
136
- }
91
+ renderCall: callRenderer(
92
+ "plan",
93
+ (args, theme) => `${planTarget(args, theme)} ${argText(args?.title)}`.trim(),
94
+ (args) => blocks([argText(args?.goal), argText(args?.detail)]).join("\n"),
95
+ ),
137
96
 
138
- function argStatus(value: unknown): PlanStatus | undefined {
139
- const text = argText(value);
140
- return STATUSES.find((status) => status === text);
141
- }
97
+ renderResult: changeView,
98
+ });
142
99
 
143
- function capLines<T>(lines: readonly T[], max: number): { shown: T[]; hidden: number } {
144
- return { shown: lines.slice(0, max), hidden: Math.max(0, lines.length - max) };
145
- }
100
+ pi.registerTool({
101
+ name: "plan_task",
102
+ label: "Plan task",
103
+ description:
104
+ "Append a task to a plan; ids follow insertion order (t1, t2, ...), and dependsOn names tasks already added.",
105
+ parameters: Type.Object({
106
+ plan: Type.String({ description: "Plan id." }),
107
+ title: Type.String({
108
+ description:
109
+ "The deliverable or behaviour in one line; plan_get and the inspector show it beside the id.",
110
+ }),
111
+ goal: Type.String({ description: "Observable result, with the command to run and its expected output." }),
112
+ detail: Type.String({
113
+ description: "Approach, interfaces to match, pitfalls, and a Where: line citing path:line.",
114
+ }),
115
+ dependsOn: Type.Optional(
116
+ Type.Array(Type.String(), { description: "Task ids this task waits on, such as t1." }),
117
+ ),
118
+ status: Type.Optional(StringEnum(STATUSES, { description: "Defaults to todo." })),
119
+ notes: Type.Optional(
120
+ Type.Array(Type.String(), { description: "Existing notes or log lines for this task." }),
121
+ ),
122
+ }),
123
+ executionMode: "sequential",
146
124
 
147
- /** A result view capped to ten rows until the user expands it, then in full. */
148
- function resultView(
149
- rows: (width: number) => string[],
150
- theme: Theme,
151
- expanded: boolean,
152
- keyHint: KeybindingHints["keyHint"],
153
- ): Component {
154
- return {
155
- render: (width) => {
156
- // Wrapping turns one long line into many rows, so the cap counts rendered rows.
157
- const { shown, hidden } = capLines(rows(width), expanded ? Infinity : COLLAPSED_LINES + 1);
158
- return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden, keyHint), width)] : shown;
125
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
126
+ const params = withoutNulls(rawParams, ["dependsOn", "status", "notes"]);
127
+ const { root, respond, requirePlan } = scoped(ctx, params.plan);
128
+ const plan = requirePlan();
129
+ // Append-only: a dependsOn id can only name a task already in the plan, so no order check is needed.
130
+ const id = `t${plan.tasks.length + 1}`;
131
+ if (!argText(params.title) || !argText(params.goal))
132
+ throw new Error(`${id} needs a title, a goal and the check that proves it.`);
133
+ if (!argText(params.detail))
134
+ throw new Error(`${id} needs a detail: the approach, the interfaces and a Where: path:line.`);
135
+ const dependsOn = taskList(params.dependsOn, `${id} dependsOn`);
136
+ for (const other of dependsOn)
137
+ if (!plan.tasks.some((item) => item.id === other))
138
+ throw new Error(`${id} dependsOn ${other}, a task this plan lacks.`);
139
+ const task: PlanTask = {
140
+ id,
141
+ title: params.title,
142
+ goal: params.goal,
143
+ detail: params.detail,
144
+ dependsOn,
145
+ status: (params.status ?? "todo") as PlanStatus,
146
+ notes: taskList(params.notes, `${id} notes`),
147
+ };
148
+ plan.tasks.push(task);
149
+ writePlan(root, plan);
150
+ return respond(`${taskLine(task)}\n${plan.id} ${planCount(plan)}`, {
151
+ plan,
152
+ id: task.id,
153
+ });
159
154
  },
160
- invalidate() {},
161
- };
162
- }
163
155
 
164
- /** pi styles errors itself, but a custom renderer replaces that default, so keep its look. */
165
- function errorView(body: string, theme: Theme, isError: boolean): Component {
166
- const mark = statusText(theme, isError ? "blocked" : "done");
167
- const text = theme.fg(isError ? "error" : "toolOutput", body || "(no output)");
168
- return new Text(`\n${mark} ${text}`, 0, 0);
169
- }
156
+ renderCall: callRenderer(
157
+ "plan_task",
158
+ (args, theme) => `${planTarget(args, theme)} ${argText(args?.title)}`.trim(),
159
+ (args, theme) =>
160
+ blocks([
161
+ argText(args?.goal),
162
+ argText(args?.detail),
163
+ Array.isArray(args?.dependsOn) ? `dependsOn ${argText(args.dependsOn.join(" "))}` : "",
164
+ statusArg(theme, args?.status),
165
+ ]).join("\n"),
166
+ ),
170
167
 
171
- function resultText(result: { content: { type: string; text?: string }[] }): string {
172
- return result.content.flatMap((part) => (part.type === "text" && part.text ? [part.text] : [])).join("\n");
173
- }
168
+ renderResult: changeView,
169
+ });
174
170
 
175
- /** The whole plan: a summary line, then one row per task; only the expansion carries goal, detail and notes. */
176
- function planLines(plan: Plan, theme: Theme, expanded: boolean, width: number): string[] {
177
- const tasks = plan.tasks.flatMap((task) =>
178
- expanded
179
- ? [...hanging(taskRow(theme, plan, task), width, task.id.length + 3), ...taskFacts(theme, task, width)]
180
- : [taskRow(theme, plan, task)],
181
- );
182
- return [
183
- "",
184
- `${theme.fg("accent", "plan")} ${planSummary(theme, plan)}`,
185
- ...(expanded
186
- ? [...fact(theme, "Goal: ", plan.goal, width), ...fact(theme, "Detail: ", plan.detail, width, 2, "dim")]
187
- : []),
188
- ...tasks,
189
- ];
190
- }
171
+ pi.registerTool({
172
+ name: "plan_update",
173
+ label: "Update plan",
174
+ description:
175
+ "Change one task's status or notes, or add a note to the plan; set no task for a cross-task ruling.",
176
+ parameters: Type.Object({
177
+ plan: Type.String({ description: "Plan id." }),
178
+ task: Type.Optional(
179
+ Type.String({ description: "Task id to change; omit to add a note to the plan instead." }),
180
+ ),
181
+ status: Type.Optional(StringEnum(STATUSES, { description: "The task's new state." })),
182
+ note: Type.Optional(
183
+ Type.String({
184
+ description: "The note to append.",
185
+ }),
186
+ ),
187
+ }),
188
+ executionMode: "sequential",
191
189
 
192
- /** What changed: the task row, the note this call appended, and where the plan now stands. */
193
- function updateLines(
194
- plan: Plan,
195
- id: string | undefined,
196
- note: string | undefined,
197
- theme: Theme,
198
- width: number,
199
- ): string[] {
200
- const task = plan.tasks.find((item) => item.id === id);
201
- return [
202
- "",
203
- ...(task ? hanging(taskRow(theme, plan, task), width, task.id.length + 3) : []),
204
- ...(note ? fact(theme, "", note, width) : []),
205
- theme.fg("muted", planSummary(theme, plan)),
206
- ];
207
- }
190
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
191
+ const params = withoutNulls(rawParams, ["task", "status", "note"]);
192
+ const { root, respond, requirePlan } = scoped(ctx, params.plan);
193
+ const plan = requirePlan();
194
+ if (!params.task) {
195
+ if (!params.note) throw new Error("plan_update needs task, or a note for the plan.");
196
+ plan.notes.push(params.note);
197
+ writePlan(root, plan);
198
+ const progress = `${plan.id} ${planCount(plan)}`;
199
+ return respond(`note: ${params.note}\n${progress}`, { plan, note: params.note });
200
+ }
201
+ if (!params.status && !params.note) throw new Error("plan_update needs status or note.");
202
+ const task = plan.tasks.find((item) => item.id === params.task);
203
+ if (!task) throw new Error(`Plan ${plan.id} has no task ${params.task}.`);
204
+ if (params.status) task.status = params.status as PlanStatus;
205
+ if (params.note) task.notes.push(params.note);
206
+ writePlan(root, plan);
207
+ // The model already holds the plan; echo only what changed and where it now stands.
208
+ const progress = `${plan.id} ${planCount(plan)}`;
209
+ return respond(`${taskLine(task)}\n${progress}`, {
210
+ plan,
211
+ id: task.id,
212
+ ...(params.note ? { note: params.note } : {}),
213
+ });
214
+ },
208
215
 
209
- function listLines(list: PlanList, active: string | undefined, theme: Theme): string[] {
210
- if (!list.plans.length && !list.unreadable.length) return [];
211
- return [
212
- "",
213
- ...list.plans.map(
214
- (plan) => `${plan.id === active ? theme.fg("accent", "›") : " "} ${planSummary(theme, plan)}`,
216
+ renderCall: callRenderer(
217
+ "plan_update",
218
+ (args, theme) =>
219
+ [planTarget(args, theme), taskTarget(args, theme), statusArg(theme, args?.status)]
220
+ .filter(Boolean)
221
+ .join(" "),
222
+ (args) => argText(args?.note),
215
223
  ),
216
- ...list.unreadable.map((name) => theme.fg("error", `? ${name} unreadable`)),
217
- ];
218
- }
219
-
220
- /** `plan update t1 done · note`: the action, its target, and the argument that matters. */
221
- function callLine(args: Record<string, unknown>, theme: Theme): Component {
222
- const action = argText(args.action);
223
- const update = action === "update";
224
- const target = update
225
- ? argText(args.task)
226
- : [argText(args.plan), action === "get" ? argText(args.task) : ""].filter(Boolean).join(" ");
227
- const status = update ? argStatus(args.status) : undefined;
228
- const note = update ? argText(args.note) : "";
229
- const head = `${theme.fg("toolTitle", theme.bold("plan"))} ${theme.fg("accent", [action || "…", target].filter(Boolean).join(" "))}`;
230
- const tail = [
231
- status ? theme.fg(STATUS[status].color, status) : "",
232
- note ? theme.fg("muted", `· ${note.length > 60 ? `${note.slice(0, 59)}…` : note}`) : "",
233
- ]
234
- .filter(Boolean)
235
- .join(" ");
236
- return new Text([head, tail].filter(Boolean).join(" "), 0, 0);
237
- }
238
224
 
239
- /** Strict models send "null" for an omitted string or list; anything else that is empty is a bug. */
240
- function blank(value: string | undefined): boolean {
241
- return !value?.trim() || value === "null";
242
- }
243
-
244
- function taskList(value: unknown, field: string): string[] {
245
- if (value === undefined || value === null || value === "null") return [];
246
- if (!Array.isArray(value)) throw new Error(`${field} must be an array.`);
247
- // pi coerces a bare "null" for an array param into ["null"] before execute runs.
248
- return value.length === 1 && value[0] === "null" ? [] : (value as string[]);
249
- }
225
+ renderResult: changeView,
226
+ });
250
227
 
251
- export default function (pi: ExtensionAPI) {
252
- // The last plan this session created, updated or read; restored from the active branch.
253
- let active: string | undefined;
228
+ pi.registerTool({
229
+ name: "plan_get",
230
+ label: "Get plan",
231
+ description:
232
+ "Read a plan: without task its header and one row per task, with task its header and that task's goal, detail and notes.",
233
+ parameters: Type.Object({
234
+ plan: Type.String({ description: "Plan id." }),
235
+ task: Type.Optional(
236
+ Type.String({ description: "Task id to read alone, with the plan's goal and detail." }),
237
+ ),
238
+ }),
239
+ executionMode: "sequential",
254
240
 
255
- function refreshWidget(ctx: ExtensionContext) {
256
- if (!ctx.hasUI) return;
257
- let plan: Plan | undefined;
258
- try {
259
- plan = active ? readPlan(repoRoot(ctx.cwd), active) : undefined;
260
- } catch {
261
- // A restored id or a corrupt file must not break the session; the tool reports the real error.
262
- plan = undefined;
263
- }
264
- if (!plan) {
265
- active = undefined;
266
- ctx.ui.setWidget(WIDGET_KEY, undefined);
267
- return;
268
- }
269
- // A finished plan clears the widget, like pi-delegate's finished jobs; new work brings it back.
270
- ctx.ui.setWidget(WIDGET_KEY, planStatus(plan) === "done" ? undefined : widgetLines(ctx.ui.theme, plan));
271
- }
241
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
242
+ const params = withoutNulls(rawParams, ["task"]);
243
+ const { respond, requirePlan } = scoped(ctx, params.plan);
244
+ const plan = requirePlan();
245
+ const task = params.task ? plan.tasks.find((item) => item.id === params.task) : undefined;
246
+ if (params.task && !task) throw new Error(`Plan ${plan.id} has no task ${params.task}.`);
247
+ const text = task ? taskText(plan, task) : planOverview(plan);
248
+ return respond(text, { text });
249
+ },
272
250
 
273
- function restore(ctx: ExtensionContext) {
274
- active = lastActive(ctx.sessionManager.getBranch());
275
- refreshWidget(ctx);
276
- }
251
+ renderCall: callRenderer("plan_get", (args, theme) =>
252
+ [planTarget(args, theme), taskTarget(args, theme)].filter(Boolean).join(" "),
253
+ ),
277
254
 
278
- pi.on("session_start", (_event, ctx) => restore(ctx));
279
- pi.on("session_tree", (_event, ctx) => restore(ctx));
255
+ renderResult: markdownView,
256
+ });
280
257
 
281
258
  pi.registerTool({
282
- name: "plan",
283
- label: "Plan",
284
- description:
285
- "Read and write the project plan: a plan at .pi/plans/<id>.json with a goal, the detail a cold reader needs, and tasks. Actions: create, update, get, list.",
286
- promptSnippet: "Write the plan for multi-step work in this project: goal, detail, one task per verifiable step",
287
- promptGuidelines: [
288
- "Mark a task `doing` when work on it starts.",
289
- "When another agent works a task, give it the `get` output for that task and update the plan here from its result; a second writer would overwrite plan state.",
290
- "Mark a task `done` only after its goal's check passed, and put the result in the note, for example `npm test -- packages/x: 42 passed`.",
291
- "Leave a task open when its outcome is unproven: `blocked` with a note of what remains, or `todo`.",
292
- "Record a cross-task ruling as a note on the plan: `update` with a note and no task.",
293
- 'When the user refers to a plan by a loose name ("continue the npc draft"), run `list`, then `get` the matching id; that makes it active.',
294
- ],
295
- parameters: PlanParams,
259
+ name: "plan_list",
260
+ label: "List plans",
261
+ description: "List every plan, newest first; with plan, that plan's tasks with their ids and statuses.",
262
+ parameters: Type.Object({
263
+ plan: Type.Optional(Type.String({ description: "Plan id." })),
264
+ }),
265
+ executionMode: "sequential",
266
+
267
+ renderCall: callRenderer("plan_list", (args, theme) => (argText(args?.plan) ? planTarget(args, theme) : "")),
296
268
 
297
269
  async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
298
- // Strict models inject literal "null" for optional params they omit; drop it from those only.
299
- const params = { ...rawParams } as typeof rawParams & Record<string, unknown>;
300
- for (const key of ["plan", "title", "goal", "detail", "tasks", "task", "status", "note"]) {
301
- if (params[key] === null || params[key] === "null") delete params[key];
270
+ const params = withoutNulls(rawParams, ["plan"]);
271
+ if (params.plan) {
272
+ const { respond, requirePlan } = scoped(ctx, params.plan);
273
+ const plan = requirePlan();
274
+ return respond(tasksText(plan), { plan });
302
275
  }
303
276
  const root = repoRoot(ctx.cwd);
304
- const respond = (text: string, action: Action, extra: Omit<PlanDetails, "action" | "active"> = {}) => {
305
- refreshWidget(ctx);
306
- return { content: [{ type: "text" as const, text }], details: { action, active, ...extra } };
307
- };
308
- const requireId = () => {
309
- const id = params.plan ?? active;
310
- if (!id) throw new Error("No active plan; run list, then pass plan.");
311
- return id;
312
- };
313
- const requirePlan = () => {
314
- const id = requireId();
315
- const plan = readPlan(root, id);
316
- if (!plan) throw new Error(`No plan ${id} in ${plansDir(root)}; run list for the ids.`);
317
- return plan;
277
+ const list = listPlans(root);
278
+ return {
279
+ content: [{ type: "text" as const, text: listText(root, list) }],
280
+ details: { list },
318
281
  };
319
-
320
- switch (params.action as Action) {
321
- case "create": {
322
- const { plan: id, title, goal, detail, tasks } = params;
323
- if (!id || !title || !goal || !detail || !tasks || blank(goal) || blank(detail))
324
- throw new Error("create needs plan, title, goal, detail and tasks.");
325
- if (tasks.some((task) => blank(task.goal)))
326
- throw new Error("Every task needs a goal and the check that proves it.");
327
- if (tasks.some((task) => blank(task.detail)))
328
- throw new Error(
329
- "Every task needs a detail: the approach, the interfaces and a Where: path:line.",
330
- );
331
- if (readPlan(root, id)) throw new Error(`Plan ${id} already exists; use get or update.`);
332
- const plan: Plan = {
333
- id,
334
- title,
335
- goal,
336
- detail,
337
- notes: [],
338
- tasks: tasks.map((task, index) => ({
339
- id: `t${index + 1}`,
340
- title: task.title,
341
- goal: task.goal,
342
- detail: task.detail,
343
- dependsOn: taskList(task.dependsOn, `t${index + 1} dependsOn`),
344
- status: (task.status ?? "todo") as PlanStatus,
345
- notes: taskList(task.notes, `t${index + 1} notes`),
346
- })),
347
- };
348
- const ids = new Map(plan.tasks.map((task, index) => [task.id, index]));
349
- for (const [index, task] of plan.tasks.entries())
350
- for (const id of task.dependsOn) {
351
- const target = ids.get(id);
352
- if (target === undefined)
353
- throw new Error(`${task.id} dependsOn ${id}, a task this plan lacks.`);
354
- if (target >= index)
355
- throw new Error(`${task.id} dependsOn ${id}; dependsOn takes only earlier ids.`);
356
- }
357
- excludePlans(root);
358
- writePlan(root, plan);
359
- active = plan.id;
360
- return respond(planText(plan), "create", { plan });
361
- }
362
-
363
- case "update": {
364
- const plan = requirePlan();
365
- if (!params.task) {
366
- if (!params.note) throw new Error("update needs task, or a note for the plan.");
367
- plan.notes.push(params.note);
368
- writePlan(root, plan);
369
- active = plan.id;
370
- const progress = `${plan.id} ${doneCount(plan)}/${plan.tasks.length}`;
371
- return respond(`note: ${params.note}\n${progress}`, "update", { plan, note: params.note });
372
- }
373
- if (!params.status && !params.note) throw new Error("update needs status or note.");
374
- const task = plan.tasks.find((item) => item.id === params.task);
375
- if (!task) throw new Error(`Plan ${plan.id} has no task ${params.task}.`);
376
- if (params.status) task.status = params.status as PlanStatus;
377
- if (params.note) task.notes.push(params.note);
378
- writePlan(root, plan);
379
- active = plan.id;
380
- // The model already holds the plan; echo only what changed and where it now stands.
381
- const progress = `${plan.id} ${doneCount(plan)}/${plan.tasks.length}`;
382
- return respond(`${taskLine(task)}\n${progress}`, "update", {
383
- plan,
384
- id: task.id,
385
- ...(params.note ? { note: params.note } : {}),
386
- });
387
- }
388
-
389
- case "get": {
390
- const plan = requirePlan();
391
- const task = params.task ? plan.tasks.find((item) => item.id === params.task) : undefined;
392
- if (params.task && !task) throw new Error(`Plan ${plan.id} has no task ${params.task}.`);
393
- active = plan.id;
394
- return respond(task ? taskText(plan, task) : planText(plan), "get", {
395
- plan,
396
- ...(task ? { id: task.id } : {}),
397
- });
398
- }
399
-
400
- case "list": {
401
- const list = listPlans(root);
402
- return respond(listText(root, list, active), "list", { list });
403
- }
404
- }
405
- throw new Error(`Unknown plan action ${params.action}.`);
406
282
  },
407
283
 
408
- renderCall: (args, theme) => callLine(args as Record<string, unknown>, theme),
409
-
410
- renderResult(result, { expanded }, theme, context) {
411
- const details = context.isError ? undefined : (result.details as PlanDetails | undefined);
412
- const plan = details?.plan;
413
- const list = details?.list;
414
- const active = details?.active;
415
- const id = details?.id;
416
- const note = details?.note;
417
- let rows: ((width: number) => string[]) | undefined;
418
- if (list) rows = () => listLines(list, active, theme);
419
- else if (plan && details?.action === "get") {
420
- const task = plan.tasks.find((item) => item.id === id);
421
- const markdown = new Markdown(
422
- hardBreaks(task ? taskText(plan, task) : planText(plan)),
423
- 0,
424
- 0,
425
- getMarkdownTheme(),
426
- );
427
- rows = (width) => ["", ...markdown.render(Math.max(1, width)).map((line) => line.trimEnd())];
428
- } else if (plan && details?.action === "update")
429
- rows = (width) => updateLines(plan, id, note, theme, width);
430
- else if (plan) rows = (width) => planLines(plan, theme, expanded, width);
431
- return rows
432
- ? resultView(rows, theme, expanded, context.keyHint)
433
- : errorView(resultText(result), theme, context.isError);
434
- },
284
+ renderResult: listView,
435
285
  });
436
286
 
287
+ /** Per call: the repo root, the result builder, and the plan the call names. */
288
+ function scoped(ctx: ExtensionContext, id: string) {
289
+ const root = repoRoot(ctx.cwd);
290
+ return {
291
+ root,
292
+ respond(text: string, extra: PlanDetails = {}) {
293
+ return { content: [{ type: "text" as const, text }], details: extra };
294
+ },
295
+ requirePlan() {
296
+ const plan = readPlan(root, id);
297
+ if (!plan) throw new Error(`No plan ${id} in ${plansDir(root)}; run plan_list for the ids.`);
298
+ return plan;
299
+ },
300
+ };
301
+ }
302
+
437
303
  pi.registerCommand("plan", {
438
- description: "Show every plan and pick the active one; /plan <id> sets it directly",
304
+ description: "Show every plan in the inspector; /plan <id> opens it on that plan",
439
305
  handler: async (args, ctx) => {
440
306
  const root = repoRoot(ctx.cwd);
441
- const setActive = (id: string) => {
442
- active = id;
443
- pi.appendEntry(ACTIVE_ENTRY, id);
444
- refreshWidget(ctx);
445
- };
307
+ const list = listPlans(root);
446
308
  const id = args.trim();
447
309
  if (id) {
448
310
  let plan: Plan | undefined;
@@ -456,21 +318,22 @@ export default function (pi: ExtensionAPI) {
456
318
  ctx.ui.notify(`No plan ${id} in ${plansDir(root)}.`, "error");
457
319
  return;
458
320
  }
459
- setActive(plan.id);
460
- ctx.ui.notify(`Active plan: ${plan.id}`, "info");
321
+ if (ctx.mode !== "tui") {
322
+ ctx.ui.notify(planText(plan), "info");
323
+ return;
324
+ }
325
+ await openPlans(ctx, list, id);
461
326
  return;
462
327
  }
463
- const list = listPlans(root);
464
328
  if (ctx.mode !== "tui") {
465
- const plan = list.plans.find((item) => item.id === active);
466
- ctx.ui.notify(plan ? planText(plan) : listText(root, list, active), "info");
329
+ ctx.ui.notify(listText(root, list), "info");
467
330
  return;
468
331
  }
469
332
  if (!list.plans.length && !list.unreadable.length) {
470
333
  ctx.ui.notify(`No plans in ${plansDir(root)}.`, "info");
471
334
  return;
472
335
  }
473
- await openPlans(ctx, list, active, setActive);
336
+ await openPlans(ctx, list, undefined);
474
337
  },
475
338
  });
476
339
  }