@deathbeam/pi-plan 0.0.2 → 0.0.4

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
@@ -1,10 +1,11 @@
1
1
  # [@deathbeam/pi-plan](https://www.npmjs.com/package/@deathbeam/pi-plan)
2
2
 
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.
3
+ Structured plans: a `plan` tool, a progress widget, and a `/plan` inspector over every plan in the project.
5
4
  The bundled `prepare-plan` skill writes a plan, and `import-plan` migrates existing plan documents (`.plans/*.md`, Cursor, Kiro, Taskmaster).
6
5
 
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`.
6
+ ![/plan inspector](media/screenshot.png)
7
+
8
+ Plans live in `.pi/plans/<id>.json` at the repository root. Add `.pi/plans/` to `.gitignore` if the first `plan create` cannot write it to `.git/info/exclude`.
8
9
 
9
10
  ## Installation
10
11
 
package/index.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
- import type {
3
- ExtensionAPI,
4
- ExtensionContext,
5
- KeybindingHints,
6
- SessionEntry,
7
- Theme,
2
+ import {
3
+ getMarkdownTheme,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ type KeybindingHints,
7
+ type SessionEntry,
8
+ type Theme,
8
9
  } from "@earendil-works/pi-coding-agent";
9
- import { type Component, Text, truncateToWidth } from "@earendil-works/pi-tui";
10
+ import { Markdown, type Component, Text, truncateToWidth } from "@earendil-works/pi-tui";
10
11
  import { Type } from "typebox";
11
- import { openPlans } from "./src/inspector.ts";
12
+ import { hardBreaks, openPlans } from "./src/inspector.ts";
12
13
  import {
13
14
  doneCount,
14
15
  excludePlans,
@@ -17,7 +18,7 @@ import {
17
18
  listPlans,
18
19
  listText,
19
20
  moreLines,
20
- nextTask,
21
+ planStatus,
21
22
  planSummary,
22
23
  planText,
23
24
  plansDir,
@@ -30,15 +31,13 @@ import {
30
31
  taskLine,
31
32
  taskRow,
32
33
  taskText,
33
- widgetLine,
34
+ widgetLines,
34
35
  writePlan,
35
36
  type Plan,
36
37
  type PlanList,
37
38
  type PlanStatus,
38
39
  } from "./src/store.ts";
39
40
 
40
- const ACTIONS = ["create", "update", "get", "list"] as const;
41
-
42
41
  type Action = (typeof ACTIONS)[number];
43
42
 
44
43
  type PlanDetails = {
@@ -54,26 +53,40 @@ type PlanDetails = {
54
53
  list?: PlanList;
55
54
  };
56
55
 
56
+ const ACTIONS = ["create", "update", "get", "list"] as const;
57
+
57
58
  const PlanParams = Type.Object({
58
59
  action: StringEnum(ACTIONS),
59
- name: Type.Optional(
60
- Type.String({ description: "Plan name in kebab-case; get and update default to the active plan." }),
60
+ plan: Type.Optional(
61
+ Type.String({ description: "Plan id in kebab-case; get and update default to the active plan." }),
61
62
  ),
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." }),
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
+ }),
65
74
  ),
66
75
  tasks: Type.Optional(
67
76
  Type.Array(
68
77
  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({
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({
75
82
  description: "Observable result, with the command to run and its expected output.",
76
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
+ ),
77
90
  status: Type.Optional(StringEnum(STATUSES, { description: "Defaults to todo." })),
78
91
  notes: Type.Optional(
79
92
  Type.Array(Type.String(), { description: "Existing notes or log lines for this task." }),
@@ -82,13 +95,18 @@ const PlanParams = Type.Object({
82
95
  { description: "create: tasks in execution order; ids t1..tn follow this order." },
83
96
  ),
84
97
  ),
85
- id: Type.Optional(
98
+ task: Type.Optional(
86
99
  Type.String({
87
- description: "update: task id to change. get: this task alone, with the plan's goal and context.",
100
+ description: "update: task id to change. get: this task alone, with the plan's goal and detail.",
88
101
  }),
89
102
  ),
90
103
  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." })),
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
+ }),
109
+ ),
92
110
  });
93
111
 
94
112
  const WIDGET_KEY = "plan";
@@ -154,7 +172,7 @@ function resultText(result: { content: { type: string; text?: string }[] }): str
154
172
  return result.content.flatMap((part) => (part.type === "text" && part.text ? [part.text] : [])).join("\n");
155
173
  }
156
174
 
157
- /** The whole plan: a summary line, then one row per task; only the expansion carries goal, context and notes. */
175
+ /** The whole plan: a summary line, then one row per task; only the expansion carries goal, detail and notes. */
158
176
  function planLines(plan: Plan, theme: Theme, expanded: boolean, width: number): string[] {
159
177
  const tasks = plan.tasks.flatMap((task) =>
160
178
  expanded
@@ -165,20 +183,12 @@ function planLines(plan: Plan, theme: Theme, expanded: boolean, width: number):
165
183
  "",
166
184
  `${theme.fg("accent", "plan")} ${planSummary(theme, plan)}`,
167
185
  ...(expanded
168
- ? [...fact(theme, "Goal: ", plan.goal, width), ...fact(theme, "Context: ", plan.context, width, 2, "dim")]
186
+ ? [...fact(theme, "Goal: ", plan.goal, width), ...fact(theme, "Detail: ", plan.detail, width, 2, "dim")]
169
187
  : []),
170
188
  ...tasks,
171
189
  ];
172
190
  }
173
191
 
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
192
  /** What changed: the task row, the note this call appended, and where the plan now stands. */
183
193
  function updateLines(
184
194
  plan: Plan,
@@ -188,10 +198,9 @@ function updateLines(
188
198
  width: number,
189
199
  ): string[] {
190
200
  const task = plan.tasks.find((item) => item.id === id);
191
- if (!task) return [];
192
201
  return [
193
202
  "",
194
- ...hanging(taskRow(theme, plan, task), width, task.id.length + 3),
203
+ ...(task ? hanging(taskRow(theme, plan, task), width, task.id.length + 3) : []),
195
204
  ...(note ? fact(theme, "", note, width) : []),
196
205
  theme.fg("muted", planSummary(theme, plan)),
197
206
  ];
@@ -202,7 +211,7 @@ function listLines(list: PlanList, active: string | undefined, theme: Theme): st
202
211
  return [
203
212
  "",
204
213
  ...list.plans.map(
205
- (plan) => `${plan.name === active ? theme.fg("accent", "›") : " "} ${planSummary(theme, plan)}`,
214
+ (plan) => `${plan.id === active ? theme.fg("accent", "›") : " "} ${planSummary(theme, plan)}`,
206
215
  ),
207
216
  ...list.unreadable.map((name) => theme.fg("error", `? ${name} unreadable`)),
208
217
  ];
@@ -213,8 +222,8 @@ function callLine(args: Record<string, unknown>, theme: Theme): Component {
213
222
  const action = argText(args.action);
214
223
  const update = action === "update";
215
224
  const target = update
216
- ? argText(args.id)
217
- : [argText(args.name), action === "get" ? argText(args.id) : ""].filter(Boolean).join(" ");
225
+ ? argText(args.task)
226
+ : [argText(args.plan), action === "get" ? argText(args.task) : ""].filter(Boolean).join(" ");
218
227
  const status = update ? argStatus(args.status) : undefined;
219
228
  const note = update ? argText(args.note) : "";
220
229
  const head = `${theme.fg("toolTitle", theme.bold("plan"))} ${theme.fg("accent", [action || "…", target].filter(Boolean).join(" "))}`;
@@ -227,6 +236,18 @@ function callLine(args: Record<string, unknown>, theme: Theme): Component {
227
236
  return new Text([head, tail].filter(Boolean).join(" "), 0, 0);
228
237
  }
229
238
 
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
+ }
250
+
230
251
  export default function (pi: ExtensionAPI) {
231
252
  // The last plan this session created, updated or read; restored from the active branch.
232
253
  let active: string | undefined;
@@ -237,7 +258,7 @@ export default function (pi: ExtensionAPI) {
237
258
  try {
238
259
  plan = active ? readPlan(repoRoot(ctx.cwd), active) : undefined;
239
260
  } catch {
240
- // A restored name or a corrupt file must not break the session; the tool reports the real error.
261
+ // A restored id or a corrupt file must not break the session; the tool reports the real error.
241
262
  plan = undefined;
242
263
  }
243
264
  if (!plan) {
@@ -245,7 +266,8 @@ export default function (pi: ExtensionAPI) {
245
266
  ctx.ui.setWidget(WIDGET_KEY, undefined);
246
267
  return;
247
268
  }
248
- ctx.ui.setWidget(WIDGET_KEY, [widgetLine(ctx.ui.theme, plan)]);
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));
249
271
  }
250
272
 
251
273
  function restore(ctx: ExtensionContext) {
@@ -260,22 +282,22 @@ export default function (pi: ExtensionAPI) {
260
282
  name: "plan",
261
283
  label: "Plan",
262
284
  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",
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",
265
287
  promptGuidelines: [
266
288
  "Mark a task `doing` when work on it starts.",
267
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.",
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`.",
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`.",
269
291
  "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.',
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.',
272
294
  ],
273
295
  parameters: PlanParams,
274
296
 
275
297
  async execute(_toolCallId, rawParams, _signal, _onUpdate, ctx) {
276
298
  // Strict models inject literal "null" for optional params they omit; drop it from those only.
277
299
  const params = { ...rawParams } as typeof rawParams & Record<string, unknown>;
278
- for (const key of ["name", "goal", "context", "tasks", "id", "status", "note"]) {
300
+ for (const key of ["plan", "title", "goal", "detail", "tasks", "task", "status", "note"]) {
279
301
  if (params[key] === null || params[key] === "null") delete params[key];
280
302
  }
281
303
  const root = repoRoot(ctx.cwd);
@@ -283,66 +305,80 @@ export default function (pi: ExtensionAPI) {
283
305
  refreshWidget(ctx);
284
306
  return { content: [{ type: "text" as const, text }], details: { action, active, ...extra } };
285
307
  };
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;
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;
290
312
  };
291
313
  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.`);
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.`);
295
317
  return plan;
296
318
  };
297
319
 
298
320
  switch (params.action as Action) {
299
321
  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.`);
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.`);
304
332
  const plan: Plan = {
305
- name,
333
+ id,
334
+ title,
306
335
  goal,
307
- context,
336
+ detail,
337
+ notes: [],
308
338
  tasks: tasks.map((task, index) => ({
309
339
  id: `t${index + 1}`,
310
340
  title: task.title,
311
- ...(task.where && task.where !== "null" ? { where: task.where } : {}),
312
- blockedBy: task.blockedBy ?? [],
313
- doneWhen: task.doneWhen,
341
+ goal: task.goal,
342
+ detail: task.detail,
343
+ dependsOn: taskList(task.dependsOn, `t${index + 1} dependsOn`),
314
344
  status: (task.status ?? "todo") as PlanStatus,
315
- notes: task.notes ?? [],
345
+ notes: taskList(task.notes, `t${index + 1} notes`),
316
346
  })),
317
347
  };
318
348
  const ids = new Map(plan.tasks.map((task, index) => [task.id, index]));
319
349
  for (const [index, task] of plan.tasks.entries())
320
- for (const id of task.blockedBy) {
350
+ for (const id of task.dependsOn) {
321
351
  const target = ids.get(id);
322
352
  if (target === undefined)
323
- throw new Error(`${task.id} is blockedBy ${id}, a task this plan lacks.`);
353
+ throw new Error(`${task.id} dependsOn ${id}, a task this plan lacks.`);
324
354
  if (target >= index)
325
- throw new Error(`${task.id} is blockedBy ${id}; blockedBy takes only earlier ids.`);
355
+ throw new Error(`${task.id} dependsOn ${id}; dependsOn takes only earlier ids.`);
326
356
  }
327
357
  excludePlans(root);
328
358
  writePlan(root, plan);
329
- active = plan.name;
359
+ active = plan.id;
330
360
  return respond(planText(plan), "create", { plan });
331
361
  }
332
362
 
333
363
  case "update": {
334
364
  const plan = requirePlan();
335
- if (!params.id) throw new Error("update needs id.");
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
+ }
336
373
  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}.`);
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}.`);
339
376
  if (params.status) task.status = params.status as PlanStatus;
340
377
  if (params.note) task.notes.push(params.note);
341
378
  writePlan(root, plan);
342
- active = plan.name;
379
+ active = plan.id;
343
380
  // 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}` : ""}`;
381
+ const progress = `${plan.id} ${doneCount(plan)}/${plan.tasks.length}`;
346
382
  return respond(`${taskLine(task)}\n${progress}`, "update", {
347
383
  plan,
348
384
  id: task.id,
@@ -352,9 +388,9 @@ export default function (pi: ExtensionAPI) {
352
388
 
353
389
  case "get": {
354
390
  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;
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;
358
394
  return respond(task ? taskText(plan, task) : planText(plan), "get", {
359
395
  plan,
360
396
  ...(task ? { id: task.id } : {}),
@@ -380,8 +416,17 @@ export default function (pi: ExtensionAPI) {
380
416
  const note = details?.note;
381
417
  let rows: ((width: number) => string[]) | undefined;
382
418
  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);
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);
385
430
  else if (plan) rows = (width) => planLines(plan, theme, expanded, width);
386
431
  return rows
387
432
  ? resultView(rows, theme, expanded, context.keyHint)
@@ -390,34 +435,34 @@ export default function (pi: ExtensionAPI) {
390
435
  });
391
436
 
392
437
  pi.registerCommand("plan", {
393
- description: "Show every plan and pick the active one; /plan <name> sets it directly",
438
+ description: "Show every plan and pick the active one; /plan <id> sets it directly",
394
439
  handler: async (args, ctx) => {
395
440
  const root = repoRoot(ctx.cwd);
396
- const setActive = (name: string) => {
397
- active = name;
398
- pi.appendEntry(ACTIVE_ENTRY, name);
441
+ const setActive = (id: string) => {
442
+ active = id;
443
+ pi.appendEntry(ACTIVE_ENTRY, id);
399
444
  refreshWidget(ctx);
400
445
  };
401
- const name = args.trim();
402
- if (name) {
446
+ const id = args.trim();
447
+ if (id) {
403
448
  let plan: Plan | undefined;
404
449
  try {
405
- plan = readPlan(root, name);
450
+ plan = readPlan(root, id);
406
451
  } catch (error) {
407
452
  ctx.ui.notify((error as Error).message, "error");
408
453
  return;
409
454
  }
410
455
  if (!plan) {
411
- ctx.ui.notify(`No plan ${name} in ${plansDir(root)}.`, "error");
456
+ ctx.ui.notify(`No plan ${id} in ${plansDir(root)}.`, "error");
412
457
  return;
413
458
  }
414
- setActive(plan.name);
415
- ctx.ui.notify(`Active plan: ${plan.name}`, "info");
459
+ setActive(plan.id);
460
+ ctx.ui.notify(`Active plan: ${plan.id}`, "info");
416
461
  return;
417
462
  }
418
463
  const list = listPlans(root);
419
464
  if (ctx.mode !== "tui") {
420
- const plan = list.plans.find((item) => item.name === active);
465
+ const plan = list.plans.find((item) => item.id === active);
421
466
  ctx.ui.notify(plan ? planText(plan) : listText(root, list, active), "info");
422
467
  return;
423
468
  }
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-plan",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Structured plans with a progress widget and a full-screen plan picker",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,6 +20,7 @@
20
20
  "index.ts",
21
21
  "src",
22
22
  "skills",
23
+ "media",
23
24
  "README.md",
24
25
  "LICENSE"
25
26
  ],
@@ -29,7 +30,8 @@
29
30
  ],
30
31
  "skills": [
31
32
  "./skills"
32
- ]
33
+ ],
34
+ "image": "https://cdn.jsdelivr.net/npm/@deathbeam/pi-plan/media/screenshot.png"
33
35
  },
34
36
  "peerDependencies": {
35
37
  "@earendil-works/pi-ai": "*",
@@ -21,29 +21,31 @@ Migrate every plan you find in the project. When the request names specific file
21
21
 
22
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
23
 
24
- 3. **Skip a taken name.** If `.pi/plans/<name>.json` already exists, report the skip and convert the next source.
24
+ 3. **Skip a taken id.** If `.pi/plans/<id>.json` already exists, report the skip and convert the next source.
25
25
 
26
26
  4. **Create one plan per source.** Use the mapping rules, then call `plan create`.
27
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.
28
+ 5. **Report.** End with one table: source file, new plan id, 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
29
 
30
30
  ## Mapping rules
31
31
 
32
32
  Map each field by what it says; its position in the file does not decide.
33
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.
34
+ - **Plan id.** The file name without its extension, in kebab-case; the plan title when the file name says nothing.
35
+ - **title.** The plan's title or goal in three to eight words.
36
+ - **goal.** The plan's goal, summary or objective, as one observable outcome plus the check that proves it.
37
+ - **detail.** The plan's context, decisions, constraints, design notes and open questions, in sections. Condense it, but keep every decision and every path.
38
+ - **notes.** A top-level Notes, log or rulings section becomes plan notes. Create the plan first, then append each note with `update` and a `note` but no `task`.
37
39
  - **Tasks.** Each top-level actionable item becomes one task.
38
40
  - `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.
