pi-todo-ledger 0.1.0 → 0.3.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. |
@@ -26,11 +28,12 @@ The schema's `$defs/task` is the exact definition.
26
28
  | `anchor` | non-empty string, optional | The check that shows the task is done, such as a test command. |
27
29
  | `evidence` | Evidence[], optional | Runs of checks, oldest first. |
28
30
 
29
- An evidence entry is `{ command, sha?, result, at }`:
31
+ An evidence entry is `{ command, sha?, ref?, result, at }`:
30
32
 
31
33
  | Property | Type | Meaning |
32
34
  | --- | --- | --- |
33
35
  | `command` | non-empty string | The check that ran. |
36
+ | `ref` | string, optional | Tool call id of the run, or `child:<id>`; up to 64 characters without whitespace. |
34
37
  | `sha` | string, optional | Revision the check ran on, such as a git commit SHA. |
35
38
  | `result` | `pass` or `fail` | How the run ended. |
36
39
  | `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. |
@@ -41,7 +44,8 @@ A `todo` `update` call adds its `evidence` items after the existing ones, and no
41
44
 
42
45
  > [!IMPORTANT]
43
46
  > Evidence is self-reported bookkeeping, not proof.
44
- > The agent writes each entry through the `todo` tool; the extension checks its shape and that `at` is not in the future, but runs nothing and cannot tell whether the command ran or how it ended.
47
+ > When recording new evidence, the extension checks its shape and time; when importing or replaying a snapshot, it preserves the recorded time.
48
+ > It runs nothing and cannot tell whether the command ran or how it ended.
45
49
  > Use it to find which checks were run and on which revision, so the next round can reuse a green run.
46
50
  > A consumer that judges whether a check passed after the last change, such as a guard that blocks closing a task, keeps the session's real tool results (the command's own output on the branch) as the source of truth and treats evidence only as a pointer to them.
47
51
 
@@ -63,6 +67,13 @@ Read the branch, not every session entry: entries on abandoned branches describe
63
67
 
64
68
  Calls that change nothing write no entry: `list`, `get`, an `update` whose values equal the current ones, a call the tool rejects, and a call a namespace validator or guard refuses.
65
69
 
70
+ ### Import into an empty list
71
+
72
+ Since 0.2.0, `todo` accepts `{ "action": "import", "path": "handover.json" }` as an additive operation within v1.
73
+ The file contains the snapshot `data` itself, not the surrounding session entry.
74
+ 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
+ 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.
76
+
66
77
  ### Migration from rpiv-todo
67
78
 
68
79
  When a branch has no `todo/v1` entry, the extension restores the list from rpiv-todo's records, newest first by kind:
@@ -159,7 +170,12 @@ const register = () =>
159
170
 
160
171
  A later registration of the same `id` replaces the earlier one; the extension ignores, with a console warning, a payload whose `v` is not 1, whose `id` is empty, or whose `check` is not a function.
161
172
 
162
- The extension calls `check(change)` for every call that would change the list: `create` (a single task or a `tasks[]` batch, with or without metadata), an `update`, `delete`, and `clear`.
173
+ The extension calls `check(change)` for every call that would change the list: `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `update`, `delete`, and `clear`.
174
+ On import, namespace validators see each relevant task as a `create`.
175
+ Guard registration accepts an optional `imports: true` field within v1.
176
+ 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`.
178
+ 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.
163
179
  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.
164
180
  `change` matches `$defs/change` in the schema and is a copy:
165
181
 
package/README.md CHANGED
@@ -8,7 +8,8 @@ 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 }`).
12
13
 
13
14
  ## Replaces rpiv-todo
14
15
 
@@ -40,6 +41,16 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
40
41
  `evidence` items are appended after the existing ones; `at` defaults to the time of the call.
41
42
  `get` shows all three fields.
42
43
 
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:
46
+
47
+ ```json
48
+ { "action": "import", "path": "handover.json" }
49
+ ```
50
+
51
+ A relative path starts in the new session's working directory.
52
+ Import keeps the task ids, dependencies, evidence, tombstones, and next id; it never merges with or replaces an existing list.
53
+
43
54
  ## Reading the list from another extension
44
55
 
45
56
  Listen for the event, or read the newest snapshot on the branch:
