pi-todo-ledger 0.11.0 → 0.12.1

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. |
@@ -78,6 +79,54 @@ New snapshots carry the writer's `sessionId`. Import uses it to set each task's
78
79
 
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).
80
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, the transfer fails; you can retry if pi rolled back its in-memory entry and the journal's identity, size and last record are unchanged.
102
+ If the journal grew, pi cannot tell the ledger which bytes it wrote, so the ledger leaves the file intact, even when the extra bytes look like part of the expected record.
103
+ If the journal grew or the ledger cannot verify the original tail, the result reports both the append error and the verification failure.
104
+ The session then refuses further ledger writes; stop pi, repair the journal and restart before retrying.
105
+ 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.
106
+ If the journal cannot be verified, that pi process blocks further ledger writes for the session; restore the journal and restart pi before retrying.
107
+ They keep the old task data and add `moved`; `list` and `get` show the destination and time, but `update` cannot change them.
108
+ A successful result includes the absolute `details.movePath`: `<agent dir>/todo-ledger/moves/<moveId>.json`, published by rename with mode `0600`.
109
+ 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.
110
+
111
+ In the destination, call `todo({action: "import", path: movePath, append: true})`.
112
+ The JSON file (`$defs/moveFile`) contains `{kind: "todo/move-v1", moveId, from, to, tasks}`; it is not a `todo/v1` snapshot.
113
+ 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.
114
+ 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.
115
+ A uid already present anywhere in the destination refuses the entire batch.
116
+ 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.
117
+ The first import writes the UUID to the snapshot's optional `receivedMoves` array in the same commit as the tasks, then emits `todo:changed`.
118
+ Another import of the same batch on that branch succeeds without writing or emitting, even after a clear or restart.
119
+ Snapshot *copy* does not import another session's receipts.
120
+ Keep the file until the destination acknowledges its import; it is safe to remove afterwards.
121
+
122
+ 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`.
123
+ The move file still carries the original wait fields.
124
+ For example, sb can refuse a move when `op === "move"` and its child still runs.
125
+ A kept task that loses dependencies is validated as an update.
126
+ 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.
127
+ All target guards must opt into imports (`imports: true`): the guard sees `op: "create"`, `params.append: true`, the original `before` and the combined `after`.
128
+ Target namespace validators see only newly appended tasks as creates.
129
+
81
130
  ### Migration from rpiv-todo
82
131
 
83
132
  When a branch has no `todo/v1` entry, the extension restores the list from rpiv-todo's records, newest first by kind:
@@ -141,7 +190,7 @@ Before a call commits, the extension runs `validate(value, task, op)` for each t
141
190
 
142
191
  - `value` is `task.metadata[ns]` after the change, or `undefined` when the call removes it (`metadata: { ns: null }`);
143
192
  - `task` is a copy of the task as it would be committed;
144
- - `op` is `"create"`, `"update"`, or `"delete"`.
193
+ - `op` is `"create"`, `"update"`, `"delete"`, or `"move"` for registrations that request move notifications.
145
194
 
146
195
  Returning a non-empty string refuses the change; returning `undefined` accepts it.
147
196
  A validator that throws refuses with `validator threw: <message>`.
@@ -253,11 +302,11 @@ const register = () =>
253
302
 
254
303
  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.
255
304
 
256
- 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`.
305
+ 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`.
257
306
  On import, namespace validators see each relevant task as a `create`.
258
307
  Guard registration accepts an optional `imports: true` field within v1.
259
308
  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.
260
- 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`.
309
+ 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`.
261
310
  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.
262
311
  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`.
263
312
  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.
@@ -265,7 +314,7 @@ A valid `update` that changes nothing, such as setting `in_progress` on a task a
265
314
 
266
315
  | Property | Meaning |
267
316
  | --- | --- |
268
- | `op` | `"create"`, `"update"`, `"delete"`, or `"clear"`. |
317
+ | `op` | `"create"`, `"update"`, `"delete"`, `"clear"`, or `"move"` for guards that opted into moves. |
269
318
  | `params` | The call's arguments as the tool received them. |
270
319
  | `before` | The whole list before the call, tombstones included. |
271
320
  | `after` | The whole list as the call would commit it. |