41
+ - `goal`: its verification, acceptance or test step, with the command when the source names it.
42
+ - `detail`: the item's body, sub-bullets and interfaces, with a `Where:` line citing `path:line` for each path it mentions.
43
+ - `dependsOn`: only the dependencies the source states, mapped to the new ids. List order alone is no dependency.
42
44
  - **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.
45
+ - **Task notes.** Execution notes and log lines go to the notes of the task they belong to.
44
46
 
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.
47
+ Fold a nested sub-step into its parent task's `detail` or notes. When a sub-step is independently verifiable, it becomes its own task with `dependsOn` on the parent.
46
48
 
47
- When an item has no verification step, set `doneWhen` to `unverified: <what to check>`.
49
+ When an item has no verification step, set its `goal` to `unverified: <what to check>`.
48
50
 
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.
51
+ Task ids follow list order (`t1..tn`); translate stated dependencies after you order the tasks. `update` changes only status and notes, so check titles, goals, details and `dependsOn` before the `create` call.
@@ -5,32 +5,51 @@ description: Turn a request into a plan of independently verifiable tasks with t
5
5
 
6
6
  # Prepare plan
7
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.
8
+ Write the plan with the `plan` tool, action `create`. The plan is the source of truth: each task is worked from `get <task>` and updated when its goal's check passes.
9
9
 
