pi-todo-ledger 0.1.0 → 0.2.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
@@ -41,7 +41,8 @@ A `todo` `update` call adds its `evidence` items after the existing ones, and no
41
41
 
42
42
  > [!IMPORTANT]
43
43
  > 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.
44
+ > When recording new evidence, the extension checks its shape and time; when importing or replaying a snapshot, it preserves the recorded time.
45
+ > It runs nothing and cannot tell whether the command ran or how it ended.
45
46
  > Use it to find which checks were run and on which revision, so the next round can reuse a green run.
46
47
  > 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
48
 
@@ -63,6 +64,13 @@ Read the branch, not every session entry: entries on abandoned branches describe
63
64
 
64
65
  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
66
 
67
+ ### Import into an empty list
68
+
69
+ Since 0.2.0, `todo` accepts `{ "action": "import", "path": "handover.json" }` as an additive operation within v1.
70
+ The file contains the snapshot `data` itself, not the surrounding session entry.
71
+ 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`.
73
+
66
74
  ### Migration from rpiv-todo
67
75
 
68
76
  When a branch has no `todo/v1` entry, the extension restores the list from rpiv-todo's records, newest first by kind:
@@ -159,7 +167,12 @@ const register = () =>
159
167
 
160
168
  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
169
 
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`.
170
+ 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`.
171
+ On import, namespace validators see each relevant task as a `create`.
172
+ Guard registration accepts an optional `imports: true` field within v1.
173
+ 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`.
175
+ 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
176
  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
177
  `change` matches `$defs/change` in the schema and is a copy:
165
178
 
package/README.md CHANGED
@@ -40,6 +40,16 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
40
40
  `evidence` items are appended after the existing ones; `at` defaults to the time of the call.
41
41
  `get` shows all three fields.
42
42
 
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
+
46
+ ```json
47
+ { "action": "import", "path": "handover.json" }
48
+ ```
49
+
50
+ A relative path starts in the new session's working directory.
51
+ Import keeps the task ids, dependencies, evidence, tombstones, and next id; it never merges with or replaces an existing list.
52
+
43
53
  ## Reading the list from another extension
44
54
 
45
55
  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
@@ -85,6 +88,11 @@ existing ones. No call removes an evidence entry or a field once set; `points: 0
85
88
  is the lowest estimate. Pi drops a `null` passed for an optional parameter before
86
89
  the tool sees it, so `points: null` changes nothing.
87
90
 
91
+ `import` reads `{ "v": 1, "tasks": [...], "nextId": n }` from a JSON file and keeps every task field as stored.
92
+ If the file is unreadable or does not match the snapshot schema, the tool reports an error and leaves the list alone.
93
+ Task ids must be unique, every `blockedBy` target must exist, and `nextId` must exceed the largest task id.
94
+ The destination must contain no tasks, including tombstones.
95
+
88
96
  ## Status transitions
89
97
 
90
98
  | From | Allowed targets |
@@ -140,7 +148,7 @@ tasks' `blockedBy` arrays.
140
148
 
141
149
  ## Persistence
142
150
 
143
- Every call that changes the list (`create`, `delete`, `clear`, or an `update`
151
+ Every call that changes the list (`create`, `import`, `delete`, `clear`, or an `update`
144
152
  that changed something) appends a `todo/v1` custom entry holding the whole list
145
153
  to the session branch, and emits `todo:changed`. Both are part of the public
146
154
  contract in [CONTRACT.md](../CONTRACT.md). Custom entries are never sent to the
@@ -167,6 +175,7 @@ any disk writes.
167
175
  | Updated without a status change | `Updated #3` |
168
176
  | Update that changed nothing | `No change: #3 already matches the requested values (status: in_progress)` |
169
177
  | Deleted | `Deleted #3: Write the parser` |
178
+ | Imported | `Imported 7 tasks` |
170
179
  | Cleared | `Cleared 7 tasks` |
171
180
  | `list` row | `[in_progress] #3 Write the parser (writing the parser) ⛓ #1,#2` |
172
181
  | `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.2.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",
@@ -118,7 +118,8 @@
118
118
  "required": ["v", "id"],
119
119
  "properties": {
120
120
  "v": { "const": 1 },
121
- "id": { "type": "string", "minLength": 1 }
121
+ "id": { "type": "string", "minLength": 1 },
122
+ "imports": { "const": true, "description": "Opt in to checking snapshot imports. Without opt-in the guard blocks imports." }
122
123
  }
123
124
  },
124
125
  "change": {
@@ -91,6 +91,8 @@ export type GuardCheck = (change: TodoChangeV1) => string | undefined | Promise<
91
91
  export interface TodoGuardEventV1 {
92
92
  v: 1;
93
93
  id: string;
94
+ /** Opt in to judging imported tasks from change.after. Absent: refuse imports. */
95
+ imports?: true;
94
96
  check: GuardCheck;
95
97
  }
96
98
 
@@ -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,30 @@
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
+ for (const { id } of snapshot.tasks) {
20
+ if (ids.has(id)) throw new Error(`duplicate task id #${id}`);
21
+ if (snapshot.nextId <= id) throw new Error(`nextId must be greater than task id #${id}`);
22
+ ids.add(id);
23
+ }
24
+ for (const task of snapshot.tasks) {
25
+ for (const dep of task.blockedBy ?? []) {
26
+ if (!ids.has(dep)) throw new Error(`#${task.id} blockedBy: #${dep} not found`);
27
+ }
28
+ }
29
+ return { tasks: snapshot.tasks, nextId: snapshot.nextId };
30
+ }
@@ -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) => {
@@ -27,6 +27,7 @@ export type Op =
27
27
  | { kind: "delete"; id: number; subject: string }
28
28
  | { kind: "list"; statusFilter?: TaskStatus; includeDeleted: boolean }
29
29
  | { kind: "get"; task: Task }
30
+ | { kind: "import" }
30
31
  | { kind: "clear"; count: number }
31
32
  | { kind: "error"; message: string };
32
33
 
@@ -46,6 +47,7 @@ export function changesState(op: Op): boolean {
46
47
  case "create":
47
48
  case "delete":
48
49
  case "clear":
50
+ case "import":
49
51
  return true;
50
52
  case "update":
51
53
  return op.changed;
@@ -212,7 +214,7 @@ function taskChanged(before: Task, after: Task): boolean {
212
214
  */
213
215
  export function applyTaskMutation(
214
216
  state: TaskState,
215
- action: TaskAction,
217
+ action: Exclude<TaskAction, "import">,
216
218
  params: TaskMutationParams,
217
219
  now: string = new Date().toISOString(),
218
220
  ): 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,
@@ -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,7 +33,7 @@ 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
 
@@ -122,6 +122,7 @@ export interface TaskMutationParams {
122
122
  anchor?: string;
123
123
  evidence?: EvidenceInput[];
124
124
  id?: number;
125
+ path?: string;
125
126
  includeDeleted?: boolean;
126
127
  /** Batch create items. One-of with `subject` on `create`. */
127
128
  tasks?: CreateTaskInput[];
@@ -172,7 +173,8 @@ const CreateTaskInputSchema = Type.Object({
172
173
  });
173
174
 
174
175
  export const TodoParamsSchema = Type.Object({
175
- action: StringEnum(["create", "update", "list", "get", "delete", "clear"] as const),
176
+ action: StringEnum(["create", "update", "list", "get", "delete", "clear", "import"] as const),
177
+ path: Type.Optional(Type.String({ description: "Snapshot file (import only); relative to the session cwd" })),
176
178
  subject: Type.Optional(
177
179
  Type.String({
178
180
  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
  }