pi-todo-ledger 0.10.0 → 0.12.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
@@ -16,7 +16,8 @@ The schema's `$defs/task` is the exact definition.
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
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. |
19
+ | `origin` | object, optional | On import from a known session, `{ session }` identifies the session that wrote the imported snapshot. A move records `{ session, id }`, the immediate source and its local id. |
20
+ | `moved` | object, optional | Source tombstone: `{ moveId, from, to, at, status }`; `at` is UTC and the inner `status` is the status to restore at the destination. The task's wire status is `deleted`. |
20
21
  | `subject` | string | Short imperative line. |
21
22
  | `status` | `pending`, `in_progress`, `completed`, `deleted` | `deleted` is a tombstone that stays in the list. |
22
23
  | `description` | string, optional | Long-form detail. |
@@ -76,6 +77,55 @@ The file contains the snapshot `data` itself, not the surrounding session entry.
76
77
  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.
77
78
  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.
78
79
 
80
+ Since 0.11.0 the `flow` tool appends through the same import path to a list that need not be empty; see [Flow templates](#5-flow-templates).
81
+
82
+ ### Move selected tasks
83
+
84
+ Since 0.12.0 a source can call `todo({action: "move", ids, to})` to hand off a batch without writing to the other session's journal.
85
+ `to` is the destination's exact session id, not a prefix, path or title; a launcher may reserve the id before opening the session.
86
+ A pi journal filename reserves 31 bytes for the timestamp, separator and `.jsonl`, leaving at most 224 ASCII bytes for the id within a 255-byte filename component.
87
+ The writer claim uses a fixed-length hash, so it fits even when the journal name reaches this limit.
88
+ All ids must be distinct existing non-deleted tasks.
89
+ When one end of a `blockedBy` edge is staying and the other is leaving, the call refuses with both ids.
90
+ Include both ends, or pass `dropBlockers: true` to remove all such edges and keep the internal ones; dependencies *of* a previously deleted task are historical and need no change.
91
+
92
+ Run the import in the destination session's own pi process; do not start a second pi on its journal to deliver the file.
93
+ Pi does not support concurrent writers to one session file.
94
+ On a local filesystem the ledger claims the journal for transfers on session start and holds that claim until shutdown or process exit.
95
+ A second live writer, an unverifiable owner, or a manager whose view disagrees with the journal cannot send or receive.
96
+ The claim covers transfer calls only: it does not coordinate other tools, older extensions, remote hosts, or manual edits to the journal.
97
+ Both sessions need a persisted pi journal: in-memory sessions and new sessions that have not yet written their first message cannot transfer tasks.
98
+ The source confirms the new snapshot's exact journal entry on disk and syncs it before emitting `todo:changed` or publishing the file.
99
+ The destination does the same before acknowledging receipt; a retry verifies the receipt in the raw journal entry, before replay normalizes any legacy fields.
100
+ Before the append the ledger records the journal's size and verifies its last complete entry.
101
+ If the append throws after writing bytes, the ledger verifies that the original journal and record are still present, truncates the extra bytes, and syncs the file before pi writes the error result.
102
+ The transfer still fails, but it can be retried; when no bytes were written no truncation is needed.
103
+ If repair cannot be completed, the error result reports the cause and the session refuses further ledger writes until the journal is repaired and pi restarted.
104
+ A sync error after append is not a rollback: the tool reports failure and restores its live list from the snapshot it can verify on disk, so a later edit cannot erase the receipt or revive a moved task.
105
+ If the journal cannot be verified, that pi process blocks further ledger writes for the session; restore the journal and restart pi before retrying.
106
+ They keep the old task data and add `moved`; `list` and `get` show the destination and time, but `update` cannot change them.
107
+ A successful result includes the absolute `details.movePath`: `<agent dir>/todo-ledger/moves/<moveId>.json`, published by rename with mode `0600`.
108
+ If the file was not written after the commit, or the path was lost, repeat the same selection and destination before clearing the source list: this reconstructs the file from its tombstones without a second move or event.
109
+
110
+ In the destination, call `todo({action: "import", path: movePath, append: true})`.
111
+ The JSON file (`$defs/moveFile`) contains `{kind: "todo/move-v1", moveId, from, to, tasks}`; it is not a `todo/v1` snapshot.
112
+ As with a snapshot import, import only a file supplied by a trusted source: the target checks the destination id, task shapes, ids, uids and dependency graph, not the sender's identity.
113
+ The batch appends in source id order starting at the target's `nextId`; `blockedBy` uses the new local ids and `origin` records the old session and id.
114
+ A uid already present anywhere in the destination refuses the entire batch.
115
+ If the session switches branches while a transfer is waiting, retry on the intended branch; a proposal for the previous branch cannot commit to the new one.
116
+ The first import writes the UUID to the snapshot's optional `receivedMoves` array in the same commit as the tasks, then emits `todo:changed`.
117
+ Another import of the same batch on that branch succeeds without writing or emitting, even after a clear or restart.
118
+ Snapshot *copy* does not import another session's receipts.
119
+ Keep the file until the destination acknowledges its import; it is safe to remove afterwards.
120
+
121
+ A source namespace registration with `moves: true` gets `validate(value, tombstone, "move")`; without it the validator sees the result of an ordinary `"delete"` on the original task: no `moved`, `metadata.waitsOn`, or `metadata.until`, and a removed key's value is `undefined`.
122
+ The move file still carries the original wait fields.
123
+ For example, sb can refuse a move when `op === "move"` and its child still runs.
124
+ A kept task that loses dependencies is validated as an update.
125
+ All source change guards must register `moves: true` to judge the batch as `op: "move"`, including any removed edges in `after`; otherwise the move is refused.
126
+ All target guards must opt into imports (`imports: true`): the guard sees `op: "create"`, `params.append: true`, the original `before` and the combined `after`.
127
+ Target namespace validators see only newly appended tasks as creates.
128
+
79
129
  ### Migration from rpiv-todo
80
130
 
81
131
  When a branch has no `todo/v1` entry, the extension restores the list from rpiv-todo's records, newest first by kind:
@@ -139,7 +189,7 @@ Before a call commits, the extension runs `validate(value, task, op)` for each t
139
189
 
140
190
  - `value` is `task.metadata[ns]` after the change, or `undefined` when the call removes it (`metadata: { ns: null }`);
141
191
  - `task` is a copy of the task as it would be committed;
142
- - `op` is `"create"`, `"update"`, or `"delete"`.
192
+ - `op` is `"create"`, `"update"`, `"delete"`, or `"move"` for registrations that request move notifications.
143
193
 
144
194
  Returning a non-empty string refuses the change; returning `undefined` accepts it.
145
195
  A validator that throws refuses with `validator threw: <message>`.
@@ -251,18 +301,19 @@ const register = () =>
251
301
 
252
302
  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.
253
303
 
254
- The extension calls `check(change)` for every call that would change the list (the ledger's own [run spend](#run-spend-metadataherdrspend) record does not reach them): `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `update`, `delete`, and `clear`.
304
+ The extension calls `check(change)` for every call that would change the list (the ledger's own [run spend](#run-spend-metadataherdrspend) record does not reach them): `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `move`, `update`, `delete`, and `clear`.
255
305
  On import, namespace validators see each relevant task as a `create`.
256
306
  Guard registration accepts an optional `imports: true` field within v1.
257
307
  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.
258
- 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`.
308
+ On a snapshot copy each opted-in guard sees one `op: "create"` with `params.action: "import"`, the original `path` or `session`, an empty `before`, and the full imported list in `after`.
259
309
  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.
310
+ A [flow append](#5-flow-templates) is an import too, with `params.flow` set: `before` holds the current list and `after` adds the appended tasks; a guard finds them as the tasks of `after` whose ids are not in `before`.
260
311
  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.
261
312
  `change` matches `$defs/change` in the schema and is a copy:
262
313
 
263
314
  | Property | Meaning |
264
315
  | --- | --- |
265
- | `op` | `"create"`, `"update"`, `"delete"`, or `"clear"`. |
316
+ | `op` | `"create"`, `"update"`, `"delete"`, `"clear"`, or `"move"` for guards that opted into moves. |
266
317
  | `params` | The call's arguments as the tool received them. |
267
318
  | `before` | The whole list before the call, tombstones included. |
268
319
  | `after` | The whole list as the call would commit it. |
@@ -291,7 +342,111 @@ The same holds along a chain of guards: when session A's guard calls `todo` for
291
342
  Calling `todo` for a session whose guard is not running further up the chain is allowed.
292
343
  A call aborted (through the tool's abort signal) while it waits for an earlier call or while its guards run commits nothing and returns `Error: call aborted; nothing changed`, a `noop` update included.
293
344
 
345
+ ## 5. Flow templates
346
+
347
+ Since 0.11.0 the `flow` tool expands a template, a YAML file that describes a fixed procedure, into todos appended to the session's list in one write.
348
+ The template describes only the shape of the procedure. Once expanded, the todos are the only record of its progress, and the file is not read again: editing a template changes the next expansion, never the todos already in a list.
349
+
350
+ ### Where templates live
351
+
352
+ | Level | Files | Read when |
353
+ | --- | --- | --- |
354
+ | user | `<agent dir>/flows/*.yaml`, the agent dir being `PI_CODING_AGENT_DIR` or `~/.pi/agent` | always |
355
+ | project | `<repository>/.pi/flows/*.yaml`, the repository being the nearest directory from the session's cwd up that holds `.git` (else the cwd) | when `ctx.isProjectTrusted()` returns `true`; a host without that method gets no project templates |
356
+
357
+ The file `<name>.yaml` defines the flow `<name>`, and its `flow` field must say the same.
358
+ Links are followed, and one file reached through two links counts once.
359
+ A name that two files define is refused with both paths, never resolved by level.
360
+ A file that is no valid template, or whose `flow` differs from its file name, is listed with its errors and refuses only the name of its file; every other flow stays usable.
361
+
362
+ ### Format
363
+
364
+ ```yaml
365
+ flow: release-pin-install # lowercase letters, digits, -
366
+ rev: 1 # whole number from 1
367
+ summary: Release a pi package, pin it, install it when idle
368
+ auth: required # or none (the default)
369
+ key: "{{pkg}}@{{version}}" # names one run of the flow
370
+ params:
371
+ pkg: { doc: package name, pattern: "^pi-[a-z0-9-]+$" }
372
+ version: { pattern: "[0-9]+\\.[0-9]+\\.[0-9]+" }
373
+ root: { pattern: "[~A-Za-z0-9._/-]+", default: "~/projects/agent-root" }
374
+ steps:
375
+ - id: release
376
+ subject: Release {{pkg}} {{version}}
377
+ do: Check tags and npm, bump the version, tag, wait for Publish.
378
+ anchor: '`test "$(npm view {{pkg}} version)" = {{version}}`'
379
+ - id: install
380
+ after: [release]
381
+ subject: Install when no train runs
382
+ run: "{{root}}/scripts/install-when-idle.sh"
383
+ monitor: true
384
+ waits: no train in progress
385
+ anchor: '`grep -qF "npm:{{pkg}}@{{version}}" ~/.pi/agent/settings.json`'
386
+ - id: prod
387
+ after: [install]
388
+ subject: Deploy {{pkg}} to production
389
+ approve: Deploy {{pkg}} {{version}} to production?
390
+ ```
391
+
392
+ | Field | Meaning |
393
+ | --- | --- |
394
+ | `flow`, `rev`, `summary` | Required. The template's name, revision, and one line about it. |
395
+ | `auth` | `required`: the call must quote the user's words that authorize the run. `none` or absent: it may. |
396
+ | `key` | Required. Identifies one run of the flow; it may hold placeholders. |
397
+ | `params.<name>` | `doc` (optional), `pattern` (optional, default `[A-Za-z0-9._@/+-]+`), `default` (optional; a param without one is required). A value must match the whole pattern: the tool wraps it in `^(?:…)$`. A default must be a quoted string that matches it; YAML would read `0.10` as the number 0.1. |
398
+ | `steps[].id`, `after` | Required id (letters, digits, `_`, `-`), and the ids of the steps it follows. |
399
+ | `steps[].subject` | Required. The todo's subject. |
400
+ | `steps[].do` | How to do the step; the first line of the todo's `description`. |
401
+ | `steps[].anchor` | Required except on an `approve` step: the check that shows the step is done. Keep side effects out of it, since a check is run again; put them in `run`. |
402
+ | `steps[].run`, `monitor` | A command to run, and `monitor: true` to run it under MonitorCreate; written into the `description`. |
403
+ | `steps[].waits` | What the step waits on once it runs; written into the `description`. The agent sets `waitsOn` when the wait starts, so a step not yet reached is not shown as held up. |
404
+ | `steps[].approve` | A question for the user. The subject gets the prefix `Needs approval: `, the anchor becomes `The user approves, quoted: <question>`, and the description asks the agent to stop until the user answers. An approve step takes no `anchor`. |
405
+
406
+ `{{name}}` in `key`, `subject`, `do`, `anchor`, `run`, `waits`, and `approve` is replaced by the param's value. Spaces inside the braces are allowed. Text such as `{{.State}}`, whose name does not start with a letter or `_`, is no placeholder and is left as written.
407
+ Any other field is unknown and refused.
408
+
409
+ ### The `flow` tool
410
+
411
+ ```ts
412
+ flow({ name?: string, params?: Record<string, string>, auth?: string, dryRun?: boolean })
413
+ ```
414
+
415
+ Without `name`, it lists the templates in reach with their params, steps, and files, then the files that are no valid template; `params`, `auth`, or `dryRun` without `name` is refused.
416
+ With `name`, it checks everything below before it writes anything. Any problem refuses the whole call with an error result (`isError: true`, text `Error: <reason>`; a template's reason lists all its problems):
417
+
418
+ - the template: an unknown name, a name in two files, a `flow` that differs from the file name, an unknown field, a placeholder naming no declared param, a duplicate step id, an `after` naming no step, a cycle, a step without an anchor, a malformed value;
419
+ - the call: an undeclared param, a required param left out, a value that does not match its pattern, a `key` that renders blank, `auth: required` without `auth`;
420
+ - the list: an open (`pending` or `in_progress`) todo whose `metadata.flow` has the same `name` and `key`. Once those todos are completed or deleted, the same key can be expanded again.
421
+
422
+ With `dryRun: true` it returns the todos it would append, with the ids they would get, and writes nothing. Their uids are drawn again on the real write.
423
+
424
+ Otherwise it appends the steps after the existing tasks, in an order where each step follows the steps it names in `after`, else as written:
425
+
426
+ - ids run from the list's `nextId`, each `after` becomes `blockedBy` with those ids, and each todo gets a fresh uid;
427
+ - each todo is `pending` with its `subject`, `anchor`, and a `description` made of `do`, the approval request, `run`, and `waits`;
428
+ - `metadata.flow` records where it came from (below).
429
+
430
+ The write is the guarded import write of the `todo` tool (§1, §3, §4), and the session's calls run one at a time as in §4.
431
+ Namespace validators see each appended task as a `create`, and the existing tasks are not judged again.
432
+ Guards see one `op: "create"` with `params` `{ action: "import", flow, rev, key, params, auth? }`, `params.params` holding every value with the defaults filled in; a guard that has not opted in to imports refuses it.
433
+ On success one `todo/v1` entry is written and `todo:changed` fires once.
434
+
435
+ ### `metadata.flow`
436
+
437
+ | Key | Type | Meaning |
438
+ | --- | --- | --- |
439
+ | `name` | non-empty string | The template's `flow`. |
440
+ | `rev` | integer ≥ 1 | Its `rev` when it was expanded. |
441
+ | `step` | non-empty string | The step's `id`. |
442
+ | `key` | non-empty string | The rendered `key` of the run. |
443
+ | `auth` | non-empty string, optional | The words the call quoted in `auth`. |
444
+
445
+ The ledger owns this namespace: it checks the shape on every create, update, and delete that carries the key, refuses any other property, and ignores a `todo:namespace` registration of `flow`.
446
+ `metadata: { flow: null }` removes it, and the todo then no longer counts toward its run's key.
447
+ It records provenance, not progress: the todo's `status`, `evidence`, and wait marks say how the run is going.
448
+
294
449
  ## Coexistence
295
450
 
296
- This package registers the tool name `todo`, as rpiv-todo does.
451
+ This package registers the tool name `todo`, as rpiv-todo does, and since 0.11.0 the tool name `flow`.
297
452
  Install one of the two: with both installed, the tool names clash.
package/README.md CHANGED
@@ -93,6 +93,39 @@ A snapshot file works too: save the `data` from a `todo/v1` entry as JSON and im
93
93
  A relative path starts in the new session's working directory.
94
94
  Import keeps the task ids, dependencies, evidence, tombstones, and next id; it never merges with or replaces an existing list.
95
95
 
96
+ ### Move selected todos to another session
97
+
98
+ To hand off two tasks without copying the rest of the plan, call `todo` once in each session:
99
+
100
+ ```ts
101
+ // Source: use the exact id of the destination, even if it has not started yet.
102
+ const sent = await todo({ action: "move", ids: [2, 5], to: targetSessionId });
103
+ // Destination: pass sent.details.movePath across the process boundary.
104
+ await todo({ action: "import", path: movePath, append: true });
105
+ ```
106
+
107
+ The source lists both tasks as `[moved]`, with the destination and time; they no longer appear in its panel or count as open.
108
+ If a dependency crosses the selection, include both ends, or pass `dropBlockers: true` to remove that edge.
109
+ The destination keeps its existing list and assigns new local ids, retaining the moved tasks' uids, statuses and evidence.
110
+ Repeating the import does not add another copy.
111
+ Send the import call to the pi process that owns the destination session; do not open a second pi on its journal.
112
+ Both sessions must have written their first message to disk.
113
+ Keep the move file until the destination confirms receipt, then remove it if you no longer need it.
114
+ See the [move contract](CONTRACT.md#move-selected-tasks) for retries and extension hooks.
115
+
116
+ ### Flow templates
117
+
118
+ A fixed procedure, such as a release followed by a pin and an install, can be written once as a YAML template and expanded into chained todos with one `flow` call.
119
+ Put templates in `~/.pi/agent/flows/<name>.yaml`, or in `<repo>/.pi/flows/<name>.yaml` for one project (read only when pi trusts the project); the file name is the flow's name.
120
+
121
+ ```text
122
+ flow({}) // list the templates and their params
123
+ flow({ name: "release-pin-install", params: { pkg: "pi-todo-ledger", version: "0.11.0", panes: "w1:p1" }, auth: "<the user's words>", dryRun: true })
124
+ ```
125
+
126
+ The tool checks the template, the params, and the list before it writes anything, then appends every step as a pending todo in one write: ids continue the list, each step's `after` becomes `blockedBy`, and each todo keeps its anchor.
127
+ After that the todos are the only record of the run. The format and the checks are in [CONTRACT.md](CONTRACT.md#5-flow-templates).
128
+
96
129
  ## Reading the list from another extension
97
130
 
98
131
  Listen for the event, or read the newest snapshot on the branch:
@@ -0,0 +1,53 @@
1
+ # Move selected todos between sessions
2
+
3
+ A move transfers responsibility for specific todos; importing a snapshot still copies a list.
4
+ The two sessions need not run at the same time, and neither writes the other's journal.
5
+ Each session has one writing pi process: deliver the import to the target's owning process rather than starting a second one on the same file.
6
+ A local transfer claim next to the journal records the host and pid; an owner publishes its unique token before checking peers.
7
+ A live peer or unverifiable owner blocks the transfer, a normally exiting owner removes its token, and a confirmed dead local pid does not hold up recovery.
8
+ This is not a general multi-writer protocol: ordinary pi appends and older clients do not participate.
9
+
10
+ ## Source
11
+
12
+ Call `todo({action: "move", ids: [4, 7], to: targetSessionId})` with the exact destination id, not a prefix or a display name.
13
+ The destination need not exist yet if the launcher knows its id.
14
+ Every selected id must exist, appear once and be non-deleted.
15
+ A dependency crossing the selection in either direction refuses the entire call; include the other task, or set `dropBlockers: true` to remove just the crossing edges.
16
+ Kept tombstones' historical dependencies do not constrain new work.
17
+
18
+ In one guarded snapshot the source records the batch UUID, destination, UTC time and former status in each selected task's `moved` field and sets its wire status to `deleted`.
19
+ This optional field distinguishes a move from a deletion without introducing a status unknown to v1 readers: old panels and close guards already ignore `deleted`.
20
+ The new tool lists moved rows by default, including destination and time, and refuses to edit them.
21
+ Namespace validators registered with `moves: true` see `op: "move"` for these tasks; older validators see the removal as `"delete"`.
22
+ Both see `"update"` for kept tasks losing blockers.
23
+ Guards must opt in with `moves: true` to judge the whole proposed change, so a guard written for single-task deletion cannot silently accept a batch.
24
+
25
+ ## File and recovery
26
+
27
+ An in-memory session or a new session without a journal cannot send or receive a move.
28
+ A transfer compares the manager's last entry with the journal tail, confirms the exact committed snapshot bytes and syncs the journal before reporting success; a retry confirms the snapshot on disk too.
29
+ If pi throws partway through appending a transfer snapshot, it restores its in-memory position but may leave part of a JSON line on disk.
30
+ Before returning the error, the ledger truncates the journal to its verified pre-append byte size and syncs it, so pi can append the tool result and the next message on clean record boundaries.
31
+ If the repair fails, the result names the failure and the ledger blocks further writes for that session.
32
+ A process or machine crash between the partial write and the truncate can still leave an incomplete line: pi journal appends are not crash-atomic, whether the record is a move, a message or another entry.
33
+ Only after committing the source snapshot does the tool publish a private JSON file under pi's agent directory, by atomic rename, and return its absolute `details.movePath`.
34
+ The file contains the batch identity, source, destination and selected tasks with their original statuses and only internal dependencies; it is not itself a list snapshot.
35
+ If publication fails after commit, or the acknowledgement is lost, repeat the exact selection and destination on the source: the tombstones materialize the *same* file, without another change event or another move.
36
+ A partial batch, a different destination or a mixture of tombstones and live ids cannot move those tombstones again.
37
+ Once the destination acknowledges the import, the caller can remove the file.
38
+
39
+ ## Destination
40
+
41
+ Call `todo({action: "import", path: movePath, append: true})` in the named destination.
42
+ Reject a wrong destination, malformed batch, dangling dependency or duplicate uid instead of partially importing it.
43
+ Assign consecutive local ids starting at `nextId` in source id order, translate internal edges with the complete mapping, and keep every other task field except `origin`, now `{session: sourceSessionId, id: oldId}`.
44
+ Target namespaces see creates, and the existing import opt-in rule applies to guards.
45
+ Store a receipt for the batch UUID in the same branch snapshot as the appended tasks; subsequent imports are no-ops even after deleting or clearing the tasks and replaying the branch.
46
+ As with other ledger changes, navigating to an earlier branch restores its history rather than spending a receipt on another timeline.
47
+ A source move and the first destination import each emit one `todo:changed`; a refusal or retry emits none.
48
+
49
+ ## Verification
50
+
51
+ Drive both sides through the registered tool, with a file as their only transport.
52
+ Check source visibility and immutability, refusal and explicit removal of crossing edges, guard and namespace refusals, source retry, destination replay and clear, id and uid handling, and both snapshots and events.
53
+ Run `npm run check` and `npm test` before pushing the branch; no release.
@@ -4,6 +4,9 @@ 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
5
  rpiv-todo's, plus snapshot import and the bookkeeping fields `points`, `anchor`, and `evidence`.
6
6
 
7
+ The `flow` tool, which appends the todos of a flow template, is described in
8
+ [CONTRACT.md](../CONTRACT.md#5-flow-templates).
9
+
7
10
  ## Actions
8
11
 
9
12
  | Action | Required params | What it does |
@@ -14,13 +17,18 @@ rpiv-todo's, plus snapshot import and the bookkeeping fields `points`, `anchor`,
14
17
  | `get` | `id` | Returns one task with its `blockedBy` and reverse `blocks` edges. |
15
18
  | `delete` | `id` | Tombstones the task (`status: "deleted"`); it is not removed. |
16
19
  | `clear` | — | Drops every task and resets the id counter to `1`. |
17
- | `import` | `path` or `session` | Restores a `todo/v1` snapshot file, or another session's latest snapshot, into an empty list. |
20
+ | `move` | `ids`, `to` | Marks selected tasks as moved and returns the transfer file in `details.movePath`. |
21
+ | `import` | `path` or `session` | Copies a snapshot into an empty list; with `path` and `append: true`, receives a move into the existing list. |
18
22
 
19
23
  ## Parameters
20
24
 
21
25
  ```ts
22
26
  todo({
23
- action: "create" | "update" | "list" | "get" | "delete" | "clear" | "import",
27
+ action: "create" | "update" | "list" | "get" | "delete" | "clear" | "import" | "move",
28
+ ids?: number[], // move: distinct local ids
29
+ to?: string, // move: exact destination session id
30
+ dropBlockers?: boolean, // move: explicitly sever crossing dependencies
31
+ append?: boolean, // import: append a move file instead of copying a snapshot
24
32
 
25
33
  path?: string, // import only; relative to the session cwd
26
34
  session?: string, // import only, instead of path: session id, unique id prefix, or .jsonl path
@@ -72,7 +80,7 @@ todo({
72
80
  status?: "pending" | "in_progress" | "completed" | "deleted",
73
81
 
74
82
  // list-only
75
- includeDeleted?: boolean, // default false — hides tombstones
83
+ includeDeleted?: boolean, // default false — hides ordinary deletions, not moved rows
76
84
  })
77
85
  ```
78
86
 
@@ -120,7 +128,8 @@ matched against the `<time>_<id>.jsonl` files in `PI_CODING_AGENT_SESSION_DIR`
120
128
  session is never matched. An exact id wins over prefix matches.
121
129
  If the file is unreadable or does not match the snapshot schema, the tool reports an error and leaves the list alone.
122
130
  Task ids must be unique, every `blockedBy` target must exist, and `nextId` must exceed the largest task id.
123
- The destination must contain no tasks, including tombstones.
131
+ A snapshot copy requires a destination with no tasks, including tombstones.
132
+ For `append: true`, see [Move selected tasks](../CONTRACT.md#move-selected-tasks).
124
133
 
125
134
  ## Status transitions
126
135
 
@@ -131,9 +140,10 @@ The destination must contain no tasks, including tombstones.
131
140
  | `completed` | `deleted` |
132
141
  | `deleted` | _(terminal)_ |
133
142
 
134
- A transition to the current status is always accepted and reported as a no-op.
143
+ A transition to the current status is accepted as a no-op unless the task has moved; move tombstones are immutable.
135
144
  `delete` keeps the task as a tombstone so historic `blockedBy` references still
136
- resolve; tombstones are hidden from `list` unless you pass `includeDeleted: true`.
145
+ resolve; ordinary deletions are hidden from `list` unless you pass `includeDeleted: true`.
146
+ Moved rows are listed by default with their destination and move time.
137
147
 
138
148
  ## Dependencies
139
149
 
@@ -159,7 +169,8 @@ tasks' `blockedBy` arrays.
159
169
  tasks: Array<{
160
170
  id: number,
161
171
  uid?: string, // stable across branches and import
162
- origin?: { session: string }, // source session on import, when known
172
+ moved?: { moveId: string, from: string, to: string, at: string, status: "pending" | "in_progress" | "completed" },
173
+ origin?: { session: string, id?: number }, // source session on import, when known
163
174
  subject: string,
164
175
  description?: string,
165
176
  activeForm?: string,
@@ -173,14 +184,15 @@ tasks' `blockedBy` arrays.
173
184
  evidence?: Array<{ command: string, sha?: string, ref?: string, result: "pass" | "fail", at: string }>,
174
185
  }>,
175
186
  nextId: number,
176
- error?: string, // present only on a rejected call
187
+ movePath?: string, // source move: absolute file path
188
+ error?: string, // present on an unsuccessful call
177
189
  }
178
190
  }
179
191
  ```
180
192
 
181
193
  ## Persistence
182
194
 
183
- Every call that changes the list (`create`, `import`, `delete`, `clear`, or an `update`
195
+ Every call that changes the list (`create`, `import`, `move`, `delete`, `clear`, or an `update`
184
196
  that changed something) appends a `todo/v1` custom entry holding the whole list
185
197
  to the session branch, and emits `todo:changed`. Both are part of the public
186
198
  contract in [CONTRACT.md](../CONTRACT.md). Custom entries are never sent to the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.10.0",
3
+ "version": "0.12.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",
@@ -57,5 +57,8 @@
57
57
  "@types/node": "26.6.6",
58
58
  "typebox": "1.4.7",
59
59
  "typescript": "7.0.2"
60
+ },
61
+ "dependencies": {
62
+ "yaml": "2.9.1"
60
63
  }
61
64
  }
@@ -16,6 +16,7 @@
16
16
  "type": "array",
17
17
  "items": { "$ref": "#/$defs/task" }
18
18
  },
19
+ "receivedMoves": { "description": "Move files already appended on this branch, including before a clear.", "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/moveId" } },
19
20
  "nextId": {
20
21
  "description": "Id the next created task receives.",
21
22
  "type": "integer",
@@ -23,16 +24,40 @@
23
24
  }
24
25
  }
25
26
  },
27
+ "moveId": { "type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" },
28
+ "moveFile": {
29
+ "type": "object",
30
+ "required": ["kind", "moveId", "from", "to", "tasks"],
31
+ "properties": {
32
+ "kind": { "const": "todo/move-v1" },
33
+ "moveId": { "$ref": "#/$defs/moveId" },
34
+ "from": { "type": "string", "minLength": 1 },
35
+ "to": { "type": "string", "minLength": 1 },
36
+ "tasks": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/task" } }
37
+ }
38
+ },
26
39
  "taskStatus": {
27
40
  "enum": ["pending", "in_progress", "completed", "deleted"]
28
41
  },
29
42
  "task": {
30
43
  "type": "object",
31
44
  "required": ["id", "subject", "status"],
45
+ "if": { "required": ["moved"] },
46
+ "then": { "properties": { "status": { "const": "deleted" } } },
32
47
  "properties": {
33
48
  "id": { "type": "integer", "minimum": 1 },
34
49
  "uid": { "type": "string", "pattern": "^t_[a-z2-7]{10}$" },
35
- "origin": { "type": "object", "required": ["session"], "properties": { "session": { "type": "string", "minLength": 1 } } },
50
+ "origin": { "type": "object", "required": ["session"], "properties": { "session": { "type": "string", "minLength": 1 }, "id": { "type": "integer", "minimum": 1 } } },
51
+ "moved": {
52
+ "type": "object", "required": ["moveId", "from", "to", "at", "status"],
53
+ "properties": {
54
+ "moveId": { "$ref": "#/$defs/moveId" },
55
+ "from": { "type": "string", "minLength": 1 },
56
+ "to": { "type": "string", "minLength": 1 },
57
+ "at": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" },
58
+ "status": { "enum": ["pending", "in_progress", "completed"] }
59
+ }
60
+ },
36
61
  "subject": { "type": "string" },
37
62
  "status": { "$ref": "#/$defs/taskStatus" },
38
63
  "description": { "type": "string" },
@@ -127,6 +152,7 @@
127
152
  "properties": {
128
153
  "v": { "const": 1 },
129
154
  "id": { "type": "string", "minLength": 1 },
155
+ "moves": { "const": true, "description": "Opt in to checking source moves. Without opt-in the guard blocks moves." },
130
156
  "imports": { "const": true, "description": "Opt in to checking snapshot imports. Without opt-in the guard blocks imports." }
131
157
  }
132
158
  },
@@ -136,7 +162,7 @@
136
162
  "type": "object",
137
163
  "required": ["op", "params", "before", "after", "sessionId", "cwd"],
138
164
  "properties": {
139
- "op": { "enum": ["create", "update", "delete", "clear"] },
165
+ "op": { "enum": ["create", "update", "delete", "clear", "move"] },
140
166
  "params": { "description": "The call's arguments as the tool received them.", "type": "object" },
141
167
  "before": { "type": "array", "items": { "$ref": "#/$defs/task" } },
142
168
  "after": { "type": "array", "items": { "$ref": "#/$defs/task" } },
@@ -155,7 +181,8 @@
155
181
  "required": ["v", "ns"],
156
182
  "properties": {
157
183
  "v": { "const": 1 },
158
- "ns": { "type": "string", "minLength": 1 }
184
+ "ns": { "type": "string", "minLength": 1 },
185
+ "moves": { "const": true, "description": "Receive move rather than delete for tasks leaving the source." }
159
186
  }
160
187
  }
161
188
  }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Where flow templates live and which are in reach of a session: `<agent dir>/flows/*.yaml` (user level) and
3
+ * `<repository root>/.pi/flows/*.yaml` (project level, only when pi says it trusts the project). `<name>.yaml` defines flow `<name>`.
4
+ * Files are read on every call, so an edited
5
+ * template applies to the next expansion and never to todos already in a list.
6
+ */
7
+
8
+ import { existsSync } from "node:fs";
9
+ import { readdir, readFile, realpath, stat } from "node:fs/promises";
10
+ import { basename, dirname, join, resolve } from "node:path";
11
+ import { type BrokenTemplate, type FlowTemplate, parseTemplate } from "./template.ts";
12
+
13
+ export type FlowLevel = "user" | "project";
14
+
15
+ export interface FlowDir {
16
+ level: FlowLevel;
17
+ dir: string;
18
+ /** Why the directory is not read: a project pi does not trust. */
19
+ skipped?: string;
20
+ }
21
+
22
+ export interface FlowCatalog {
23
+ dirs: FlowDir[];
24
+ /** Valid templates by name; a name with more than one file is refused by `find`. */
25
+ templates: Map<string, FlowTemplate[]>;
26
+ broken: BrokenTemplate[];
27
+ }
28
+
29
+ /** The nearest directory from `cwd` up that holds `.git`, else `cwd` itself. */
30
+ export function repositoryRoot(cwd: string): string {
31
+ const start = resolve(cwd);
32
+ for (let dir = start; ; dir = dirname(dir)) {
33
+ if (existsSync(join(dir, ".git"))) return dir;
34
+ if (dirname(dir) === dir) return start;
35
+ }
36
+ }
37
+
38
+ async function agentDir(): Promise<string> {
39
+ const { getAgentDir } = await import("@earendil-works/pi-coding-agent");
40
+ return getAgentDir();
41
+ }
42
+
43
+ /** The template directories of a session, user level first. */
44
+ export async function flowDirs(cwd: string, projectTrusted: boolean): Promise<FlowDir[]> {
45
+ const project = join(repositoryRoot(cwd), ".pi", "flows");
46
+ return [
47
+ { level: "user", dir: join(await agentDir(), "flows") },
48
+ { level: "project", dir: project, ...(projectTrusted ? {} : { skipped: "pi does not trust this project" }) },
49
+ ];
50
+ }
51
+
52
+ /** `*.yaml` files of `dir` (links followed), sorted; a missing directory has none. */
53
+ async function yamlFiles(dir: string): Promise<string[]> {
54
+ let names: string[];
55
+ try {
56
+ names = await readdir(dir);
57
+ } catch {
58
+ return [];
59
+ }
60
+ const files: string[] = [];
61
+ for (const name of names.filter((n) => n.endsWith(".yaml")).sort()) {
62
+ const path = join(dir, name);
63
+ try {
64
+ if ((await stat(path)).isFile()) files.push(path);
65
+ } catch {
66
+ // A dangling link is no template.
67
+ }
68
+ }
69
+ return files;
70
+ }
71
+
72
+ export async function loadCatalog(dirs: FlowDir[]): Promise<FlowCatalog> {
73
+ const templates = new Map<string, FlowTemplate[]>();
74
+ const broken: BrokenTemplate[] = [];
75
+ // One file linked into both levels (or reached by two links) is one template, not a duplicate.
76
+ const seen = new Set<string>();
77
+ for (const { dir, skipped } of dirs) {
78
+ if (skipped) continue;
79
+ for (const file of await yamlFiles(dir)) {
80
+ const real = await realpath(file).catch(() => file);
81
+ if (seen.has(real)) continue;
82
+ seen.add(real);
83
+ let text: string;
84
+ try {
85
+ text = await readFile(file, "utf8");
86
+ } catch (error) {
87
+ broken.push({ file, errors: [`cannot read: ${(error as Error).message}`] });
88
+ continue;
89
+ }
90
+ // The file name names the flow, so a broken file blocks only its own name.
91
+ const name = basename(file, ".yaml");
92
+ const parsed = parseTemplate(text, file);
93
+ if (!parsed.ok) broken.push({ ...parsed.broken, flow: name });
94
+ else if (parsed.template.flow !== name) {
95
+ broken.push({ file, flow: name, errors: [`flow ${parsed.template.flow} does not match the file name; name the file ${parsed.template.flow}.yaml or the flow ${name}`] });
96
+ } else templates.set(name, [...(templates.get(name) ?? []), parsed.template]);
97
+ }
98
+ }
99
+ return { dirs, templates, broken };
100
+ }
101
+
102
+ /** The one valid template named `name`, or why the call cannot use it. */
103
+ export function findTemplate(catalog: FlowCatalog, name: string): { template: FlowTemplate } | { error: string } {
104
+ const valid = catalog.templates.get(name) ?? [];
105
+ const invalid = catalog.broken.filter((b) => b.flow === name);
106
+ const files = [...valid.map((t) => t.file), ...invalid.map((b) => b.file)];
107
+ if (files.length > 1) return { error: `flow ${name} is defined in more than one file; keep one:\n${files.map((f) => ` ${f}`).join("\n")}` };
108
+ if (invalid.length) return { error: `flow ${name} in ${invalid[0]!.file} is not a valid template:\n${invalid[0]!.errors.map((e) => ` - ${e}`).join("\n")}` };
109
+ if (valid.length === 1) return { template: valid[0]! };
110
+ const known = [...catalog.templates.keys()].sort();
111
+ const skipped = catalog.dirs.filter((d) => d.skipped).map((d) => ` (${d.dir} not read: ${d.skipped})`);
112
+ return { error: `unknown flow ${name}; known: ${known.length ? known.join(", ") : "none"}${skipped.join("")}` };
113
+ }