pi-todo-ledger 0.5.0 → 0.7.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
@@ -152,6 +152,35 @@ Error: metadata.<ns> refused #<id>: <reason>
152
152
  `clear`, `list`, and `get` run no validators.
153
153
  Namespaces nobody registered pass unchecked.
154
154
 
155
+ ### Optional Herdr launch identity (`metadata.herdr`)
156
+
157
+ When `pi-herdr-agents` acknowledges a `subagent` launch with `details.status: "started"` and echoes the call's `item`, the ledger looks up that task in the **calling session**.
158
+ `item` can be a stable task uid or `<session8>#<id>`, where `session8` is the first eight hex digits of the calling session id.
159
+ A numeric reference identifies the task present at dispatch: ordinary updates keep that identity even on a legacy task without a uid, while clearing or replaying the list invalidates a pending legacy binding.
160
+ Missing, unknown, foreign-session, or tombstoned items and failed or uncertain launches leave the list unchanged.
161
+
162
+ A match issues a normal guarded `update`: `owner` becomes the full `details.name`, and `metadata.herdr` records the launch:
163
+
164
+ ```json
165
+ { "name": "api-worker", "id": "0accb6d1-4380-4d51-a6d7-81dd0408d82f", "pane": "w1:p4" }
166
+ ```
167
+
168
+ `name` is verbatim; `id` is the child **run id** (`details.id`), not the parent's session id or a path-derived id.
169
+ `pane` is the acknowledged `details.worktree.paneId` and is absent for ordinary launches.
170
+ The top-level fields always describe the latest assignment. An old pane id does not carry forward. For example, after a reviewer joins a worker on the same task, `owner` and `metadata.herdr.id` identify the reviewer.
171
+
172
+ New writers also store `metadata.herdr.runs`: up to six `{ name, id, pane?, session?, agent? }` records, unique by run id, newest last. `session` is the launch acknowledgement's `sessionFile`. Once the list exceeds six, `metadata.herdr.older` counts the discarded records. An earlier v1 record without `runs` counts as one binding. A reader that finds a repeated run id (in imported or hand-edited metadata) keeps that id's last record in its last position, then applies the cap of six, so the next write is unique again. The snapshot version remains 1.
173
+
174
+ A successful `subagent_resume` appends its new run id when its acknowledged `sessionPath` matches a retained session path on exactly one non-deleted task in the calling session. An unknown or ambiguous path binds nothing.
175
+ Other metadata stays intact; a refusal leaves the launch successful but adds the reason to its response.
176
+ Manual `owner` updates (including `self`) are still allowed; the optional `herdr` record describes the last bound launch, not proof of a live pane or of the current owner's identity.
177
+
178
+ Use `metadata.herdr.id` as the stable key when resolving or messaging the worker.
179
+ Use a name with `/boss send` only when it matches the name Straw Boss shows; on an unlabeled pane it may derive `api-worker` from the launch script for `API worker`.
180
+ For names longer than 24 UTF-16 units, Straw Boss displays just the first 23 units plus `…` in the `sb_name` pane token.
181
+ Resolve the live pane at read time rather than targeting that cosmetic label or a saved pane id.
182
+ This namespace needs no new status, schema field, or contract version.
183
+
155
184
  ## 4. Change guards
156
185
 
157
186
  A namespace validator judges one task's value.
package/README.md CHANGED
@@ -43,9 +43,13 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
43
43
  `get` shows all three fields.
44
44
 
45
45
  `create`, `update`, `get`, and `list` print each task's stable `uid` if it has one (for example, `t_k7wrx2jzfq`).
46
- Pass that value as a subagent's `item`; use the shorter `#id` only within the list.
46
+ Pass that value as a Herdr `subagent`'s `item` (or use `<session8>#<id>` from the same session).
47
+ Once the launch is acknowledged, the ledger sets `owner` to the child's full name and records its run id in [`metadata.herdr`](CONTRACT.md#optional-herdr-launch-identity-metadataherdr).
48
+ Use `metadata.herdr.id` to resolve or message the worker by its run key.
49
+ Use a name with `/boss send` only if it matches the name Straw Boss shows; a launch named `API worker` may appear there as `api-worker`.
50
+ You can still set `owner` by hand.
47
51
 