package/README.md CHANGED
@@ -93,6 +93,26 @@ 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
+
96
116
  ### Flow templates
97
117
 
98
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.
@@ -0,0 +1,54 @@
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
+ The ledger checks the journal without modifying it: if the same file still ends at the same byte with the same record, the transfer can be retried.
31
+ Pi does not report how many bytes it wrote before throwing, so the ledger preserves any extra bytes rather than risk removing another writer's entry.
32
+ If the journal grew or the original tail cannot be verified, the result names both failures and the ledger blocks further writes for that session until the journal is repaired and pi restarted.
33
+ This cannot stop pi itself from appending a tool result after a partial line.
34
+ 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`.
35
+ 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.
36
+ 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.
37
+ A partial batch, a different destination or a mixture of tombstones and live ids cannot move those tombstones again.
38
+ Once the destination acknowledges the import, the caller can remove the file.
39
+
40
+ ## Destination
41
+
42
+ Call `todo({action: "import", path: movePath, append: true})` in the named destination.
43
+ Reject a wrong destination, malformed batch, dangling dependency or duplicate uid instead of partially importing it.
44
+ 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}`.
45
+ Target namespaces see creates, and the existing import opt-in rule applies to guards.
46
+ 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.
47
+ As with other ledger changes, navigating to an earlier branch restores its history rather than spending a receipt on another timeline.
48
+ A source move and the first destination import each emit one `todo:changed`; a refusal or retry emits none.
49
+
50
+ ## Verification
51
+
52
+ Drive both sides through the registered tool, with a file as their only transport.
53
+ 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.
54
+ Run `npm run check` and `npm test` before pushing the branch; no release.
@@ -17,13 +17,18 @@ The `flow` tool, which appends the todos of a flow template, is described in
17
17
  | `get` | `id` | Returns one task with its `blockedBy` and reverse `blocks` edges. |
18
18
  | `delete` | `id` | Tombstones the task (`status: "deleted"`); it is not removed. |
19
19
  | `clear` | — | Drops every task and resets the id counter to `1`. |
20
- | `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. |
21
22
 
22
23
  ## Parameters
23
24
 
24
25
  ```ts