10
10
  ## Process
11
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.
12
+ 1. **Orient.** Read the code the change touches, its callers, its tests and the repo instructions. Every fact, `path:line` and command in the plan comes from code you or a helper read, not from memory. Stop when you can name the behaviour to change, the seam it goes through, and the check that proves it.
13
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.
14
+ 2. **Gather facts before writing.** When others explore for you, ask each for a report with `path:line` evidence: current behaviour, seams, callers, tests and checks. Write the plan from those reports and the user's decisions. A plan written from conversation memory cites nothing and leaves every task to guesswork.
15
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.
16
+ 3. **Resolve decisions.** Find facts in the code and docs rather than asking. Ask the user only for a decision that changes the plan. Settle a blocking choice before the plan exists and record it in the plan `detail`.
17
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.
18
+ 4. **Write the plan detail.** Plan `detail` is markdown in sections:
19
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.
20
+ - Current behaviour, with `path:line` for each site.
21
+ - The problem: why that code is wrong today.
22
+ - The chosen design, and the alternatives rejected, with the reason.
23
+ - Accepted behaviour changes.
24
+ - Out of scope.
25
+ - Open questions.
21
26
 
22
- 5. **Create the plan.** One `plan create` call. Task ids follow list order, so write `blockedBy` with those ids.
27
+ 5. **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.
23
28
 
