pi-todo-ledger 0.3.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/CONTRACT.md CHANGED
@@ -26,6 +26,7 @@ The schema's `$defs/task` is the exact definition.
26
26
  | `metadata` | object, optional | Free-form fields; each top-level key is a namespace (see [Namespaces](#3-namespaces)). |
27
27
  | `points` | number from 0 to 10, optional | Effort estimate. |
28
28
  | `anchor` | non-empty string, optional | The check that shows the task is done, such as a test command. |
29
+ | `graph` | `single-loop`, `fan-out/fan-in`, `orchestrator-worker`, optional | Since 0.4.0: the work graph of the plan the task belongs to. Update replaces it; `null` on update clears it. A reader that finds no `graph` but a `metadata.graph` holding one of these names may treat it as the graph, as this extension does on replay and import. |
29
30
  | `evidence` | Evidence[], optional | Runs of checks, oldest first. |
30
31
 
31
32
  An evidence entry is `{ command, sha?, ref?, result, at }`:
@@ -70,6 +71,7 @@ Calls that change nothing write no entry: `list`, `get`, an `update` whose value
70
71
  ### Import into an empty list
71
72
 
72
73
  Since 0.2.0, `todo` accepts `{ "action": "import", "path": "handover.json" }` as an additive operation within v1.
74
+ Since 0.4.0, `{ "action": "import", "session": "<id, unique id prefix, or .jsonl path>" }` reads the snapshot from the newest `todo/v1` entry on another session's current branch instead, looking ids up in pi's session directories; a snapshot without `sessionId` takes the source session's id.
73
75
  The file contains the snapshot `data` itself, not the surrounding session entry.
74
76
  Import requires an empty list (even a tombstone counts as a task), unique task ids, a task for every `blockedBy` id, and a `nextId` greater than every task id.
75
77
  New snapshots carry the writer's `sessionId`. Import uses it to set each task's `origin.session`, replacing any previous source. If the snapshot lacks `sessionId`, import leaves `origin` untouched. All other task fields, including historical evidence timestamps, and the supplied `nextId` are preserved.
@@ -174,7 +176,7 @@ The extension calls `check(change)` for every call that would change the list: `
174
176
  On import, namespace validators see each relevant task as a `create`.
175
177
  Guard registration accepts an optional `imports: true` field within v1.
176
178
  If any registered guard has not opted in, the tool returns `Error: guard <id> refused: guard does not accept imports` without calling the guards or committing the list.
177
- Otherwise each guard sees one `op: "create"` with `params.action: "import"`, the original `path`, an empty `before`, and the full imported list in `after`.
179
+ Otherwise each guard sees one `op: "create"` with `params.action: "import"`, the original `path` or `session`, an empty `before`, and the full imported list in `after`.
178
180
  A guard that accepts imports must judge the tasks in `change.after`, not `change.params`: the arguments name the snapshot file but do not contain its tasks.
179
181
  A valid `update` that changes nothing, such as setting `in_progress` on a task already in progress after `/reload`, reaches the guards too, flagged `noop: true`: it is how an agent restates a task's state, and a guard may track it.
180
182
  `change` matches `$defs/change` in the schema and is a copy:
package/README.md CHANGED
@@ -10,6 +10,7 @@ On top of them it publishes a bookkeeping contract, [CONTRACT.md](CONTRACT.md):
10
10
  - **Change guards.** An extension that must approve whole calls (including creates without metadata, batches, deletes, and `clear`) registers an async guard with `todo:guard`; the tool awaits it before committing.
11
11
  - **Stable identity.** Each new task gets a `uid` that survives replay and import. Imported tasks also name their source session when the snapshot records it.
12
12
  - **Bookkeeping fields.** Tasks gain `points` (effort, 0 to 10), `anchor` (the check that shows the task is done), and `evidence` (an append-only list of check runs, each `{ command, sha?, ref?, result, at }`).
13
+ - **Work graph.** A task can name the graph of the plan it belongs to: `single-loop`, `fan-out/fan-in`, or `orchestrator-worker`. `list` groups open tasks by it.
13
14
 
14
15
  ## Replaces rpiv-todo
15
16
 
@@ -41,8 +42,34 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
41
42
  `evidence` items are appended after the existing ones; `at` defaults to the time of the call.
42
43
  `get` shows all three fields.
43
44
 
44
- To pick up another session's list, save the `data` from its latest `todo/v1` entry as JSON.
45
- In the new session, call `todo` before creating any tasks:
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
+
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.
54
+ One session often runs several plans, so each task carries its own.
55
+ An update replaces it and `graph: null` clears it.
56
+ When an open task names a graph, `list` shows open tasks under one `<graph>:` header per graph, then `no graph:`, then `closed:`.
57
+ A `metadata.graph` holding one of the three names, as earlier sessions wrote it, is read as `graph` when the list is restored or imported.
58
+
59
+ ```text
60
+ { "action": "create", "tasks": [{ "subject": "Port the parser", "graph": "fan-out/fan-in" }, { "subject": "Port the printer", "graph": "fan-out/fan-in" }] }
61
+ ```
62
+
63
+ To pick up another session's list, for example after its pane died, call `todo` in the new session before creating any tasks and name the old session by its id, a unique prefix of it, or its `.jsonl` file:
64
+
65
+ ```json
66
+ { "action": "import", "session": "01a2130c" }
67
+ ```
68
+
69
+ The tool looks the id up in pi's session directories (`PI_CODING_AGENT_SESSION_DIR` when set, and `sessions` under the agent directory, `PI_CODING_AGENT_DIR` or `~/.pi/agent`) and restores the newest `todo/v1` snapshot on that session's current branch.
70
+ An id that matches several sessions, or none, is refused.
71
+
72
+ A snapshot file works too: save the `data` from a `todo/v1` entry as JSON and import it by path.
46
73
 
47
74
  ```json
48
75
  { "action": "import", "path": "handover.json" }
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
@@ -14,7 +14,7 @@ rpiv-todo's, plus snapshot import and the bookkeeping fields `points`, `anchor`,
14
14
  | `get` | `id` | Returns one task with its `blockedBy` and reverse `blocks` edges. |
15
15
  | `delete` | `id` | Tombstones the task (`status: "deleted"`); it is not removed. |
16
16
  | `clear` | — | Drops every task and resets the id counter to `1`. |
17
- | `import` | `path` | Restores a `todo/v1` snapshot file into an empty list. |
17
+ | `import` | `path` or `session` | Restores a `todo/v1` snapshot file, or another session's latest snapshot, into an empty list. |
18
18
 
19
19
  ## Parameters
20
20
 
@@ -23,6 +23,7 @@ todo({
23
23
  action: "create" | "update" | "list" | "get" | "delete" | "clear" | "import",
24
24
 
25
25
  path?: string, // import only; relative to the session cwd
26
+ session?: string, // import only, instead of path: session id, unique id prefix, or .jsonl path
26
27
 
27
28
  // create-only (one-of: subject or tasks[])
28
29
  subject?: string, // required for single create
@@ -36,6 +37,7 @@ todo({
36
37
  metadata?: Record<string, unknown>,
37
38
  points?: number,
38
39
  anchor?: string,
40
+ graph?: string,
39
41
  evidence?: Evidence[],
40
42
  }>,
41
43
 
@@ -46,6 +48,7 @@ todo({
46
48
  metadata?: Record<string, unknown>, // on update, a null value deletes that key
47
49
  points?: number, // effort, 0 to 10; update replaces
48
50
  anchor?: string, // the check that shows the task is done; update replaces
51
+ graph?: "single-loop" | "fan-out/fan-in" | "orchestrator-worker" | null, // update replaces; null clears (update only)
49
52
  evidence?: Array<{ // check runs; update appends, never replaces
50
53
  command: string,
51
54
  ref?: string, // tool call id or child:<id>; ≤64 characters, no whitespace
@@ -72,7 +75,7 @@ todo({
72
75
  `create` takes either `subject` (one task) or `tasks[]` (several independent
73
76
  tasks). Passing both is rejected, even with a blank `subject`. Each item carries
74
77
  its own `description`, `activeForm`, `blockedBy`, `owner`, `metadata`, `points`,
75
- `anchor` and `evidence`; the same
78
+ `anchor`, `graph` and `evidence`; the same
76
79
  fields at the top level of a batch are rejected rather than dropped. The batch is validated first and committed
77
80
  together: one bad item fails the whole call and leaves the list unchanged.
78
81
  Items in `tasks[]` cannot `blockedBy` each other; those ids do not exist until
@@ -87,9 +90,22 @@ array.
87
90
  `update` replaces `points` and `anchor` and appends `evidence` items after the
88
91
  existing ones. No call removes an evidence entry or a field once set; `points: 0`
89
92
  is the lowest estimate. Pi drops a `null` passed for an optional parameter before
90
- the tool sees it, so `points: null` changes nothing.
93
+ the tool sees it, so `points: null` changes nothing. `graph` is the exception:
94
+ its schema admits `null`, and `update` with `graph: null` removes the field, along
95
+ with a `metadata.graph` that holds a graph name, so a reload does not bring it back.
96
+
97
+ `graph` accepts only `single-loop`, `fan-out/fan-in`, and `orchestrator-worker`.
98
+ On replay and import, a task without `graph` whose `metadata.graph` holds one of
99
+ these names is read with that graph; its metadata is kept as it was.
91
100
 
92
101
  `import` reads `{ "v": 1, "tasks": [...], "nextId": n }` from a JSON file and keeps every task field as stored.
102
+ With `session` instead of `path`, it reads the newest valid `todo/v1` entry on the
103
+ current branch (the one ending at the last entry) of another session's file. A
104
+ `session` ending in `.jsonl` or containing a path separator is a file path
105
+ relative to the cwd; anything else is a full session id or a unique id prefix,
106
+ matched against the `<time>_<id>.jsonl` files in `PI_CODING_AGENT_SESSION_DIR`
107
+ (when set) and `<agent dir>/sessions`, directly or one directory down. The calling
108
+ session is never matched. An exact id wins over prefix matches.
93
109
  If the file is unreadable or does not match the snapshot schema, the tool reports an error and leaves the list alone.
94
110
  Task ids must be unique, every `blockedBy` target must exist, and `nextId` must exceed the largest task id.
95
111
  The destination must contain no tasks, including tombstones.
@@ -141,6 +157,7 @@ tasks' `blockedBy` arrays.
141
157
  metadata?: Record<string, unknown>,
142
158
  points?: number,
143
159
  anchor?: string,
160
+ graph?: "single-loop" | "fan-out/fan-in" | "orchestrator-worker",
144
161
  evidence?: Array<{ command: string, sha?: string, ref?: string, result: "pass" | "fail", at: string }>,
145
162
  }>,
146
163
  nextId: number,
@@ -170,6 +187,10 @@ any disk writes.
170
187
 
171
188
  ## Content strings
172
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
+
173
194
  | Situation | `content[0].text` |
174
195
  | --- | --- |
175
196
  | Created | `Created #3: Write the parser (pending)` |
@@ -181,8 +202,9 @@ any disk writes.
181
202
  | Imported | `Imported 7 tasks` |
182
203
  | Cleared | `Cleared 7 tasks` |
183
204
  | `list` row | `[in_progress] #3 Write the parser (writing the parser) ⛓ #1,#2` |
205
+ | `list` when an open task names a graph | `<graph>:` then its open rows, for each graph in id order of first use; then `no graph:` and `closed:` with the remaining rows |
184
206
  | `list` with nothing to show | `No tasks` |
185
- | `get` | `#3 [pending] Write the parser`, then one indented line per set field: `description`, `activeForm`, `blockedBy`, `blocks`, `owner`, `points`, `anchor`, and one `evidence: pass npm test @abc1234 (2026-11-24T09:00:00.000Z)` line per run |
207
+ | `get` | `#3 [pending] Write the parser`, then one indented line per set field: `description`, `activeForm`, `blockedBy`, `blocks`, `owner`, `points`, `anchor`, `graph`, and one `evidence: pass npm test @abc1234 (2026-11-24T09:00:00.000Z)` line per run |
186
208
  | Any rejection | `Error: <message>` |
187
209
 
188
210
  The `No change` reply exists so a model that re-issues an identical update sees
@@ -195,16 +217,19 @@ that it was a no-op instead of a fresh `Updated #N`.
195
217
  | `subject required for create` | `create` without a non-blank `subject` and without `tasks[]`. |
196
218
  | `create requires subject or tasks[], not both` | `create` with both `subject` and `tasks[]`. |
197
219
  | `tasks[] must be non-empty` | `create` with `tasks: []`. |
198
- | `create with tasks[] takes <fields> on each item, not at the top level` | `create` with `tasks[]` and a top-level `description`, `activeForm`, `blockedBy`, `owner`, `metadata`, `points`, `anchor`, or `evidence`. |
220
+ | `create with tasks[] takes <fields> on each item, not at the top level` | `create` with `tasks[]` and a top-level `description`, `activeForm`, `blockedBy`, `owner`, `metadata`, `points`, `anchor`, `graph`, or `evidence`. |
199
221
  | `tasks[N]: subject required for create` | A batch item with a blank or missing subject. |
200
222
  | `blockedBy: #N not found` | `create` naming an unknown dependency. |
201
223
  | `blockedBy: #N is deleted` | `create` naming a tombstoned dependency. |
202
224
  | `blockedBy: #N is another item in this batch; create the prerequisite first, then the dependent with blockedBy` | A `tasks[]` item naming a sibling that this call would assign. |
203
225
  | `id required for update` / `get` / `delete` | `id` omitted. |
204
226
  | `#N not found` | No task with that id. |
205
- | `update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, points, anchor, evidence, addBlockedBy, or removeBlockedBy` | `update` with only an `id`. |
227
+ | `update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, points, anchor, graph, evidence, addBlockedBy, or removeBlockedBy` | `update` with only an `id`. |
206
228
  | `points must be a number from 0 to 10` | `points` out of range; prefixed `tasks[N]: ` for a batch item. |
207
229
  | `anchor must be a non-empty string` | Blank `anchor`. |
230
+ | `graph must be single-loop, fan-out/fan-in, or orchestrator-worker` | Any other `graph`, or `null` on create; on update the message adds ` (null clears)`; prefixed `tasks[N]: ` for a batch item. |
231
+ | `path or session required for import` / `import takes path or session, not both` | `import` with neither or both. |
232
+ | `no session <id> in <dirs>` / `session <id> is ambiguous: <ids>` / `session <id> has no todo/v1 snapshot` | `import` with a `session` that matches no session, several, or one without a snapshot (flagged `isError`, like every import failure). |
208
233
  | `evidence[N]: command must be a non-empty string` / `result must be "pass" or "fail"` / `sha must be a string` / `at must be an ISO 8601 time` / `at must not be in the future` | A malformed evidence item; `at` may lie at most five minutes after the call. |
209
234
  | `metadata.<ns> refused #N: <reason>` | A namespace validator refused the change (see [CONTRACT.md](../CONTRACT.md#3-namespaces)). |
210
235
  | `guard <id> refused: <reason>` / `guard <id> timed out after 10000 ms` | A change guard refused the call (see [CONTRACT.md](../CONTRACT.md#4-change-guards)). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.3.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",
@@ -64,6 +64,10 @@
64
64
  "type": "string",
65
65
  "minLength": 1
66
66
  },
67
+ "graph": {
68
+ "description": "The work graph of the plan the task belongs to.",
69
+ "enum": ["single-loop", "fan-out/fan-in", "orchestrator-worker"]
70
+ },
67
71
  "evidence": {
68
72
  "description": "Runs of checks, oldest first. Append-only: a later snapshot of the same task starts with the earlier snapshot's entries.",
69
73
  "type": "array",
@@ -1,18 +1,34 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import type { TaskState } from "../state/state.ts";
4
+ import { withLegacyGraph } from "../state/state-reducer.ts";
4
5
  import { isSnapshotV1 } from "./schema.ts";
6
+ import { readSessionSnapshot } from "./session-source.ts";
7
+
8
+ /** Where an import reads from: a snapshot file, or another session's latest snapshot entry. */
9
+ export interface ImportSource {
10
+ path?: string;
11
+ /** A full or unique-prefix session id, or a session `.jsonl` path. */
12
+ session?: string;
13
+ /** The importing session's id, never matched by `session`. */
14
+ self: string;
15
+ }
5
16
 
6
17
  /** Prepare the imported state without writing it; the caller holds the session lock. */
7
- export async function readImport(before: TaskState, cwd: string, path?: string, signal?: AbortSignal): Promise<TaskState> {
18
+ export async function readImport(before: TaskState, cwd: string, source: ImportSource, signal?: AbortSignal): Promise<TaskState> {
8
19
  if (before.tasks.length) throw new Error(`import needs an empty list; this list has ${before.tasks.length} tasks`);
9
- if (!path) throw new Error("path required for import");
10
- const raw = await readFile(resolve(cwd, path), { encoding: "utf8", signal });
20
+ const { path, session } = source;
21
+ if (path && session) throw new Error("import takes path or session, not both");
11
22
  let snapshot: unknown;
12
- try {
13
- snapshot = JSON.parse(raw);
14
- } catch {
15
- throw new Error("import file is not valid JSON");
23
+ if (session) snapshot = await readSessionSnapshot(session, cwd, source.self, signal);
24
+ else if (!path) throw new Error("path or session required for import");
25
+ else {
26
+ const raw = await readFile(resolve(cwd, path), { encoding: "utf8", signal });
27
+ try {
28
+ snapshot = JSON.parse(raw);
29
+ } catch {
30
+ throw new Error("import file is not valid JSON");
31
+ }
16
32
  }
17
33
  if (!isSnapshotV1(snapshot)) throw new Error("import file does not match the todo/v1 snapshot schema");
18
34
  const ids = new Set<number>();
@@ -31,7 +47,7 @@ export async function readImport(before: TaskState, cwd: string, path?: string,
31
47
  if (!ids.has(dep)) throw new Error(`#${task.id} blockedBy: #${dep} not found`);
32
48
  }
33
49
  }
34
- const session = snapshot.sessionId;
35
- const tasks = session ? snapshot.tasks.map(task => ({ ...task, origin: { session } })) : snapshot.tasks;
50
+ const origin = snapshot.sessionId;
51
+ const tasks = snapshot.tasks.map(task => withLegacyGraph(origin ? { ...task, origin: { session: origin } } : task));
36
52
  return { tasks, nextId: snapshot.nextId };
37
53
  }
@@ -0,0 +1,82 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve, sep } from "node:path";
4
+ import { SNAPSHOT_ENTRY_TYPE } from "./contract.ts";
5
+ import { isSnapshotV1 } from "./schema.ts";
6
+
7
+ /** Pi's session directories: `PI_CODING_AGENT_SESSION_DIR` when set, and `<agent dir>/sessions`. */
8
+ async function sessionRoots(): Promise<string[]> {
9
+ const { getAgentDir } = await import("@earendil-works/pi-coding-agent");
10
+ const custom = process.env.PI_CODING_AGENT_SESSION_DIR;
11
+ const roots = [...(custom ? [custom.replace(/^~(?=$|[\\/])/, homedir())] : []), join(getAgentDir(), "sessions")];
12
+ return [...new Set(roots.map((root) => resolve(root)))];
13
+ }
14
+
15
+ /** Session files (`<time>_<id>.jsonl`) directly in a root or one directory below it, by session id. */
16
+ async function sessionFiles(roots: string[], signal?: AbortSignal): Promise<Map<string, string>> {
17
+ const files = new Map<string, string>();
18
+ const add = (dir: string, name: string) => {
19
+ const match = /_([^_]+)\.jsonl$/.exec(name);
20
+ if (match && !files.has(match[1]!)) files.set(match[1]!, join(dir, name));
21
+ };
22
+ const list = (dir: string) => readdir(dir, { withFileTypes: true }).catch(() => []);
23
+ for (const root of roots) {
24
+ for (const entry of await list(root)) {
25
+ signal?.throwIfAborted();
26
+ if (entry.isFile()) add(root, entry.name);
27
+ else if (entry.isDirectory()) {
28
+ const dir = join(root, entry.name);
29
+ for (const child of await list(dir)) if (child.isFile()) add(dir, child.name);
30
+ }
31
+ }
32
+ }
33
+ return files;
34
+ }
35
+
36
+ /** The session file a `session` import names: a `.jsonl` path, or a full or unique-prefix session id. */
37
+ async function resolveSessionFile(session: string, cwd: string, self: string, signal?: AbortSignal): Promise<string> {
38
+ if (session.endsWith(".jsonl") || session.includes("/") || session.includes(sep)) return resolve(cwd, session);
39
+ const roots = await sessionRoots();
40
+ const files = await sessionFiles(roots, signal);
41
+ files.delete(self);
42
+ const exact = files.get(session);
43
+ if (exact) return exact;
44
+ const matches = [...files.keys()].filter((id) => id.startsWith(session)).sort();
45
+ if (matches.length === 0) throw new Error(`no session ${session} in ${roots.join(", ")}`);
46
+ if (matches.length > 1) throw new Error(`session ${session} is ambiguous: ${matches.join(", ")}`);
47
+ return files.get(matches[0]!)!;
48
+ }
49
+
50
+ type Entry = { type?: string; id?: string; parentId?: string | null; customType?: string; data?: unknown };
51
+
52
+ /**
53
+ * The newest valid `todo/v1` snapshot on the current branch of a session file
54
+ * (the branch ending at its last entry), stamped with the source session's id
55
+ * when the snapshot does not carry one. Unvalidated beyond the schema; the
56
+ * caller checks it as it checks a snapshot file.
57
+ */
58
+ export async function readSessionSnapshot(session: string, cwd: string, self: string, signal?: AbortSignal): Promise<unknown> {
59
+ const file = await resolveSessionFile(session, cwd, self, signal);
60
+ const entries: Entry[] = [];
61
+ for (const line of (await readFile(file, { encoding: "utf8", signal })).split("\n")) {
62
+ if (!line.trim()) continue;
63
+ try {
64
+ entries.push(JSON.parse(line) as Entry);
65
+ } catch {
66
+ // Pi skips a malformed line too.
67
+ }
68
+ }
69
+ const header = entries.find((entry) => entry.type === "session");
70
+ const id = header?.id ?? /_([^_]+)\.jsonl$/.exec(file)?.[1] ?? session;
71
+ const byId = new Map(entries.filter((entry) => entry.id && entry.type !== "session").map((entry) => [entry.id!, entry]));
72
+ let cursor = [...byId.values()].at(-1);
73
+ const seen = new Set<string>();
74
+ while (cursor && !seen.has(cursor.id!)) {
75
+ seen.add(cursor.id!);
76
+ if (cursor.type === "custom" && cursor.customType === SNAPSHOT_ENTRY_TYPE && isSnapshotV1(cursor.data)) {
77
+ return cursor.data.sessionId ? cursor.data : { ...cursor.data, sessionId: id };
78
+ }
79
+ cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;
80
+ }
81
+ throw new Error(`session ${id} has no todo/v1 snapshot`);
82
+ }
@@ -2,6 +2,7 @@ import { SNAPSHOT_ENTRY_TYPE } from "../ledger/contract.ts";
2
2
  import { isSnapshotV1 } from "../ledger/schema.ts";
3
3
  import { LEGACY_STATE_ENTRY_TYPE, type Task, type TaskDetails, type TaskStatus, TOOL_NAME } from "../tool/types.ts";
4
4
  import { EMPTY_STATE, type TaskState } from "./state.ts";
5
+ import { withLegacyGraph } from "./state-reducer.ts";
5
6
 
6
7
  const TASK_STATUSES: ReadonlySet<unknown> = new Set<TaskStatus>(["pending", "in_progress", "completed", "deleted"]);
7
8
 
@@ -39,7 +40,7 @@ export function isTaskDetails(value: unknown): value is TaskDetails {
39
40
 
40
41
  /** Fresh `TaskState` from a persisted snapshot — deep-copies the tasks so replay never aliases branch data. */
41
42
  function stateOf(details: { tasks: Task[]; nextId: number }): TaskState {
42
- return { tasks: structuredClone(details.tasks), nextId: details.nextId };
43
+ return { tasks: structuredClone(details.tasks).map(withLegacyGraph), nextId: details.nextId };
43
44
  }
44
45
 
45
46
  /**
@@ -2,6 +2,8 @@ import { randomBytes } from "node:crypto";
2
2
  import {
3
3
  type Evidence,
4
4
  type EvidenceInput,
5
+ GRAPHS,
6
+ isGraph,
5
7
  POINTS_MAX,
6
8
  POINTS_MIN,
7
9
  type Task,
@@ -72,6 +74,7 @@ const BATCH_ITEM_FIELDS = [
72
74
  "metadata",
73
75
  "points",
74
76
  "anchor",
77
+ "graph",
75
78
  "evidence",
76
79
  ] as const;
77
80
 
@@ -83,7 +86,12 @@ const BATCH_ITEM_FIELDS = [
83
86
  /** How far ahead of the call time an evidence `at` may lie, for clock skew between machines. */
84
87
  export const EVIDENCE_FUTURE_TOLERANCE_MS = 5 * 60_000;
85
88
 
86
- function validateLedgerFields(spec: TaskMutationParams, now: string): string | undefined {
89
+ const GRAPH_ERROR = `graph must be ${GRAPHS.slice(0, -1).join(", ")}, or ${GRAPHS.at(-1)}`;
90
+
91
+ function validateLedgerFields(spec: TaskMutationParams, now: string, clearable = false): string | undefined {
92
+ if (spec.graph !== undefined && !isGraph(spec.graph) && !(clearable && spec.graph === null)) {
93
+ return clearable ? `${GRAPH_ERROR} (null clears)` : GRAPH_ERROR;
94
+ }
87
95
  if (spec.points !== undefined) {
88
96
  const p = spec.points;
89
97
  if (typeof p !== "number" || !Number.isFinite(p) || p < POINTS_MIN || p > POINTS_MAX) {
@@ -132,6 +140,17 @@ function toEvidence(input: EvidenceInput, now: string): Evidence {
132
140
  };
133
141
  }
134
142
 
143
+ /**
144
+ * Read a legacy `metadata.graph` holding a valid graph name as the task's `graph`,
145
+ * unless the task names one itself. Metadata stays as it was, so readers of the
146
+ * old key keep working and recorded history is not rewritten.
147
+ */
148
+ export function withLegacyGraph(task: Task): Task {
149
+ if (task.graph !== undefined) return task;
150
+ const legacy = task.metadata?.graph;
151
+ return isGraph(legacy) ? { ...task, graph: legacy } : task;
152
+ }
153
+
135
154
  function asCreateItem(value: unknown): TaskMutationParams | undefined {
136
155
  if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
137
156
  return value as TaskMutationParams;
@@ -151,8 +170,9 @@ function buildCreatedTask(id: number, spec: TaskMutationParams, subject: string,
151
170
  if (spec.metadata) newTask.metadata = { ...spec.metadata };
152
171
  if (spec.points !== undefined) newTask.points = spec.points;
153
172
  if (spec.anchor !== undefined) newTask.anchor = spec.anchor;
173
+ if (isGraph(spec.graph)) newTask.graph = spec.graph;
154
174
  if (spec.evidence?.length) newTask.evidence = spec.evidence.map((e) => toEvidence(e, now));
155
- return newTask;
175
+ return withLegacyGraph(newTask);
156
176
  }
157
177
 
158
178
  function validateCreateBlockedBy(
@@ -203,6 +223,7 @@ function taskChanged(before: Task, after: Task): boolean {
203
223
  before.owner !== after.owner ||
204
224
  before.points !== after.points ||
205
225
  before.anchor !== after.anchor ||
226
+ before.graph !== after.graph ||
206
227
  (before.evidence?.length ?? 0) !== (after.evidence?.length ?? 0) ||
207
228
  !sameNumberList(before.blockedBy, after.blockedBy) ||
208
229
  !sameRecord(before.metadata, after.metadata)
@@ -298,15 +319,16 @@ export function applyTaskMutation(
298
319
  params.metadata !== undefined ||
299
320
  params.points !== undefined ||
300
321
  params.anchor !== undefined ||
322
+ params.graph !== undefined ||
301
323
  (params.evidence && params.evidence.length > 0) ||
302
324
  (params.addBlockedBy && params.addBlockedBy.length > 0) ||
303
325
  (params.removeBlockedBy && params.removeBlockedBy.length > 0);
304
326
  if (!hasMutation)
305
327
  return errorResult(
306
328
  state,
307
- "update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, points, anchor, evidence, addBlockedBy, or removeBlockedBy",
329
+ "update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, points, anchor, graph, evidence, addBlockedBy, or removeBlockedBy",
308
330
  );
309
- const ledgerError = validateLedgerFields(params, now);
331
+ const ledgerError = validateLedgerFields(params, now, true);
310
332
  if (ledgerError) return errorResult(state, ledgerError);
311
333
 
312
334
  let newStatus = current.status;
@@ -352,16 +374,23 @@ export function applyTaskMutation(
352
374
  if (params.owner !== undefined) updated.owner = params.owner;
353
375
  if (params.points !== undefined) updated.points = params.points;
354
376
  if (params.anchor !== undefined) updated.anchor = params.anchor;
377
+ if (params.graph === null) delete updated.graph;
378
+ else if (isGraph(params.graph)) updated.graph = params.graph;
355
379
  if (params.evidence?.length) {
356
380
  updated.evidence = [...(current.evidence ?? []), ...params.evidence.map((e) => toEvidence(e, now))];
357
381
  }
358
382
  if (newBlockedBy.length) updated.blockedBy = newBlockedBy;
359
383
  else delete updated.blockedBy;
384
+ if (params.graph === null && isGraph(newMetadata?.graph)) {
385
+ // Clearing the graph also clears the legacy key that load would read back as one.
386
+ const { graph: _legacy, ...rest } = newMetadata;
387
+ newMetadata = Object.keys(rest).length ? rest : undefined;
388
+ }
360
389
  if (newMetadata === undefined) delete updated.metadata;
361
390
  else updated.metadata = newMetadata;
362
391
 
363
392
  const newTasks = [...state.tasks];
364
- newTasks[idx] = updated;
393
+ newTasks[idx] = withLegacyGraph(updated);
365
394
  return {
366
395
  state: { tasks: newTasks, nextId: state.nextId },
367
396
  op: {
@@ -369,7 +398,7 @@ export function applyTaskMutation(
369
398
  id: updated.id,
370
399
  fromStatus: current.status,
371
400
  toStatus: newStatus,
372
- changed: taskChanged(current, updated),
401
+ changed: taskChanged(current, newTasks[idx]),
373
402
  },
374
403
  };
375
404
  }
@@ -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
  // ---------------------------------------------------------------------------
@@ -69,7 +68,7 @@ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
69
68
  'To change a task\'s status, call update with the task id and the target status, e.g. {"action":"update","id":3,"status":"completed"} or {"action":"update","id":3,"status":"in_progress","activeForm":"writing tests"}. status is the field that changes the task; an update without a mutable field (status or another) is rejected.',
70
69
  "Use blockedBy to express dependencies (A is blocked by B). On create, pass blockedBy as the initial set. On update, use addBlockedBy / removeBlockedBy (additive merge — do not resend the full array). Cycles are rejected.",
71
70
  "To create several independent tasks at once, pass create with tasks: [{subject}, ...]. Do not also pass subject. tasks[] cannot blockedBy each other (ids do not exist until the call commits); create the prerequisite first, then the dependent with blockedBy. Dependency chains stay single-create.",
72
- "Use import with a snapshot file path to restore a handed-over list into an empty session list.",
71
+ "Use import with a snapshot file path, or session (an earlier session's id), to restore a handed-over list into an empty session list.",
73
72
  "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
74
73
  "Subject must be short and imperative (e.g. 'Research existing tool'); description is for long-form detail. activeForm is a present-continuous label shown while in_progress.",
75
74
  "Optional bookkeeping fields: points (effort, 0 to 10), anchor (the check that shows the task is done, e.g. a test command), and evidence (runs of checks, each {command, sha?, result: pass|fail, at?}). On update, points and anchor replace; evidence is appended, never replaced.",
@@ -113,7 +112,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
113
112
  let result: ApplyResult;
114
113
  if (action === "import") {
115
114
  try {
116
- result = { state: await readImport(before, ctx.cwd, input.path, signal), op: { kind: "import" } };
115
+ result = { state: await readImport(before, ctx.cwd, { path: input.path, session: input.session, self: sessionId }, signal), op: { kind: "import" } };
117
116
  } catch (error) {
118
117
  return refuse(action, input, before, signal?.aborted ? ABORTED : String(error instanceof Error ? error.message : error));
119
118
  }
@@ -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,28 +1,53 @@
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
17
  /**
19
- * Multi-line presentation for the `get` action. Order of rows is pinned by
20
- * pre-refactor `todo.ts:354-376` — description, activeForm, blockedBy, blocks,
21
- * owner — so envelope-level snapshot tests stay byte-equivalent.
18
+ * `list` body. When an open task names a graph, open tasks are grouped under
19
+ * `<graph>:` headers in first-seen order, then `no graph:`, then `closed:` for
20
+ * the rest; otherwise one line per task in id order.
21
+ */
22
+ function formatList(view: readonly Task[]): string {
23
+ if (!view.some((t) => isOpen(t) && t.graph)) return view.map(formatListLine).join("\n");
24
+ const groups = new Map<string, Task[]>();
25
+ const closed: Task[] = [];
26
+ for (const t of view) {
27
+ if (!isOpen(t)) closed.push(t);
28
+ else {
29
+ const key = t.graph ?? "";
30
+ groups.set(key, [...(groups.get(key) ?? []), t]);
31
+ }
32
+ }
33
+ const ungrouped = groups.get("");
34
+ groups.delete("");
35
+ const lines: string[] = [];
36
+ const section = (header: string, tasks: Task[] | undefined) => {
37
+ if (tasks?.length) lines.push(`${header}:`, ...tasks.map(formatListLine));
38
+ };
39
+ for (const [graph, tasks] of groups) section(graph, tasks);
40
+ section("no graph", ungrouped);
41
+ section("closed", closed);
42
+ return lines.join("\n");
43
+ }
44
+
45
+ /**
46
+ * `get` shows the local id and stable uid on the first line, followed by the set fields.
22
47
  */
23
48
  function formatGetLines(task: Task, state: TaskState): string {
24
49
  const blocks = deriveBlocks(state.tasks).get(task.id) ?? [];
25
- const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}`];
50
+ const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}${resultSuffix(task)}`];
26
51
  if (task.description) lines.push(` description: ${sanitizeTerminalText(task.description)}`);
27
52
  if (task.activeForm) lines.push(` activeForm: ${sanitizeTerminalText(task.activeForm)}`);
28
53
  if (task.blockedBy?.length) {
@@ -34,6 +59,7 @@ function formatGetLines(task: Task, state: TaskState): string {
34
59
  if (task.owner) lines.push(` owner: ${sanitizeTerminalText(task.owner)}`);
35
60
  if (task.points !== undefined) lines.push(` points: ${task.points}`);
36
61
  if (task.anchor) lines.push(` anchor: ${sanitizeTerminalText(task.anchor)}`);
62
+ if (task.graph) lines.push(` graph: ${task.graph}`);
37
63
  for (const e of task.evidence ?? []) {
38
64
  const sha = e.sha ? ` @${sanitizeTerminalText(e.sha)}` : "";
39
65
  lines.push(` evidence: ${e.result} ${sanitizeTerminalText(e.command)}${sha} (${sanitizeTerminalText(e.at)})`);
@@ -44,8 +70,6 @@ function formatGetLines(task: Task, state: TaskState): string {
44
70
  /**
45
71
  * Pure formatter: `(op, state) → string`. Closed switch on `op.kind` —
46
72
  * adding a new `Op` variant fails to compile here until a branch is added.
47
- * The strings on each branch are byte-equivalent to pre-refactor `todo.ts`
48
- * reducer output.
49
73
  */
50
74
  export function formatContent(op: Op, state: TaskState): string {
51
75
  switch (op.kind) {
@@ -55,16 +79,17 @@ export function formatContent(op: Op, state: TaskState): string {
55
79
  .map((id) => {
56
80
  const created = state.tasks.find((x) => x.id === id);
57
81
  if (!created) return `Created #${id}`;
58
- return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)`;
82
+ return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)${resultSuffix(created)}`;
59
83
  })
60
84
  .join("\n");
61
85
  }
62
86
  case "update": {
87
+ const suffix = resultSuffix(state.tasks.find(t => t.id === op.id)!);
63
88
  if (!op.changed) {
64
- 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}`;
65
90
  }
66
91
  const transition = op.fromStatus !== op.toStatus ? ` (${op.fromStatus} → ${op.toStatus})` : "";
67
- return `Updated #${op.id}${transition}`;
92
+ return `Updated #${op.id}${transition}${suffix}`;
68
93
  }
69
94
  case "delete":
70
95
  return `Deleted #${op.id}: ${sanitizeTerminalText(op.subject)}`;
@@ -76,7 +101,7 @@ export function formatContent(op: Op, state: TaskState): string {
76
101
  let view = state.tasks;
77
102
  if (!op.includeDeleted) view = view.filter((t) => t.status !== "deleted");
78
103
  if (op.statusFilter) view = view.filter((t) => t.status === op.statusFilter);
79
- return view.length === 0 ? "No tasks" : view.map(formatListLine).join("\n");
104
+ return view.length === 0 ? "No tasks" : formatList(view);
80
105
  }
81
106
  case "get":
82
107
  return formatGetLines(op.task, state);
package/src/tool/types.ts CHANGED
@@ -56,6 +56,12 @@ export interface EvidenceInput {
56
56
  at?: string;
57
57
  }
58
58
 
59
+ /** The work graphs a plan can name (pi-straw-boss prompts/planning.md §1). */
60
+ export const GRAPHS = ["single-loop", "fan-out/fan-in", "orchestrator-worker"] as const;
61
+ export type Graph = (typeof GRAPHS)[number];
62
+ export const isGraph = (value: unknown): value is Graph =>
63
+ typeof value === "string" && (GRAPHS as readonly string[]).includes(value);
64
+
59
65
  /** Inclusive bounds of `Task.points`. */
60
66
  export const POINTS_MIN = 0;
61
67
  export const POINTS_MAX = 10;
@@ -75,6 +81,8 @@ export interface Task {
75
81
  points?: number;
76
82
  /** The check that shows this task is done, e.g. a test command. */
77
83
  anchor?: string;
84
+ /** The work graph of the plan this task belongs to. */
85
+ graph?: Graph;
78
86
  /** Runs of checks, oldest first. Append-only. */
79
87
  evidence?: Evidence[];
80
88
  }
@@ -108,6 +116,7 @@ export interface CreateTaskInput {
108
116
  metadata?: Record<string, unknown>;
109
117
  points?: number;
110
118
  anchor?: string;
119
+ graph?: string;
111
120
  evidence?: EvidenceInput[];
112
121
  }
113
122
 
@@ -124,9 +133,12 @@ export interface TaskMutationParams {
124
133
  metadata?: Record<string, unknown>;
125
134
  points?: number;
126
135
  anchor?: string;
136
+ /** A graph name; `null` clears it on update. */
137
+ graph?: string | null;
127
138
  evidence?: EvidenceInput[];
128
139
  id?: number;
129
140
  path?: string;
141
+ session?: string;
130
142
  includeDeleted?: boolean;
131
143
  /** Batch create items. One-of with `subject` on `create`. */
132
144
  tasks?: CreateTaskInput[];
@@ -174,12 +186,14 @@ const CreateTaskInputSchema = Type.Object({
174
186
  ),
175
187
  points: Type.Optional(PointsSchema("Effort points, 0 to 10")),
176
188
  anchor: Type.Optional(AnchorSchema("The check that shows this task is done, e.g. a test command")),
189
+ graph: Type.Optional(Type.String()),
177
190
  evidence: Type.Optional(EvidenceSchema("Check runs already recorded for this task")),
178
191
  });
179
192
 
180
193
  export const TodoParamsSchema = Type.Object({
181
194
  action: StringEnum(["create", "update", "list", "get", "delete", "clear", "import"] as const),
182
195
  path: Type.Optional(Type.String({ description: "Snapshot file (import only); relative to the session cwd" })),
196
+ session: Type.Optional(Type.String({ description: "Or a session id, id prefix, or .jsonl (import only)" })),
183
197
  subject: Type.Optional(
184
198
  Type.String({
185
199
  description: "Task subject line (required for create unless tasks[] is set)",
@@ -224,6 +238,11 @@ export const TodoParamsSchema = Type.Object({
224
238
  "The check that shows this task is done, e.g. a test command (create or update; update replaces)",
225
239
  ),
226
240
  ),
241
+ graph: Type.Optional(
242
+ Type.Union([Type.String(), Type.Null()], {
243
+ description: "single-loop, fan-out/fan-in, or orchestrator-worker; null clears",
244
+ }),
245
+ ),
227
246
  evidence: Type.Optional(
228
247
  EvidenceSchema(
229
248
  "Check runs to record: the initial list on create; on update, appended to the task's evidence (never replaced or removed)",
@@ -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
+ }