pi-todo-ledger 0.2.0 → 0.4.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
@@ -15,6 +15,8 @@ The schema's `$defs/task` is the exact definition.
15
15
  | Property | Type | Meaning |
16
16
  | --- | --- | --- |
17
17
  | `id` | integer ≥ 1 | Unique within one list, that is one branch of one session. Ids are not stable identities: `clear` restarts them at 1, and two branches of a session (after `/tree`) can give the same id to different tasks. |
18
+ | `uid` | string, optional | A random `t_` plus ten lowercase base32 characters. Create assigns it once; update, replay, and import retain it. Older tasks keep no uid. |
19
+ | `origin` | object, optional | On import from a known session, `{ session }` identifies the session that wrote the imported snapshot. |
18
20
  | `subject` | string | Short imperative line. |
19
21
  | `status` | `pending`, `in_progress`, `completed`, `deleted` | `deleted` is a tombstone that stays in the list. |
20
22
  | `description` | string, optional | Long-form detail. |
@@ -24,13 +26,15 @@ The schema's `$defs/task` is the exact definition.
24
26
  | `metadata` | object, optional | Free-form fields; each top-level key is a namespace (see [Namespaces](#3-namespaces)). |
25
27
  | `points` | number from 0 to 10, optional | Effort estimate. |
26
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. |
27
30
  | `evidence` | Evidence[], optional | Runs of checks, oldest first. |
28
31
 
29
- An evidence entry is `{ command, sha?, result, at }`:
32
+ An evidence entry is `{ command, sha?, ref?, result, at }`:
30
33
 
31
34
  | Property | Type | Meaning |
32
35
  | --- | --- | --- |
33
36
  | `command` | non-empty string | The check that ran. |
37
+ | `ref` | string, optional | Tool call id of the run, or `child:<id>`; up to 64 characters without whitespace. |
34
38
  | `sha` | string, optional | Revision the check ran on, such as a git commit SHA. |
35
39
  | `result` | `pass` or `fail` | How the run ended. |
36
40
  | `at` | string | ISO 8601 time of the run in UTC, as `Date.prototype.toISOString` writes it. The tool converts the caller's time to that form, fills in the call time when the caller leaves it out, and rejects a time more than five minutes after the call. |
@@ -67,9 +71,10 @@ Calls that change nothing write no entry: `list`, `get`, an `update` whose value
67
71
  ### Import into an empty list
68
72
 
69
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.
70
75
  The file contains the snapshot `data` itself, not the surrounding session entry.
71
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.
72
- It preserves all task fields, including historical evidence timestamps, and commits one `todo/v1` entry with the supplied `nextId`.
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.
73
78
 
74
79
  ### Migration from rpiv-todo
75
80
 
@@ -171,7 +176,7 @@ The extension calls `check(change)` for every call that would change the list: `
171
176
  On import, namespace validators see each relevant task as a `create`.
172
177
  Guard registration accepts an optional `imports: true` field within v1.
173
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.
174
- 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`.
175
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.
176
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.
177
182
  `change` matches `$defs/change` in the schema and is a copy:
package/README.md CHANGED
@@ -8,7 +8,9 @@ On top of them it publishes a bookkeeping contract, [CONTRACT.md](CONTRACT.md):
8
8
  - **Change event.** `todo:changed` on `pi.events` carries `{ v: 1, sessionId, tasks }` after every change and when a session's list is restored.
9
9
  - **Namespace validators.** An extension that owns `metadata.<ns>` registers a validator with `todo:namespace`; the tool runs it before committing and returns its refusal as a tool error.
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
- - **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?, result, at }`).
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
+ - **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.
12
14
 
13
15
  ## Replaces rpiv-todo
14
16
 
@@ -40,8 +42,26 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
40
42
  `evidence` items are appended after the existing ones; `at` defaults to the time of the call.
41
43
  `get` shows all three fields.
42
44
 
43
- To pick up another session's list, save the `data` from its latest `todo/v1` entry as JSON.
44
- In the new session, call `todo` before creating any tasks:
45
+ `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
+ One session often runs several plans, so each task carries its own.
47
+ An update replaces it and `graph: null` clears it.
48
+ When an open task names a graph, `list` shows open tasks under one `<graph>:` header per graph, then `no graph:`, then `closed:`.
49
+ 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.
50
+
51
+ ```text
52
+ { "action": "create", "tasks": [{ "subject": "Port the parser", "graph": "fan-out/fan-in" }, { "subject": "Port the printer", "graph": "fan-out/fan-in" }] }
53
+ ```
54
+
55
+ 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:
56
+
57
+ ```json
58
+ { "action": "import", "session": "01a2130c" }
59
+ ```
60
+
61
+ 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.
62
+ An id that matches several sessions, or none, is refused.
63
+
64
+ A snapshot file works too: save the `data` from a `todo/v1` entry as JSON and import it by path.
45
65
 
46
66
  ```json
47
67
  { "action": "import", "path": "handover.json" }
@@ -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,8 +48,10 @@ 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,
54
+ ref?: string, // tool call id or child:<id>; ≤64 characters, no whitespace
51
55
  sha?: string, // revision the check ran on
52
56
  result: "pass" | "fail",
53
57
  at?: string, // ISO 8601; stored in UTC; defaults to the time of the call
@@ -71,7 +75,7 @@ todo({
71
75
  `create` takes either `subject` (one task) or `tasks[]` (several independent
72
76
  tasks). Passing both is rejected, even with a blank `subject`. Each item carries
73
77
  its own `description`, `activeForm`, `blockedBy`, `owner`, `metadata`, `points`,
74
- `anchor` and `evidence`; the same
78
+ `anchor`, `graph` and `evidence`; the same
75
79
  fields at the top level of a batch are rejected rather than dropped. The batch is validated first and committed
76
80
  together: one bad item fails the whole call and leaves the list unchanged.
77
81
  Items in `tasks[]` cannot `blockedBy` each other; those ids do not exist until
@@ -86,9 +90,22 @@ array.
86
90
  `update` replaces `points` and `anchor` and appends `evidence` items after the
87
91
  existing ones. No call removes an evidence entry or a field once set; `points: 0`
88
92
  is the lowest estimate. Pi drops a `null` passed for an optional parameter before
89
- 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.
90
100
 
91
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.
92
109
  If the file is unreadable or does not match the snapshot schema, the tool reports an error and leaves the list alone.
93
110
  Task ids must be unique, every `blockedBy` target must exist, and `nextId` must exceed the largest task id.
94
111
  The destination must contain no tasks, including tombstones.
@@ -129,6 +146,8 @@ tasks' `blockedBy` arrays.
129
146
  params: Record<string, unknown>,
130
147
  tasks: Array<{
131
148
  id: number,
149
+ uid?: string, // stable across branches and import
150
+ origin?: { session: string }, // source session on import, when known
132
151
  subject: string,
133
152
  description?: string,
134
153
  activeForm?: string,
@@ -138,7 +157,8 @@ tasks' `blockedBy` arrays.
138
157
  metadata?: Record<string, unknown>,
139
158
  points?: number,
140
159
  anchor?: string,
141
- evidence?: Array<{ command: string, sha?: string, result: "pass" | "fail", at: string }>,
160
+ graph?: "single-loop" | "fan-out/fan-in" | "orchestrator-worker",
161
+ evidence?: Array<{ command: string, sha?: string, ref?: string, result: "pass" | "fail", at: string }>,
142
162
  }>,
143
163
  nextId: number,
144
164
  error?: string, // present only on a rejected call
@@ -178,8 +198,9 @@ any disk writes.
178
198
  | Imported | `Imported 7 tasks` |
179
199
  | Cleared | `Cleared 7 tasks` |
180
200
  | `list` row | `[in_progress] #3 Write the parser (writing the parser) ⛓ #1,#2` |
201
+ | `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 |
181
202
  | `list` with nothing to show | `No tasks` |
182
- | `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 |
203
+ | `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 |
183
204
  | Any rejection | `Error: <message>` |
184
205
 
185
206
  The `No change` reply exists so a model that re-issues an identical update sees
@@ -192,16 +213,19 @@ that it was a no-op instead of a fresh `Updated #N`.
192
213
  | `subject required for create` | `create` without a non-blank `subject` and without `tasks[]`. |
193
214
  | `create requires subject or tasks[], not both` | `create` with both `subject` and `tasks[]`. |
194
215
  | `tasks[] must be non-empty` | `create` with `tasks: []`. |
195
- | `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`. |
216
+ | `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`. |
196
217
  | `tasks[N]: subject required for create` | A batch item with a blank or missing subject. |
197
218
  | `blockedBy: #N not found` | `create` naming an unknown dependency. |
198
219
  | `blockedBy: #N is deleted` | `create` naming a tombstoned dependency. |
199
220
  | `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. |
200
221
  | `id required for update` / `get` / `delete` | `id` omitted. |
201
222
  | `#N not found` | No task with that id. |
202
- | `update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, points, anchor, evidence, addBlockedBy, or removeBlockedBy` | `update` with only an `id`. |
223
+ | `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`. |
203
224
  | `points must be a number from 0 to 10` | `points` out of range; prefixed `tasks[N]: ` for a batch item. |
204
225
  | `anchor must be a non-empty string` | Blank `anchor`. |
226
+ | `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. |
227
+ | `path or session required for import` / `import takes path or session, not both` | `import` with neither or both. |
228
+ | `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). |
205
229
  | `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. |
206
230
  | `metadata.<ns> refused #N: <reason>` | A namespace validator refused the change (see [CONTRACT.md](../CONTRACT.md#3-namespaces)). |