24
- ## Writing doneWhen
29
+ Each task is executed from `get <task>` alone: the plan's goal and detail, and that one task. Write it for a reader who never saw this conversation.
25
30
 
26
- A good check names the result, the command, and the expected output:
31
+ - `title`: the deliverable or behaviour, one line.
32
+ - `goal`: the observable result and the command that proves it.
33
+ - `detail`: the approach, the interfaces it must match, the pitfalls, and a `Where:` line citing `path:line` for each file that changes.
34
+
35
+ Add `dependsOn` only for a real dependency; tasks without one run at the same time, so keep their files disjoint.
36
+
37
+ 6. **Self-check.** Trace every requirement in the request to a task, and every task to a goal with a check. 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 <task>` will show it and confirm it can be done and checked without this conversation.
38
+
39
+ 7. **Create the plan.** One `plan create` call. Set `title` to three to eight words naming the outcome. Task ids follow list order (`t1..tn`), so write `dependsOn` with those ids.
40
+
41
+ ## Writing a goal
42
+
43
+ The plan `goal` and a task `goal` mean the same thing: the observable outcome plus the check that proves it, for example:
27
44
 
28
45
  - `npm test -- packages/x: 42 passed`
29
46
  - `curl localhost:8080/health returns 200 with {"ok":true}`
30
47
  - `open the settings page and press Save: the toast reads Saved`
31
48
 
49
+ The plan goal is the final verification of the whole plan. Mark a task `done` only after its goal's check passed.
50
+
32
51
  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
52
 
34
53
  ## Hand off
35
54
 
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.
55
+ Report the plan id, the task count and any decision still open. Planning ends here: start the tasks when the user asks for it.
package/src/inspector.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { rawKeyHint, getMarkdownTheme, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
+ Box,
3
4
  Markdown,
5
+ Text,
4
6
  type Component,
5
7
  type Keybinding,
6
8
  type KeybindingsManager,
@@ -8,16 +10,17 @@ import {
8
10
  type TuiMouseEvent,
9
11
  truncateToWidth,
10
12
  visibleWidth,
11
- wrapTextWithAnsi,
12
13
  } from "@earendil-works/pi-tui";
13
14
  import {
14
15
  doneCount,
15
16
  hanging,
16
17
  nextTask,
18
+ noteItem,
17
19
  planCount,
18
20
  planStatus,
19
21
  statusText,
20
22
  type Plan,
23
+ type PlanStatus,
21
24
  type PlanList,
22
25
  type PlanTask,
23
26
  } from "./store.ts";
@@ -30,26 +33,24 @@ type PlansScreenOptions = {
30
33
  keys: KeybindingsManager;
31
34
  /** Terminal rows, read per frame. */
32
35
  height: () => number;
33
- setActive: (name: string) => void;
36
+ setActive: (id: string) => void;
34
37
  onClose: () => void;
35
38
  requestRender: () => void;
36
39
  };
37
40
 
41
+ type Focus = "list" | "detail";
42
+
38
43
  /** Fixed rows: title, top rule, bottom rule, footer. */
39
44
  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
45
  /** Rendered markdown by theme, then width and text; cleared by invalidate() and on a width change. */
43
46
  const MARKDOWN_CACHE = new WeakMap<Theme, Map<string, string[]>>();
44
47
 
45
- type Focus = "list" | "detail";
46
-
47
48
  function hint(keys: KeybindingsManager, ids: Keybinding[], description: string): string {
48
49
  return rawKeyHint(ids.flatMap((id) => keys.getKeys(id)).join("/"), description);
49
50
  }
50
51
 
51
52
  /** 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
+ export function hardBreaks(text: string): string {
53
54
  const lines = text.split("\n");
54
55
  let fenced = false;
55
56
  return lines
@@ -63,7 +64,7 @@ function hardBreaks(text: string): string {
63
64
  }
64
65
 
65
66
  /** 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
+ function markdown(theme: Theme, text: string, width: number): string[] {
67
68
  let cache = MARKDOWN_CACHE.get(theme);
68
69
  if (!cache) MARKDOWN_CACHE.set(theme, (cache = new Map()));
69
70
  const key = `${width} ${text}`;
@@ -78,40 +79,47 @@ function markdown(theme: Theme, text: string, width: number, indent = 0): string
78
79
  while (lines.length && !lines.at(-1)) lines.pop();
79
80
  cache.set(key, lines);
80
81
  }
81
- return lines.map((line) => " ".repeat(indent) + line);
82
+ return lines;
82
83
  }
83
84
 
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 {
85
+ /** A section heading: the word in accent on a rule to the pane edge. */
86
+ function section(theme: Theme, word: string, width: number): string {
86
87
  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;
88
+ const rule = "─".repeat(Math.max(0, width - visibleWidth(head)));
89
+ return head + theme.fg("borderMuted", rule);
89
90
  }
90
91
 
91
- /** The title row: the glyph, the title, and the id at the right edge, with the blockers still open after it. */
92
+ /** The block header: glyph, muted id, title, then the blockers still open after a dim separator. */
92
93
  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);
94
+ const open = task.dependsOn.filter((id) => !plan.tasks.some((item) => item.id === id && item.status === "done"));
95
+ const after = open.length ? ` ${theme.fg("muted", `· after ${open.join(", ")}`)}` : "";
95
96
  // Accent means headings and labels, so the task the reader is on is bold text instead.
96
97
  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];
98
+ const [first = "", ...rest] = hanging(
99
+ `${theme.fg("muted", task.id)} ${current ? theme.bold(title) : title}${after}`,
100
+ width,
101
+ 2,
102
+ );
103
+ return [`${statusText(theme, task.status)} ${first}`, ...rest];
101
104
  }
102
105
 
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)];
106
+ /** A blank row, the field's accent label on a line of its own, then its value at column 0. */
107
+ function field(theme: Theme, label: string, value: string, width: number): string[] {
108
+ return ["", theme.fg("accent", label), ...markdown(theme, value, width)];
112
109
  }
113
110
 
114
- /** One task: its title row, then the check, where and notes of every task still open. */
111
+ /** pi-delegate's tool rows tint a job by status; a task uses the same pi background tokens. */
112
+ function blockBg(theme: Theme, status: PlanStatus): (text: string) => string {
113
+ const bg = {
114
+ doing: "toolPendingBg",
115
+ blocked: "toolErrorBg",
116
+ done: "toolSuccessBg",
117
+ todo: "userMessageBg",
118
+ } as const;
119
+ return (text) => theme.bg(bg[status], text);
120
+ }
121
+
122
+ /** One task as a full-width block tinted by its status, like pi-delegate's transcript entries. */
115
123
  function taskBlock(
116
124
  plan: Plan,
117
125
  task: PlanTask,
@@ -120,36 +128,44 @@ function taskBlock(
120
128
  current: boolean,
121
129
  expanded: boolean,
122
130
  ): 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
- "",
131
+ const inner = Math.max(1, width - 2);
132
+ const groups = [
133
+ taskLines(plan, task, theme, inner, current),
134
+ ...(!expanded && task.status === "done"
135
+ ? []
136
+ : [
137
+ field(theme, "Goal", task.goal, inner),
138
+ ...(task.detail ? [field(theme, "Detail", task.detail, inner)] : []),
139
+ ...(task.notes.length ? [field(theme, "Notes", task.notes.join("\n\n"), inner)] : []),
140
+ ]),
132
141
  ];
142
+ // Same padding as pi's tool-call boxes: one column each side, one row above and below.
143
+ const box = new Box(1, 1, blockBg(theme, task.status));
144
+ // field() leads each group with its blank row, so the groups stay one blank apart.
145
+ box.addChild(new Text(groups.flat().join("\n"), 0, 0));
146
+ // pi-delegate puts one blank row above each block.
147
+ return ["", ...box.render(width)];
133
148
  }
134
149
 
135
- /** Goal, tasks and context as three sections; the headings show where the reader is in a long plan. */
150
+ /** Goal, tasks, detail and notes as sections; the headings show where the reader is in a long plan. */
136
151
  function taskRows(plan: Plan, theme: Theme, width: number, expanded: boolean): string[] {
137
152
  const current = plan.tasks.find((task) => task.status === "doing") ?? nextTask(plan);
138
153
  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
154
  return [
142
155
  ...markdown(theme, plan.goal, width),
143
156
  "",
144
- section(theme, "Tasks", width, theme.fg("muted", ` ${planCount(plan)}`)),
157
+ section(theme, "Tasks", width),
145
158
  ...blocks,
146
159
  "",
147
- section(theme, "Context", width),
148
- ...markdown(theme, plan.context, width),
160
+ section(theme, "Detail", width),
161
+ ...markdown(theme, plan.detail, width),
162
+ ...(plan.notes.length
163
+ ? ["", section(theme, "Notes", width), ...markdown(theme, plan.notes.flatMap(noteItem).join("\n"), width)]
164
+ : []),
149
165
  ].map((line) => truncateToWidth(line, width, "…", true));
150
166
  }
151
167
 
152
- /** Two rows per plan, like pi-delegate's job rows: cursor, status glyph, name and count, then the goal. */
168
+ /** Two rows per plan, like pi-delegate's job rows: cursor, status glyph, id and count, then the title. */
153
169
  function sidebarRows(
154
170
  plans: Plan[],
155
171
  unreadable: string[],
@@ -167,18 +183,18 @@ function sidebarRows(
167
183
  const cursor = chosen ? theme.fg(focus === "list" ? "accent" : "muted", "›") : " ";
168
184
  return {
169
185
  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}`),