48
- The panel and `/todos` indent each open task under its first unfinished blocker and show its owner as `@owner`.
52
+ `/todos` and the panel's full view indent each open task under its first unfinished blocker; the panel's default focus view lists tasks flat and names every unfinished blocker after the subject. Both show the owner as `@owner`.
49
53
  To mark a task as waiting for someone, set `metadata.waitsOn` to their name; to defer it until a particular time, set `metadata.until` to an ISO timestamp, e.g. `2027-01-15T09:00:00+08:00`.
50
54
  An open task shows `⏸` with the name or the future deadline in local time.
51
55
  These keys are display conventions: they neither schedule a wake-up nor change the task's `status` or the `todo/v1` contract.
@@ -106,18 +110,22 @@ Without one, the extension reads `rpiv-todo/config.json` from the same directori
106
110
  ```json
107
111
  {
108
112
  "maxWidgetLines": 8,
109
- "collapseKey": "alt+t"
113
+ "collapseKey": "alt+t",
114
+ "view": "full"
110
115
  }
111
116
  ```
112
117
 
113
118
  | Setting | What it does | Default |
114
119
  | --- | --- | --- |
115
- | `maxWidgetLines` | Content rows the panel may use, heading included. Minimum `3`. Pi's tool-output expansion mode shows all tasks. | `12` |
120
+ | `view` | `"focus"` lists the tasks in progress and the next open ones, and folds the rest into one summary row. `"full"` shows the whole dependency tree. | `"focus"` |
121
+ | `maxWidgetLines` | Content rows the panel may use, heading included. Minimum `3`. Pi's tool-output expansion mode lifts the limit. | `12` |
116
122
  | `collapseKey` | Key that collapses and expands the panel, in pi keybinding form (`alt+o`, `ctrl+shift+t`). `"off"` registers no shortcut. Needs `/reload` to rebind. | `"ctrl+shift+t"` |
117
123
  | `guidance` | Replaces the built-in instructions the extension gives the model about the todo list (`promptSnippet`, `promptGuidelines`). Needs `/reload`. | built-ins |
118
124
 
119
125
  More detail: [Configuration](docs/configuration.md), [`todo` tool reference](docs/tool-schema.md), [Panel and `/todos`](docs/overlay.md).