207
231
  | `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.2.0",
3
+ "version": "0.4.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",
@@ -10,6 +10,7 @@
10
10
  "required": ["v", "tasks", "nextId"],
11
11
  "properties": {
12
12
  "v": { "const": 1 },
13
+ "sessionId": { "type": "string", "minLength": 1 },
13
14
  "tasks": {
14
15
  "description": "Every task in id order, including deleted tombstones.",
15
16
  "type": "array",
@@ -30,6 +31,8 @@
30
31
  "required": ["id", "subject", "status"],
31
32
  "properties": {
32
33
  "id": { "type": "integer", "minimum": 1 },
34
+ "uid": { "type": "string", "pattern": "^t_[a-z2-7]{10}$" },
35
+ "origin": { "type": "object", "required": ["session"], "properties": { "session": { "type": "string", "minLength": 1 } } },
33
36
  "subject": { "type": "string" },
34
37
  "status": { "$ref": "#/$defs/taskStatus" },
35
38
  "description": { "type": "string" },
@@ -61,6 +64,10 @@
61
64
  "type": "string",
62
65
  "minLength": 1
63
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
+ },
64
71
  "evidence": {
65
72
  "description": "Runs of checks, oldest first. Append-only: a later snapshot of the same task starts with the earlier snapshot's entries.",
66
73
  "type": "array",
@@ -72,6 +79,7 @@
72
79
  "type": "object",
73
80
  "required": ["command", "result", "at"],
74
81
  "properties": {
82
+ "ref": { "type": "string", "maxLength": 64, "pattern": "^\\S*$" },
75
83
  "command": {
76
84
  "description": "The check that ran.",
77
85
  "type": "string",
@@ -32,6 +32,7 @@ export const READY_EVENT = "todo:ready";
32
32
 
33
33
  /** Data of a `todo/v1` session entry. */
34
34
  export interface TodoSnapshotV1 {
35
+ sessionId?: string;
35
36
  v: 1;
36
37
  tasks: Task[];
37
38
  nextId: number;
@@ -104,8 +105,8 @@ export function copyTasks(tasks: readonly Task[]): Task[] {
104
105
  return structuredClone(tasks) as Task[];
105
106
  }
106
107
 
107
- export function toSnapshot(state: TaskState): TodoSnapshotV1 {
108
- return { v: CONTRACT_VERSION, tasks: copyTasks(state.tasks), nextId: state.nextId };
108
+ export function toSnapshot(state: TaskState, sessionId: string): TodoSnapshotV1 {
109
+ return { v: CONTRACT_VERSION, sessionId, tasks: copyTasks(state.tasks), nextId: state.nextId };
109
110
  }
110
111
 
111
112
  export function toChangedEvent(sessionId: string, state: TaskState): TodoChangedEventV1 {
@@ -1,23 +1,44 @@
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>();
19
- for (const { id } of snapshot.tasks) {
35
+ const uids = new Set<string>();
36
+ for (const { id, uid } of snapshot.tasks) {
20
37
  if (ids.has(id)) throw new Error(`duplicate task id #${id}`);
