pi-todo-ledger 0.3.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 +3 -1
- package/README.md +21 -2
- package/docs/tool-schema.md +27 -6
- package/package.json +1 -1
- package/schema/todo-v1.schema.json +4 -0
- package/src/ledger/import-snapshot.ts +25 -9
- package/src/ledger/session-source.ts +82 -0
- package/src/state/replay.ts +2 -1
- package/src/state/state-reducer.ts +35 -6
- package/src/todo.ts +2 -2
- package/src/tool/response-envelope.ts +32 -1
- package/src/tool/types.ts +19 -0
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,26 @@ 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
|
-
|
|
45
|
-
|
|
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.
|
|
46
65
|
|
|
47
66
|
```json
|
|
48
67
|
{ "action": "import", "path": "handover.json" }
|
package/docs/tool-schema.md
CHANGED
|
@@ -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,
|
|
@@ -181,8 +198,9 @@ any disk writes.
|
|
|
181
198
|
| Imported | `Imported 7 tasks` |
|
|
182
199
|
| Cleared | `Cleared 7 tasks` |
|
|
183
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 |
|
|
184
202
|
| `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 |
|
|
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 |
|
|
186
204
|
| Any rejection | `Error: <message>` |
|
|
187
205
|
|
|
188
206
|
The `No change` reply exists so a model that re-issues an identical update sees
|
|
@@ -195,16 +213,19 @@ that it was a no-op instead of a fresh `Updated #N`.
|
|
|
195
213
|
| `subject required for create` | `create` without a non-blank `subject` and without `tasks[]`. |
|
|
196
214
|
| `create requires subject or tasks[], not both` | `create` with both `subject` and `tasks[]`. |
|
|
197
215
|
| `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`. |
|
|
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`. |
|
|
199
217
|
| `tasks[N]: subject required for create` | A batch item with a blank or missing subject. |
|
|
200
218
|
| `blockedBy: #N not found` | `create` naming an unknown dependency. |
|
|
201
219
|
| `blockedBy: #N is deleted` | `create` naming a tombstoned dependency. |
|
|
202
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. |
|
|
203
221
|
| `id required for update` / `get` / `delete` | `id` omitted. |
|
|
204
222
|
| `#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`. |
|
|
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`. |
|
|
206
224
|
| `points must be a number from 0 to 10` | `points` out of range; prefixed `tasks[N]: ` for a batch item. |
|
|
207
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). |
|
|
208
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. |
|
|
209
230
|
| `metadata.<ns> refused #N: <reason>` | A namespace validator refused the change (see [CONTRACT.md](../CONTRACT.md#3-namespaces)). |
|
|
210
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.
|
|
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",
|
|
@@ -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,
|
|
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
|
-
|
|
10
|
-
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
|
35
|
-
const 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
|
+
}
|
package/src/state/replay.ts
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
401
|
+
changed: taskChanged(current, newTasks[idx]),
|
|
373
402
|
},
|
|
374
403
|
};
|
|
375
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
|
}
|
|
@@ -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
|
|
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
|
@@ -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)",
|