pi-todo-ledger 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,6 +42,14 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
42
42
  `evidence` items are appended after the existing ones; `at` defaults to the time of the call.
43
43
  `get` shows all three fields.
44
44
 
45
+ `create`, `update`, `get`, and `list` print each task's stable `uid` if it has one (for example, `t_k7wrx2jzfq`).
46
+ Pass that value as a subagent's `item`; use the shorter `#id` only within the list.
47
+
48
+ The panel and `/todos` indent each open task under its first unfinished blocker and show its owner as `@owner`.
49
+ To mark a task as waiting for someone, set `metadata.waitsOn` to their name; to defer it until a particular time, set `metadata.until` to an ISO timestamp, e.g. `2027-01-15T09:00:00+08:00`.
50
+ An open task shows `⏸` with the name or the future deadline in local time.
51
+ These keys are display conventions: they neither schedule a wake-up nor change the task's `status` or the `todo/v1` contract.
52
+
45
53
  `graph` names the work graph of the plan a task belongs to, one of `single-loop`, `fan-out/fan-in`, and `orchestrator-worker`; any other value is refused.
46
54
  One session often runs several plans, so each task carries its own.
47
55
  An update replaces it and `graph: null` clears it.
package/docs/overlay.md CHANGED
@@ -23,13 +23,13 @@ snapshots are saved.
23
23
 
24
24
  ## Anatomy of a row
25
25
 
26
- ```
27
- ● Todos (2/5)
28
- ├─ ✓ Create DemoTodo domain entity
29
- ├─ ✓ Create IDemoTodoRepository interface
30
- ├─ ◐ Create DemoTodoRepository (creating the repository)
31
- ├─ ○ Register DI bindings
32
- └─ ○ Add integration tests
26
+ ```text
27
+ ● Todos (0/5) · fan-out/fan-in
28
+ ├─ ◐ #1 Scope @Ari
29
+ ├─ ○ #3 API
30
+ ├─ ○ #4 Check API
31
+ ├─ ○ #5 UI
32
+ └─ ⏸ #2 Approve waits Pat
33
33
  ```
34
34
 
35
35
  - **Heading** — `● Todos (done/total)` in the accent color while any task is
@@ -39,10 +39,11 @@ snapshots are saved.
39
39
  Completed and deleted subjects render dim and struck through.
40
40
  - **activeForm** — appended dim in parentheses, only while the task is
41
41
  `in_progress`.
42
- - **Dependencies** — appended as `⛓ #1,#2` when the task has a `blockedBy` set.
43
- - **`#id` prefix** — shown on every row only when at least one visible task
44
- carries a `blockedBy`. Without a `⛓ #N` anywhere, the per-row ids have nothing
45
- to point at, so they are omitted.
42
+ - **Waiting** — `⏸` replaces the open-task glyph when `metadata.waitsOn` names a party or `metadata.until` is an ISO time in the future. The row shows the party, the local deadline, or both. An elapsed deadline no longer marks a task as waiting.
43
+ - **Owner** — `@owner` follows the subject in muted text.
44
+ - **Dependencies** — open rows nest under the first unfinished `blockedBy` id; siblings are visited in id order. Other unfinished blockers appear in the `⛓ #1,#2` tail. If another prerequisite interrupts a branch, `↳ #N` names the parent the row returns to.
45
+ - **Graph** — the heading names the graph when all open tasks share it; otherwise a root shows its own graph, if set.
46
+ - **`#id` prefix** — shown on every overlay row when at least one visible task carries a `blockedBy`.
46
47
  - **Prefixes** — `├─` on each row, `└─` on the last one. A blank spacer line is
47
48
  always appended below the panel so it is not flush against the input box.
48
49
 
@@ -86,21 +87,16 @@ label rather than advertising an unbindable key.
86
87
 
87
88
  ## `/todos`
88
89
 
89
- `/todos` prints the whole list grouped by status, independent of the overlay's
90
- row budget and auto-hiding:
90
+ `/todos` shows the whole dependency tree, independent of the overlay's row budget and auto-hiding.
91
+ Completed tasks follow in their own section.
91
92
 