186
+ `${cursor} ${statusText(theme, planStatus(plan))} ${theme.fg(chosen ? "accent" : "text", plan.id)} ${theme.fg("muted", planCount(plan))}`,
187
+ theme.fg("dim", ` ${plan.id === active ? "active · " : ""}${plan.title}`),
172
188
  ],
173
189
  index: planIndex,
174
190
  };
175
191
  }),
176
- ...unreadable.map((name) => ({ lines: [theme.fg("error", ` ? ${name} unreadable`)] })),
192
+ ...unreadable.map((file) => ({ lines: [theme.fg("error", ` ? ${file} unreadable`)] })),
177
193
  ];
178
194
  const rows = all.flatMap((entry) => entry.lines.map((line, at) => ({ line, index: entry.index, head: at === 0 })));
179
195
  const selectedRow = rows.findIndex((row) => row.index === selected);
180
196
  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.
197
+ // A window never opens on a plan's second row, which would show a title with no id above it.
182
198
  while (start > 0 && !rows[start]!.head) start--;
183
199
  const shown = rows.slice(start, start + height);
184
200
  return {
@@ -205,12 +221,12 @@ export class PlansScreen implements Component {
205
221
  private lastBody = { height: 0, total: 0 };
206
222
  private lastIndexes: (number | undefined)[] = [];
207
223
  private lastSidebar = 0;
208
- private lastTextWidth = 0;
224
+ private lastWidth = 0;
209
225
 
210
226
  constructor(options: PlansScreenOptions) {
211
227
  this.options = options;
212
228
  this.active = options.active;
213
- const found = options.active ? options.plans.findIndex((plan) => plan.name === options.active) : -1;
229
+ const found = options.active ? options.plans.findIndex((plan) => plan.id === options.active) : -1;
214
230
  this.index = Math.max(0, found);
215
231
  }
216
232
 
@@ -253,7 +269,7 @@ export class PlansScreen implements Component {
253
269
  const sidebar = sidebarRows(plans, unreadable, this.index, this.active, this.focus, theme, sidebarWidth, body);
254
270
  this.lastIndexes = sidebar.indexes;
255
271
  const detail = plan
256
- ? this.detail(plan, Math.min(detailWidth, MAX_TEXT_WIDTH), detailWidth, body)
272
+ ? this.detail(plan, detailWidth, body)
257
273
  : [row(theme.fg("muted", "No readable plans."), detailWidth)];
258
274
  return [title, rule, ...sidebar.lines.map((line, index) => `${line} ${detail[index] ?? ""}`), rule, footer];
259
275
  }
@@ -267,8 +283,8 @@ export class PlansScreen implements Component {
267
283
  else if (keys.matches(data, "tui.select.confirm")) {
268
284
  const plan = this.options.plans[this.index];
269
285
  if (!plan) return;
270
- this.active = plan.name;
271
- setActive(plan.name);
286
+ this.active = plan.id;
287
+ setActive(plan.id);
272
288
  } else if (keys.matches(data, "app.tools.expand")) {
273
289
  this.expanded = !this.expanded;
274
290
  this.top = 0;
@@ -297,21 +313,18 @@ export class PlansScreen implements Component {
297
313
  return { handled: true };
298
314
  }
299
315
 
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[] {
316
+ /** The right pane: the plan's header stays put over the goal, tasks and detail, with a scroll counter below. */
317
+ private detail(plan: Plan, width: number, body: number): string[] {
302
318
  const { theme } = this.options;
303
- if (this.lastTextWidth !== textWidth) {
304
- this.lastTextWidth = textWidth;
319
+ if (this.lastWidth !== width) {
320
+ this.lastWidth = width;
305
321
  MARKDOWN_CACHE.delete(theme);
306
322
  }
307
323
  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);
324
+ const progress = theme.fg("muted", `· ${doneCount(plan)} of ${plan.tasks.length} done${blocked}`);
325
+ const header = `${statusText(theme, planStatus(plan))} ${theme.fg("accent", plan.id)} ${theme.fg("text", plan.title)} ${progress}`;
326
+ const height = Math.max(0, body - 2);
327
+ const all = taskRows(plan, theme, width, this.expanded);
315
328
  const start = Math.min(this.top, Math.max(0, all.length - height));
316
329
  this.top = start;
317
330
  this.lastBody = { height, total: all.length };
@@ -322,7 +335,7 @@ export class PlansScreen implements Component {
322
335
  );
323
336
  // Right-aligned like pi-delegate's counter; every row is padded so the pane's right edge holds still.
324
337
  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) =>
338
+ return [header, ...shown, ...Array(Math.max(0, height - shown.length)).fill(""), tail].map((line) =>
326
339
  truncateToWidth(line, width, "…", true),
327
340
  );
328
341
  }
@@ -353,7 +366,7 @@ export function openPlans(
353
366
  ctx: ExtensionContext,
354
367
  list: PlanList,
355
368
  active: string | undefined,
356
- setActive: (name: string) => void,
369
+ setActive: (id: string) => void,
357
370
  ): Promise<void> {
358
371
  const screen = { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 } } as const;
359
372
  return ctx.ui.custom<void>(
package/src/store.ts CHANGED
@@ -4,24 +4,24 @@ import { dirname, join, resolve } from "node:path";
4
4
  import type { KeybindingHints, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
5
5
  import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
6
6
 
7
- export const STATUSES = ["todo", "doing", "done", "blocked"] as const;
8
-
9
7
  export type PlanStatus = (typeof STATUSES)[number];
10
8
 
11
9
  export type PlanTask = {
12
10
  id: string;
13
11
  title: string;
14
- where?: string;
15
- blockedBy: string[];
16
- doneWhen: string;
12
+ goal: string;
13
+ detail: string;
14
+ dependsOn: string[];
17
15
  status: PlanStatus;
18
16
  notes: string[];
19
17
  };
20
18
 
21
19
  export type Plan = {
22
- name: string;
20
+ id: string;
21
+ title: string;
23
22
  goal: string;
24
- context: string;
23
+ detail: string;
24
+ notes: string[];
25
25
  tasks: PlanTask[];
26
26
  };
27
27
 
@@ -31,6 +31,8 @@ export type PlanList = {
31
31
  };
32
32
 
33
33
  /** One status vocabulary for the widget, the tool results and the /plan overlay. */
34
+ export const STATUSES = ["todo", "doing", "done", "blocked"] as const;
35
+
34
36
  export const STATUS = {
35
37
  todo: { glyph: "○", color: "muted" },
36
38
  doing: { glyph: "◐", color: "warning" },
@@ -38,7 +40,7 @@ export const STATUS = {
38
40
  blocked: { glyph: "✗", color: "error" },
39
41
  } as const satisfies Record<PlanStatus, { glyph: string; color: string }>;
40
42
 
41
- const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
43
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
42
44
  const PLANS_IGNORE = ".pi/plans/";
43
45
 
44
46
  /** Plans live at <repoRoot>/.pi/plans, beside pi-delegate's .pi/worktrees; outside git, the session cwd is the root. */
@@ -60,14 +62,42 @@ export function plansDir(root: string): string {
60
62
  return join(root, ".pi", "plans");
61
63
  }
62
64
 
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`);
65
+ function planPath(root: string, id: string): string {
66
+ if (!ID.test(id)) throw new Error(`Plan id "${id}" must be kebab-case, for example my-plan.`);
67
+ return join(plansDir(root), `${id}.json`);
66
68
  }
67
69
 
68
- export function readPlan(root: string, name: string): Plan | undefined {
70
+ function isTask(value: unknown): value is PlanTask {
71
+ const task = value as PlanTask;
72
+ return (
73
+ typeof task?.id === "string" &&
74
+ typeof task.title === "string" &&
75
+ typeof task.goal === "string" &&
76
+ typeof task.detail === "string" &&
77
+ Array.isArray(task.dependsOn) &&
78
+ Array.isArray(task.notes) &&
79
+ STATUSES.includes(task.status)
80
+ );
81
+ }
82
+
83
+ /** A file without the current shape is no plan: old files stay unreadable instead of crashing a renderer. */
84
+ function isPlan(value: unknown): value is Plan {
85
+ const plan = value as Plan;
86
+ return (
87
+ Array.isArray(plan?.tasks) &&
88
+ plan.tasks.every(isTask) &&
89
+ typeof plan.id === "string" &&
90
+ typeof plan.title === "string" &&
91
+ typeof plan.goal === "string" &&
92
+ typeof plan.detail === "string" &&
93
+ Array.isArray(plan.notes)
94
+ );
95
+ }
96
+
97
+ export function readPlan(root: string, id: string): Plan | undefined {
69
98
  try {
70
- return JSON.parse(readFileSync(planPath(root, name), "utf8")) as Plan;
99
+ const value: unknown = JSON.parse(readFileSync(planPath(root, id), "utf8"));
100
+ return isPlan(value) ? value : undefined;
71
101
  } catch (error) {
72
102
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
73
103
  throw error;
@@ -75,7 +105,7 @@ export function readPlan(root: string, name: string): Plan | undefined {
75
105
  }
76
106
 
77
107
  export function writePlan(root: string, plan: Plan): void {
78
- const file = planPath(root, plan.name);
108
+ const file = planPath(root, plan.id);
79
109
  mkdirSync(dirname(file), { recursive: true });
80
110
  // Temp file plus rename: a crash mid-write leaves the previous plan intact.
81
111
  // shortcut: one writer, no lock; add one if a second process can write plans
@@ -96,9 +126,9 @@ export function listPlans(root: string): PlanList {
96
126
  const unreadable: string[] = [];
97
127
  for (const file of files.filter((name) => name.endsWith(".json")).sort()) {
98
128
  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);
129
+ const value: unknown = JSON.parse(readFileSync(join(plansDir(root), file), "utf8"));
130
+ if (!isPlan(value)) throw new Error("not a plan");
131
+ plans.push(value);
102
132
  } catch {
103
133
  unreadable.push(file.slice(0, -5));
104
134
  }
@@ -139,51 +169,62 @@ export function doneCount(plan: Plan): number {
139
169
  /** The first todo task whose blockers are all done, the one to dispatch next. */
140
170
  export function nextTask(plan: Plan): PlanTask | undefined {
141
171
  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)));
172
+ return plan.tasks.find((task) => task.status === "todo" && task.dependsOn.every((id) => done.has(id)));
143
173
  }
144
174
 
145
175
  export function taskLine(task: PlanTask): string {
146
176
  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}`);
177
+ if (task.dependsOn.length) parts.push(`dependsOn ${task.dependsOn.join(" ")}`);
149
178
  return parts.join(" — ");
150
179
  }
151
180
 
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
- ];
181
+ /** Notes as list items; a continuation line indents by two so it stays inside its item. */
182
+ export function noteItem(note: string): string[] {
183
+ const [first = "", ...rest] = note.split("\n");
184
+ return [`- ${first}`, ...rest.map((line) => ` ${line}`)];
158
185
  }
159
186
 
160
- export function planText(plan: Plan): string {
187
+ function planBlock(plan: Plan): string {
161
188
  return [
162
- `plan ${plan.name} ${doneCount(plan)}/${plan.tasks.length}`,
163
- `goal: ${plan.goal}`,
164
- `context: ${plan.context}`,
165
- ...plan.tasks.flatMap(taskLines),
189
+ `# Plan ${plan.id}: ${plan.title} (${doneCount(plan)}/${plan.tasks.length} done)`,
190
+ "",
191
+ "## Goal",
192
+ plan.goal,
193
+ "",
194
+ "## Detail",
195
+ plan.detail,
196
+ ...(plan.notes.length ? ["", "## Notes", ...plan.notes.flatMap(noteItem)] : []),
166
197
  ].join("\n");
167
198
  }
168
199
 
169
- export function taskText(plan: Plan, task: PlanTask): string {
200
+ function taskBlock(task: PlanTask): string {
170
201
  return [
171
- `plan ${plan.name} ${doneCount(plan)}/${plan.tasks.length}`,
172
- `goal: ${plan.goal}`,
173
- `context: ${plan.context}`,
202
+ `## Task ${task.id} [${task.status}]: ${task.title}`,
203
+ ...(task.dependsOn.length ? [`Depends on: ${task.dependsOn.join(", ")}`] : []),
204
+ "",
205
+ "### Goal",
206
+ task.goal,
174
207
  "",
175
- ...taskLines(task),
208
+ "### Detail",
209
+ task.detail,
210
+ ...(task.notes.length ? ["", "### Notes", ...task.notes.flatMap(noteItem)] : []),
176
211
  ].join("\n");
177
212
  }
178
213
 
214
+ /** One `get` result as markdown: the plan, then every task as its own section. */
215
+ export function planText(plan: Plan): string {
216
+ return [planBlock(plan), ...plan.tasks.map((task) => taskBlock(task))].join("\n\n");
217
+ }
218
+
219
+ /** The same plan header, then the one task an executor works from. */
220
+ export function taskText(plan: Plan, task: PlanTask): string {
221
+ return [planBlock(plan), taskBlock(task)].join("\n\n");
222
+ }
223
+
179
224
  export function listText(root: string, list: PlanList, active: string | undefined): string {
180
225
  if (!list.plans.length && !list.unreadable.length) return `No plans in ${plansDir(root)}.`;
181
226
  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
- }),
227
+ ...list.plans.map((plan) => `${plan.id === active ? "*" : " "} ${plan.id} ${plan.title} ${planCount(plan)}`),
187
228
  ...list.unreadable.map((name) => `? ${name} unreadable`),
188
229
  ].join("\n");
189
230
  }
@@ -196,14 +237,9 @@ export function planCount(plan: Plan): string {
196
237
  return `${doneCount(plan)}/${plan.tasks.length}`;
197
238
  }
198
239
 
199
- /** `name 1/4 · doing t2 · next t3`: the line the widget, the tool header and the list all lead with. */
240
+ /** `id title 1/4`: the line the widget head, the tool result header and the list all lead with. */
200
241
  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(" · "))}`;
242
+ return `${theme.fg("accent", plan.id)} ${plan.title} ${theme.fg("muted", planCount(plan))}`;
207
243
  }
208
244
 
209
245
  /** The plan's own status: done when every task is, doing while one is, todo otherwise. */
@@ -214,8 +250,8 @@ export function planStatus(plan: Plan): Exclude<PlanStatus, "blocked"> {
214
250
 
215
251
  /** A task row: glyph, id, title, and the blockers still open; a done blocker is no noise worth showing. */
216
252
  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(" ")}`)}` : "";
253
+ const open = task.dependsOn.filter((id) => !plan.tasks.some((item) => item.id === id && item.status === "done"));
254
+ const blocked = open.length ? ` ${theme.fg("muted", `· dependsOn ${open.join(" ")}`)}` : "";
219
255
  return `${statusText(theme, task.status)} ${theme.fg("accent", task.id)} ${task.title}${blocked}`;
220
256
  }
221
257
 
@@ -240,12 +276,11 @@ export function fact(
240
276
  );
241
277
  }
242
278
 
243
- /** The lines under a task row: where it lives, its check, and its dim notes as written. */
279
+ /** The lines under a task row: its goal, its brief as dim text, and its dim notes as written. */
244
280
  export function taskFacts(theme: Theme, task: PlanTask, width: number): string[] {
245
281
  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),
282
+ ...fact(theme, "Goal: ", task.goal, width),
283
+ ...(task.detail ? fact(theme, "Detail: ", task.detail, width, 2, "dim") : []),
249
284
  ...task.notes.flatMap((note) => fact(theme, "", note, width)),
250
285
  ];
251
286
  }
@@ -255,7 +290,12 @@ export function moreLines(theme: Theme, hidden: number, keyHint: KeybindingHints
255
290
  return `${theme.fg("muted", `... (${hidden} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
256
291
  }
257
292
 
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)}`;
293
+ /** The widget head, then one line per task in progress: parallel delegates can run several at once. */
294
+ export function widgetLines(theme: Theme, plan: Plan): string[] {
295
+ return [
296
+ `${theme.fg("accent", "plan")} ${plan.title} ${theme.fg("muted", planCount(plan))}`,
297
+ ...plan.tasks
298
+ .filter((task) => task.status === "doing")
299
+ .map((task) => ` ${theme.fg("muted", task.id)} ${task.title}`),
300
+ ];
261
301
  }