120
- The panel's text is localized when [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n) is installed, and English otherwise.
126
+ The panel's text follows the locale chosen in [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n) when it is installed.
127
+ Traditional Chinese needs `--locale zh-TW` or a `zh_TW` system locale, because the `/languages` picker offers only Simplified `zh`.
128
+ Without rpiv-i18n the panel is Traditional Chinese under a `zh_TW` or `zh_Hant` system locale and English otherwise; see [Localization](docs/overlay.md#localization).
121
129
 
122
130
  ## License
123
131
 
@@ -31,6 +31,7 @@ The extension never writes this file — you create and edit it yourself.
31
31
  {
32
32
  "maxWidgetLines": 8,
33
33
  "collapseKey": "alt+t",
34
+ "view": "full",
34
35
  "guidance": {
35
36
  "promptSnippet": "Use the `todo` tool to track multi-step work before starting it.",
36
37
  "promptGuidelines": [
@@ -41,10 +42,23 @@ The extension never writes this file — you create and edit it yourself.
41
42
  }
42
43
  ```
43
44
 
45
+ ## `view`
46
+
47
+ **Default `"focus"`.** How the overlay lays out the list.
48
+
49
+ - `"focus"` shows the tasks in progress with their worker runs, the next two
50
+ open tasks (three when nothing is in progress), and one summary row for the
51
+ rest, such as `+1 in progress, 5 pending, 2 completed`.
52
+ - `"full"` shows the whole dependency tree, as releases up to 0.6.0 did.
53
+ - Any other value, or none, means `"focus"`.
54
+ - Read fresh on every render, like `maxWidgetLines`, so no `/reload`.
55
+
56
+ [overlay.md](./overlay.md#focus-view) describes both layouts.
57
+
44
58
  ## `maxWidgetLines`
45
59
 
46
60
  **Default `12`.** The content-row budget for the overlay — the heading row and,
47
- on overflow, the `+N more` summary row both count against it. Only the trailing
61
+ on overflow, the summary row both count against it. Only the trailing
48
62
  blank spacer sits outside the budget, so `12` renders up to 13 terminal rows.
49
63
 
50
64
  - Floor of `3`. A number below `3` falls back to the default.
@@ -52,8 +66,9 @@ blank spacer sits outside the budget, so `12` renders up to 13 terminal rows.
52
66
  - No ceiling.
53
67
  - Read fresh on every render, so a change takes effect on the next repaint —
54
68
  no `/reload`.
55
- - Pi's tool-output expansion mode (`ctrl+o` by default) temporarily overrides
56
- this budget and shows every task; collapsing restores the configured budget.
69
+ - Pi's tool-output expansion mode (`ctrl+o` by default) temporarily lifts
70
+ this budget; collapsing restores it. In the full view that shows every task.
71
+ The focus view keeps its selection and only stops cutting rows for space.
57
72
 
58
73
  ## `collapseKey`
59
74
 
package/docs/overlay.md CHANGED
@@ -21,8 +21,35 @@ and taking the last saved snapshot, which replaces the whole list
21
21
  (last-write-wins). See [tool-schema.md](./tool-schema.md#persistence) for where
22
22
  snapshots are saved.
23
23
 
24
+ ## Focus view
25
+
26
+ The panel opens in the focus view. It shows what is being worked on and what comes next, and folds the rest into one row:
27
+
28
+ ```text
29
+ ● Todos (0/8)
30
+ ├─ ◐ #8 執行等待
31
+ │ └ fixture-test · astra · 執行中 6s
32
+ ├─ ○ #1 檢查畫面
33
+ ├─ ○ #2 確認版面
34
+ └─ +5 待處理
35
+ ```
36
+
37
+ Rows come in this order, until the row budget runs out:
38
+
39
+ 1. the heading;
40
+ 2. every task in progress, each followed by its run rows;
41
+ 3. the next two open tasks in display order, or the next three when nothing is in progress;
42
+ 4. completed tasks from the current turn, only if rows are left after the run rows;
43
+ 5. one summary row counting the hidden tasks in progress, pending, and completed, in that order, such as `+1 in progress, 5 pending, 2 completed` (`+1 進行中、5 待處理、2 已完成` in zh-TW). Zero counts are left out, and with nothing hidden there is no summary row.
44
+
45
+ `maxWidgetLines` is a hard cap here too: tasks in progress that do not fit are counted in the summary, and run rows that do not fit fold into `· N runs`.
46
+ Rows are flat, so the `⛓` tail lists every unfinished blocker of a task; `⏸`, owners, and the other marks are the same as in the full view.
47
+ Pi's tool-output expansion mode lifts the row cap but keeps this selection. Set `"view": "full"` (see [configuration.md](./configuration.md#view)) for the tree below, or use `/todos` to see everything once.
48
+
24
49
  ## Anatomy of a row
25
50
 
51
+ The full view (`"view": "full"`) draws the whole dependency tree:
52
+
26
53
  ```text
27
54
  ● Todos (0/5) · fan-out/fan-in
28
55
  ├─ ◐ #1 Scope @Ari
@@ -38,7 +65,7 @@ snapshots are saved.
38
65
  - **Glyphs** — `○` pending, `◐` in_progress, `✓` completed, `✗` deleted.
39
66
  Completed and deleted subjects render dim and struck through.
40
67
  - **activeForm** — appended dim in parentheses, only while the task is
41
- `in_progress`.
68
+ `in_progress` and only when it differs from the subject (ignoring leading and trailing spaces).
42
69
  - **Waiting** — `⏸` replaces the open-task glyph when `metadata.waitsOn` names a party or `metadata.until` is an ISO time in the future. The row shows the party, the local deadline, or both. An elapsed deadline no longer marks a task as waiting.
43
70
  - **Owner** — `@owner` follows the subject in muted text.
44
71
  - **Dependencies** — open rows nest under the first unfinished `blockedBy` id; siblings are visited in id order. Other unfinished blockers appear in the `⛓ #1,#2` tail. If another prerequisite interrupts a branch, `↳ #N` names the parent the row returns to.
@@ -49,10 +76,31 @@ snapshots are saved.
49
76
 
50
77
  Rows longer than the terminal width are truncated with `…`.
51
78
 
79
+ ## Worker runs under a task
80
+
81
+ When pi-herdr-agents is loaded, each task lists its live bound runs (`metadata.herdr.runs`) under its row: name, short model, state, and time in that state.
82
+ A run that is not working keeps its one row and gains a mark before its name:
83
+
84
+ - `◇ … · idle 3m` (zh-TW `閒置`), dim: its turn ended, or a persistent specialist sits between tasks (Maestro lifecycle `waiting`).
85
+ - `? … · waiting 42s` (zh-TW `等待回覆`), in the warning color: the pane shows a dialog, approval, or question (Maestro lifecycle `blocked`).
86
+
87
+ Starting and working runs carry no mark; other lifecycle kinds show their state word only.
88
+ A pending cancel replaces the state with `cancelling` or `cancel unconfirmed` and drops the mark.
89
+ Run rows count against the row budget; a task whose runs do not fit shows `· N runs` instead.
90
+
91
+ The panel asks the Subagents widget to hide a run only once it knows the run's row reached the screen:
92
+
93
+ - In Pi's inline renderer every widget line is written, so a row drawn on two frames in a row counts.
94
+ - Pi's fullscreen layout can clip the panel after it is drawn. Each run row there ends in an invisible marker unique to the panel and run: an escape sequence shaped like OSC 8 with an `id` parameter and no URI. Pi counts it as zero width, and terminals drop it (Ghostty and Herdr discard it as an invalid OSC 8), so it neither shows nor opens a link. Right after Pi paints a frame, the panel looks in `getScreenLines()` for a line that starts with the exact row it drew, marker included. A row the layout cut off is absent, and a row under a popup, a search highlight, or a selection no longer matches, so in both cases its run stays in the Subagents widget. A changed claim triggers one more frame, so the Subagents widget catches up one frame later.
95
+ - A renderer that offers neither gives no evidence, and the Subagents widget keeps every run.
96
+
97
+ Collapsing the panel, or the run leaving the panel, returns the run to the Subagents widget.
98
+
52
99
  ## Overflow
53
100
 
54
101
  The content-row budget is `maxWidgetLines` (default `12`), and the heading counts
55
- against it. When there are more tasks than fit:
102
+ against it. The focus view applies it as described [above](#focus-view). In the
103
+ full view, when there are more tasks than fit:
56
104
 
57
105
  1. one row is reserved for the summary line;
58
106
  2. completed tasks are dropped first, newest first — the oldest completed rows
@@ -61,8 +109,8 @@ against it. When there are more tasks than fit:
61
109
  truncated;
62
110
  4. the last row becomes `+N more (X completed, Y pending)`.
63
111
 
64
- Use Pi's tool-output expansion shortcut (`ctrl+o` by default) to expand the
65
- widget and show every task. Collapsing Pi's tool output reapplies the configured
112
+ In the full view, Pi's tool-output expansion shortcut (`ctrl+o` by default)
113
+ expands the widget to show every task. Collapsing Pi's tool output reapplies the configured
66
114
  row budget. Unfinished work is therefore the last thing to disappear in the
67
115
  compact view. See [configuration.md](./configuration.md#maxwidgetlines) for the
68
116
  budget's floor and reload semantics.
@@ -107,18 +155,28 @@ tasks. Tombstoned tasks are never listed.
107
155
 
108
156
  ## Localization
109
157
 
110
- The overlay heading, the `+N more` summary, the collapse hint, the `/todos`
158
+ The overlay heading, both summary rows, the collapse hint, the `/todos`
111
159
  section headers, and the status words all localize through
112
160
  [`@juicesharp/rpiv-i18n`](https://www.npmjs.com/package/@juicesharp/rpiv-i18n)
113
161
  when that package is installed. Bundled locales: `de`, `en`, `es`, `fr`, `pt`,
114
- `pt-BR`, `ru`, `uk`, `zh`.
162
+ `pt-BR`, `ru`, `uk`, `zh` (Simplified), and `zh-TW` (Traditional).
163
+
164
+ The `/languages` picker has no Traditional Chinese entry; its `中文 (zh)` is
165
+ Simplified. An explicit choice always wins, and the system locale is only the
166
+ default. To get Traditional Chinese, use one of:
167
+
168
+ - `pi --locale zh-TW`;
169
+ - `{ "locale": "zh-TW" }` in rpiv-i18n's `locale.json` (see its README for the path);
170
+ - **System default** in `/languages`, with `LC_ALL`, `LC_MESSAGES`, or `LANG` set to
171
+ a `zh_TW` or `zh_Hant` locale such as `zh_TW.UTF-8`.
115
172
 
116
173
  LLM-facing output — the tool response envelope, reducer error messages, and the
117
174
  schema descriptions — stays English by design.
118
175
 
119
176
  The SDK is a soft optional peer, loaded through a dynamic import at module init.
120
- When it is absent, every call site returns its inline English literal and the
121
- extension stays online: no warning, no crash. Install it at any time with
177
+ When it is absent, the panel is Traditional Chinese under a `zh_TW` or `zh_Hant`
178
+ system locale and English otherwise, and the extension stays online: no warning,
179
+ no crash. Install it at any time with
122
180
  `pi install npm:@juicesharp/rpiv-i18n` and restart the session. To add or
123
181
  override a translation, drop a `locales/<code>.json` file mirroring `en.json` —
124
182
  see the `@juicesharp/rpiv-i18n` README's "Contributing translations" section.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.5.0",
3
+ "version": "0.7.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",
package/src/config.ts CHANGED
@@ -39,6 +39,24 @@ export function configCandidates(): string[] {
39
39
  return [CONFIG_NAME, LEGACY_CONFIG_NAME].flatMap((name) => dirs.map((dir) => join(dir, name, "config.json")));
40
40
  }
41
41
 
42
+ /**
43
+ * The locale rpiv-i18n's `/languages` picker saved, read the way rpiv-config reads it:
44
+ * the `$XDG_CONFIG_HOME` file wins when it exists, else `~/.config/rpiv-i18n/locale.json`.
45
+ */
46
+ export function savedLocale(): string | undefined {
47
+ for (const dir of configDirs()) {
48
+ const path = join(dir, "rpiv-i18n", "locale.json");
49
+ if (!existsSync(path)) continue;
50
+ try {
51
+ const locale = (JSON.parse(readFileSync(path, "utf-8")) as { locale?: unknown } | null)?.locale;
52
+ return typeof locale === "string" && locale ? locale : undefined;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+
42
60
  /** Parse a JSON config file; `{}` for malformed JSON or a non-object value (with a warning). */
43
61
  function readJsonObject(path: string): Record<string, unknown> {
44
62
  try {
@@ -84,6 +102,19 @@ interface TodoConfig {
84
102
  * entirely. Validation happens in `resolveCollapseKey`, not at load.
85
103
  */
86
104
  collapseKey?: string;
105
+ /** Panel layout: `"focus"` (default) or `"full"`. Validated in `getView`. */
106
+ view?: unknown;
107
+ }
108
+
109
+ /** Panel layout: the compact focus view, or the whole dependency tree. */
110
+ export type OverlayView = "focus" | "full";
111
+
112
+ /** Default panel layout when `view` is missing or not one of the two names. */
113
+ export const DEFAULT_VIEW: OverlayView = "focus";
114
+
115
+ /** Panel layout, read fresh on every render like getMaxWidgetLines(); anything but `"full"` is focus. */
116
+ export function getView(): OverlayView {
117
+ return loadConfig().view === "full" ? "full" : DEFAULT_VIEW;
87
118
  }
88
119
 
89
120
  /** Default content-row budget when the config is missing/invalid — the prior
package/src/index.ts CHANGED
@@ -33,7 +33,9 @@ import {
33
33
  READY_EVENT,
34
34
  toChangedEvent,
35
35
  } from "./ledger/contract.ts";
36
+ import { makeFinishCall } from "./ledger/finish-call.ts";
36
37
  import { GuardRegistry } from "./ledger/guards.ts";
38
+ import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
37
39
  import { NamespaceRegistry } from "./ledger/namespaces.ts";
38
40
  import { I18N_NAMESPACE } from "./state/i18n-bridge.ts";
39
41
  import { replayFromBranch } from "./state/replay.ts";
@@ -167,7 +169,7 @@ export default function (
167
169
  const { TodoOverlay } = await loadTodoOverlay();
168
170
  if (generation !== lifecycleGeneration || !uiCtx) return;
169
171
 
170
- todoOverlay ??= new TodoOverlay();
172
+ todoOverlay ??= new TodoOverlay(p => pi.events.emit('pi-herdr-agents:run-rows:v1', p));
171
173
  todoOverlay.setUICtx(uiCtx);
172
174
  if (resetCompletedDisplayState) todoOverlay.resetCompletedDisplayState();
173
175
  todoOverlay.update();
@@ -186,7 +188,9 @@ export default function (
186
188
  if (ignored) console.warn(`[pi-todo-ledger] ignored ${ignored}`);
187
189
  });
188
190
 
189
- registerTodoTool(pi, namespaces, guards);
191
+ const finish = makeFinishCall(pi, namespaces, guards);
192
+ registerTodoTool(pi, finish);
193
+ registerHerdrOwner(pi, finish);
190
194
  registerTodosCommand(pi);
191
195
  pi.events.emit(READY_EVENT, { v: CONTRACT_VERSION });
192
196
 
@@ -308,7 +312,7 @@ export default function (
308
312
  // Reads getTodos() at render time; do NOT call replayFromBranch here
309
313
  // (branch is stale — message_end runs after tool_execution_end).
310
314
  pi.on("tool_execution_end", async (event) => {
311
- if (event.toolName !== TOOL_NAME || event.isError) return;
315
+ if ((event.toolName !== TOOL_NAME && event.toolName !== "subagent") || event.isError) return;
312
316
  try {
313
317
  await updateTodoOverlay();
314
318
  } catch (e) {
@@ -0,0 +1,46 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { changesState, type ApplyResult } from "../state/state-reducer.ts";
3
+ import type { TaskState } from "../state/state.ts";
4
+ import { commitState, replaceState } from "../state/store.ts";
5
+ import { buildToolResult } from "../tool/response-envelope.ts";
6
+ import type { TaskAction, TaskMutationParams } from "../tool/types.ts";
7
+ import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSnapshot } from "./contract.ts";
8
+ import type { GuardRegistry } from "./guards.ts";
9
+ import { changedTasks, type NamespaceRegistry } from "./namespaces.ts";
10
+
11
+ export const ABORTED = "call aborted; nothing changed";
12
+
13
+ export function refuse(action: TaskAction, input: TaskMutationParams, state: TaskState, message: string) {
14
+ return { ...buildToolResult(action, input, state, { kind: "error", message }), isError: true };
15
+ }
16
+
17
+ /** Shared commit boundary for tool calls and acknowledged Herdr launches. Caller holds the session lock. */
18
+ 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) => {
20
+ const guardChange = {
21
+ op: action === "import" ? "create" as const : action as GuardOp,
22
+ params: input, before: before.tasks, after: result.state.tasks, sessionId, cwd,
23
+ };
24
+ if (!changesState(result.op)) {
25
+ // A valid no-op update reaches guards, but writes no entry and emits no event.
26
+ if (result.op.kind === "update") {
27
+ const refusal = await guards.check({ ...guardChange, noop: true });
28
+ if (refusal) return refuse(action, input, before, refusal);
29
+ if (signal?.aborted) return refuse(action, input, before, ABORTED);
30
+ }
31
+ commitState(sessionId, result.state);
32
+ return buildToolResult(action, input, result.state, result.op);
33
+ }
34
+ const refusal = namespaces.check(changedTasks(result.op, input, result.state)) ?? (await guards.check(guardChange));
35
+ if (refusal) return refuse(action, input, before, refusal);
36
+ 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));
39
+ if (action === "clear") replaceState(sessionId, result.state);
40
+ else commitState(sessionId, result.state);
41
+ pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
42
+ return buildToolResult(action, input, result.state, result.op);
43
+ };
44
+ }
45
+
46
+ export type FinishCall = ReturnType<typeof makeFinishCall>;
@@ -0,0 +1,82 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { withSessionLock } from "../state/session-lock.ts";
3
+ import { applyTaskMutation } from "../state/state-reducer.ts";
4
+ import { getState, listGeneration, sid } from "../state/store.ts";
5
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
6
+ import type { FinishCall } from "./finish-call.ts";
7
+ import { runningGuard } from "./guards.ts";
8
+
9
+ import { bindRun, history } from "./herdr-runs.ts";
10
+
11
+ const uid = /^t_[a-z2-7]{10}$/;
12
+ const local = /^([a-f0-9]{8})#([1-9]\d*)$/i;
13
+ const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
14
+ const nonblank = (x: unknown): x is string => typeof x === "string" && x.trim().length > 0;
15
+
16
+ interface LaunchTarget { item: string; id: number; uid?: string; generation: symbol }
17
+
18
+ /** Per-load observer. A returned name is data, not a shell argument or a pane lookup. */
19
+ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
20
+ // A numeric id can be reused by clear or a branch switch before Herdr acknowledges the launch.
21
+ // Pin the list generation for a legacy task; ordinary updates replace task objects but retain this identity.
22
+ const pending = new Map<string, Map<string, LaunchTarget>>();
23
+ pi.on("tool_call", (event, ctx) => {
24
+ if (event.toolName !== "subagent" || typeof event.input.item !== "string") return;
25
+ const item = event.input.item;
26
+ const match = local.exec(item);
27
+ if (!match) return;
28
+ const session = sid(ctx);
29
+ if (session.slice(0, 8).toLowerCase() !== match[1].toLowerCase()) return;
30
+ const task = getState(session).tasks.find(t => t.id === Number(match[2]) && t.status !== "deleted");
31
+ const generation = listGeneration(session);
32
+ if (!task || !generation) return;
33
+ const calls = pending.get(session) ?? new Map<string, LaunchTarget>();
34
+ calls.set(event.toolCallId, { item, id: task.id, uid: task.uid, generation });
35
+ pending.set(session, calls);
36
+ });
37
+ // A blocked call need not produce a result. Drop any leftover captures at the turn boundary.
38
+ pi.on("agent_end", (_event, ctx) => { pending.delete(sid(ctx)); });
39
+ pi.on("tool_result", async (event, ctx) => {
40
+ const resume = event.toolName === "subagent_resume";
41
+ if (!resume && event.toolName !== "subagent") return;
42
+ const session = sid(ctx);
43
+ const calls = pending.get(session);
44
+ const capture = calls?.get(event.toolCallId);
45
+ calls?.delete(event.toolCallId);
46
+ if (!calls?.size) pending.delete(session);
47
+ const d = event.details;
48
+ if (event.isError || !record(d) || d.status !== "started" || !nonblank(d.name) || !nonblank(d.id)) return;
49
+ const item = d.item;
50
+ const path = resume ? event.input.sessionPath : d.sessionFile;
51
+ if (resume ? (!nonblank(path) || path !== d.sessionPath) : (typeof item !== "string" || item !== event.input.item)) return;
52
+ const pinned = capture?.item === item ? capture : undefined;
53
+ if (!resume && !pinned && !(typeof item === 'string' && uid.test(item))) return;
54
+ const pane = record(d.worktree) ? d.worktree.paneId : undefined;
55
+ const agent = d.agent ?? event.input.agent;
56
+ const run = { name: d.name, id: d.id, ...(nonblank(path) ? {session:path} : {}), ...(nonblank(agent) ? {agent} : {}), ...(nonblank(pane) ? { pane } : {}) };
57
+ const warn = (why: string) => ({
58
+ content: [...event.content, { type: "text" as const, text: `Todo owner binding: ${sanitizeTerminalText(why)}` }],
59
+ structuredContent: event.structuredContent,
60
+ });
61
+ if (runningGuard(session)) return warn("cannot update the list from its own change guard");
62
+ try {
63
+ return await withSessionLock(session, async () => {
64
+ const before = getState(session);
65
+ if (pinned && !pinned.uid && listGeneration(session) !== pinned.generation) return;
66
+ const matches = resume ? before.tasks.filter(t => t.status !== 'deleted' && history(t.metadata?.herdr).runs.some(r => r.session === path)) : [];
67
+ if (resume && matches.length !== 1) return;
68
+ const task = resume ? matches[0] : pinned && !pinned.uid
69
+ ? before.tasks.find(t => t.id === pinned.id && !t.uid)
70
+ : before.tasks.find(t => t.uid === (pinned?.uid ?? item));
71
+ if (!task || task.status === "deleted") return;
72
+ const herdr = bindRun(task.metadata?.herdr, run);
73
+ const params = { action: "update", id: task.id, owner: herdr.name, metadata: { herdr } };
74
+ const result = await finish(session, ctx.cwd, "update", params, before, applyTaskMutation(before, "update", params));
75
+ if (result.details.error) return warn(result.details.error);
76
+ });
77
+ } catch (error) {
78
+ // Herdr already launched the child. Don't turn a persistence error into a failed launch/retry.
79
+ return warn(error instanceof Error ? error.message : String(error));
80
+ }
81
+ });
82
+ }
@@ -0,0 +1,44 @@
1
+ export interface BoundRun {
2
+ id: string;
3
+ name: string;
4
+ pane?: string;
5
+ session?: string;
6
+ agent?: string;
7
+ }
8
+ export function history(value: unknown): { runs: BoundRun[]; older: number } {
9
+ if (!value || typeof value !== "object") return { runs: [], older: 0 };
10
+ const h = value as Record<string, unknown>;
11
+ const valid = (Array.isArray(h.runs) ? h.runs : [h]).filter(
12
+ (r): r is BoundRun =>
13
+ r && typeof r.id === "string" && typeof r.name === "string",
14
+ );
15
+ // Imported or hand-edited metadata may repeat an id: keep its last record, in its last position.
16
+ const seen = new Set<string>();
17
+ const unique: BoundRun[] = [];
18
+ for (let i = valid.length - 1; i >= 0; i--) {
19
+ if (seen.has(valid[i].id)) continue;
20
+ seen.add(valid[i].id);
21
+ unique.push(valid[i]);
22
+ }
23
+ unique.reverse();
24
+ const stored =
25
+ typeof h.older === "number" && Number.isSafeInteger(h.older) && h.older > 0
26
+ ? h.older
27
+ : 0;
28
+ return {
29
+ runs: unique.slice(-6),
30
+ older: stored + Math.max(0, unique.length - 6),
31
+ };
32
+ }
33
+ export function bindRun(previous: unknown, newest: BoundRun) {
34
+ const { runs, older } = history(previous);
35
+ const next = [...runs.filter((r) => r.id !== newest.id), newest];
36
+ const dropped = older + Math.max(0, next.length - 6);
37
+ return {
38
+ name: newest.name,
39
+ id: newest.id,
40
+ ...(newest.pane ? { pane: newest.pane } : {}),
41
+ runs: next.slice(-6),
42
+ ...(dropped ? { older: dropped } : {}),
43
+ };
44
+ }
@@ -8,6 +8,7 @@
8
8
  "overlay.more": "more",
9
9
  "overlay.expandHint": "{key} to expand",
10
10
  "overlay.collapsed": "collapsed",
11
+ "overlay.separator": ", ",
11
12
 
12
13
  "command.no_todos": "No todos yet. Ask the agent to add some!",
13
14
  "command.requires_interactive": "/todos requires interactive mode",
@@ -0,0 +1,33 @@
1
+ {
2
+ "status.pending": "待處理",
3
+ "status.in_progress": "進行中",
4
+ "status.completed": "已完成",
5
+ "status.deleted": "已刪除",
6
+ "overlay.heading": "Todos",
7
+ "overlay.more": "項未顯示",
8
+ "overlay.expandHint": "按 {key} 展開",
9
+ "overlay.collapsed": "已收合",
10
+ "overlay.separator": "、",
11
+ "command.no_todos": "目前沒有待辦事項。",
12
+ "command.requires_interactive": "/todos 需要互動模式",
13
+ "command.section.pending": "── 待處理 ──",
14
+ "command.section.in_progress": "── 進行中 ──",
15
+ "command.section.completed": "── 已完成 ──",
16
+ "wait.party": "等",
17
+ "wait.until": "等到",
18
+ "run.count": "個工作階段",
19
+ "run.cancel.requested": "取消中",
20
+ "run.cancel.unconfirmed": "取消未確認",
21
+ "run.tool.thread_wait": "等 thread",
22
+ "run.active.reviewer": "審查中",
23
+ "run.kind.active": "執行中",
24
+ "run.kind.running": "執行中",
25
+ "run.kind.starting": "啟動中",
26
+ "run.state.idle": "閒置",
27
+ "run.state.waiting": "等待回覆",
28
+ "run.kind.interrupted": "已中斷",
29
+ "run.kind.stalled": "停滯",
30
+ "run.kind.finalizing": "收尾中",
31
+ "run.kind.completed": "已完成",
32
+ "run.kind.failed": "失敗"
33
+ }
@@ -10,6 +10,7 @@
10
10
  "overlay.more": "更多",
11
11
  "overlay.expandHint": "按 {key} 展开",
12
12
  "overlay.collapsed": "已折叠",
13
+ "overlay.separator": "、",
13
14
 
14
15
  "command.no_todos": "暂无任务。可以让 agent 添加一些!",
15
16
  "command.requires_interactive": "/todos 需要交互模式",