92
- ```
93
- 2/7 completed · 1 in progress · 4 pending
94
- ── Pending ──
95
- ○ #4 Register DI bindings
96
- ○ #5 Add integration tests ⛓ #4
97
- ○ #6 Wire up the HTTP endpoint
98
- ○ #7 Update the API docs
99
- ── In Progress ──
100
- ◐ #3 Create DemoTodoRepository (creating the repository)
101
- ── Completed ──
102
- ✓ #1 Create DemoTodo domain entity
103
- ✓ #2 Create IDemoTodoRepository interface
93
+ ```text
94
+ 1 in progress · 4 pending · fan-out/fan-in
95
+ ◐ #1 Scope @Ari
96
+ ○ #3 API
97
+ ○ #4 Check API
98
+ ○ #5 UI
99
+ ⏸ #2 Approve waits Pat
104
100
  ```
105
101
 
106
102
  The header omits any count that is zero. Sections appear only when they have
@@ -187,6 +187,10 @@ any disk writes.
187
187
 
188
188
  ## Content strings
189
189
 
190
+ The table shows the base messages.
191
+ `create`, `update` (including a no-op), `list`, and `get` append the stable `uid` to each task's summary line when it has one.
192
+ An open task that follows the [waiting convention](../README.md#using-it) also shows `⏸` and its reason on that line.
193
+
190
194
  | Situation | `content[0].text` |
191
195
  | --- | --- |
192
196
  | Created | `Created #3: Write the parser (pending)` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -18,7 +18,8 @@ import { COLLAPSE_KEY_OFF, getMaxWidgetLines, resolveCollapseKey } from "./confi
18
18
  import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
19
19
  import { selectHasActive, selectOverlayLayout, selectShowTaskIds, selectTodoCounts } from "./state/selectors.ts";
20
20
  import { getRenderState } from "./state/store.ts";
21
- import { formatOverlayTaskLine } from "./view/format.ts";
21
+ import { formatPlanTaskLine } from "./view/format.ts";
22
+ import { planView } from "./view/plan.ts";
22
23
 
23
24
  const WIDGET_KEY = "rpiv-todos";
24
25
 