25
26
  todo({
26
- 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
27
32
 
28
33
  path?: string, // import only; relative to the session cwd
29
34
  session?: string, // import only, instead of path: session id, unique id prefix, or .jsonl path
@@ -75,7 +80,7 @@ todo({
75
80
  status?: "pending" | "in_progress" | "completed" | "deleted",
76
81
 
77
82
  // list-only
78
- includeDeleted?: boolean, // default false — hides tombstones
83
+ includeDeleted?: boolean, // default false — hides ordinary deletions, not moved rows
79
84
  })
80
85
  ```
81
86
 
@@ -123,7 +128,8 @@ matched against the `<time>_<id>.jsonl` files in `PI_CODING_AGENT_SESSION_DIR`
123
128
  session is never matched. An exact id wins over prefix matches.
124
129
  If the file is unreadable or does not match the snapshot schema, the tool reports an error and leaves the list alone.
125
130
  Task ids must be unique, every `blockedBy` target must exist, and `nextId` must exceed the largest task id.
126
- 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).
127
133
 
128
134
  ## Status transitions
129
135
 
@@ -134,9 +140,10 @@ The destination must contain no tasks, including tombstones.
134
140
  | `completed` | `deleted` |
135
141
  | `deleted` | _(terminal)_ |
136
142
 
137
- 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.
138
144
  `delete` keeps the task as a tombstone so historic `blockedBy` references still
139
- 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.
140
147
 
141
148
  ## Dependencies
142
149
 
@@ -162,7 +169,8 @@ tasks' `blockedBy` arrays.
162
169
  tasks: Array<{
163
170
  id: number,
164
171
  uid?: string, // stable across branches and import
165
- 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
166
174
  subject: string,
167
175
  description?: string,
168
176
  activeForm?: string,
@@ -176,14 +184,15 @@ tasks' `blockedBy` arrays.
176
184
  evidence?: Array<{ command: string, sha?: string, ref?: string, result: "pass" | "fail", at: string }>,
177
185
  }>,
178
186
  nextId: number,
179
- error?: string, // present only on a rejected call
187
+ movePath?: string, // source move: absolute file path
188
+ error?: string, // present on an unsuccessful call
180
189
  }
181
190
  }
182
191
  ```
183
192
 
184
193
  ## Persistence
185
194
 
186
- 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`
187
196
  that changed something) appends a `todo/v1` custom entry holding the whole list
188
197
  to the session branch, and emits `todo:changed`. Both are part of the public
189
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.11.0",
3
+ "version": "0.12.1",
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",
@@ -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
  }
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  import { FLOW_NAMESPACE, validateFlowMetadata } from "./flow/metadata.ts";
38
38
  import { FLOW_TOOL_NAME, registerFlowTool } from "./flow/tool.ts";
39
39
  import { makeCommitNow, makeFinishCall } from "./ledger/finish-call.ts";
40
+ import { TransferWriters } from "./ledger/transfer-writers.ts";
40
41
  import { GuardRegistry } from "./ledger/guards.ts";
41
42
  import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
42
43
  import { registerHerdrSpend } from "./ledger/herdr-spend.ts";
@@ -214,7 +215,8 @@ export default function (
214
215
  });
215
216
 
216
217
  const finish = makeFinishCall(pi, namespaces, guards);
217
- registerTodoTool(pi, finish);
218
+ const transferWriters = new TransferWriters();
219
+ registerTodoTool(pi, finish, transferWriters);
218
220
  registerFlowTool(pi, finish);
219
221
  registerHerdrOwner(pi, finish);
220
222
  registerHerdrSpend(pi, makeCommitNow(pi, namespaces));
@@ -301,6 +303,12 @@ export default function (
301
303
  if (!isStaleCtxError(e)) throw e;
302
304
  return;
303
305
  }
306
+ // Establish the owning process even when another copy opens the journal before its first transfer.
307
+ // Ordinary bookkeeping stays available; only transfers require this claim and report its refusal.
308
+ const journal = ctx.sessionManager.getSessionFile?.();
309
+ if (journal) {
310
+ try { transferWriters.claim(id, journal); } catch { /* A transfer must claim successfully itself. */ }
311
+ }
304
312
  if (!warned.has(id)) {
305
313
  const message = conflictWarning(pi, ctx);
306
314
  if (message) {
@@ -342,6 +350,7 @@ export default function (
342
350
  s = "";
343
351
  }
344
352
  // The shutting-down session's own data slot is always evicted.
353
+ transferWriters.release(s);
345
354
  evictSession(s);
346
355
  // Overlay teardown is sid-gated: a child shutdown (distinct sid) must not
347
356
  // dispose the foreground's overlay. Only the foreground's own shutdown
@@ -36,6 +36,7 @@ export interface TodoSnapshotV1 {
36
36
  v: 1;
37
37
  tasks: Task[];
38
38
  nextId: number;
39
+ receivedMoves?: string[];
39
40
  }
40
41
 
41
42
  /** Payload of `todo:changed`. */
@@ -51,7 +52,7 @@ export interface TodoReadyEventV1 {
51
52
  }
52
53
 
53
54
  /** The kind of change a namespace validator is asked about. */
54
- export type NamespaceOp = "create" | "update" | "delete";
55
+ export type NamespaceOp = "create" | "update" | "delete" | "move";
55
56
 
56
57
  /**
57
58
  * Returns a refusal reason, or `undefined` to accept. `value` is
@@ -64,11 +65,13 @@ export type NamespaceValidator = (value: unknown, task: Task, op: NamespaceOp) =
64
65
  export interface TodoNamespaceEventV1 {
65
66
  v: 1;
66
67
  ns: string;
68
+ /** Opt in to `op: "move"`; older validators see an ordinary deletion, without the move marker or wait fields. */
69
+ moves?: true;
67
70
  validate: NamespaceValidator;
68
71
  }
69
72
 
70
73
  /** The `todo` actions that change the list, i.e. the calls a guard sees. */
71
- export type GuardOp = "create" | "update" | "delete" | "clear";
74
+ export type GuardOp = "create" | "update" | "delete" | "clear" | "move";
72
75
 
73
76
  /** What a guard is asked to judge: one call that would change the list. */
74
77
  export interface TodoChangeV1 {
@@ -94,6 +97,8 @@ export interface TodoGuardEventV1 {
94
97
  id: string;
95
98
  /** Opt in to judging imported tasks from change.after. Absent: refuse imports. */
96
99
  imports?: true;
100
+ /** Opt in to judging the batch removal and any dropped blocker edges. */
101
+ moves?: true;
97
102
  check: GuardCheck;
98
103
  }
99
104
 
@@ -106,7 +111,8 @@ export function copyTasks(tasks: readonly Task[]): Task[] {
106
111
  }
107
112
 
108
113
  export function toSnapshot(state: TaskState, sessionId: string): TodoSnapshotV1 {
109
- return { v: CONTRACT_VERSION, sessionId, tasks: copyTasks(state.tasks), nextId: state.nextId };
114
+ return { v: CONTRACT_VERSION, sessionId, tasks: copyTasks(state.tasks), nextId: state.nextId,
115
+ ...(state.receivedMoves && { receivedMoves: [...state.receivedMoves] }) };
110
116
  }
111
117
 
112
118
  export function toChangedEvent(sessionId: string, state: TaskState): TodoChangedEventV1 {
@@ -5,9 +5,14 @@ import { commitState, replaceState } from "../state/store.ts";
5
5
  import { buildToolResult } from "../tool/response-envelope.ts";
6
6
  import type { TaskAction, TaskMutationParams } from "../tool/types.ts";
7
7
  import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSnapshot } from "./contract.ts";
8
+ import type { TransferJournal } from "./transfer-journal.ts";
8
9
  import type { GuardRegistry } from "./guards.ts";
9
10
  import { changedTasks, type NamespaceRegistry } from "./namespaces.ts";
10
11
 
12
+ // If even the physical snapshot cannot be read back, no writer using this process's live slot may replace it.
13
+ const fenced = new Set<string>();
14
+ export const blockedWrite = (sid: string) => fenced.has(sid) ? "ledger writes blocked; restart pi with the recovered session journal" : undefined;
15
+
11
16
  export const ABORTED = "call aborted; nothing changed";
12
17
 
13
18
  export function refuse(action: TaskAction, input: TaskMutationParams, state: TaskState, message: string) {
@@ -16,11 +21,15 @@ export function refuse(action: TaskAction, input: TaskMutationParams, state: Tas
16
21
 
17
22
  /** Shared commit boundary for tool calls and acknowledged Herdr launches. Caller holds the session lock. */
18
23
  export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry, guards: GuardRegistry) {
19
- return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal) => {
24
+ return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal, onOriginalBranch?: () => boolean, journal?: TransferJournal) => {
25
+ const blocked = blockedWrite(sessionId);
26
+ if (blocked && action !== "list" && action !== "get") return refuse(action, input, before, blocked);
20
27
  const guardChange = {
21
28
  op: action === "import" ? "create" as const : action as GuardOp,
22
29
  params: input, before: before.tasks, after: result.state.tasks, sessionId, cwd,
23
30
  };
31
+ const branchRefusal = () => refuse(action, input, before, "session branch changed during transfer; retry on the intended branch");
32
+ if (onOriginalBranch && !onOriginalBranch()) return branchRefusal();
24
33
  if (!changesState(result.op)) {
25
34
  // A valid no-op update reaches guards, but writes no entry and emits no event.
26
35
  if (result.op.kind === "update") {
@@ -28,14 +37,36 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
28
37
  if (refusal) return refuse(action, input, before, refusal);
29
38
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
30
39
  }
40
+ if (result.op.kind === "received") journal?.confirmRecorded(result.op.moveId, "target");
31
41
  commitState(sessionId, result.state);
32
42
  return buildToolResult(action, input, result.state, result.op);
33
43
  }
34
44
  const refusal = namespaces.check(changedTasks(result.op, input, result.state, before)) ?? (await guards.check(guardChange));
35
45
  if (refusal) return refuse(action, input, before, refusal);
36
46
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
37
- // Append before committing the live slot; even nested tool calls survive replay, and a failed append changes nothing.
38
- pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
47
+ if (onOriginalBranch && !onOriginalBranch()) return branchRefusal();
48
+ const snapshot = toSnapshot(result.state, sessionId);
49
+ const tail = journal?.checkCurrent();
50
+ let appended = false;
51
+ try {
52
+ pi.appendEntry(SNAPSHOT_ENTRY_TYPE, snapshot);
53
+ appended = true;
54
+ journal?.confirm(snapshot);
55
+ } catch (error) {
56
+ if (!journal || !tail) throw error;
57
+ const reason = error instanceof Error ? error.message : String(error);
58
+ let recovered = before;
59
+ try {
60
+ if (appended) recovered = journal.recoverState();
61
+ else journal.verifyUnchangedAfterFailure(tail);
62
+ } catch (repairError) {
63
+ fenced.add(sessionId);
64
+ const detail = repairError instanceof Error ? repairError.message : String(repairError);
65
+ return refuse(action, input, before, `${reason}; journal recovery failed: ${detail}; ${blockedWrite(sessionId)}. Tell the user the journal needs repair before continuing.`);
66
+ }
67
+ commitState(sessionId, recovered);
68
+ return refuse(action, input, recovered, reason);
69
+ }
39
70
  if (action === "clear") replaceState(sessionId, result.state);
40
71
  else commitState(sessionId, result.state);
41
72
  pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
@@ -52,6 +83,8 @@ export type FinishCall = ReturnType<typeof makeFinishCall>;
52
83
  */
53
84
  export function makeCommitNow(pi: ExtensionAPI, namespaces: NamespaceRegistry) {
54
85
  return (sessionId: string, input: TaskMutationParams, before: TaskState): string | undefined => {
86
+ const blocked = blockedWrite(sessionId);
87
+ if (blocked) return blocked;
55
88
  const result = applyTaskMutation(before, "update", input);
56
89
  if (result.op.kind === "error") return result.op.message;
57
90
  if (!changesState(result.op)) return undefined;
@@ -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, { check: GuardCheck; imports: boolean }>();
34
+ private readonly guards = new Map<string, { check: GuardCheck; imports: boolean; moves: 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, { check: payload.check as GuardCheck, imports: payload.imports === true });
55
+ this.guards.set(payload.id, { check: payload.check as GuardCheck, imports: payload.imports === true, moves: payload.moves === true });
56
56
  return undefined;
57
57
  }
58
58
 
@@ -61,10 +61,11 @@ 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
- const guards = change.params.action === "import" ? [...this.guards] : this.guards;
65
- if (change.params.action === "import") {
64
+ const optIn = change.op === "move" ? "moves" : change.params.action === "import" ? "imports" : undefined;
65
+ const guards = optIn ? [...this.guards] : this.guards;
66
+ if (optIn) {
66
67
  for (const [id, guard] of guards) {
67
- if (!guard.imports) return `guard ${id} refused: guard does not accept imports`;
68
+ if (!guard[optIn]) return `guard ${id} refused: guard does not accept ${optIn}`;
68
69
  }
69
70
  }
70
71
  for (const [id, { check }] of guards) {
@@ -50,7 +50,7 @@ export async function readImport(before: TaskState, cwd: string, source: ImportS
50
50
  }
51
51
  const origin = snapshot.sessionId;
52
52
  const tasks = snapshot.tasks.map(task => withLegacyGraph(origin ? { ...task, origin: { session: origin } } : task));
53
- return { tasks, nextId: snapshot.nextId };
53
+ return { ...before, tasks, nextId: snapshot.nextId };
54
54
  }
55
55
 
56
56
  /** One task an append adds. `blockedBy` holds 1-based positions of earlier items in the same batch, not list ids, so a batch has no cycle. */
@@ -95,7 +95,7 @@ export function prepareAppend(before: TaskState, items: readonly AppendItem[]):
95
95
  ...(item.anchor !== undefined ? { anchor: item.anchor } : {}),
96
96
  };
97
97
  });
98
- const state = { tasks: [...before.tasks, ...added], nextId: first + added.length };
98
+ const state = { ...before, tasks: [...before.tasks, ...added], nextId: first + added.length };
99
99
  if (!isSnapshotV1({ v: 1, tasks: added, nextId: state.nextId })) throw new Error("the appended tasks do not match the todo/v1 snapshot schema");
100
100
  return { state, taskIds: added.map((t) => t.id) };
101
101
  }