@@ -2,7 +2,7 @@
2
2
 
3
3
  Complete parameter schema, status machine, response envelope, and error strings
4
4
  for the `todo` tool registered by pi-todo-ledger. The actions and parameters are
5
- rpiv-todo's, plus the bookkeeping fields `points`, `anchor`, and `evidence`.
5
+ rpiv-todo's, plus snapshot import and the bookkeeping fields `points`, `anchor`, and `evidence`.
6
6
 
7
7
  ## Actions
8
8
 
@@ -14,12 +14,15 @@ rpiv-todo's, plus the bookkeeping fields `points`, `anchor`, and `evidence`.
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
18
 
18
19
  ## Parameters
19
20
 
20
21
  ```ts
21
22
  todo({
22
- action: "create" | "update" | "list" | "get" | "delete" | "clear",
23
+ action: "create" | "update" | "list" | "get" | "delete" | "clear" | "import",
24
+
25
+ path?: string, // import only; relative to the session cwd
23
26
 
24
27
  // create-only (one-of: subject or tasks[])
25
28
  subject?: string, // required for single create
@@ -45,6 +48,7 @@ todo({
45
48
  anchor?: string, // the check that shows the task is done; update replaces
46
49
  evidence?: Array<{ // check runs; update appends, never replaces
47
50
  command: string,
51
+ ref?: string, // tool call id or child:<id>; ≤64 characters, no whitespace
48
52
  sha?: string, // revision the check ran on
49
53
  result: "pass" | "fail",
50
54
  at?: string, // ISO 8601; stored in UTC; defaults to the time of the call
@@ -85,6 +89,11 @@ existing ones. No call removes an evidence entry or a field once set; `points: 0
85
89
  is the lowest estimate. Pi drops a `null` passed for an optional parameter before
86
90
  the tool sees it, so `points: null` changes nothing.
87
91
 
92
+ `import` reads `{ "v": 1, "tasks": [...], "nextId": n }` from a JSON file and keeps every task field as stored.
93
+ If the file is unreadable or does not match the snapshot schema, the tool reports an error and leaves the list alone.
94
+ Task ids must be unique, every `blockedBy` target must exist, and `nextId` must exceed the largest task id.
95
+ The destination must contain no tasks, including tombstones.
96
+
88
97
  ## Status transitions
89
98
 
90
99
  | From | Allowed targets |
@@ -121,6 +130,8 @@ tasks' `blockedBy` arrays.
121
130
  params: Record<string, unknown>,
122
131
  tasks: Array<{
123
132
  id: number,
133
+ uid?: string, // stable across branches and import
134
+ origin?: { session: string }, // source session on import, when known
124
135
  subject: string,
125
136
  description?: string,
126
137
  activeForm?: string,
@@ -130,7 +141,7 @@ tasks' `blockedBy` arrays.
130
141
  metadata?: Record<string, unknown>,
131
142
  points?: number,
132
143
  anchor?: string,
133
- evidence?: Array<{ command: string, sha?: string, result: "pass" | "fail", at: string }>,
144
+ evidence?: Array<{ command: string, sha?: string, ref?: string, result: "pass" | "fail", at: string }>,
134
145
  }>,
135
146
  nextId: number,
136
147
  error?: string, // present only on a rejected call
@@ -140,7 +151,7 @@ tasks' `blockedBy` arrays.
140
151
 
141
152
  ## Persistence
142
153
 
143
- Every call that changes the list (`create`, `delete`, `clear`, or an `update`
154
+ Every call that changes the list (`create`, `import`, `delete`, `clear`, or an `update`
144
155
  that changed something) appends a `todo/v1` custom entry holding the whole list
145
156
  to the session branch, and emits `todo:changed`. Both are part of the public
146
157
  contract in [CONTRACT.md](../CONTRACT.md). Custom entries are never sent to the
@@ -167,6 +178,7 @@ any disk writes.
167
178
  | Updated without a status change | `Updated #3` |
168
179
  | Update that changed nothing | `No change: #3 already matches the requested values (status: in_progress)` |
169
180
  | Deleted | `Deleted #3: Write the parser` |
181
+ | Imported | `Imported 7 tasks` |
170
182
  | Cleared | `Cleared 7 tasks` |
171
183
  | `list` row | `[in_progress] #3 Write the parser (writing the parser) ⛓ #1,#2` |
172
184
  | `list` with nothing to show | `No tasks` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.1.0",
3
+ "version": "0.3.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" },
@@ -72,6 +75,7 @@
72
75
  "type": "object",