@@ -140,7 +141,11 @@ export class TodoOverlay {
140
141
  const overlayTasks = this.selectOverlayTasks(snapshot);
141
142
  if (overlayTasks.length === 0) return [];
142
143
 
143
- const overlayState = { tasks: overlayTasks, nextId: snapshot.nextId };
144
+ const plan = planView(overlayTasks);
145
+ // Keep completed rows in their old slots; fill open slots in display order before budgeting.
146
+ let nextOpen = 0;
147
+ const tasks = overlayTasks.map(t => t.status === "completed" ? t : plan.ordered[nextOpen++]);
148
+ const overlayState = { tasks, nextId: snapshot.nextId };
144
149
  const truncate = (line: string): string => truncateToWidth(line, width, "…");
145
150
  const counts = selectTodoCounts(overlayState);
146
151
  const hasActive = selectHasActive(overlayState);
@@ -149,7 +154,8 @@ export class TodoOverlay {
149
154
  const headingColor = hasActive ? "accent" : "dim";
150
155
  const headingIcon = hasActive ? "●" : "○";
151
156
  const headingText = `${t("overlay.heading", OVERLAY_HEADING)} (${counts.completed}/${counts.total})`;
152
- const heading = truncate(`${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}`);
157
+ const graph = plan.sharedGraph ? ` · ${theme.fg("dim", plan.sharedGraph)}` : "";
158
+ const heading = truncate(`${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}${graph}`);
153
159
 
154
160
  // Collapsed view: just the heading + a dim "└─" expand hint, then the
155
161
  // trailing spacer. Short-circuit before the budget math and the completed-
@@ -178,7 +184,7 @@ export class TodoOverlay {
178
184
  const bodyBudget = this.uiCtx?.getToolsExpanded?.() === true ? overlayTasks.length : getMaxWidgetLines() - 1;
179
185
  const layout = selectOverlayLayout(overlayState, bodyBudget);
180
186
  for (const task of layout.visible) {
181
- lines.push(truncate(`${theme.fg("dim", "├─")} ${formatOverlayTaskLine(task, theme, showIds)}`));
187
+ lines.push(truncate(`${theme.fg("dim", "├─")} ${formatPlanTaskLine(task, theme, showIds, plan.rows.get(task.id))}`));
182
188
  }
183
189
 
184
190
  const newlyDisplayedCompletedTaskIds = overlayTasks
package/src/todo.ts CHANGED
@@ -36,12 +36,11 @@ import {
36
36
  TOOL_NAME,
37
37
  TodoParamsSchema,
38
38
  } from "./tool/types.ts";
39
- import { formatCommandTaskLine, renderTodoCall, renderTodoResult } from "./view/format.ts";
39
+ import { formatPlanTaskLine, renderTodoCall, renderTodoResult } from "./view/format.ts";
40
+ import { planView } from "./view/plan.ts";
40
41
 
41
42
  // English fallbacks for localized /todos section headers — the box-drawing
42
43
  // decoration is part of the localized string so translators can adjust spacing.
43
- const SECTION_PENDING = "── Pending ──";
44
- const SECTION_IN_PROGRESS = "── In Progress ──";
45
44
  const SECTION_COMPLETED = "── Completed ──";
46
45
 
47
46
  // ---------------------------------------------------------------------------
@@ -183,7 +182,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
183
182
 
184
183
  export function registerTodosCommand(pi: ExtensionAPI): void {
185
184
  pi.registerCommand(COMMAND_NAME, {
186
- description: "Show all todos on the current branch, grouped by status",
185
+ description: "Show the current branch's plan by dependency, then its completed todos",
187
186
  handler: async (_args, ctx) => {
188
187
  if (!ctx.hasUI) {
189
188
  ctx.ui.notify(t("command.requires_interactive", ERR_REQUIRES_INTERACTIVE), "error");
@@ -195,7 +194,8 @@ export function registerTodosCommand(pi: ExtensionAPI): void {
195
194
  ctx.ui.notify(t("command.no_todos", MSG_NO_TODOS), "info");
196
195
  return;
197
196
  }
198
- const groups = selectTasksByStatus(state);
197
+ const { completed } = selectTasksByStatus(state);
198
+ const plan = planView(visible);
199
199
  const counts = selectTodoCounts(state);
200
200
 
201
201
  const header: string[] = [];
@@ -203,18 +203,12 @@ export function registerTodosCommand(pi: ExtensionAPI): void {
203
203
  if (counts.inProgress > 0) header.push(`${counts.inProgress} ${formatStatusLabel("in_progress")}`);
204
204
  if (counts.pending > 0) header.push(`${counts.pending} ${formatStatusLabel("pending")}`);
205
205
 
206
- const lines: string[] = [header.join(" · ")];
207
- if (groups.pending.length > 0) {
208
- lines.push(t("command.section.pending", SECTION_PENDING));
209
- for (const task of groups.pending) lines.push(formatCommandTaskLine(task, "○"));
210
- }
211
- if (groups.inProgress.length > 0) {
212
- lines.push(t("command.section.in_progress", SECTION_IN_PROGRESS));
213
- for (const task of groups.inProgress) lines.push(formatCommandTaskLine(task, "◐"));
214
- }
215
- if (groups.completed.length > 0) {
206
+ if (plan.sharedGraph) header.push(plan.sharedGraph);
207
+ const lines = [header.join(" · ")];
208
+ for (const task of plan.ordered) lines.push(` ${formatPlanTaskLine(task, ctx.ui.theme, true, plan.rows.get(task.id))}`);
209
+ if (completed.length) {
216
210
  lines.push(t("command.section.completed", SECTION_COMPLETED));
217
- for (const task of groups.completed) lines.push(formatCommandTaskLine(task, "✓"));
211
+ for (const task of completed) lines.push(` ${formatPlanTaskLine(task, ctx.ui.theme, true)}`);
218
212
  }
219
213
 
220
214
  ctx.ui.notify(lines.join("\n"), "info");
@@ -1,22 +1,19 @@
1
1
  import type { TaskState } from "../state/state.ts";
2
2
  import type { Op } from "../state/state-reducer.ts";
3
3
  import { deriveBlocks } from "../state/task-graph.ts";
4
+ import { isOpen, resultSuffix } from "../view/task-labels.ts";
4
5
  import { sanitizeTerminalText } from "./sanitize.ts";
5
6
  import type { Task, TaskAction, TaskDetails, TaskMutationParams } from "./types.ts";
6
7
 
7
8
  /**
8
- * Format a single task as a `[status] #id subject [(activeForm)] [⛓ #dep,…]`
9
- * line. Used by the `list` content branch only — the overlay and `/todos`
10
- * formatting paths use `view/format.ts` for richer presentations.
9
+ * Compact `list` row for the caller. The widget and /todos use the tree layout instead.
11
10
  */
12
11
  function formatListLine(t: Task): string {
13
12
  const block = t.blockedBy?.length ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}` : "";
14
13
  const form = t.status === "in_progress" && t.activeForm ? ` (${sanitizeTerminalText(t.activeForm)})` : "";
15
- return `[${t.status}] #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}`;
14
+ return `[${t.status}] #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}${resultSuffix(t)}`;
16
15
  }
17
16
 
18
- const isOpen = (t: Task): boolean => t.status === "pending" || t.status === "in_progress";
19
-
20
17
  /**
21
18
  * `list` body. When an open task names a graph, open tasks are grouped under
22
19
  * `<graph>:` headers in first-seen order, then `no graph:`, then `closed:` for
@@ -46,13 +43,11 @@ function formatList(view: readonly Task[]): string {
46
43
  }
47
44
 
48
45
  /**
49
- * Multi-line presentation for the `get` action. Order of rows is pinned by
50
- * pre-refactor `todo.ts:354-376` — description, activeForm, blockedBy, blocks,
51
- * owner — so envelope-level snapshot tests stay byte-equivalent.
46
+ * `get` shows the local id and stable uid on the first line, followed by the set fields.
52
47
  */
53
48
  function formatGetLines(task: Task, state: TaskState): string {
54
49
  const blocks = deriveBlocks(state.tasks).get(task.id) ?? [];
55
- const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}`];
50
+ const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}${resultSuffix(task)}`];
56
51
  if (task.description) lines.push(` description: ${sanitizeTerminalText(task.description)}`);
57
52
  if (task.activeForm) lines.push(` activeForm: ${sanitizeTerminalText(task.activeForm)}`);
58
53
  if (task.blockedBy?.length) {
@@ -75,8 +70,6 @@ function formatGetLines(task: Task, state: TaskState): string {
75
70
  /**
76
71
  * Pure formatter: `(op, state) → string`. Closed switch on `op.kind` —
77
72
  * adding a new `Op` variant fails to compile here until a branch is added.
78
- * The strings on each branch are byte-equivalent to pre-refactor `todo.ts`
79
- * reducer output.
80
73
  */
81
74
  export function formatContent(op: Op, state: TaskState): string {
82
75
  switch (op.kind) {
@@ -86,16 +79,17 @@ export function formatContent(op: Op, state: TaskState): string {
86
79
  .map((id) => {
87
80
  const created = state.tasks.find((x) => x.id === id);
88
81
  if (!created) return `Created #${id}`;
89
- return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)`;
82
+ return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)${resultSuffix(created)}`;
90
83
  })
91
84
  .join("\n");
92
85
  }
93
86
  case "update": {
87
+ const suffix = resultSuffix(state.tasks.find(t => t.id === op.id)!);
94
88
  if (!op.changed) {
95
- return `No change: #${op.id} already matches the requested values (status: ${op.toStatus})`;
89
+ return `No change: #${op.id} already matches the requested values (status: ${op.toStatus})${suffix}`;
96
90
  }
97
91
  const transition = op.fromStatus !== op.toStatus ? ` (${op.fromStatus} → ${op.toStatus})` : "";
98
- return `Updated #${op.id}${transition}`;
92
+ return `Updated #${op.id}${transition}${suffix}`;
99
93
  }
100
94
  case "delete":
101
95
  return `Deleted #${op.id}: ${sanitizeTerminalText(op.subject)}`;
@@ -5,6 +5,8 @@ import { selectTaskSubjectById } from "../state/selectors.ts";
5
5
  import type { TaskState } from "../state/state.ts";
6
6
  import { sanitizeTerminalText } from "../tool/sanitize.ts";
7
7
  import type { Task, TaskAction, TaskDetails, TaskMutationParams, TaskStatus } from "../tool/types.ts";
8
+ import type { PlanRow } from "./plan.ts";
9
+ import { uidSuffix, waitingLabel } from "./task-labels.ts";
8
10
 
9
11
  // Re-export so legacy import paths (todo.ts, tests) continue to resolve;
10
12
  // the canonical definition lives in the i18n bridge.
@@ -67,39 +69,33 @@ export function overlayStatusGlyph(status: TaskStatus, theme: Theme): string {
67
69
  }
68
70
 
69
71
  /**
70
- * Format a single task row for the persistent overlay. The subject color
72
+ * Format a task row for the overlay or /todos. The subject color
71
73
  * reflects task state while IDs and supporting metadata stay visually quiet.
72
74
  */
73
- export function formatOverlayTaskLine(t: Task, theme: Theme, showId: boolean): string {
74
- const glyph = overlayStatusGlyph(t.status, theme);
75
+ export function formatPlanTaskLine(t: Task, theme: Theme, showId: boolean, row?: PlanRow): string {
76
+ const wait = waitingLabel(t);
77
+ const glyph = wait ? theme.fg("warning", "⏸") : overlayStatusGlyph(t.status, theme);
75
78
  const subjectColor =
76
79
  t.status === "in_progress" ? "accent" : t.status === "completed" || t.status === "deleted" ? "muted" : "text";
77
80
  let subject = theme.fg(subjectColor, sanitizeTerminalText(t.subject));
78
81
  if (t.status === "completed" || t.status === "deleted") {
79
82
  subject = theme.strikethrough(subject);
80
83
  }
81
- let line = `${glyph}`;
84
+ let line = `${" ".repeat(row?.depth ?? 0)}${glyph}`;
82
85
  if (showId) line += ` ${theme.fg("dim", `#${t.id}`)}`;
83
86
  line += ` ${subject}`;
87
+ if (t.owner) line += ` ${theme.fg("muted", `@${sanitizeTerminalText(t.owner)}`)}`;
88
+ if (wait) line += ` ${theme.fg("muted", wait)}`;
84
89
  if (t.status === "in_progress" && t.activeForm) {
85
90
  line += ` ${theme.fg("muted", `(${sanitizeTerminalText(t.activeForm)})`)}`;
86
91
  }
87
- if (t.blockedBy && t.blockedBy.length > 0) {
88
- line += ` ${theme.fg("muted", `⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}`)}`;
89
- }
92
+ if (row?.graph) line += ` ${theme.fg("dim", row.graph)}`;
93
+ if (row?.resumeParent !== undefined) line += ` ${theme.fg("dim", `↳ #${row.resumeParent}`)}`;
94
+ const blockers = row?.otherBlockers ?? t.blockedBy;
95
+ if (blockers?.length) line += ` ${theme.fg("muted", `⛓ ${blockers.map(id => `#${id}`).join(",")}`)}`;
90
96
  return line;
91
97
  }
92
98
 
93
- /**
94
- * Format a single task line for the `/todos` slash command (no glyph color,
95
- * indented bullet prefix).
96
- */
97
- export function formatCommandTaskLine(t: Task, glyph: string): string {
98
- const form = t.status === "in_progress" && t.activeForm ? ` (${sanitizeTerminalText(t.activeForm)})` : "";
99
- const block = t.blockedBy?.length ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}` : "";
100
- return ` ${glyph} #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}`;
101
- }
102
-
103
99
  // ---------------------------------------------------------------------------
104
100
  // Tool render hooks — wrapped so `todo.ts` becomes a thin call-site.
105
101
  // ---------------------------------------------------------------------------
@@ -136,16 +132,23 @@ export function renderTodoCall(
136
132
  }
137
133
 
138
134
  /**
139
- * `renderResult` body. A failed call renders `✗` with its reason; a successful
140
- * `create`/`update`/`delete` echoes the task's status; anything else is `✓`.
135
+ * A refusal renders its reason. Task results show only the affected or requested
136
+ * rows; operations with no rows keep the short success mark.
141
137
  */
142
138
  export function renderTodoResult(result: ToolResultView, theme: Theme, isError = false): Text {
143
139
  const failure = failureReason(result, isError);
144
140
  if (failure !== undefined) return new Text(theme.fg("error", failure ? `✗ ${failure}` : "✗"), 0, 0);
145
141
 
146
- const status = echoedStatus(result.details as TaskDetails | undefined);
147
- if (status) {
148
- return new Text(theme.fg(STATUS_COLOR[status], `${STATUS_GLYPH[status]} ${formatStatusLabel(status)}`), 0, 0);
142
+ const details = result.details as TaskDetails | undefined;
143
+ const tasks = echoedTasks(details);
144
+ if (tasks.length) {
145
+ const rows = tasks.map(task => {
146
+ const wait = waitingLabel(task);
147
+ const label = wait ? `⏸ ${wait}` : `${STATUS_GLYPH[task.status]} ${formatStatusLabel(task.status)}`;
148
+ const subject = details?.action === "list" || tasks.length > 1 ? ` ${sanitizeTerminalText(task.subject)}` : "";
149
+ return `${theme.fg(wait ? "warning" : STATUS_COLOR[task.status], label)} #${task.id}${subject}${theme.fg("dim", uidSuffix(task))}`;
150
+ });
151
+ return new Text(rows.join("\n"), 0, 0);
149
152
  }
150
153
  return new Text(theme.fg("success", "✓"), 0, 0);
151
154
  }
@@ -164,21 +167,16 @@ function failureReason(result: ToolResultView, isError: boolean): string | undef
164
167
  return sanitizeTerminalText(message.split("\n")[0]);
165
168
  }
166
169
 
167
- /** Status the result card echoes: the task the call created, updated or deleted. */
168
- function echoedStatus(details: TaskDetails | undefined): TaskStatus | undefined {
169
- if (!details) return undefined;
170
+ /** Use the result's snapshot, not the live slot: a historic card belongs to its own call. */
171
+ function echoedTasks(details?: TaskDetails): Task[] {
172
+ if (!details?.tasks || !details.params) return [];
170
173
  const params = details.params as TaskMutationParams;
171
174
  switch (details.action) {
172
- case "create":
173
- return details.tasks.at(-1)?.status;
174
- case "update":
175
- return params.status ?? details.tasks.find((t) => t.id === params.id)?.status;
176
- case "delete":
177
- return details.tasks.find((t) => t.id === params.id)?.status;
178
- case "list":
175
+ case "create": return details.tasks.slice(-(params.tasks?.length ?? 1));
179
176
  case "get":
180
- case "import":
181
- case "clear":
182
- return undefined;
177
+ case "update":
178
+ case "delete": return details.tasks.filter(t => t.id === params.id);
179
+ case "list": return details.tasks.filter(t => (params.includeDeleted || t.status !== "deleted") && (!params.status || t.status === params.status));
180
+ default: return [];
183
181
  }
184
182
  }
@@ -0,0 +1,74 @@
1
+ import { isGraph, type Task } from "../tool/types.ts";
2
+ import { isOpen } from "./task-labels.ts";
3
+
4
+ export interface PlanRow {
5
+ depth: number;
6
+ graph?: Task["graph"];
7
+ otherBlockers: number[];
8
+ /** A cross-edge interrupted the displayed branch; identify the parent explicitly. */
9
+ resumeParent?: number;
10
+ }
11
+
12
+ /** Read-only projection shared by the widget and /todos. Edges to finished work don't indent a row. */
13
+ export function planView(tasks: readonly Task[]) {
14
+ const open = tasks.filter(isOpen).sort((a, b) => a.id - b.id);
15
+ const graph = open[0]?.graph;
16
+ const sharedGraph = isGraph(graph) && open.every(task => task.graph === graph) ? graph : undefined;
17
+ const byId = new Map(open.map(task => [task.id, task]));
18
+ const rows = new Map<number, PlanRow>();
19
+ // Only the mutation and import paths enforce unique ids; don't traverse ambiguous legacy edges.
20
+ if (byId.size !== open.length) return { ordered: open, sharedGraph, rows };
21
+ const blockers = new Map<number, number[]>();
22
+ const children = new Map<number, Task[]>();
23
+ const roots: Task[] = [];
24
+ for (const task of open) {
25
+ const deps = (task.blockedBy ?? []).filter(id => byId.has(id));
26
+ blockers.set(task.id, deps);
27
+ if (!deps.length) roots.push(task);
28
+ else {
29
+ const siblings = children.get(deps[0]) ?? [];
30
+ siblings.push(task);
31
+ children.set(deps[0], siblings);
32
+ }
33
+ }
34
+
35
+ // Visit first-parent subtrees in id order. For a join, emit any remaining prerequisites
36
+ // before the joined row. Iterative even for a long chain restored from a snapshot.
37
+ const ordered: Task[] = [];
38
+ const reached = new Set<number>();
39
+ const ancestry: number[] = [];
40
+ const branches = roots.slice().reverse();
41
+ while (branches.length) {
42
+ const branch = branches.pop()!;
43
+ const siblings = children.get(branch.id) ?? [];
44
+ for (let i = siblings.length - 1; i >= 0; i--) branches.push(siblings[i]);
45
+ const stack = [{ task: branch, emit: false }];
46
+ while (stack.length) {
47
+ const { task, emit } = stack.pop()!;
48
+ const deps = blockers.get(task.id)!;
49
+ if (!emit) {
50
+ if (reached.has(task.id)) continue;
51
+ reached.add(task.id);
52
+ stack.push({ task, emit: true });
53
+ for (let i = deps.length - 1; i >= 0; i--) {
54
+ if (!reached.has(deps[i])) stack.push({ task: byId.get(deps[i])!, emit: false });
55
+ }
56
+ continue;
57
+ }
58
+ const parent = rows.get(deps[0]);
59
+ const depth = parent ? parent.depth + 1 : 0;
60
+ const resumeParent = parent && ancestry[depth - 1] !== deps[0] ? deps[0] : undefined;
61
+ rows.set(task.id, {
62
+ depth, otherBlockers: deps.slice(1), resumeParent,
63
+ graph: !depth && !sharedGraph && isGraph(task.graph) ? task.graph : undefined,
64
+ });
65
+ if (resumeParent !== undefined) ancestry.length = 0;
66
+ ancestry.length = depth;
67
+ ancestry[depth] = task.id;
68
+ ordered.push(task);
69
+ }
70
+ }
71
+ // Replay predates cycle checks. Never hide a historical row we couldn't place in a tree.
72
+ for (const task of open) if (!rows.has(task.id)) ordered.push(task);
73
+ return { ordered, rows, sharedGraph };
74
+ }
@@ -0,0 +1,29 @@
1
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
2
+ import type { Task } from "../tool/types.ts";
3
+
4
+ export function isOpen(task: Task): boolean {
5
+ return task.status === "pending" || task.status === "in_progress";
6
+ }
7
+
8
+ // A legacy task can lack a uid. A made-up one would not identify it to other extensions.
9
+ export function uidSuffix(task: Task): string {
10
+ return typeof task.uid === "string" ? ` ${sanitizeTerminalText(task.uid)}` : "";
11
+ }
12
+
13
+ const isoDateTime = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/i;
14
+ const localTime = new Intl.DateTimeFormat(undefined, { dateStyle: "short", timeStyle: "short" });
15
+
16
+ /** A hint for this render, never a status transition or a stored field. */
17
+ export function waitingLabel(task: Task): string {
18
+ if (!isOpen(task)) return "";
19
+ const who = task.metadata?.waitsOn;
20
+ const party = typeof who === "string" ? sanitizeTerminalText(who).trim() : "";
21
+ const until = task.metadata?.until;
22
+ const time = typeof until === "string" && isoDateTime.test(until) ? Date.parse(until) : NaN;
23
+ return [party && `waits ${party}`, time > Date.now() && `until ${localTime.format(time)}`].filter(Boolean).join(" · ");
24
+ }
25
+
26
+ export function resultSuffix(task: Task): string {
27
+ const wait = waitingLabel(task);
28
+ return `${uidSuffix(task)}${wait ? ` ⏸ ${wait}` : ""}`;
29
+ }