38
+ if (uid !== undefined) {
39
+ if (uids.has(uid)) throw new Error(`duplicate task uid ${uid} (#${id})`);
40
+ uids.add(uid);
41
+ }
21
42
  if (snapshot.nextId <= id) throw new Error(`nextId must be greater than task id #${id}`);
22
43
  ids.add(id);
23
44
  }
@@ -26,5 +47,7 @@ export async function readImport(before: TaskState, cwd: string, path?: string,
26
47
  if (!ids.has(dep)) throw new Error(`#${task.id} blockedBy: #${dep} not found`);
27
48
  }
28
49
  }
29
- return { tasks: snapshot.tasks, nextId: snapshot.nextId };
50
+ const origin = snapshot.sessionId;
51
+ const tasks = snapshot.tasks.map(task => withLegacyGraph(origin ? { ...task, origin: { session: origin } } : task));
52
+ return { tasks, nextId: snapshot.nextId };
30
53
  }
@@ -16,6 +16,6 @@ export const TODO_V1_SCHEMA: Record<string, unknown> = JSON.parse(readFileSync(S
16
16
  const validator = Compile(TODO_V1_SCHEMA as never);
17
17
 
18
18
  /** True when `value` is valid `todo/v1` entry data. */
19
- export function isSnapshotV1(value: unknown): value is { v: 1; tasks: Task[]; nextId: number } {
19
+ export function isSnapshotV1(value: unknown): value is { v: 1; sessionId?: string; tasks: Task[]; nextId: number } {
20
20
  return validator.Check(value);
21
21
  }
@@ -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
  /**
@@ -1,6 +1,9 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import {
2
3
  type Evidence,
3
4
  type EvidenceInput,
5
+ GRAPHS,
6
+ isGraph,
4
7
  POINTS_MAX,
5
8
  POINTS_MIN,
6
9
  type Task,
@@ -71,6 +74,7 @@ const BATCH_ITEM_FIELDS = [
71
74
  "metadata",
72
75
  "points",
73
76
  "anchor",
77
+ "graph",
74
78
  "evidence",
75
79
  ] as const;
76
80
 
@@ -82,7 +86,12 @@ const BATCH_ITEM_FIELDS = [
82
86
  /** How far ahead of the call time an evidence `at` may lie, for clock skew between machines. */
83
87
  export const EVIDENCE_FUTURE_TOLERANCE_MS = 5 * 60_000;
84
88
 
85
- 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
+ }
86
95
  if (spec.points !== undefined) {
87
96
  const p = spec.points;
88
97
  if (typeof p !== "number" || !Number.isFinite(p) || p < POINTS_MIN || p > POINTS_MAX) {
@@ -107,6 +116,9 @@ function validateEvidenceInput(value: unknown, now: string): string | undefined
107
116
  const e = value as Record<string, unknown>;
108
117
  if (typeof e.command !== "string" || !e.command.trim()) return "command must be a non-empty string";
109
118
  if (e.result !== "pass" && e.result !== "fail") return 'result must be "pass" or "fail"';
119
+ if (e.ref !== undefined && (typeof e.ref !== "string" || !e.ref || Array.from(e.ref).length > 64 || /\s/u.test(e.ref))) {
120
+ return "ref must be a non-empty string of up to 64 characters without whitespace";
121
+ }
110
122
  if (e.sha !== undefined && typeof e.sha !== "string") return "sha must be a string";
111
123
  if (e.at !== undefined && (typeof e.at !== "string" || Number.isNaN(Date.parse(e.at)))) {
112
124
  return "at must be an ISO 8601 time";
@@ -121,12 +133,24 @@ function validateEvidenceInput(value: unknown, now: string): string | undefined
121
133
  function toEvidence(input: EvidenceInput, now: string): Evidence {
122
134
  return {
123
135
  command: input.command,
136
+ ...(input.ref !== undefined ? { ref: input.ref } : {}),
124
137
  ...(input.sha !== undefined ? { sha: input.sha } : {}),
125
138
  result: input.result,
126
139
  at: input.at === undefined ? now : new Date(input.at).toISOString(),
127
140
  };
128
141
  }
129
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
+
130
154
  function asCreateItem(value: unknown): TaskMutationParams | undefined {
131
155
  if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
132
156
  return value as TaskMutationParams;
@@ -135,6 +159,7 @@ function asCreateItem(value: unknown): TaskMutationParams | undefined {
135
159
  function buildCreatedTask(id: number, spec: TaskMutationParams, subject: string, now: string): Task {
136
160
  const newTask: Task = {
137
161
  id,
162
+ uid: `t_${Array.from(randomBytes(10), byte => "abcdefghijklmnopqrstuvwxyz234567"[byte & 31]).join("")}`,
138
163
  subject,
139
164
  status: "pending",
140
165
  };
@@ -145,8 +170,9 @@ function buildCreatedTask(id: number, spec: TaskMutationParams, subject: string,
145
170
  if (spec.metadata) newTask.metadata = { ...spec.metadata };
146
171
  if (spec.points !== undefined) newTask.points = spec.points;
147
172
  if (spec.anchor !== undefined) newTask.anchor = spec.anchor;
173
+ if (isGraph(spec.graph)) newTask.graph = spec.graph;
148
174
  if (spec.evidence?.length) newTask.evidence = spec.evidence.map((e) => toEvidence(e, now));
149
- return newTask;
175
+ return withLegacyGraph(newTask);
150
176
  }
151
177
 
152
178
  function validateCreateBlockedBy(
@@ -197,6 +223,7 @@ function taskChanged(before: Task, after: Task): boolean {
197
223
  before.owner !== after.owner ||
198
224
  before.points !== after.points ||
199
225
  before.anchor !== after.anchor ||
226
+ before.graph !== after.graph ||
200
227
  (before.evidence?.length ?? 0) !== (after.evidence?.length ?? 0) ||
201
228
  !sameNumberList(before.blockedBy, after.blockedBy) ||
202
229
  !sameRecord(before.metadata, after.metadata)
@@ -292,15 +319,16 @@ export function applyTaskMutation(
292
319
  params.metadata !== undefined ||
293
320
  params.points !== undefined ||
294
321
  params.anchor !== undefined ||
322
+ params.graph !== undefined ||
295
323
  (params.evidence && params.evidence.length > 0) ||
296
324
  (params.addBlockedBy && params.addBlockedBy.length > 0) ||
297
325
  (params.removeBlockedBy && params.removeBlockedBy.length > 0);
298
326
  if (!hasMutation)
299
327
  return errorResult(
300
328
  state,
301
- "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",
302
330
  );
303
- const ledgerError = validateLedgerFields(params, now);
331
+ const ledgerError = validateLedgerFields(params, now, true);
304
332
  if (ledgerError) return errorResult(state, ledgerError);
305
333
 
306
334
  let newStatus = current.status;
@@ -346,16 +374,23 @@ export function applyTaskMutation(
346
374
  if (params.owner !== undefined) updated.owner = params.owner;
347
375
  if (params.points !== undefined) updated.points = params.points;
348
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;
349
379
  if (params.evidence?.length) {
350
380
  updated.evidence = [...(current.evidence ?? []), ...params.evidence.map((e) => toEvidence(e, now))];
351
381
  }
352
382
  if (newBlockedBy.length) updated.blockedBy = newBlockedBy;
353
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
+ }
354
389
  if (newMetadata === undefined) delete updated.metadata;
355
390
  else updated.metadata = newMetadata;
356
391
 
357
392
  const newTasks = [...state.tasks];
358
- newTasks[idx] = updated;
393
+ newTasks[idx] = withLegacyGraph(updated);
359
394
  return {
360
395
  state: { tasks: newTasks, nextId: state.nextId },
361
396
  op: {
@@ -363,7 +398,7 @@ export function applyTaskMutation(
363
398
  id: updated.id,
364
399
  fromStatus: current.status,
365
400
  toStatus: newStatus,
366
- changed: taskChanged(current, updated),
401
+ changed: taskChanged(current, newTasks[idx]),
367
402
  },
368
403
  };
369
404
  }
package/src/todo.ts CHANGED
@@ -69,7 +69,7 @@ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
69
69
  '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
70
  "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
71
  "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.",
72
+ "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
73
  "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
74
74
  "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
75
  "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 +113,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
113
113
  let result: ApplyResult;
114
114
  if (action === "import") {
115
115
  try {
116
- result = { state: await readImport(before, ctx.cwd, input.path, signal), op: { kind: "import" } };
116
+ result = { state: await readImport(before, ctx.cwd, { path: input.path, session: input.session, self: sessionId }, signal), op: { kind: "import" } };
117
117
  } catch (error) {
118
118
  return refuse(action, input, before, signal?.aborted ? ABORTED : String(error instanceof Error ? error.message : error));
119
119
  }
@@ -152,7 +152,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
152
152
  // replay. Pi's own codemode persists its `store()` the same way.
153
153
  // The entry is written before the live state commits: if appending throws, the call
154
154
  // fails with the list unchanged, so live state never runs ahead of the branch.
155
- pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state));
155
+ pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
156
156
  commitState(sessionId, result.state);
157
157
  pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
158
158
  return buildToolResult(action, input, result.state, result.op);
@@ -15,6 +15,36 @@ function formatListLine(t: Task): string {
15
15
  return `[${t.status}] #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}`;
16
16
  }
17
17
 
18
+ const isOpen = (t: Task): boolean => t.status === "pending" || t.status === "in_progress";
19
+
20
+ /**
21
+ * `list` body. When an open task names a graph, open tasks are grouped under
22
+ * `<graph>:` headers in first-seen order, then `no graph:`, then `closed:` for
23
+ * the rest; otherwise one line per task in id order.
24
+ */
25
+ function formatList(view: readonly Task[]): string {
26
+ if (!view.some((t) => isOpen(t) && t.graph)) return view.map(formatListLine).join("\n");
27
+ const groups = new Map<string, Task[]>();
28
+ const closed: Task[] = [];
29
+ for (const t of view) {
30
+ if (!isOpen(t)) closed.push(t);
31
+ else {
32
+ const key = t.graph ?? "";
33
+ groups.set(key, [...(groups.get(key) ?? []), t]);
34
+ }
35
+ }
36
+ const ungrouped = groups.get("");
37
+ groups.delete("");
38
+ const lines: string[] = [];
39
+ const section = (header: string, tasks: Task[] | undefined) => {
40
+ if (tasks?.length) lines.push(`${header}:`, ...tasks.map(formatListLine));
41
+ };
42
+ for (const [graph, tasks] of groups) section(graph, tasks);
43
+ section("no graph", ungrouped);
44
+ section("closed", closed);
45
+ return lines.join("\n");
46
+ }
47
+
18
48
  /**
19
49
  * Multi-line presentation for the `get` action. Order of rows is pinned by
20
50
  * pre-refactor `todo.ts:354-376` — description, activeForm, blockedBy, blocks,
@@ -34,6 +64,7 @@ function formatGetLines(task: Task, state: TaskState): string {
34
64
  if (task.owner) lines.push(` owner: ${sanitizeTerminalText(task.owner)}`);
35
65
  if (task.points !== undefined) lines.push(` points: ${task.points}`);
36
66
  if (task.anchor) lines.push(` anchor: ${sanitizeTerminalText(task.anchor)}`);
67
+ if (task.graph) lines.push(` graph: ${task.graph}`);
37
68
  for (const e of task.evidence ?? []) {
38
69
  const sha = e.sha ? ` @${sanitizeTerminalText(e.sha)}` : "";
39
70
  lines.push(` evidence: ${e.result} ${sanitizeTerminalText(e.command)}${sha} (${sanitizeTerminalText(e.at)})`);
@@ -76,7 +107,7 @@ export function formatContent(op: Op, state: TaskState): string {
76
107
  let view = state.tasks;
77
108
  if (!op.includeDeleted) view = view.filter((t) => t.status !== "deleted");
78
109
  if (op.statusFilter) view = view.filter((t) => t.status === op.statusFilter);
79
- return view.length === 0 ? "No tasks" : view.map(formatListLine).join("\n");
110
+ return view.length === 0 ? "No tasks" : formatList(view);
80
111
  }
81
112
  case "get":
82
113
  return formatGetLines(op.task, state);
package/src/tool/types.ts CHANGED
@@ -39,6 +39,7 @@ export type EvidenceResult = "pass" | "fail";
39
39
 
40
40
  /** One recorded run of a check: what ran, on which revision, how it ended, and when. */
41
41
  export interface Evidence {
42
+ ref?: string;
42
43
  command: string;
43
44
  sha?: string;
44
45
  result: EvidenceResult;
@@ -48,17 +49,26 @@ export interface Evidence {
48
49
 
49
50
  /** Evidence as a caller supplies it: `at` defaults to the time of the call. */
50
51
  export interface EvidenceInput {
52
+ ref?: string;
51
53
  command: string;
52
54
  sha?: string;
53
55
  result: EvidenceResult;
54
56
  at?: string;
55
57
  }
56
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
+
57
65
  /** Inclusive bounds of `Task.points`. */
58
66
  export const POINTS_MIN = 0;
59
67
  export const POINTS_MAX = 10;
60
68
 
61
69
  export interface Task {
70
+ uid?: string;
71
+ origin?: { session: string };
62
72
  id: number;
63
73
  subject: string;
64
74
  description?: string;
@@ -71,6 +81,8 @@ export interface Task {
71
81
  points?: number;
72
82
  /** The check that shows this task is done, e.g. a test command. */
73
83
  anchor?: string;
84
+ /** The work graph of the plan this task belongs to. */
85
+ graph?: Graph;
74
86
  /** Runs of checks, oldest first. Append-only. */
75
87
  evidence?: Evidence[];
76
88
  }
@@ -104,6 +116,7 @@ export interface CreateTaskInput {
104
116
  metadata?: Record<string, unknown>;
105
117
  points?: number;
106
118
  anchor?: string;
119
+ graph?: string;
107
120
  evidence?: EvidenceInput[];
108
121
  }
109
122
 
@@ -120,9 +133,12 @@ export interface TaskMutationParams {
120
133
  metadata?: Record<string, unknown>;
121
134
  points?: number;
122
135
  anchor?: string;
136
+ /** A graph name; `null` clears it on update. */
137
+ graph?: string | null;
123
138
  evidence?: EvidenceInput[];
124
139
  id?: number;
125
140
  path?: string;
141
+ session?: string;
126
142
  includeDeleted?: boolean;
127
143
  /** Batch create items. One-of with `subject` on `create`. */
128
144
  tasks?: CreateTaskInput[];
@@ -139,6 +155,7 @@ const PointsSchema = (description: string) =>
139
155
  const AnchorSchema = (description: string) => Type.String({ minLength: 1, description });
140
156
 
141
157
  const EvidenceInputSchema = Type.Object({
158
+ ref: Type.Optional(Type.String({ minLength: 1, maxLength: 64, pattern: "^\\S*$", description: "Run or child:<id>" })),
142
159
  command: Type.String({ minLength: 1, description: "The check that ran, e.g. 'npm test -- replay'" }),
143
160
  sha: Type.Optional(Type.String({ description: "Revision the check ran on, e.g. a git commit SHA" })),
144
161
  result: StringEnum(["pass", "fail"] as const, { description: "How the run ended" }),
@@ -169,12 +186,14 @@ const CreateTaskInputSchema = Type.Object({
169
186
  ),
170
187
  points: Type.Optional(PointsSchema("Effort points, 0 to 10")),
171
188
  anchor: Type.Optional(AnchorSchema("The check that shows this task is done, e.g. a test command")),
189
+ graph: Type.Optional(Type.String()),
172
190
  evidence: Type.Optional(EvidenceSchema("Check runs already recorded for this task")),
173
191
  });
174
192
 
175
193
  export const TodoParamsSchema = Type.Object({
176
194
  action: StringEnum(["create", "update", "list", "get", "delete", "clear", "import"] as const),
177
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)" })),
178
197
  subject: Type.Optional(
179
198
  Type.String({
180
199
  description: "Task subject line (required for create unless tasks[] is set)",
@@ -219,6 +238,11 @@ export const TodoParamsSchema = Type.Object({
219
238
  "The check that shows this task is done, e.g. a test command (create or update; update replaces)",
220
239
  ),
221
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
+ ),
222
246
  evidence: Type.Optional(
223
247
  EvidenceSchema(
224
248
  "Check runs to record: the initial list on create; on update, appended to the task's evidence (never replaced or removed)",