73
76
  "required": ["command", "result", "at"],
74
77
  "properties": {
78
+ "ref": { "type": "string", "maxLength": 64, "pattern": "^\\S*$" },
75
79
  "command": {
76
80
  "description": "The check that ran.",
77
81
  "type": "string",
@@ -118,7 +122,8 @@
118
122
  "required": ["v", "id"],
119
123
  "properties": {
120
124
  "v": { "const": 1 },
121
- "id": { "type": "string", "minLength": 1 }
125
+ "id": { "type": "string", "minLength": 1 },
126
+ "imports": { "const": true, "description": "Opt in to checking snapshot imports. Without opt-in the guard blocks imports." }
122
127
  }
123
128
  },
124
129
  "change": {
@@ -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;
@@ -91,6 +92,8 @@ export type GuardCheck = (change: TodoChangeV1) => string | undefined | Promise<
91
92
  export interface TodoGuardEventV1 {
92
93
  v: 1;
93
94
  id: string;
95
+ /** Opt in to judging imported tasks from change.after. Absent: refuse imports. */
96
+ imports?: true;
94
97
  check: GuardCheck;
95
98
  }
96
99
 
@@ -102,8 +105,8 @@ export function copyTasks(tasks: readonly Task[]): Task[] {
102
105
  return structuredClone(tasks) as Task[];
103
106
  }
104
107
 
105
- export function toSnapshot(state: TaskState): TodoSnapshotV1 {
106
- 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 };
107
110
  }
108
111
 
109
112
  export function toChangedEvent(sessionId: string, state: TaskState): TodoChangedEventV1 {
@@ -31,7 +31,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
31
31
  }
32
32
 
33
33
  export class GuardRegistry {
34
- private readonly guards = new Map<string, GuardCheck>();
34
+ private readonly guards = new Map<string, { check: GuardCheck; imports: boolean }>();
35
35
  private readonly timeoutMs: number;
36
36
 
37
37
  constructor(timeoutMs: number) {
@@ -52,7 +52,7 @@ export class GuardRegistry {
52
52
  if (typeof payload.check !== "function") {
53
53
  return `${GUARD_EVENT}: check must be a function (id "${payload.id}")`;
54
54
  }
55
- this.guards.set(payload.id, payload.check as GuardCheck);
55
+ this.guards.set(payload.id, { check: payload.check as GuardCheck, imports: payload.imports === true });
56
56
  return undefined;
57
57
  }
58
58
 
@@ -61,7 +61,13 @@ export class GuardRegistry {
61
61
  * Returns the first refusal as the tool's error message, or `undefined`.
62
62
  */
63
63
  async check(change: TodoChangeV1): Promise<string | undefined> {
64
- for (const [id, check] of this.guards) {
64
+ const guards = change.params.action === "import" ? [...this.guards] : this.guards;
65
+ if (change.params.action === "import") {
66
+ for (const [id, guard] of guards) {
67
+ if (!guard.imports) return `guard ${id} refused: guard does not accept imports`;
68
+ }
69
+ }
70
+ for (const [id, { check }] of guards) {
65
71
  const reason = await this.runOne(id, check, change);
66
72
  if (reason !== undefined) return reason;
67
73
  }
@@ -0,0 +1,37 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import type { TaskState } from "../state/state.ts";
4
+ import { isSnapshotV1 } from "./schema.ts";
5
+
6
+ /** 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> {
8
+ 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 });
11
+ let snapshot: unknown;
12
+ try {
13
+ snapshot = JSON.parse(raw);
14
+ } catch {
15
+ throw new Error("import file is not valid JSON");
16
+ }
17
+ if (!isSnapshotV1(snapshot)) throw new Error("import file does not match the todo/v1 snapshot schema");
18
+ const ids = new Set<number>();
19
+ const uids = new Set<string>();
20
+ for (const { id, uid } of snapshot.tasks) {
21
+ if (ids.has(id)) throw new Error(`duplicate task id #${id}`);
22
+ if (uid !== undefined) {
23
+ if (uids.has(uid)) throw new Error(`duplicate task uid ${uid} (#${id})`);
24
+ uids.add(uid);
25
+ }
26
+ if (snapshot.nextId <= id) throw new Error(`nextId must be greater than task id #${id}`);
27
+ ids.add(id);
28
+ }
29
+ for (const task of snapshot.tasks) {
30
+ for (const dep of task.blockedBy ?? []) {
31
+ if (!ids.has(dep)) throw new Error(`#${task.id} blockedBy: #${dep} not found`);
32
+ }
33
+ }
34
+ const session = snapshot.sessionId;
35
+ const tasks = session ? snapshot.tasks.map(task => ({ ...task, origin: { session } })) : snapshot.tasks;
36
+ return { tasks, nextId: snapshot.nextId };
37
+ }
@@ -33,6 +33,8 @@ function metadataKeys(value: unknown): string[] {
33
33
  export function changedTasks(op: Op, params: TaskMutationParams, next: TaskState): TaskChange[] {
34
34
  const find = (id: number) => next.tasks.find((t) => t.id === id);
35
35
  switch (op.kind) {
36
+ case "import":
37
+ return next.tasks.map((task) => ({ task, op: "create", touched: [] }));
36
38
  case "create": {
37
39
  const items = Array.isArray(params.tasks) ? params.tasks : undefined;
38
40
  return op.taskIds.flatMap((id, i) => {
@@ -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
  }
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import {
2
3
  type Evidence,
3
4
  type EvidenceInput,
@@ -27,6 +28,7 @@ export type Op =
27
28
  | { kind: "delete"; id: number; subject: string }
28
29
  | { kind: "list"; statusFilter?: TaskStatus; includeDeleted: boolean }
29
30
  | { kind: "get"; task: Task }
31
+ | { kind: "import" }
30
32
  | { kind: "clear"; count: number }
31
33
  | { kind: "error"; message: string };
32
34
 
@@ -46,6 +48,7 @@ export function changesState(op: Op): boolean {
46
48
  case "create":
47
49
  case "delete":
48
50
  case "clear":
51
+ case "import":
49
52
  return true;
50
53
  case "update":
51
54
  return op.changed;
@@ -105,6 +108,9 @@ function validateEvidenceInput(value: unknown, now: string): string | undefined
105
108
  const e = value as Record<string, unknown>;
106
109
  if (typeof e.command !== "string" || !e.command.trim()) return "command must be a non-empty string";
107
110
  if (e.result !== "pass" && e.result !== "fail") return 'result must be "pass" or "fail"';
111
+ if (e.ref !== undefined && (typeof e.ref !== "string" || !e.ref || Array.from(e.ref).length > 64 || /\s/u.test(e.ref))) {
112
+ return "ref must be a non-empty string of up to 64 characters without whitespace";
113
+ }
108
114
  if (e.sha !== undefined && typeof e.sha !== "string") return "sha must be a string";
109
115
  if (e.at !== undefined && (typeof e.at !== "string" || Number.isNaN(Date.parse(e.at)))) {
110
116
  return "at must be an ISO 8601 time";
@@ -119,6 +125,7 @@ function validateEvidenceInput(value: unknown, now: string): string | undefined
119
125
  function toEvidence(input: EvidenceInput, now: string): Evidence {
120
126
  return {
121
127
  command: input.command,
128
+ ...(input.ref !== undefined ? { ref: input.ref } : {}),
122
129
  ...(input.sha !== undefined ? { sha: input.sha } : {}),
123
130
  result: input.result,
124
131
  at: input.at === undefined ? now : new Date(input.at).toISOString(),
@@ -133,6 +140,7 @@ function asCreateItem(value: unknown): TaskMutationParams | undefined {
133
140
  function buildCreatedTask(id: number, spec: TaskMutationParams, subject: string, now: string): Task {
134
141
  const newTask: Task = {
135
142
  id,
143
+ uid: `t_${Array.from(randomBytes(10), byte => "abcdefghijklmnopqrstuvwxyz234567"[byte & 31]).join("")}`,
136
144
  subject,
137
145
  status: "pending",
138
146
  };
@@ -212,7 +220,7 @@ function taskChanged(before: Task, after: Task): boolean {
212
220
  */
213
221
  export function applyTaskMutation(
214
222
  state: TaskState,
215
- action: TaskAction,
223
+ action: Exclude<TaskAction, "import">,
216
224
  params: TaskMutationParams,
217
225
  now: string = new Date().toISOString(),
218
226
  ): ApplyResult {
package/src/todo.ts CHANGED
@@ -16,10 +16,11 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
16
  import { loadConfig, validateGuidanceFields } from "./config.ts";
17
17
  import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSnapshot } from "./ledger/contract.ts";
18
18
  import { type GuardRegistry, runningGuard } from "./ledger/guards.ts";
19
+ import { readImport } from "./ledger/import-snapshot.ts";
19
20
  import { changedTasks, type NamespaceRegistry } from "./ledger/namespaces.ts";
20
21
  import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
21
22
  import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
22
- import { applyTaskMutation, changesState } from "./state/state-reducer.ts";
23
+ import { applyTaskMutation, type ApplyResult, changesState } from "./state/state-reducer.ts";
23
24
  import { withSessionLock } from "./state/session-lock.ts";
24
25
  import type { TaskState } from "./state/state.ts";
25
26
  import { commitState, getRenderState, getState, sid } from "./state/store.ts";
@@ -68,6 +69,7 @@ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
68
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.',
69
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.",
70
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.",
71
73
  "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
72
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.",
73
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.",
@@ -86,7 +88,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
86
88
  name: TOOL_NAME,
87
89
  label: TOOL_LABEL,
88
90
  description:
89
- "Manage a task list for tracking multi-step progress. Actions: create (new task, or several independent tasks at once via tasks[]), update (change status/fields/dependencies), list (all tasks, optionally filtered by status), get (single task details), delete (tombstone), clear (reset all). Status: pending → in_progress → completed, plus deleted tombstone. Use this to plan and track multi-step work like research, design, and implementation.",
91
+ "Manage a task list for tracking multi-step progress. Actions: create (new task, or several independent tasks at once via tasks[]), update (change status/fields/dependencies), list (all tasks, optionally filtered by status), get (single task details), delete (tombstone), clear (reset all), import (restore a snapshot file into an empty list). Status: pending → in_progress → completed, plus deleted tombstone. Use this to plan and track multi-step work like research, design, and implementation.",
90
92
  promptSnippet: guidance.promptSnippet ?? DEFAULT_PROMPT_SNIPPET,
91
93
  promptGuidelines: guidance.promptGuidelines ?? DEFAULT_PROMPT_GUIDELINES,
92
94
  parameters: TodoParamsSchema,
@@ -108,9 +110,18 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
108
110
  const before = getState(sessionId);
109
111
  // A call aborted while it waited in the queue, or while its guards ran, commits nothing.
110
112
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
111
- const result = applyTaskMutation(before, action, input);
113
+ let result: ApplyResult;
114
+ if (action === "import") {
115
+ try {
116
+ result = { state: await readImport(before, ctx.cwd, input.path, signal), op: { kind: "import" } };
117
+ } catch (error) {
118
+ return refuse(action, input, before, signal?.aborted ? ABORTED : String(error instanceof Error ? error.message : error));
119
+ }
120
+ } else {
121
+ result = applyTaskMutation(before, action, input);
122
+ }
112
123
  const guardChange = {
113
- op: action as GuardOp,
124
+ op: action === "import" ? "create" as const : action as GuardOp,
114
125
  params: input as Record<string, unknown>,
115
126
  before: before.tasks,
116
127
  after: result.state.tasks,
@@ -141,7 +152,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
141
152
  // replay. Pi's own codemode persists its `store()` the same way.
142
153
  // The entry is written before the live state commits: if appending throws, the call
143
154
  // fails with the list unchanged, so live state never runs ahead of the branch.
144
- pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state));
155
+ pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
145
156
  commitState(sessionId, result.state);
146
157
  pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
147
158
  return buildToolResult(action, input, result.state, result.op);
@@ -68,6 +68,8 @@ export function formatContent(op: Op, state: TaskState): string {
68
68
  }
69
69
  case "delete":
70
70
  return `Deleted #${op.id}: ${sanitizeTerminalText(op.subject)}`;
71
+ case "import":
72
+ return `Imported ${state.tasks.length} tasks`;
71
73
  case "clear":
72
74
  return `Cleared ${op.count} tasks`;
73
75
  case "list": {
package/src/tool/types.ts CHANGED
@@ -33,12 +33,13 @@ export const MSG_NO_TODOS = "No todos yet. Ask the agent to add some!";
33
33
 
34
34
  export type TaskStatus = "pending" | "in_progress" | "completed" | "deleted";
35
35
 
36
- export type TaskAction = "create" | "update" | "list" | "get" | "delete" | "clear";
36
+ export type TaskAction = "create" | "update" | "list" | "get" | "delete" | "clear" | "import";
37
37
 
38
38
  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,6 +49,7 @@ 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;
@@ -59,6 +61,8 @@ export const POINTS_MIN = 0;
59
61
  export const POINTS_MAX = 10;
60
62
 
61
63
  export interface Task {
64
+ uid?: string;
65
+ origin?: { session: string };
62
66
  id: number;
63
67
  subject: string;
64
68
  description?: string;
@@ -122,6 +126,7 @@ export interface TaskMutationParams {
122
126
  anchor?: string;
123
127
  evidence?: EvidenceInput[];
124
128
  id?: number;
129
+ path?: string;
125
130
  includeDeleted?: boolean;
126
131
  /** Batch create items. One-of with `subject` on `create`. */
127
132
  tasks?: CreateTaskInput[];
@@ -138,6 +143,7 @@ const PointsSchema = (description: string) =>
138
143
  const AnchorSchema = (description: string) => Type.String({ minLength: 1, description });
139
144
 
140
145
  const EvidenceInputSchema = Type.Object({
146
+ ref: Type.Optional(Type.String({ minLength: 1, maxLength: 64, pattern: "^\\S*$", description: "Run or child:<id>" })),
141
147
  command: Type.String({ minLength: 1, description: "The check that ran, e.g. 'npm test -- replay'" }),
142
148
  sha: Type.Optional(Type.String({ description: "Revision the check ran on, e.g. a git commit SHA" })),
143
149
  result: StringEnum(["pass", "fail"] as const, { description: "How the run ended" }),
@@ -172,7 +178,8 @@ const CreateTaskInputSchema = Type.Object({
172
178
  });
173
179
 
174
180
  export const TodoParamsSchema = Type.Object({
175
- action: StringEnum(["create", "update", "list", "get", "delete", "clear"] as const),
181
+ action: StringEnum(["create", "update", "list", "get", "delete", "clear", "import"] as const),
182
+ path: Type.Optional(Type.String({ description: "Snapshot file (import only); relative to the session cwd" })),
176
183
  subject: Type.Optional(
177
184
  Type.String({
178
185
  description: "Task subject line (required for create unless tasks[] is set)",
@@ -44,6 +44,7 @@ export const ACTION_GLYPH: Record<TaskAction, string> = {
44
44
  get: "›",
45
45
  list: "☰",
46
46
  clear: "∅",
47
+ import: "↓",
47
48
  };
48
49
 
49
50
  /**
@@ -116,7 +117,9 @@ export function renderTodoCall(
116
117
  let text = theme.fg("toolTitle", theme.bold("todo "));
117
118
  if (args.action) text += theme.fg("muted", ACTION_GLYPH[args.action] ?? args.action);
118
119
 
119
- if (args.action === "create" && args.subject) {
120
+ if (args.action === "import" && args.path) {
121
+ text += ` ${theme.fg("dim", sanitizeTerminalText(args.path))}`;
122
+ } else if (args.action === "create" && args.subject) {
120
123
  text += ` ${theme.fg("dim", sanitizeTerminalText(args.subject))}`;
121
124
  } else if (args.action === "create" && Array.isArray(args.tasks)) {
122
125
  text += ` ${theme.fg("dim", `${args.tasks.length} tasks`)}`;
@@ -174,6 +177,7 @@ function echoedStatus(details: TaskDetails | undefined): TaskStatus | undefined
174
177
  return details.tasks.find((t) => t.id === params.id)?.status;
175
178
  case "list":
176
179
  case "get":
180
+ case "import":
177
181
  case "clear":
178
182
  return undefined;
179
183
  }