@deathbeam/pi-plan 0.0.0-stage → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tomas Slusny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # [@deathbeam/pi-plan](https://www.npmjs.com/package/@deathbeam/pi-plan)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Structured plans: a `plan` tool, a progress widget, and a `/plan` picker over every plan in the project.
4
+ Each task carries its own `doneWhen` check, and `plan get <id>` returns one task with the plan's goal and context.
5
+ The bundled `prepare-plan` skill writes a plan, and `import-plan` migrates existing plan documents (`.plans/*.md`, Cursor, Kiro, Taskmaster).
6
+
7
+ Plans live in `.pi/plans/<name>.json` at the repository root. Add `.pi/plans/` to `.gitignore` if the first `plan create` cannot write it to `.git/info/exclude`.
8
+
9
+ ## Installation
10
+
11
+ ```sh
12
+ # Choose one:
13
+ pi install npm:@deathbeam/pi-plan # this package
14
+ pi install git:github.com/deathbeam/pi-packages # all my packages
15
+ ```
16
+
17
+ ## Development
18
+
19
+ From the repo root:
20
+
21
+ ```sh
22
+ npm install
23
+ npm test -- packages/pi-plan
24
+ pi install ./packages/pi-plan
25
+ ```
package/index.ts ADDED
@@ -0,0 +1,431 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ KeybindingHints,
6
+ SessionEntry,
7
+ Theme,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { type Component, Text, truncateToWidth } from "@earendil-works/pi-tui";
10
+ import { Type } from "typebox";
11
+ import { openPlans } from "./src/inspector.ts";
12
+ import {
13
+ doneCount,
14
+ excludePlans,
15
+ fact,
16
+ hanging,
17
+ listPlans,
18
+ listText,
19
+ moreLines,
20
+ nextTask,
21
+ planSummary,
22
+ planText,
23
+ plansDir,
24
+ readPlan,
25
+ repoRoot,
26
+ STATUS,
27
+ statusText,
28
+ STATUSES,
29
+ taskFacts,
30
+ taskLine,
31
+ taskRow,
32
+ taskText,
33
+ widgetLine,
34
+ writePlan,
35
+ type Plan,
36
+ type PlanList,
37
+ type PlanStatus,
38
+ } from "./src/store.ts";
39
+
40
+ const ACTIONS = ["create", "update", "get", "list"] as const;
41
+
42
+ type Action = (typeof ACTIONS)[number];
43
+
44
+ type PlanDetails = {
45
+ action: Action;
46
+ active?: string;
47
+ /** create, get and update: the plan as it stands after the call. */
48
+ plan?: Plan;
49
+ /** get and update: the task the call is about. */
50
+ id?: string;
51
+ /** update: the note this call appended. */
52
+ note?: string;
53
+ /** list: every plan the call found. */
54
+ list?: PlanList;
55
+ };
56
+
57
+ const PlanParams = Type.Object({
58
+ action: StringEnum(ACTIONS),
59
+ name: Type.Optional(
60
+ Type.String({ description: "Plan name in kebab-case; get and update default to the active plan." }),
61
+ ),
62
+ goal: Type.Optional(Type.String({ description: "create: the observable outcome." })),
63
+ context: Type.Optional(
64
+ Type.String({ description: "create: current behaviour, seams, decisions, constraints, out of scope." }),
65
+ ),
66
+ tasks: Type.Optional(
67
+ Type.Array(
68
+ Type.Object({
69
+ title: Type.String({ description: "Deliverable or behaviour, one line." }),
70
+ where: Type.Optional(Type.String({ description: "Files or paths the task touches." })),
71
+ blockedBy: Type.Optional(
72
+ Type.Array(Type.String(), { description: "Task ids this task waits on, such as t1." }),
73
+ ),
74
+ doneWhen: Type.String({
75
+ description: "Observable result, with the command to run and its expected output.",
76
+ }),
77
+ status: Type.Optional(StringEnum(STATUSES, { description: "Defaults to todo." })),
78
+ notes: Type.Optional(
79
+ Type.Array(Type.String(), { description: "Existing notes or log lines for this task." }),
80
+ ),
81
+ }),
82
+ { description: "create: tasks in execution order; ids t1..tn follow this order." },
83
+ ),
84
+ ),
85
+ id: Type.Optional(
86
+ Type.String({
87
+ description: "update: task id to change. get: this task alone, with the plan's goal and context.",
88
+ }),
89
+ ),
90
+ status: Type.Optional(StringEnum(STATUSES, { description: "update: the task's new state." })),
91
+ note: Type.Optional(Type.String({ description: "update: text appended to the task's notes." })),
92
+ });
93
+
94
+ const WIDGET_KEY = "plan";
95
+ const ACTIVE_ENTRY = "plan";
96
+ /** pi caps a collapsed tool result at ten rows; the expansion shows all of them. */
97
+ const COLLAPSED_LINES = 10;
98
+
99
+ function lastActive(entries: SessionEntry[]): string | undefined {
100
+ let active: string | undefined;
101
+ for (const entry of entries) {
102
+ // A /plan selection is a custom entry; a tool call carries the plan it touched in its details.
103
+ if (entry.type === "custom" && entry.customType === ACTIVE_ENTRY && typeof entry.data === "string")
104
+ active = entry.data;
105
+ else if (entry.type === "message" && entry.message.role === "toolResult") {
106
+ if (entry.message.toolName !== "plan") continue;
107
+ const details = entry.message.details as PlanDetails | undefined;
108
+ if (typeof details?.active === "string") active = details.active;
109
+ }
110
+ }
111
+ return active;
112
+ }
113
+
114
+ /** Strict models send literal "null" for optional params they omit; a renderer treats it as absent. */
115
+ function argText(value: unknown): string {
116
+ const text = typeof value === "string" ? value.trim() : "";
117
+ return text === "null" ? "" : text;
118
+ }
119
+
120
+ function argStatus(value: unknown): PlanStatus | undefined {
121
+ const text = argText(value);
122
+ return STATUSES.find((status) => status === text);
123
+ }
124
+
125
+ function capLines<T>(lines: readonly T[], max: number): { shown: T[]; hidden: number } {
126
+ return { shown: lines.slice(0, max), hidden: Math.max(0, lines.length - max) };
127
+ }
128
+
129
+ /** A result view capped to ten rows until the user expands it, then in full. */
130
+ function resultView(
131
+ rows: (width: number) => string[],
132
+ theme: Theme,
133
+ expanded: boolean,
134
+ keyHint: KeybindingHints["keyHint"],
135
+ ): Component {
136
+ return {
137
+ render: (width) => {
138
+ // Wrapping turns one long line into many rows, so the cap counts rendered rows.
139
+ const { shown, hidden } = capLines(rows(width), expanded ? Infinity : COLLAPSED_LINES + 1);
140
+ return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden, keyHint), width)] : shown;
141
+ },
142
+ invalidate() {},
143
+ };
144
+ }
145
+
146
+ /** pi styles errors itself, but a custom renderer replaces that default, so keep its look. */
147
+ function errorView(body: string, theme: Theme, isError: boolean): Component {
148
+ const mark = statusText(theme, isError ? "blocked" : "done");
149
+ const text = theme.fg(isError ? "error" : "toolOutput", body || "(no output)");
150
+ return new Text(`\n${mark} ${text}`, 0, 0);
151
+ }
152
+
153
+ function resultText(result: { content: { type: string; text?: string }[] }): string {
154
+ return result.content.flatMap((part) => (part.type === "text" && part.text ? [part.text] : [])).join("\n");
155
+ }
156
+
157
+ /** The whole plan: a summary line, then one row per task; only the expansion carries goal, context and notes. */
158
+ function planLines(plan: Plan, theme: Theme, expanded: boolean, width: number): string[] {
159
+ const tasks = plan.tasks.flatMap((task) =>
160
+ expanded
161
+ ? [...hanging(taskRow(theme, plan, task), width, task.id.length + 3), ...taskFacts(theme, task, width)]
162
+ : [taskRow(theme, plan, task)],
163
+ );
164
+ return [
165
+ "",
166
+ `${theme.fg("accent", "plan")} ${planSummary(theme, plan)}`,
167
+ ...(expanded
168
+ ? [...fact(theme, "Goal: ", plan.goal, width), ...fact(theme, "Context: ", plan.context, width, 2, "dim")]
169
+ : []),
170
+ ...tasks,
171
+ ];
172
+ }
173
+
174
+ /** One task of a plan: its row, then the check and notes that make it a brief. */
175
+ function focusLines(plan: Plan, id: string, theme: Theme, width: number): string[] {
176
+ const task = plan.tasks.find((item) => item.id === id);
177
+ return task
178
+ ? ["", ...hanging(taskRow(theme, plan, task), width, task.id.length + 3), ...taskFacts(theme, task, width)]
179
+ : [];
180
+ }
181
+
182
+ /** What changed: the task row, the note this call appended, and where the plan now stands. */
183
+ function updateLines(
184
+ plan: Plan,
185
+ id: string | undefined,
186
+ note: string | undefined,
187
+ theme: Theme,
188
+ width: number,
189
+ ): string[] {
190
+ const task = plan.tasks.find((item) => item.id === id);
191
+ if (!task) return [];
192
+ return [
193
+ "",
194
+ ...hanging(taskRow(theme, plan, task), width, task.id.length + 3),
195
+ ...(note ? fact(theme, "", note, width) : []),
196
+ theme.fg("muted", planSummary(theme, plan)),
197
+ ];
198
+ }
199
+
200
+ function listLines(list: PlanList, active: string | undefined, theme: Theme): string[] {
201
+ if (!list.plans.length && !list.unreadable.length) return [];
202
+ return [
203
+ "",
204
+ ...list.plans.map(
205
+ (plan) => `${plan.name === active ? theme.fg("accent", "›") : " "} ${planSummary(theme, plan)}`,
206
+ ),
207
+ ...list.unreadable.map((name) => theme.fg("error", `? ${name} unreadable`)),
208
+ ];
209
+ }
210
+
211
+ /** `plan update t1 done · note`: the action, its target, and the argument that matters. */
212
+ function callLine(args: Record<string, unknown>, theme: Theme): Component {
213
+ const action = argText(args.action);
214
+ const update = action === "update";
215
+ const target = update
216
+ ? argText(args.id)
217
+ : [argText(args.name), action === "get" ? argText(args.id) : ""].filter(Boolean).join(" ");
218
+ const status = update ? argStatus(args.status) : undefined;
219
+ const note = update ? argText(args.note) : "";
220
+ const head = `${theme.fg("toolTitle", theme.bold("plan"))} ${theme.fg("accent", [action || "…", target].filter(Boolean).join(" "))}`;
221
+ const tail = [
222
+ status ? theme.fg(STATUS[status].color, status) : "",
223
+ note ? theme.fg("muted", `· ${note.length > 60 ? `${note.slice(0, 59)}…` : note}`) : "",
224
+ ]
225
+ .filter(Boolean)
226
+ .join(" ");
227
+ return new Text([head, tail].filter(Boolean).join(" "), 0, 0);
228
+ }
229
+
230
+ export default function (pi: ExtensionAPI) {
231
+ // The last plan this session created, updated or read; restored from the active branch.
232
+ let active: string | undefined;
233
+
234
+ function refreshWidget(ctx: ExtensionContext) {
235
+ if (!ctx.hasUI) return;
236
+ let plan: Plan | undefined;
237
+ try {
238
+ plan = active ? readPlan(repoRoot(ctx.cwd), active) : undefined;
239
+ } catch {
240
+ // A restored name or a corrupt file must not break the session; the tool reports the real error.
241
+ plan = undefined;
242
+ }
243
+ if (!plan) {
244
+ active = undefined;
245
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
246
+ return;
247
+ }
248
+ ctx.ui.setWidget(WIDGET_KEY, [widgetLine(ctx.ui.theme, plan)]);
249
+ }
250
+
251
+ function restore(ctx: ExtensionContext) {
252
+ active = lastActive(ctx.sessionManager.getBranch());
253
+ refreshWidget(ctx);
254
+ }
255
+
256
+ pi.on("session_start", (_event, ctx) => restore(ctx));
257
+ pi.on("session_tree", (_event, ctx) => restore(ctx));
258
+
259
+ pi.registerTool({
260
+ name: "plan",
261
+ label: "Plan",
262
+ description:
263
+ "Read and write the project plan: a task list at .pi/plans/<name>.json. Actions: create, update, get, list.",
264
+ promptSnippet: "Track multi-step work as a plan in this project, one task per verifiable step",
265
+ promptGuidelines: [
266
+ "Mark a task `doing` when work on it starts.",
267
+ "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.",
268
+ "Mark a task `done` only after its doneWhen check passed, and put that check and its result in the note, for example `npm test -- packages/x: 42 passed`.",
269
+ "Leave a task open when its outcome is unproven: `blocked` with a note of what remains, or `todo`.",
270
+ "Record a scope change as a `Ruling:` note giving the change and the reason.",
271
+ 'When the user refers to a plan by a loose name ("continue the npc draft"), run `list`, then `get` the matching name; that makes it active.',
272
+ ],
273
+ parameters: PlanParams,
274
+
275
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
276
+ // Strict models inject literal "null" for optional params they omit; drop it from those only.
277
+ const params = { ...rawParams } as typeof rawParams & Record<string, unknown>;
278
+ for (const key of ["name", "goal", "context", "tasks", "id", "status", "note"]) {
279
+ if (params[key] === null || params[key] === "null") delete params[key];
280
+ }
281
+ const root = repoRoot(ctx.cwd);
282
+ const respond = (text: string, action: Action, extra: Omit<PlanDetails, "action" | "active"> = {}) => {
283
+ refreshWidget(ctx);
284
+ return { content: [{ type: "text" as const, text }], details: { action, active, ...extra } };
285
+ };
286
+ const requireName = () => {
287
+ const name = params.name ?? active;
288
+ if (!name) throw new Error("No active plan; run list, then pass name.");
289
+ return name;
290
+ };
291
+ const requirePlan = () => {
292
+ const name = requireName();
293
+ const plan = readPlan(root, name);
294
+ if (!plan) throw new Error(`No plan ${name} in ${plansDir(root)}; run list for the names.`);
295
+ return plan;
296
+ };
297
+
298
+ switch (params.action as Action) {
299
+ case "create": {
300
+ const { name, goal, context, tasks } = params;
301
+ if (!name || !goal || !context || !tasks)
302
+ throw new Error("create needs name, goal, context and tasks.");
303
+ if (readPlan(root, name)) throw new Error(`Plan ${name} already exists; use get or update.`);
304
+ const plan: Plan = {
305
+ name,
306
+ goal,
307
+ context,
308
+ tasks: tasks.map((task, index) => ({
309
+ id: `t${index + 1}`,
310
+ title: task.title,
311
+ ...(task.where && task.where !== "null" ? { where: task.where } : {}),
312
+ blockedBy: task.blockedBy ?? [],
313
+ doneWhen: task.doneWhen,
314
+ status: (task.status ?? "todo") as PlanStatus,
315
+ notes: task.notes ?? [],
316
+ })),
317
+ };
318
+ const ids = new Map(plan.tasks.map((task, index) => [task.id, index]));
319
+ for (const [index, task] of plan.tasks.entries())
320
+ for (const id of task.blockedBy) {
321
+ const target = ids.get(id);
322
+ if (target === undefined)
323
+ throw new Error(`${task.id} is blockedBy ${id}, a task this plan lacks.`);
324
+ if (target >= index)
325
+ throw new Error(`${task.id} is blockedBy ${id}; blockedBy takes only earlier ids.`);
326
+ }
327
+ excludePlans(root);
328
+ writePlan(root, plan);
329
+ active = plan.name;
330
+ return respond(planText(plan), "create", { plan });
331
+ }
332
+
333
+ case "update": {
334
+ const plan = requirePlan();
335
+ if (!params.id) throw new Error("update needs id.");
336
+ if (!params.status && !params.note) throw new Error("update needs status or note.");
337
+ const task = plan.tasks.find((item) => item.id === params.id);
338
+ if (!task) throw new Error(`Plan ${plan.name} has no task ${params.id}.`);
339
+ if (params.status) task.status = params.status as PlanStatus;
340
+ if (params.note) task.notes.push(params.note);
341
+ writePlan(root, plan);
342
+ active = plan.name;
343
+ // The model already holds the plan; echo only what changed and where it now stands.
344
+ const next = nextTask(plan);
345
+ const progress = `${plan.name} ${doneCount(plan)}/${plan.tasks.length}${next ? ` · next ${next.id}` : ""}`;
346
+ return respond(`${taskLine(task)}\n${progress}`, "update", {
347
+ plan,
348
+ id: task.id,
349
+ ...(params.note ? { note: params.note } : {}),
350
+ });
351
+ }
352
+
353
+ case "get": {
354
+ const plan = requirePlan();
355
+ const task = params.id ? plan.tasks.find((item) => item.id === params.id) : undefined;
356
+ if (params.id && !task) throw new Error(`Plan ${plan.name} has no task ${params.id}.`);
357
+ active = plan.name;
358
+ return respond(task ? taskText(plan, task) : planText(plan), "get", {
359
+ plan,
360
+ ...(task ? { id: task.id } : {}),
361
+ });
362
+ }
363
+
364
+ case "list": {
365
+ const list = listPlans(root);
366
+ return respond(listText(root, list, active), "list", { list });
367
+ }
368
+ }
369
+ throw new Error(`Unknown plan action ${params.action}.`);
370
+ },
371
+
372
+ renderCall: (args, theme) => callLine(args as Record<string, unknown>, theme),
373
+
374
+ renderResult(result, { expanded }, theme, context) {
375
+ const details = context.isError ? undefined : (result.details as PlanDetails | undefined);
376
+ const plan = details?.plan;
377
+ const list = details?.list;
378
+ const active = details?.active;
379
+ const id = details?.id;
380
+ const note = details?.note;
381
+ let rows: ((width: number) => string[]) | undefined;
382
+ if (list) rows = () => listLines(list, active, theme);
383
+ else if (plan && details?.action === "update") rows = (width) => updateLines(plan, id, note, theme, width);
384
+ else if (plan && id) rows = (width) => focusLines(plan, id, theme, width);
385
+ else if (plan) rows = (width) => planLines(plan, theme, expanded, width);
386
+ return rows
387
+ ? resultView(rows, theme, expanded, context.keyHint)
388
+ : errorView(resultText(result), theme, context.isError);
389
+ },
390
+ });
391
+
392
+ pi.registerCommand("plan", {
393
+ description: "Show every plan and pick the active one; /plan <name> sets it directly",
394
+ handler: async (args, ctx) => {
395
+ const root = repoRoot(ctx.cwd);
396
+ const setActive = (name: string) => {
397
+ active = name;
398
+ pi.appendEntry(ACTIVE_ENTRY, name);
399
+ refreshWidget(ctx);
400
+ };
401
+ const name = args.trim();
402
+ if (name) {
403
+ let plan: Plan | undefined;
404
+ try {
405
+ plan = readPlan(root, name);
406
+ } catch (error) {
407
+ ctx.ui.notify((error as Error).message, "error");
408
+ return;
409
+ }
410
+ if (!plan) {
411
+ ctx.ui.notify(`No plan ${name} in ${plansDir(root)}.`, "error");
412
+ return;
413
+ }
414
+ setActive(plan.name);
415
+ ctx.ui.notify(`Active plan: ${plan.name}`, "info");
416
+ return;
417
+ }
418
+ const list = listPlans(root);
419
+ if (ctx.mode !== "tui") {
420
+ const plan = list.plans.find((item) => item.name === active);
421
+ ctx.ui.notify(plan ? planText(plan) : listText(root, list, active), "info");
422
+ return;
423
+ }
424
+ if (!list.plans.length && !list.unreadable.length) {
425
+ ctx.ui.notify(`No plans in ${plansDir(root)}.`, "info");
426
+ return;
427
+ }
428
+ await openPlans(ctx, list, active, setActive);
429
+ },
430
+ });
431
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-plan",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Structured plans with a progress widget and a full-screen plan picker",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/deathbeam/pi-packages.git",
10
+ "directory": "packages/pi-plan"
11
+ },
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi-extension"
15
+ ],
16
+ "engines": {
17
+ "node": ">=22.19.0"
18
+ },
19
+ "files": [
20
+ "index.ts",
21
+ "src",
22
+ "skills",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "pi": {
27
+ "extensions": [
28
+ "./index.ts"
29
+ ],
30
+ "skills": [
31
+ "./skills"
32
+ ]
33
+ },
34
+ "peerDependencies": {
35
+ "@earendil-works/pi-ai": "*",
36
+ "@earendil-works/pi-coding-agent": "*",
37
+ "@earendil-works/pi-tui": "*"
38
+ }
39
+ }
@@ -0,0 +1,49 @@
1
+ ---
2
+ name: import-plan
3
+ description: Migrate existing plan documents into plan state; use when asked to migrate, import or convert plans, or when work starts from .plans, Cursor, Kiro or Taskmaster plans.
4
+ ---
5
+
6
+ # Import plan
7
+
8
+ Move existing plan documents into the `plan` tool: one `plan create` call per document.
9
+
10
+ Migrate every plan you find in the project. When the request names specific files or plans, convert only those.
11
+
12
+ ## Process
13
+
14
+ 1. **Find the sources.** Look for the known locations:
15
+
16
+ - `.plans/*.md` — `## Goal`, `## Context`, `## Notes`, and `- [ ]` tasks with `Where:`, `Blocked by:` and `Done when:` sub-bullets.
17
+ - `.cursor/plans/*.plan.md` — YAML frontmatter with a `todos` list of `id`, `content` and `status`.
18
+ - `.kiro/specs/*/tasks.md` — numbered checkbox tasks, each with a `_Requirements:_` reference.
19
+ - `.taskmaster/tasks/tasks.json` — `id`, `title`, `details`, `testStrategy`, `dependencies`, `status` and `subtasks` per task.
20
+ - `docs/plans/*.md` — plan-like markdown, including plan-mode `Plan:` numbered lists and superpowers-style `### Task N:` sections.
21
+
22
+ 2. **Read a source whole.** Read every task list, checkbox, status field, note and log line before mapping. The mapping below covers the common formats; a format you have not seen gets mapped by the same rules.
23
+
24
+ 3. **Skip a taken name.** If `.pi/plans/<name>.json` already exists, report the skip and convert the next source.
25
+
26
+ 4. **Create one plan per source.** Use the mapping rules, then call `plan create`.
27
+
28
+ 5. **Report.** End with one table: source file, new plan name, tasks by status, and what you skipped or guessed. Tell the user they can remove the source files once the plan reads correctly. Never edit or delete a source yourself.
29
+
30
+ ## Mapping rules
31
+
32
+ Map each field by what it says; its position in the file does not decide.
33
+
34
+ - **Name.** The plan title, or the file name without its extension, in kebab-case.
35
+ - **goal.** The plan's goal, summary or objective, as one observable outcome.
36
+ - **context.** The plan's context, decisions, constraints, design notes, open questions and general notes. Condense it, but keep every decision and every path.
37
+ - **Tasks.** Each top-level actionable item becomes one task.
38
+ - `title`: the item's text.
39
+ - `where`: the files and paths it mentions.
40
+ - `doneWhen`: its verification, acceptance or test step.
41
+ - `blockedBy`: only the dependencies the source states, mapped to the new ids. List order alone is no dependency.
42
+ - **Status.** A checked or completed item is `done`. An in-progress item, or the next open one the source marks as current, is `doing`. Everything else is `todo`. Take every status from the source.
43
+ - **Notes.** Execution notes, log lines and rulings go to the notes of the task they belong to.
44
+
45
+ Fold a nested sub-step into its parent task's `doneWhen` or notes. When a sub-step is independently verifiable, it becomes its own task with `blockedBy` on the parent.
46
+
47
+ When an item has no verification step, set `doneWhen` to `unverified: <what to check>`.
48
+
49
+ Task ids follow list order (`t1..tn`); translate stated dependencies after you order the tasks. `update` changes only status and notes, so check titles, `doneWhen` and `blockedBy` before the `create` call.
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: prepare-plan
3
+ description: Turn a request into a plan of independently verifiable tasks with the plan tool; use before implementing multi-step work.
4
+ ---
5
+
6
+ # Prepare plan
7
+
8
+ Write the plan with the `plan` tool, action `create`. The plan is the source of truth: each task is worked from it and updated when its check passes.
9
+
10
+ ## Process
11
+
12
+ 1. **Orient.** Gather the request, repo instructions, the code the change touches, its callers, its tests, and prior patterns. Stop when you can name the behaviour to change, the seam it goes through, and the check that proves it. If the plan exists, report it and continue with `update`; use a new name only for new work.
13
+
14
+ 2. **Resolve decisions.** Find facts in the code and docs rather than asking. Ask the user only for a decision that changes the plan. Record an assumption in `context` instead of leaving a task that a later reader cannot execute. Settle a blocking choice before the plan exists.
15
+
16
+ 3. **Write the tasks.** Prefer existing code and the smallest change that meets the goal. Split the work into tasks that are independently verifiable and leave the repo working. For a feature, slice by behaviour rather than by layer: "create with status and notes", not "add schema", then "add handler". For a wide mechanical refactor, plan expand, migrate, contract.
17
+
18
+ Each task is executed from `get <id>` alone: the goal, the context and that one task. Write it for a reader who never saw this conversation: exact paths, the interfaces it must match, and its check. Add `blockedBy` only for a real dependency; tasks without one can run at the same time, so keep their `where` files disjoint.
19
+
20
+ 4. **Self-check.** Trace every requirement in the request to a task, and every task to a concrete `doneWhen`. Replace each "handle edge cases" or "write tests" with the behaviour and the check. Confirm that no task names a path or interface that a later task defines differently. Read each task as `get <id>` will show it and confirm it can be done and checked without this conversation.
21
+
22
+ 5. **Create the plan.** One `plan create` call. Task ids follow list order, so write `blockedBy` with those ids.
23
+
24
+ ## Writing doneWhen
25
+
26
+ A good check names the result, the command, and the expected output:
27
+
28
+ - `npm test -- packages/x: 42 passed`
29
+ - `curl localhost:8080/health returns 200 with {"ok":true}`
30
+ - `open the settings page and press Save: the toast reads Saved`
31
+
32
+ For manual or visual work, describe the observation and how to reproduce it. When no check exists yet, write the one to run: `unverified: confirm X with Y`.
33
+
34
+ ## Hand off
35
+
36
+ Report the plan name, the task count, and any decision still open. Planning ends here: start the tasks when the user asks for it.
@@ -0,0 +1,374 @@
1
+ import { rawKeyHint, getMarkdownTheme, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Markdown,
4
+ type Component,
5
+ type Keybinding,
6
+ type KeybindingsManager,
7
+ matchesKey,
8
+ type TuiMouseEvent,
9
+ truncateToWidth,
10
+ visibleWidth,
11
+ wrapTextWithAnsi,
12
+ } from "@earendil-works/pi-tui";
13
+ import {
14
+ doneCount,
15
+ hanging,
16
+ nextTask,
17
+ planCount,
18
+ planStatus,
19
+ statusText,
20
+ type Plan,
21
+ type PlanList,
22
+ type PlanTask,
23
+ } from "./store.ts";
24
+
25
+ type PlansScreenOptions = {
26
+ plans: Plan[];
27
+ unreadable: string[];
28
+ active?: string;
29
+ theme: Theme;
30
+ keys: KeybindingsManager;
31
+ /** Terminal rows, read per frame. */
32
+ height: () => number;
33
+ setActive: (name: string) => void;
34
+ onClose: () => void;
35
+ requestRender: () => void;
36
+ };
37
+
38
+ /** Fixed rows: title, top rule, bottom rule, footer. */
39
+ const CHROME_ROWS = 4;
40
+ /** Prose past this width is hard to follow on a wide terminal; the pane leaves the rest empty. */
41
+ const MAX_TEXT_WIDTH = 120;
42
+ /** Rendered markdown by theme, then width and text; cleared by invalidate() and on a width change. */
43
+ const MARKDOWN_CACHE = new WeakMap<Theme, Map<string, string[]>>();
44
+
45
+ type Focus = "list" | "detail";
46
+
47
+ function hint(keys: KeybindingsManager, ids: Keybinding[], description: string): string {
48
+ return rawKeyHint(ids.flatMap((id) => keys.getKeys(id)).join("/"), description);
49
+ }
50
+
51
+ /** Markdown reads a lone newline as a space; a planner's one-newline paragraph break is meant as a break. */
52
+ function hardBreaks(text: string): string {
53
+ const lines = text.split("\n");
54
+ let fenced = false;
55
+ return lines
56
+ .map((line, index) => {
57
+ const fence = /^\s*(```|~~~)/.test(line);
58
+ const block = fenced || fence || /^\s*([-*+]|\d+\.)\s/.test(line) || /^\s*#/.test(line);
59
+ if (fence) fenced = !fenced;
60
+ return block || !lines[index + 1] ? line : `${line} `;
61
+ })
62
+ .join("\n");
63
+ }
64
+
65
+ /** Markdown rendered at one width, cached per theme: render() runs every frame and contexts can be long. */
66
+ function markdown(theme: Theme, text: string, width: number, indent = 0): string[] {
67
+ let cache = MARKDOWN_CACHE.get(theme);
68
+ if (!cache) MARKDOWN_CACHE.set(theme, (cache = new Map()));
69
+ const key = `${width} ${text}`;
70
+ let lines = cache.get(key);
71
+ if (!lines) {
72
+ const component = new Markdown(hardBreaks(text), 0, 0, getMarkdownTheme(), {
73
+ color: (t) => theme.fg("text", t),
74
+ });
75
+ // Markdown pads every row to its width; the pane pads again, so trim before composing.
76
+ lines = component.render(Math.max(1, width)).map((line) => line.trimEnd());
77
+ while (lines.length && !lines[0]) lines.shift();
78
+ while (lines.length && !lines.at(-1)) lines.pop();
79
+ cache.set(key, lines);
80
+ }
81
+ return lines.map((line) => " ".repeat(indent) + line);
82
+ }
83
+
84
+ /** A section heading: the word in accent, a rule to the pane edge, and the tasks heading's own count. */
85
+ function section(theme: Theme, word: string, width: number, trailing = ""): string {
86
+ const head = `${theme.bold(theme.fg("accent", word))} `;
87
+ const rule = "─".repeat(Math.max(0, width - visibleWidth(head) - visibleWidth(trailing)));
88
+ return head + theme.fg("borderMuted", rule) + trailing;
89
+ }
90
+
91
+ /** The title row: the glyph, the title, and the id at the right edge, with the blockers still open after it. */
92
+ function taskLines(plan: Plan, task: PlanTask, theme: Theme, width: number, current: boolean): string[] {
93
+ const open = task.blockedBy.filter((id) => !plan.tasks.some((item) => item.id === id && item.status === "done"));
94
+ const id = theme.fg("muted", open.length ? `${task.id} · after ${open.join(", ")}` : task.id);
95
+ // Accent means headings and labels, so the task the reader is on is bold text instead.
96
+ const title = theme.fg("text", task.title);
97
+ const [first = "", ...rest] = hanging(current ? theme.bold(title) : title, width, 2);
98
+ // The id sits beside the first row only, so that row loses the room the id and its gap take.
99
+ const room = Math.max(1, width - 3 - visibleWidth(id));
100
+ return [`${statusText(theme, task.status)} ${truncateToWidth(first, room, "…", true)} ${id}`, ...rest];
101
+ }
102
+
103
+ /** An accent label padded into one column, then its value in the column beside it. */
104
+ function field(theme: Theme, label: string, value: string, width: number, prose = false): string[] {
105
+ const lead = ` ${theme.fg("accent", label.padEnd(9))} `;
106
+ const column = visibleWidth(lead);
107
+ const lines = prose
108
+ ? markdown(theme, value, Math.max(1, width - column))
109
+ : wrapTextWithAnsi(theme.fg("text", value), Math.max(1, width - column));
110
+ const [first = "", ...rest] = lines;
111
+ return [lead + first, ...rest.map((line) => " ".repeat(column) + line)];
112
+ }
113
+
114
+ /** One task: its title row, then the check, where and notes of every task still open. */
115
+ function taskBlock(
116
+ plan: Plan,
117
+ task: PlanTask,
118
+ theme: Theme,
119
+ width: number,
120
+ current: boolean,
121
+ expanded: boolean,
122
+ ): string[] {
123
+ const head = taskLines(plan, task, theme, width, current);
124
+ if (!expanded && task.status === "done") return head;
125
+ return [
126
+ ...head,
127
+ // Both labels pad to nine columns, so the two values start in one column.
128
+ ...field(theme, "Done when", task.doneWhen, width, true),
129
+ ...(task.where ? field(theme, "Where", task.where, width) : []),
130
+ ...task.notes.flatMap((note) => ["", ...markdown(theme, note, Math.max(1, width - 2), 2)]),
131
+ "",
132
+ ];
133
+ }
134
+
135
+ /** Goal, tasks and context as three sections; the headings show where the reader is in a long plan. */
136
+ function taskRows(plan: Plan, theme: Theme, width: number, expanded: boolean): string[] {
137
+ const current = plan.tasks.find((task) => task.status === "doing") ?? nextTask(plan);
138
+ const blocks = plan.tasks.flatMap((task) => taskBlock(plan, task, theme, width, task === current, expanded));
139
+ // The next heading brings its own leading blank line, so a task's trailing one would double it.
140
+ if (blocks.at(-1) === "") blocks.pop();
141
+ return [
142
+ ...markdown(theme, plan.goal, width),
143
+ "",
144
+ section(theme, "Tasks", width, theme.fg("muted", ` ${planCount(plan)}`)),
145
+ ...blocks,
146
+ "",
147
+ section(theme, "Context", width),
148
+ ...markdown(theme, plan.context, width),
149
+ ].map((line) => truncateToWidth(line, width, "…", true));
150
+ }
151
+
152
+ /** Two rows per plan, like pi-delegate's job rows: cursor, status glyph, name and count, then the goal. */
153
+ function sidebarRows(
154
+ plans: Plan[],
155
+ unreadable: string[],
156
+ selected: number,
157
+ active: string | undefined,
158
+ focus: Focus,
159
+ theme: Theme,
160
+ width: number,
161
+ height: number,
162
+ ): { lines: string[]; indexes: (number | undefined)[] } {
163
+ const all: { lines: string[]; index?: number }[] = [
164
+ ...plans.map((plan, planIndex) => {
165
+ const chosen = planIndex === selected;
166
+ // The cursor dims while the detail pane takes the keys, so the user sees which pane is live.
167
+ const cursor = chosen ? theme.fg(focus === "list" ? "accent" : "muted", "›") : " ";
168
+ return {
169
+ lines: [
170
+ `${cursor} ${statusText(theme, planStatus(plan))} ${theme.fg(chosen ? "accent" : "text", plan.name)} ${theme.fg("muted", planCount(plan))}`,
171
+ theme.fg("dim", ` ${plan.name === active ? "active · " : ""}${plan.goal}`),
172
+ ],
173
+ index: planIndex,
174
+ };
175
+ }),
176
+ ...unreadable.map((name) => ({ lines: [theme.fg("error", ` ? ${name} unreadable`)] })),
177
+ ];
178
+ const rows = all.flatMap((entry) => entry.lines.map((line, at) => ({ line, index: entry.index, head: at === 0 })));
179
+ const selectedRow = rows.findIndex((row) => row.index === selected);
180
+ let start = Math.max(0, Math.min(selectedRow - Math.floor(height / 2), rows.length - height));
181
+ // A window never opens on a plan's second row, which would show a goal with no name above it.
182
+ while (start > 0 && !rows[start]!.head) start--;
183
+ const shown = rows.slice(start, start + height);
184
+ return {
185
+ lines: [
186
+ ...shown.map(
187
+ (row) => truncateToWidth(row.line, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│"),
188
+ ),
189
+ ...Array(Math.max(0, height - shown.length)).fill(
190
+ " ".repeat(Math.max(0, width - 1)) + theme.fg("borderMuted", "│"),
191
+ ),
192
+ ],
193
+ indexes: shown.map((row) => row.index),
194
+ };
195
+ }
196
+
197
+ /** The /plan screen, laid out like pi-delegate's: the plans on the left, the selected one's tasks on the right. */
198
+ export class PlansScreen implements Component {
199
+ private readonly options: PlansScreenOptions;
200
+ private index: number;
201
+ private active: string | undefined;
202
+ private focus: Focus = "list";
203
+ private top = 0;
204
+ private expanded = false;
205
+ private lastBody = { height: 0, total: 0 };
206
+ private lastIndexes: (number | undefined)[] = [];
207
+ private lastSidebar = 0;
208
+ private lastTextWidth = 0;
209
+
210
+ constructor(options: PlansScreenOptions) {
211
+ this.options = options;
212
+ this.active = options.active;
213
+ const found = options.active ? options.plans.findIndex((plan) => plan.name === options.active) : -1;
214
+ this.index = Math.max(0, found);
215
+ }
216
+
217
+ invalidate() {
218
+ MARKDOWN_CACHE.delete(this.options.theme);
219
+ }
220
+
221
+ render(width: number): string[] {
222
+ const { plans, unreadable, theme, height, keys } = this.options;
223
+ const rows = Math.max(0, height());
224
+ const body = Math.max(0, rows - CHROME_ROWS);
225
+ const sidebarWidth = Math.min(40, Math.max(16, Math.floor(width * 0.35)), Math.max(1, width - 2));
226
+ const detailWidth = Math.max(1, width - sidebarWidth - 1);
227
+ this.lastSidebar = sidebarWidth;
228
+ const row = (text: string, columns = width) => truncateToWidth(text, columns, "…", true);
229
+ const list = this.focus === "list";
230
+ const title = row(
231
+ `${theme.fg(list ? "accent" : "muted", list ? "[Plans]" : "Plans")} ` +
232
+ `${theme.fg(list ? "muted" : "accent", list ? "Tasks" : "[Tasks]")}` +
233
+ theme.fg("dim", ` · ${plans.length + unreadable.length} in .pi/plans`),
234
+ );
235
+ const rule = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
236
+ // Always-on keys first, so the pane's own hints can spill off a narrow line.
237
+ const paneHints = list
238
+ ? hint(keys, ["tui.select.up", "tui.select.down"], "select plan")
239
+ : `${hint(keys, ["tui.select.up", "tui.select.down"], "scroll")} · ${hint(keys, ["tui.altScreen.pageUp", "tui.altScreen.pageDown"], "page")}`;
240
+ const footer = row(
241
+ theme.fg(
242
+ "dim",
243
+ [
244
+ rawKeyHint("←/→", "pane"),
245
+ hint(keys, ["tui.select.confirm"], "make active"),
246
+ hint(keys, ["tui.select.cancel"], "close"),
247
+ hint(keys, ["app.tools.expand"], this.expanded ? "collapse" : "expand"),
248
+ paneHints,
249
+ ].join(" · "),
250
+ ),
251
+ );
252
+ const plan = plans[this.index];
253
+ const sidebar = sidebarRows(plans, unreadable, this.index, this.active, this.focus, theme, sidebarWidth, body);
254
+ this.lastIndexes = sidebar.indexes;
255
+ const detail = plan
256
+ ? this.detail(plan, Math.min(detailWidth, MAX_TEXT_WIDTH), detailWidth, body)
257
+ : [row(theme.fg("muted", "No readable plans."), detailWidth)];
258
+ return [title, rule, ...sidebar.lines.map((line, index) => `${line} ${detail[index] ?? ""}`), rule, footer];
259
+ }
260
+
261
+ handleInput(data: string): void {
262
+ const { keys, onClose, setActive } = this.options;
263
+ const detail = this.focus === "detail";
264
+ if (keys.matches(data, "tui.select.cancel")) onClose();
265
+ else if (matchesKey(data, "left")) this.focus = "list";
266
+ else if (matchesKey(data, "right")) this.focus = "detail";
267
+ else if (keys.matches(data, "tui.select.confirm")) {
268
+ const plan = this.options.plans[this.index];
269
+ if (!plan) return;
270
+ this.active = plan.name;
271
+ setActive(plan.name);
272
+ } else if (keys.matches(data, "app.tools.expand")) {
273
+ this.expanded = !this.expanded;
274
+ this.top = 0;
275
+ } else if (detail && keys.matches(data, "tui.altScreen.pageUp")) this.scroll(-this.pageSize());
276
+ else if (detail && keys.matches(data, "tui.altScreen.pageDown")) this.scroll(this.pageSize());
277
+ else if (detail && keys.matches(data, "tui.altScreen.top")) this.top = 0;
278
+ else if (detail && keys.matches(data, "tui.altScreen.bottom")) this.top = Infinity;
279
+ else if (keys.matches(data, "tui.select.up")) this.move(-1);
280
+ else if (keys.matches(data, "tui.select.down")) this.move(1);
281
+ this.options.requestRender();
282
+ }
283
+
284
+ // Fullscreen turns on mouse tracking, so the wheel arrives here instead of as arrow keys.
285
+ handleMouse(event: TuiMouseEvent) {
286
+ if (event.type === "wheel" && event.wheelDelta) {
287
+ if (event.x < this.lastSidebar) this.select(event.wheelDelta < 0 ? -1 : 1);
288
+ else this.scroll(event.wheelDelta);
289
+ } else if (event.type === "click" && event.button === "left" && event.x < this.lastSidebar) {
290
+ const target = this.lastIndexes[event.y - 2];
291
+ if (event.y < 2 || event.y - 2 >= this.lastBody.height || target === undefined) return;
292
+ this.index = target;
293
+ this.top = 0;
294
+ } else if (event.type === "click" && event.button === "left") this.focus = "detail";
295
+ else return;
296
+ this.options.requestRender();
297
+ return { handled: true };
298
+ }
299
+
300
+ /** The right pane: the plan's name stays put over the goal, tasks and context, with a counter below. */
301
+ private detail(plan: Plan, textWidth: number, width: number, body: number): string[] {
302
+ const { theme } = this.options;
303
+ if (this.lastTextWidth !== textWidth) {
304
+ this.lastTextWidth = textWidth;
305
+ MARKDOWN_CACHE.delete(theme);
306
+ }
307
+ const blocked = plan.tasks.some((task) => task.status === "blocked") ? " · blocked" : "";
308
+ const progress = theme.fg("muted", `${doneCount(plan)} of ${plan.tasks.length} done${blocked}`);
309
+ const name = theme.fg("accent", plan.name);
310
+ const header = [
311
+ name + " ".repeat(Math.max(0, textWidth - visibleWidth(name) - visibleWidth(progress))) + progress,
312
+ ];
313
+ const height = Math.max(0, body - header.length - 1);
314
+ const all = taskRows(plan, theme, textWidth, this.expanded);
315
+ const start = Math.min(this.top, Math.max(0, all.length - height));
316
+ this.top = start;
317
+ this.lastBody = { height, total: all.length };
318
+ const shown = all.slice(start, start + height);
319
+ const counter = theme.fg(
320
+ "muted",
321
+ shown.length ? `${start + 1}–${start + shown.length}/${all.length}` : `0/${all.length}`,
322
+ );
323
+ // Right-aligned like pi-delegate's counter; every row is padded so the pane's right edge holds still.
324
+ const tail = " ".repeat(Math.max(0, width - visibleWidth(counter))) + counter;
325
+ return [...header, ...shown, ...Array(Math.max(0, height - shown.length)).fill(""), tail].map((line) =>
326
+ truncateToWidth(line, width, "…", true),
327
+ );
328
+ }
329
+
330
+ // Detail focus scrolls by a line; list focus moves the cursor.
331
+ private move(step: number) {
332
+ if (this.focus === "detail") this.scroll(step);
333
+ else this.select(step);
334
+ }
335
+
336
+ private select(step: number) {
337
+ this.index = Math.max(0, Math.min(this.options.plans.length - 1, this.index + step));
338
+ this.top = 0;
339
+ }
340
+
341
+ // pi's alt-screen viewport pages by a window height minus a small overlap.
342
+ private pageSize() {
343
+ return Math.max(1, this.lastBody.height - 4);
344
+ }
345
+
346
+ private scroll(delta: number) {
347
+ const maxTop = Math.max(0, this.lastBody.total - this.lastBody.height);
348
+ this.top = Math.max(0, Math.min(maxTop, this.top + delta));
349
+ }
350
+ }
351
+
352
+ export function openPlans(
353
+ ctx: ExtensionContext,
354
+ list: PlanList,
355
+ active: string | undefined,
356
+ setActive: (name: string) => void,
357
+ ): Promise<void> {
358
+ const screen = { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 } } as const;
359
+ return ctx.ui.custom<void>(
360
+ (tui, theme, keys, done) =>
361
+ new PlansScreen({
362
+ plans: list.plans,
363
+ unreadable: list.unreadable,
364
+ active,
365
+ theme,
366
+ keys,
367
+ height: () => tui.terminal.rows,
368
+ setActive,
369
+ onClose: () => done(undefined),
370
+ requestRender: () => tui.requestRender(),
371
+ }),
372
+ screen,
373
+ );
374
+ }
package/src/store.ts ADDED
@@ -0,0 +1,261 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import type { KeybindingHints, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
5
+ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
6
+
7
+ export const STATUSES = ["todo", "doing", "done", "blocked"] as const;
8
+
9
+ export type PlanStatus = (typeof STATUSES)[number];
10
+
11
+ export type PlanTask = {
12
+ id: string;
13
+ title: string;
14
+ where?: string;
15
+ blockedBy: string[];
16
+ doneWhen: string;
17
+ status: PlanStatus;
18
+ notes: string[];
19
+ };
20
+
21
+ export type Plan = {
22
+ name: string;
23
+ goal: string;
24
+ context: string;
25
+ tasks: PlanTask[];
26
+ };
27
+
28
+ export type PlanList = {
29
+ plans: Plan[];
30
+ unreadable: string[];
31
+ };
32
+
33
+ /** One status vocabulary for the widget, the tool results and the /plan overlay. */
34
+ export const STATUS = {
35
+ todo: { glyph: "○", color: "muted" },
36
+ doing: { glyph: "◐", color: "warning" },
37
+ done: { glyph: "✓", color: "success" },
38
+ blocked: { glyph: "✗", color: "error" },
39
+ } as const satisfies Record<PlanStatus, { glyph: string; color: string }>;
40
+
41
+ const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
42
+ const PLANS_IGNORE = ".pi/plans/";
43
+
44
+ /** Plans live at <repoRoot>/.pi/plans, beside pi-delegate's .pi/worktrees; outside git, the session cwd is the root. */
45
+ export function repoRoot(cwd: string): string {
46
+ try {
47
+ return (
48
+ execFileSync("git", ["rev-parse", "--show-toplevel"], {
49
+ cwd,
50
+ encoding: "utf8",
51
+ stdio: ["ignore", "pipe", "ignore"],
52
+ }).trim() || cwd
53
+ );
54
+ } catch {
55
+ return cwd;
56
+ }
57
+ }
58
+
59
+ export function plansDir(root: string): string {
60
+ return join(root, ".pi", "plans");
61
+ }
62
+
63
+ function planPath(root: string, name: string): string {
64
+ if (!NAME.test(name)) throw new Error(`Plan name "${name}" must be kebab-case, for example my-plan.`);
65
+ return join(plansDir(root), `${name}.json`);
66
+ }
67
+
68
+ export function readPlan(root: string, name: string): Plan | undefined {
69
+ try {
70
+ return JSON.parse(readFileSync(planPath(root, name), "utf8")) as Plan;
71
+ } catch (error) {
72
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ export function writePlan(root: string, plan: Plan): void {
78
+ const file = planPath(root, plan.name);
79
+ mkdirSync(dirname(file), { recursive: true });
80
+ // Temp file plus rename: a crash mid-write leaves the previous plan intact.
81
+ // shortcut: one writer, no lock; add one if a second process can write plans
82
+ const tmp = `${file}.tmp`;
83
+ writeFileSync(tmp, `${JSON.stringify(plan, null, 2)}\n`);
84
+ renameSync(tmp, file);
85
+ }
86
+
87
+ export function listPlans(root: string): PlanList {
88
+ let files: string[];
89
+ try {
90
+ files = readdirSync(plansDir(root));
91
+ } catch (error) {
92
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { plans: [], unreadable: [] };
93
+ throw error;
94
+ }
95
+ const plans: Plan[] = [];
96
+ const unreadable: string[] = [];
97
+ for (const file of files.filter((name) => name.endsWith(".json")).sort()) {
98
+ try {
99
+ const plan = JSON.parse(readFileSync(join(plansDir(root), file), "utf8")) as Plan;
100
+ if (!Array.isArray(plan?.tasks)) throw new Error("no tasks");
101
+ plans.push(plan);
102
+ } catch {
103
+ unreadable.push(file.slice(0, -5));
104
+ }
105
+ }
106
+ return { plans, unreadable };
107
+ }
108
+
109
+ /** Adds .pi/plans/ to the repo's info/exclude once, the way pi-delegate hides .pi/worktrees. */
110
+ export function excludePlans(root: string): void {
111
+ try {
112
+ const file = resolve(
113
+ root,
114
+ execFileSync("git", ["rev-parse", "--git-path", "info/exclude"], {
115
+ cwd: root,
116
+ encoding: "utf8",
117
+ stdio: ["ignore", "pipe", "ignore"],
118
+ }).trim(),
119
+ );
120
+ const current = existsSync(file) ? readFileSync(file, "utf8") : "";
121
+ if (
122
+ current
123
+ .split("\n")
124
+ .map((line) => line.trim())
125
+ .includes(PLANS_IGNORE)
126
+ )
127
+ return;
128
+ mkdirSync(dirname(file), { recursive: true });
129
+ appendFileSync(file, `${current && !current.endsWith("\n") ? "\n" : ""}${PLANS_IGNORE}\n`);
130
+ } catch {
131
+ // Not a git repo, or a .git that cannot be written; plans stay untracked either way.
132
+ }
133
+ }
134
+
135
+ export function doneCount(plan: Plan): number {
136
+ return plan.tasks.filter((task) => task.status === "done").length;
137
+ }
138
+
139
+ /** The first todo task whose blockers are all done, the one to dispatch next. */
140
+ export function nextTask(plan: Plan): PlanTask | undefined {
141
+ const done = new Set(plan.tasks.filter((task) => task.status === "done").map((task) => task.id));
142
+ return plan.tasks.find((task) => task.status === "todo" && task.blockedBy.every((id) => done.has(id)));
143
+ }
144
+
145
+ export function taskLine(task: PlanTask): string {
146
+ const parts = [`${task.id} [${task.status}] ${task.title}`];
147
+ if (task.blockedBy.length) parts.push(`blockedBy ${task.blockedBy.join(" ")}`);
148
+ if (task.where) parts.push(`where ${task.where}`);
149
+ return parts.join(" — ");
150
+ }
151
+
152
+ /** One task as text: the status line, then the check and notes indented under it. */
153
+ export function taskLines(task: PlanTask): string[] {
154
+ return [
155
+ taskLine(task),
156
+ ...[`doneWhen: ${task.doneWhen}`, ...task.notes.map((note) => `note: ${note}`)].map((line) => ` ${line}`),
157
+ ];
158
+ }
159
+
160
+ export function planText(plan: Plan): string {
161
+ return [
162
+ `plan ${plan.name} ${doneCount(plan)}/${plan.tasks.length}`,
163
+ `goal: ${plan.goal}`,
164
+ `context: ${plan.context}`,
165
+ ...plan.tasks.flatMap(taskLines),
166
+ ].join("\n");
167
+ }
168
+
169
+ export function taskText(plan: Plan, task: PlanTask): string {
170
+ return [
171
+ `plan ${plan.name} ${doneCount(plan)}/${plan.tasks.length}`,
172
+ `goal: ${plan.goal}`,
173
+ `context: ${plan.context}`,
174
+ "",
175
+ ...taskLines(task),
176
+ ].join("\n");
177
+ }
178
+
179
+ export function listText(root: string, list: PlanList, active: string | undefined): string {
180
+ if (!list.plans.length && !list.unreadable.length) return `No plans in ${plansDir(root)}.`;
181
+ return [
182
+ ...list.plans.map((plan) => {
183
+ const next = nextTask(plan);
184
+ const mark = plan.name === active ? "*" : " ";
185
+ return `${mark} ${plan.name} ${planCount(plan)}${next ? ` · next ${next.id}` : ""}`;
186
+ }),
187
+ ...list.unreadable.map((name) => `? ${name} unreadable`),
188
+ ].join("\n");
189
+ }
190
+
191
+ export function statusText(theme: Theme, status: PlanStatus): string {
192
+ return theme.fg(STATUS[status].color, STATUS[status].glyph);
193
+ }
194
+
195
+ export function planCount(plan: Plan): string {
196
+ return `${doneCount(plan)}/${plan.tasks.length}`;
197
+ }
198
+
199
+ /** `name 1/4 · doing t2 · next t3`: the line the widget, the tool header and the list all lead with. */
200
+ export function planSummary(theme: Theme, plan: Plan): string {
201
+ const stats = [planCount(plan)];
202
+ const doing = plan.tasks.find((task) => task.status === "doing");
203
+ if (doing) stats.push(`doing ${doing.id}`);
204
+ const next = nextTask(plan);
205
+ if (next) stats.push(`next ${next.id}`);
206
+ return `${theme.fg("accent", plan.name)} ${theme.fg("muted", stats.join(" · "))}`;
207
+ }
208
+
209
+ /** The plan's own status: done when every task is, doing while one is, todo otherwise. */
210
+ export function planStatus(plan: Plan): Exclude<PlanStatus, "blocked"> {
211
+ if (plan.tasks.length && plan.tasks.every((task) => task.status === "done")) return "done";
212
+ return plan.tasks.some((task) => task.status === "doing") ? "doing" : "todo";
213
+ }
214
+
215
+ /** A task row: glyph, id, title, and the blockers still open; a done blocker is no noise worth showing. */
216
+ export function taskRow(theme: Theme, plan: Plan, task: PlanTask): string {
217
+ const open = task.blockedBy.filter((id) => !plan.tasks.some((item) => item.id === id && item.status === "done"));
218
+ const blocked = open.length ? ` ${theme.fg("muted", `· blockedBy ${open.join(" ")}`)}` : "";
219
+ return `${statusText(theme, task.status)} ${theme.fg("accent", task.id)} ${task.title}${blocked}`;
220
+ }
221
+
222
+ /** Wrapped rows whose continuations sit `indent` columns in, so a wrapped line never reads as a new one. */
223
+ export function hanging(text: string, width: number, indent: number): string[] {
224
+ return wrapTextWithAnsi(text, Math.max(1, width - indent)).map(
225
+ (line, index) => (index ? " ".repeat(indent) : "") + line,
226
+ );
227
+ }
228
+
229
+ /** A labelled line under a task row or in the plan header: the label muted so it reads as a key, the value in `color`, wrapping in the label's column. */
230
+ export function fact(
231
+ theme: Theme,
232
+ label: string,
233
+ text: string,
234
+ width: number,
235
+ indent = 2,
236
+ color: ThemeColor = label ? "text" : "dim",
237
+ ): string[] {
238
+ return hanging((label ? theme.fg("muted", label) : "") + theme.fg(color, text), width - indent, label.length).map(
239
+ (line) => " ".repeat(indent) + line,
240
+ );
241
+ }
242
+
243
+ /** The lines under a task row: where it lives, its check, and its dim notes as written. */
244
+ export function taskFacts(theme: Theme, task: PlanTask, width: number): string[] {
245
+ return [
246
+ // Paths are reference, not the point of the task; the check is.
247
+ ...(task.where ? fact(theme, "Where: ", task.where, width, 2, "dim") : []),
248
+ ...fact(theme, "Done when: ", task.doneWhen, width),
249
+ ...task.notes.flatMap((note) => fact(theme, "", note, width)),
250
+ ];
251
+ }
252
+
253
+ /** pi's built-in expand hint; callers place it on its own row, so it carries no leading newline. */
254
+ export function moreLines(theme: Theme, hidden: number, keyHint: KeybindingHints["keyHint"]): string {
255
+ return `${theme.fg("muted", `... (${hidden} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
256
+ }
257
+
258
+ /** The one-line widget: the plan summary every other view also leads with. */
259
+ export function widgetLine(theme: Theme, plan: Plan): string {
260
+ return `${theme.fg("accent", "plan")} ${planSummary(theme, plan)}`;
261
+ }