pi-todo-ledger 0.8.1 → 0.9.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/README.md CHANGED
@@ -53,6 +53,7 @@ The panel lists each task's live bound runs under it.
53
53
  A run that belongs to no task, such as a scout sent out on the side, is listed under an `Other workers` group (`其他 worker` in zh-TW) after the tasks, in the same row format; the panel shows that group even when the list is empty.
54
54
  The panel claims every run row it paints, so the host's Subagents box shows only the runs the panel does not.
55
55
  See [docs/overlay.md](docs/overlay.md#other-workers).
56
+ With pi-straw-boss loaded, the panel also shows the merge-train cars the session sent (`🚂 1128c ▰▰▰▱▱▱▱ merge 12m`) and the questions it asked that wait on you (`⏸ 等你:…`), each under the todo it belongs to, else in a group; see [docs/overlay.md](docs/overlay.md#cars-and-questions-pi-straw-boss).
56
57
 
57
58
  `/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`.
58
59
  To mark a task as waiting, pass `waitsOn` with what it waits on (a person, CI, `trains to end`); to defer it until a particular time, pass `until` with an ISO timestamp, e.g. `2027-01-15T09:00:00+08:00`.
package/docs/overlay.md CHANGED
@@ -10,7 +10,7 @@ The widget is mounted above the Pi editor under the key `rpiv-todos`, the key rp
10
10
  | Stage | Condition |
11
11
  | --- | --- |
12
12
  | Created | At the first session start that has a UI. A headless session never creates it. |
13
- | Registered | While at least one overlay-visible task exists, or the run host lists a run of this session (see [Other workers](#other-workers)). The widget unregisters itself when both are gone, and re-registers when a task or a run appears. With no task, a refresh after a `subagent` or `subagent_resume` call, or at the end of a turn, finds the new run. |
13
+ | Registered | While at least one overlay-visible task exists, or the run host lists a run of this session (see [Other workers](#other-workers)), or pi-straw-boss lists a car or a question of it (see [Cars and questions](#cars-and-questions-pi-straw-boss)). The widget unregisters itself when all are gone, and re-registers when one appears. With no task, a refresh after a `subagent` or `subagent_resume` call, or at the end of a turn, finds the new run; a car or question is found within 5 seconds. |
14
14
  | Bound | Only the foreground session's overlay is refreshed. A detached or child session has its own task state and never rebinds or repaints the foreground panel. |
15
15
  | Disposed | On the foreground session's shutdown. A child session shutting down leaves the overlay alone. |
16
16
 
@@ -133,6 +133,49 @@ The group follows the row budget:
133
133
 
134
134
  The panel claims a group row the way it claims a bound run row: only a row painted in full, checked by its exact line in the fullscreen layout. A row cut by the width, clipped by the layout, covered by a popup, or folded into the summary stays unclaimed, so the Subagents widget keeps showing that run. When no ledger claims a run, the host's own widget is the fallback that shows it.
135
135
 
136
+ ## Cars and questions (pi-straw-boss)
137
+
138
+ With pi-straw-boss (sb) loaded, the panel also shows what sb knows of the session and the host's run rows do not: the merge-train
139
+ cars it sent, and the questions it asked that wait on you. It reads them from two probes on `pi.events`, as it reads the run rows:
140
+ `straw-boss:car-rows:v1` and `straw-boss:ask-rows:v1` (sb's `docs/specs/2026-11-28-car-rows.md` and `2026-11-28-boss-asks.md`).
141
+ Without sb, or with an sb that does not answer them, nothing of them shows and the panel is as before.
142
+
143
+ ```text
144
+ ● Todos (1/10)
145
+ ├─ ◐ #2 MP-5801 FE2 訂單列表改版
146
+ │ ├ fe2-list-build · opus · 執行中 31m
147
+ │ └ 🚂 1128c ▰▰▰▱▱▱▱ merge 12m · 等 1128b
148
+ ├─ ◐ #3 MP-5804 v3 出貨單 API 修正
149
+ │ ├ ⏸ 等你:MP-5804 要不要連同 ws04 一起部署? 4m
150
+ │ └ v3-ship-review · opus · 審查中 9m
151
+ ├─ ○ #5 MP-5790 ws04 升級前檢查
152
+ ├─ 其他 worker
153
+ │ └ train-scout · opus · 執行中 3m
154
+ └─ 其他車廂
155
+ └ 📮 已送出 3m · 調度員還沒收 · MP-5779
156
+ ```
157
+
158
+ - A car row goes under the todo sb names in its `item` (the todo's uid, or `<session8>#<id>` whose eight characters are those of the
159
+ `session` the probe names): sb picks the open todo whose subject names the car's ticket. An item the panel cannot match goes in
160
+ the car's group. sb writes every word of the row (`🚂 1128c ▰▰▰▱▱▱▱ merge`, `✅ 1128c 已落地 1.62.0-beta.24`, `↩ 退回`);
161
+ the panel adds the time in the car's current stage and what it waits on, and colours a warning row `warning` and a returned or
162
+ dropped one `error`. A car with no todo goes in the group sb names, `其他車廂` / `Other cars`, or `火車` / `Trains` for the trains an
163
+ integrator received cars for.
164
+ - A question row, `⏸ 等你:<question> 4m` (`⏸ waits on you: …`), goes under the todo it blocks: the todo sb bound when the question was
165
+ asked, by its id and uid. The uid must still be that todo's: after `clear` a new todo can take the id, and a question bound to the
166
+ old one, or bound with no uid, goes in the group instead. The question is cut at 48 columns; `/boss asks` prints it whole. Only this session's questions and its subagents' show. One
167
+ with no todo here goes in a `等你` / `Waiting on you` group, the first group, as `⏸ <question> 4m`. Another session's questions
168
+ are on `/boss asks` and sb's GUI.
169
+ - Car and question rows rank with run rows (see [Overflow](#overflow)): a todo's live rows are its questions, its runs, then its cars, all
170
+ together, and their groups rank with Other workers. A row in a group whose todo has no row carries its todo's number.
171
+ - In [compact mode](#compact-mode) they share the todo's row like runs. The row after ` ⟶ ` is the one that most wants attention: a
172
+ question waiting on you first, then a returned or dropped car, then a working run, a run waiting for a reply or a car that warns,
173
+ then the rest, idle runs last.
174
+ - The summary row counts the rows a group leaves out, such as `⏸ 等你 1` or `2 其他車廂`. The collapsed row counts the questions
175
+ waiting on you: `└─ ⏸ 等你 1 · ctrl+shift+t 焦點`.
176
+ - sb reads its rows every 15 seconds, between turns too; the panel looks every 5 seconds and redraws when they changed, so a
177
+ question asked in a dialog shows while the dialog waits.
178
+
136
179
  ## Overflow
137
180
 
138
181
  The content-row budget is `maxWidgetLines` (default `12`), and the heading counts
@@ -140,10 +183,11 @@ against it. When the rows do not all fit, one row is reserved for the summary,
140
183
  and both views hand out the rest by rank, in display order within each rank:
141
184
 
142
185
  1. task rows of the tasks in progress;
143
- 2. live run rows, all runs of one task together, with that task's row when it has
144
- none yet; a task in progress whose runs do not fit keeps its row and shows
145
- `· N runs`;
146
- 3. the [Other workers](#other-workers) group, holding the live runs whose task got no row;
186
+ 2. live rows (runs, and sb's cars and questions), all of one task's together, with
187
+ that task's row when it has none yet; a task in progress whose runs do not fit
188
+ keeps its row and shows `· N runs`;
189
+ 3. the groups, holding the live rows whose task got no row: `Waiting on you`,
190
+ [Other workers](#other-workers), then the car groups;
147
191
  4. open tasks with no live run;
148
192
  5. completed tasks with no live run, oldest first.
149
193
 
@@ -180,7 +224,8 @@ Other workers group takes one row:
180
224
  - After ` ⟶ ` comes the most active run (working, then waiting for a reply, then
181
225
  other states, idle last; the host's order breaks ties), in the run row format,
182
226
  then `+N` for the task's other live runs.
183
- - A narrow row cuts the task part with `…` first, so the run stays whole.
227
+ - A narrow row cuts the task part with `…` first, so the run stays whole. A long question or car line is cut before the `+N`,
228
+ which always stays; a row with no room for its `+N` claims none of its runs.
184
229
  - The ranks above still apply; runs simply cost no rows, and the group costs one.
185
230
  A task with no live run keeps its plain row.
186
231
  - A compact row painted in full claims every run it stands for, `+N` included,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.8.1",
3
+ "version": "0.9.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/index.ts CHANGED
@@ -53,6 +53,7 @@ import {
53
53
  import { registerTodosCommand, registerTodoTool, TOOL_NAME } from "./todo.ts";
54
54
  import type { TodoOverlay } from "./todo-overlay.ts";
55
55
  import { RUN_ROWS_EVENT } from "./view/live-runs.ts";
56
+ import { askRows, carRows, type SbQuery, sbSignature } from "./view/sb-rows.ts";
56
57
 
57
58
  // Held in a variable so the type checker does not require the optional peer.
58
59
  const I18N_LOADER: string = "@juicesharp/rpiv-i18n/loader";
@@ -64,6 +65,9 @@ type I18nLoader = {
64
65
  /** Delay the overlay graph pre-warm until Pi's startup work has settled. */
65
66
  export const PREWARM_DELAY_MS = 2000;
66
67
 
68
+ /** How often the foreground looks whether sb's car or ask rows changed: sb reads them every 15 s, between turns too (an ask waits in a dialog). */
69
+ export const SB_LOOK_MS = 5000;
70
+
67
71
  type TodoOverlayModule = typeof import("./todo-overlay.ts");
68
72
  type TodoOverlayImporter = () => Promise<TodoOverlayModule>;
69
73
 
@@ -163,15 +167,17 @@ export default function (
163
167
 
164
168
  // The host's run-rows probe. Without a claim it only reads this session's runs.
165
169
  const queryRuns = (p: object) => pi.events.emit(RUN_ROWS_EVENT, p);
166
- /** Whether the host lists any run of this session: such runs show on the panel even with no task. */
167
- const hostHasRuns = (): boolean => {
170
+ // sb's car-rows and ask-rows probes (src/view/sb-rows.ts); with no sb loaded they stay unanswered.
171
+ const querySb: SbQuery = (event, p) => pi.events.emit(event, p);
172
+ /** Whether the host lists any run of this session, or sb any car or ask of it: such rows show on the panel even with no task. */
173
+ const hostHasRows = (): boolean => {
168
174
  const p: { rows?: { rows?: unknown } } = {};
169
175
  try {
170
176
  queryRuns(p);
171
177
  } catch {
172
178
  return false;
173
179
  }
174
- return Array.isArray(p.rows?.rows) && p.rows.rows.length > 0;
180
+ return (Array.isArray(p.rows?.rows) && p.rows.rows.length > 0) || carRows(querySb).rows.length > 0 || askRows(querySb).rows.length > 0;
175
181
  };
176
182
 
177
183
  async function updateTodoOverlay(
@@ -179,12 +185,12 @@ export default function (
179
185
  generation = lifecycleGeneration,
180
186
  ): Promise<void> {
181
187
  const hasVisibleTasks = getRenderState().tasks.some((task) => task.status !== "deleted");
182
- if (!uiCtx || (!todoOverlay && !hasVisibleTasks && !hostHasRuns())) return;
188
+ if (!uiCtx || (!todoOverlay && !hasVisibleTasks && !hostHasRows())) return;
183
189
 
184
190
  const { TodoOverlay } = await loadTodoOverlay();
185
191
  if (generation !== lifecycleGeneration || !uiCtx) return;
186
192
 
187
- todoOverlay ??= new TodoOverlay(queryRuns);
193
+ todoOverlay ??= new TodoOverlay(queryRuns, querySb);
188
194
  todoOverlay.setUICtx(uiCtx);
189
195
  if (resetCompletedDisplayState) todoOverlay.resetCompletedDisplayState();
190
196
  todoOverlay.update();
@@ -256,6 +262,25 @@ export default function (
256
262
  if (isForeground) await updateTodoOverlay(true);
257
263
  };
258
264
 
265
+ // sb's rows change with no event of this session (a car moves, an ask opens while a dialog waits): while a foreground
266
+ // session has a UI, look every SB_LOOK_MS and redraw when they changed. Stopped with that session.
267
+ let sbLook: ReturnType<typeof setInterval> | undefined;
268
+ const stopSbLook = () => {
269
+ if (sbLook) clearInterval(sbLook);
270
+ sbLook = undefined;
271
+ };
272
+ const startSbLook = () => {
273
+ stopSbLook();
274
+ let seen = sbSignature(querySb);
275
+ sbLook = setInterval(() => {
276
+ const now = sbSignature(querySb);
277
+ if (now === seen) return;
278
+ seen = now;
279
+ void refresh().catch(() => undefined);
280
+ }, SB_LOOK_MS);
281
+ sbLook.unref?.();
282
+ };
283
+
259
284
  const warned = new Set<string>();
260
285
  pi.on("session_start", async (_event, ctx) => {
261
286
  let id: string;
@@ -287,6 +312,7 @@ export default function (
287
312
  if (id !== getActiveRenderSession()) return;
288
313
  const generation = ++lifecycleGeneration;
289
314
  uiCtx = ctx.ui;
315
+ startSbLook();
290
316
  await updateTodoOverlay(true, generation);
291
317
  });
292
318
 
@@ -319,6 +345,7 @@ export default function (
319
345
  // replaced session cannot inherit the stale overlay or UI context.
320
346
  lifecycleGeneration++;
321
347
  uiCtx = undefined;
348
+ stopSbLook();
322
349
  // `dispose()`'s first act is setWidget(KEY, undefined) on a possibly-stale
323
350
  // ui proxy, which can throw. evictSession(s) above already deleted this
324
351
  // slot, so leaving `activeRenderSession` pointing at it would resolve
@@ -14,6 +14,10 @@
14
14
  "overlay.separator": "、",
15
15
  "overlay.others": "其他 worker",
16
16
  "overlay.worker.other": "worker",
17
+ "overlay.asks": "等你",
18
+ "overlay.asks.count": "等你 {n}",
19
+ "overlay.cars": "其他車廂",
20
+ "ask.waits": "等你:",
17
21
  "command.no_todos": "目前沒有待辦事項。",
18
22
  "command.requires_interactive": "/todos 需要互動模式",
19
23
  "command.section.pending": "── 待處理 ──",
@@ -41,7 +41,9 @@ import { type PlanRow, planView } from "./view/plan.ts";
41
41
  import type { Task } from "./tool/types.ts";
42
42
 
43
43
  import { history } from "./ledger/herdr-runs.ts";
44
- import { liveRows, runLine, runState, type Query, type RunRow } from "./view/live-runs.ts";
44
+ import { liveRows, runLine, type Query, type RunRow } from "./view/live-runs.ts";
45
+ import { attribute, budget, children, type Group, type Live, mostActive, type RowsContext, runsOf } from "./view/allot.ts";
46
+ import { askLine, askRows, carLine, carRows, type SbQuery } from "./view/sb-rows.ts";
45
47
 
46
48
  const WIDGET_KEY = "rpiv-todos";
47
49
 
@@ -51,7 +53,6 @@ const OVERLAY_MORE = "more";
51
53
  const OVERLAY_KEY_HINT = "{key} {next}";
52
54
  const OVERLAY_COLLAPSED = "collapsed";
53
55
  const OVERLAY_SEPARATOR = ", ";
54
- const OVERLAY_OTHERS = "Other workers";
55
56
 
56
57
  /** What the panel shows: one of the two views, or the two-line collapsed state. */
57
58
  type PanelState = OverlayView | "collapsed";
@@ -69,41 +70,18 @@ interface Frame {
69
70
  ticking: boolean;
70
71
  }
71
72
 
72
- /** Runs of the Other workers group that fit `rows`: the heading and at least one run, or none. */
73
- const groupFit = (rows: number, runs: number) => (runs > 0 && rows >= 2 ? Math.min(runs, rows - 1) : 0);
74
-
75
- /** The rows one budget gives, decided by rank (see TodoOverlay.allot). */
76
- interface Allotment {
77
- /** Tasks that get a row, in display order. */
78
- shown: Task[];
79
- /** Shown tasks whose run rows are drawn; any other shown task with runs counts them on its row. */
80
- withRuns: Set<Task>;
81
- /** The Other workers group: live runs of this session whose task has no row. */
82
- workers: RunRow[];
83
- /** How many of `workers` get a row under the group heading. */
84
- group: number;
85
- /** Rows the budget leaves unused. */
86
- left: number;
87
- }
88
-
89
73
  /** Narrowest left part (branch, glyph, id, start of the subject) a compact row keeps before its run. */
90
74
  const COMPACT_MIN_LEFT = 12;
91
75
 
92
- /** How a run ranks for the one spot on a compact row: working, then waiting for a reply, then the rest, idle last. */
93
- const ACTIVITY: Record<string, number> = { running: 0, waiting: 1, idle: 3 };
94
- const mostActive = (runs: readonly RunRow[]) =>
95
- runs.reduce((best, r) => ((ACTIVITY[runState(r) ?? ""] ?? 2) < (ACTIVITY[runState(best) ?? ""] ?? 2) ? r : best));
96
-
97
76
  /** What one frame's row drawing needs, shared by the full and focus views. */
98
- interface DrawContext {
77
+ interface DrawContext extends RowsContext {
99
78
  theme: Theme;
100
79
  width: number;
101
80
  truncate: (line: string) => string;
102
- bound: Map<number, ReturnType<typeof history>>;
103
- live: ReturnType<typeof liveRows>;
104
81
  /** Live runs of this session bound to no task on the panel, in the host's order. */
105
82
  others: RunRow[];
106
- runOwners: Map<string, number>;
83
+ /** The groups of the frame, as the allotment gave them rows. */
84
+ groups: { group: Group; n: number }[];
107
85
  showIds: boolean;
108
86
  now: number;
109
87
  evidence: "inline" | "screen" | undefined;
@@ -111,6 +89,26 @@ interface DrawContext {
111
89
  compact: boolean;
112
90
  }
113
91
 
92
+ /** A live row's words: a run as the host's row, a car as sb words it, an ask with its question. `grouped`: under the asks' heading. */
93
+ function liveText(l: Live, draw: DrawContext, grouped: boolean): string {
94
+ const fg = (color: Parameters<Theme["fg"]>[0], text: string) => draw.theme.fg(color, text);
95
+ if (l.kind === "run") return runLine(l.run, draw.now, fg);
96
+ return l.kind === "car" ? carLine(l.car, draw.now, fg) : askLine(l.ask, draw.now, fg, grouped);
97
+ }
98
+
99
+ /** `2 waiting on you`, as the collapsed panel and the summary count the asks. */
100
+ const askCount = (n: number) => t("overlay.asks.count", "{n} waiting on you").replace("{n}", String(n));
101
+
102
+ /** What each group leaves out, for the summary row: workers, asks, or cars by their group. */
103
+ function groupsLeft(groups: readonly { group: Group; n: number }[]): string[] {
104
+ return groups
105
+ .filter(({ group, n }) => n < group.rows.length)
106
+ .map(({ group, n }) => {
107
+ const k = group.rows.length - n;
108
+ return group.kind === "run" ? formatWorkerCount(k) : group.kind === "ask" ? `⏸ ${askCount(k)}` : `${k} ${group.title}`;
109
+ });
110
+ }
111
+
114
112
  export class TodoOverlay {
115
113
  private uiCtx: ExtensionUIContext | undefined;
116
114
  private widgetRegistered = false;
@@ -130,8 +128,10 @@ export class TodoOverlay {
130
128
  private readonly nonce = Math.random().toString(36).slice(2, 10);
131
129
  private tick?: ReturnType<typeof setInterval>;
132
130
  private query?: Query;
133
- constructor(query?: Query) {
131
+ private sb?: SbQuery;
132
+ constructor(query?: Query, sb?: SbQuery) {
134
133
  this.query = query;
134
+ this.sb = sb;
135
135
  }
136
136
 
137
137
  private sendClaim(ids: string[]) {
@@ -252,8 +252,8 @@ export class TodoOverlay {
252
252
  const snapshot = this.getSnapshot();
253
253
  const visible = this.selectOverlayTasks(snapshot);
254
254
 
255
- // With no task to show, the panel stays for this session's runs (the Other workers group).
256
- if (visible.length === 0 && !liveRows(this.query)?.size) {
255
+ // With no task to show, the panel stays for this session's runs (the Other workers group), cars and asks.
256
+ if (visible.length === 0 && !liveRows(this.query)?.size && !carRows(this.sb).rows.length && !askRows(this.sb).rows.length) {
257
257
  this.finishFrame([]);
258
258
  if (this.widgetRegistered) {
259
259
  this.uiCtx.setWidget(WIDGET_KEY, undefined);
@@ -387,7 +387,9 @@ export class TodoOverlay {
387
387
  const overlayTasks = this.selectOverlayTasks(snapshot);
388
388
  // Every state asks the host: runs bound to no task join the Other workers group, or its count.
389
389
  const live = liveRows(this.query);
390
- if (overlayTasks.length === 0 && !live?.size) {
390
+ const cars = carRows(this.sb);
391
+ const asks = askRows(this.sb);
392
+ if (overlayTasks.length === 0 && !live?.size && !cars.rows.length && !asks.rows.length) {
391
393
  this.finishFrame([]);
392
394
  return [];
393
395
  }
@@ -409,7 +411,8 @@ export class TodoOverlay {
409
411
  truncateToWidth(line, width, "…");
410
412
  const counts = selectTodoCounts(overlayState);
411
413
  const hasActive = selectHasActive(overlayState);
412
- const showIds = (hasRuns && !!live?.size) || selectShowTaskIds(overlayState);
414
+ const owners = attribute(overlayTasks, cars, asks);
415
+ const showIds = (hasRuns && !!live?.size) || owners.size > 0 || selectShowTaskIds(overlayState);
413
416
 
414
417
  const headingColor = hasActive ? "accent" : "dim";
415
418
  const headingIcon = hasActive ? "●" : "○";
@@ -427,8 +430,12 @@ export class TodoOverlay {
427
430
  truncate,
428
431
  bound,
429
432
  live,
433
+ cars: cars.rows,
434
+ asks,
430
435
  others,
436
+ groups: [],
431
437
  runOwners: new Map([...bound].flatMap(([id, h]) => h.runs.map(r => [r.id, id] as const))),
438
+ owners,
432
439
  showIds,
433
440
  now: Date.now(),
434
441
  evidence: this.evidence(),
@@ -444,9 +451,13 @@ export class TodoOverlay {
444
451
  // collapsed) — render a static collapsed label instead of advertising an
445
452
  // unbound key. Nothing is claimed; the tick keeps the count current.
446
453
  if (this.current() === "collapsed") {
447
- this.finishFrame([], others.length > 0);
454
+ this.finishFrame([], others.length > 0 || asks.rows.length > 0);
448
455
  const hint = this.keyHint() ?? t("overlay.collapsed", OVERLAY_COLLAPSED);
449
- const count = others.length ? `+${formatWorkerCount(others.length)}` : undefined;
456
+ const counts = [
457
+ others.length ? `+${formatWorkerCount(others.length)}` : "",
458
+ asks.rows.length ? `⏸ ${askCount(asks.rows.length)}` : "",
459
+ ].filter(Boolean);
460
+ const count = counts.length ? counts.join(t("overlay.separator", OVERLAY_SEPARATOR)) : undefined;
450
461
  return this.withTrailingSpacer([heading, this.closingRow(draw, count, hint)]);
451
462
  }
452
463
 
@@ -478,7 +489,7 @@ export class TodoOverlay {
478
489
  return this.withTrailingSpacer([heading, ...body]);
479
490
  }
480
491
 
481
- /** The whole dependency tree, budgeted by rank (see allot), then the Other workers group (the `"full"` view). */
492
+ /** The whole dependency tree, budgeted by rank (see view/allot.ts), then the groups (the `"full"` view). */
482
493
  private fullBody(
483
494
  overlayState: { tasks: Task[]; nextId: number },
484
495
  plan: ReturnType<typeof planView>,
@@ -486,16 +497,16 @@ export class TodoOverlay {
486
497
  draw: DrawContext,
487
498
  ): string[] {
488
499
  const all = [...selectVisibleTasks(overlayState)];
489
- const { shown, summarized, hintRow, hint, others } = this.budgeted(all, all.length, bodyBudget, draw);
500
+ const { shown, summarized, hintRow, hint } = this.budgeted(all, all.length, bodyBudget, draw);
490
501
  const frame: Frame = { drawn: [], marked: new Map(), ticking: false };
491
502
  const lines = this.drawTasks(
492
503
  shown.shown.map((task) => ({ task, row: plan.rows.get(task.id) })),
493
504
  shown.withRuns,
494
- !summarized && !hintRow && !shown.group,
505
+ !summarized && !hintRow && !shown.groups.some((g) => g.n),
495
506
  draw,
496
507
  frame,
497
508
  );
498
- lines.push(...this.drawGroup(draw.others.slice(0, shown.group), !summarized && !hintRow, draw, frame));
509
+ lines.push(...this.drawGroups(shown.groups, !summarized && !hintRow, draw, frame));
499
510
  this.endFrame(frame, draw);
500
511
  if (hintRow) lines.push(this.closingRow(draw, undefined, hint));
501
512
  if (!summarized) return lines;
@@ -511,16 +522,16 @@ export class TodoOverlay {
511
522
  const more = t("overlay.more", OVERLAY_MORE);
512
523
  parts.push(`+${overflow} ${more} (${overflowParts.map(([n, status]) => `${n} ${formatStatusLabel(status)}`).join(", ")})`);
513
524
  }
514
- if (shown.group < others) parts.push(`${parts.length ? "" : "+"}${formatWorkerCount(others - shown.group)}`);
525
+ for (const left of groupsLeft(shown.groups)) parts.push(`${parts.length ? "" : "+"}${left}`);
515
526
  lines.push(this.closingRow(draw, parts.join(t("overlay.separator", OVERLAY_SEPARATOR)), hint));
516
527
  return lines;
517
528
  }
518
529
 
519
530
  /**
520
531
  * The focus view (default): in-progress tasks with their runs, the next open
521
- * tasks (two, or three when nothing is in progress), the Other workers group,
522
- * then this turn's completed rows, budgeted by rank (see allot), and one summary
523
- * row counting whatever is hidden. Completed rows are drawn before the group.
532
+ * tasks (two, or three when nothing is in progress), the groups, then this
533
+ * turn's completed rows, budgeted by rank (see view/allot.ts), and one summary row
534
+ * counting whatever is hidden. Completed rows are drawn before the groups.
524
535
  * Rows are flat, so every unfinished blocker goes to the `⛓` tail.
525
536
  */
526
537
  private focusBody(
@@ -534,7 +545,7 @@ export class TodoOverlay {
534
545
  const completed = overlayTasks.filter((t) => t.status === "completed");
535
546
  const next = pending.slice(0, inProgress.length ? 2 : 3);
536
547
  const total = inProgress.length + pending.length + completed.length;
537
- const { shown, summarized, hintRow, hint, others } = this.budgeted(
548
+ const { shown, summarized, hintRow, hint } = this.budgeted(
538
549
  [...inProgress, ...next, ...completed],
539
550
  total,
540
551
  bodyBudget,
@@ -556,11 +567,11 @@ export class TodoOverlay {
556
567
  const lines = this.drawTasks(
557
568
  shown.shown.map((task) => ({ task, row: flat(task) })),
558
569
  shown.withRuns,
559
- !summarized && !hintRow && !shown.group,
570
+ !summarized && !hintRow && !shown.groups.some((g) => g.n),
560
571
  draw,
561
572
  frame,
562
573
  );
563
- lines.push(...this.drawGroup(draw.others.slice(0, shown.group), !summarized && !hintRow, draw, frame));
574
+ lines.push(...this.drawGroups(shown.groups, !summarized && !hintRow, draw, frame));
564
575
  this.endFrame(frame, draw);
565
576
  if (hintRow) lines.push(this.closingRow(draw, undefined, hint));
566
577
  if (!summarized) return lines;
@@ -576,90 +587,28 @@ export class TodoOverlay {
576
587
  )
577
588
  .filter(([n]) => n > 0)
578
589
  .map(([n, status]) => `${n} ${formatStatusLabel(status)}`);
579
- if (shown.group < others) parts.push(formatWorkerCount(others - shown.group));
590
+ parts.push(...groupsLeft(shown.groups));
580
591
  const summary = `+${parts.join(t("overlay.separator", OVERLAY_SEPARATOR))}`;
581
592
  lines.push(this.closingRow(draw, summary, hint));
582
593
  return lines;
583
594
  }
584
595
 
585
- private groupCandidates(visible: readonly Task[], draw: DrawContext): RunRow[] {
586
- const ids = new Set(visible.map(task => task.id));
587
- return [...(draw.live?.values() ?? [])].filter(run => !ids.has(draw.runOwners.get(run.id) ?? -1));
588
- }
589
-
590
- /** Live run rows bound to a task (empty when the host gave no rows). */
591
- private children(task: Task, draw: DrawContext): RunRow[] {
592
- const { runs } = draw.bound.get(task.id) ?? history(undefined);
593
- return runs.flatMap((r) => draw.live?.get(r.id) ?? []);
594
- }
595
-
596
596
  /**
597
- * Give `slots` rows to the candidates (in display order) by rank:
598
- * 1. in-progress task rows;
599
- * 2. live run rows, all of one task's together, with that task's row when it has none yet;
600
- * 3. the Other workers group, holding every live run whose task got no row;
601
- * 4. open tasks without a live run;
602
- * 5. completed tasks without a live run.
603
- * A task with live runs that missed rank 2 gets no row, so its runs join the group.
604
- * An in-progress task whose runs do not fit keeps its row and counts them.
605
- * `compact`: runs take no rows of their own, and the group takes one row.
597
+ * The allotment for `budget` rows (see `budget` in view/allot.ts). With nothing to summarize, the hint takes its own
598
+ * row only when one is spare. Sets `draw.groups` and `draw.compact`.
606
599
  */
607
- private allot(candidates: readonly Task[], slots: number, draw: DrawContext, compact: boolean): Allotment {
608
- const chosen = new Set<Task>();
609
- const withRuns = new Set<Task>();
610
- let used = 0;
611
- const take = (rows: number) => {
612
- if (used + rows > slots) return false;
613
- used += rows;
614
- return true;
615
- };
616
- for (const task of candidates) if (task.status === "in_progress" && take(1)) chosen.add(task);
617
- for (const task of candidates) {
618
- const runs = this.children(task, draw).length;
619
- if (runs && take((compact ? 0 : runs) + Number(!chosen.has(task)))) {
620
- chosen.add(task);
621
- withRuns.add(task);
622
- }
623
- }
624
- const workers = this.groupCandidates([...chosen], draw);
625
- const group = compact ? (workers.length && take(1) ? workers.length : 0) : groupFit(slots - used, workers.length);
626
- if (!compact) used += group ? 1 + group : 0;
627
- for (const done of [false, true])
628
- for (const task of candidates)
629
- if ((task.status === "completed") === done && !chosen.has(task) && !this.children(task, draw).length && take(1))
630
- chosen.add(task);
631
- return { shown: candidates.filter((task) => chosen.has(task)), withRuns, workers, group, left: slots - used };
632
- }
633
-
634
- /**
635
- * The allotment for `budget` rows, keeping one for the summary when anything of
636
- * `total` tasks or the group is left out. With nothing to summarize, the hint takes
637
- * its own row only when one is spare. When some live run would get no row of its
638
- * own, the panel switches to compact mode (each run joins its task's row, the group
639
- * takes one row). Sets `draw.others` to the group and `draw.compact`.
640
- */
641
- private budgeted(candidates: readonly Task[], total: number, budget: number, draw: DrawContext) {
642
- const cut = (a: Allotment) => a.shown.length < total || a.group < a.workers.length;
643
- const fit = (compact: boolean) => {
644
- const first = this.allot(candidates, budget, draw, compact);
645
- return cut(first)
646
- ? { shown: this.allot(candidates, budget - 1, draw, compact), summarized: true }
647
- : { shown: first, summarized: false };
648
- };
649
- let { shown, summarized } = fit(false);
650
- draw.compact =
651
- shown.group < shown.workers.length ||
652
- shown.shown.some((task) => this.children(task, draw).length > 0 && !shown.withRuns.has(task));
653
- if (draw.compact) ({ shown, summarized } = fit(true));
654
- draw.others = shown.workers;
600
+ private budgeted(candidates: readonly Task[], total: number, rows: number, draw: DrawContext) {
601
+ const { shown, summarized, compact } = budget(candidates, total, rows, draw);
602
+ draw.compact = compact;
603
+ draw.groups = shown.groups;
655
604
  const hint = this.keyHint();
656
605
  const hintRow = !summarized && hint !== undefined && shown.left > 0;
657
- return { shown, summarized, hintRow, hint, others: shown.workers.length };
606
+ return { shown, summarized, hintRow, hint };
658
607
  }
659
608
 
660
609
  /** End the frame's claim bookkeeping; a group folded into the summary keeps the tick so its count stays current. */
661
610
  private endFrame(frame: Frame, draw: DrawContext) {
662
- this.finishFrame(frame.drawn, frame.ticking || draw.others.length > 0, frame.marked);
611
+ this.finishFrame(frame.drawn, frame.ticking || draw.groups.length > 0, frame.marked);
663
612
  }
664
613
 
665
614
  /**
@@ -681,29 +630,41 @@ export class TodoOverlay {
681
630
  }
682
631
  }
683
632
 
633
+ /** One live row under the dim tree branch: a run as drawRun draws it, a car or an ask as sb words it. `grouped`: under the asks' heading. */
634
+ private drawLive(lines: string[], l: Live, branch: string, draw: DrawContext, frame: Frame, grouped = false) {
635
+ if (l.kind === "run") return this.drawRun(lines, l.run, branch, draw, frame);
636
+ frame.ticking = true;
637
+ lines.push(draw.truncate(draw.theme.fg("dim", branch) + liveText(l, draw, grouped)));
638
+ }
639
+
684
640
  /**
685
- * A compact row: `left` (a task row or the group heading), then ` ⟶ ` and the most
686
- * active of `runs`, then `+N` for the others. The left part is cut first, so the run
687
- * stays whole. A row shown in full claims every run it stands for; one cut into the
688
- * run, or with no room for the left part, carries no marker and claims none.
689
- * In the group (`group`), a run of a hidden task carries its task number.
641
+ * A compact row: `left` (a task row or a group heading), then ` ⟶ ` and the live row
642
+ * that most wants attention, then `+N` for the others. The left part is cut first, so the
643
+ * live row stays whole. A row shown in full claims every run it stands for; one cut into
644
+ * the live row, or with no room for the left part, carries no marker and claims none.
645
+ * In a group (`group`), a row of a hidden task carries its task number.
690
646
  */
691
- private drawCompact(lines: string[], left: string, runs: RunRow[], draw: DrawContext, frame: Frame, group = false) {
692
- const { theme, width, truncate, now, evidence } = draw;
693
- const lead = mostActive(runs);
694
- const owner = draw.runOwners.get(lead.id);
695
- const right =
696
- theme.fg("dim", " ⟶ ") +
697
- (group && owner !== undefined ? `#${owner} ` : "") +
698
- runLine(lead, now, (color, text) => theme.fg(color, text)) +
699
- (runs.length > 1 ? theme.fg("dim", ` +${runs.length - 1}`) : "");
647
+ private drawCompact(lines: string[], left: string, rows: Live[], draw: DrawContext, frame: Frame, group?: Group) {
648
+ const { theme, width, truncate, evidence } = draw;
649
+ const lead = mostActive(rows);
650
+ const owner = lead.kind === "run" ? draw.runOwners.get(lead.run.id) : draw.owners.get(lead.key);
651
+ const head = theme.fg("dim", " ⟶ ") + (group && owner !== undefined ? `#${owner} ` : "");
652
+ const tail = rows.length > 1 ? theme.fg("dim", ` +${rows.length - 1}`) : "";
653
+ // sb's words can run long (a question, a return's reason): only they are cut, never the `+N` that stands for the runs
654
+ // the row claims (carrows-review-F002). A run row is short and stays whole to be claimed. With no room even for the
655
+ // count, nothing is cut here: the row is then cut whole below, and claims nothing.
656
+ let text = liveText(lead, draw, group?.kind === "ask");
657
+ const textRoom = width - COMPACT_MIN_LEFT - visibleWidth(head) - visibleWidth(tail);
658
+ if (lead.kind !== "run" && textRoom > 0 && visibleWidth(text) > textRoom) text = truncateToWidth(text, textRoom, "…");
659
+ const right = head + text + tail;
700
660
  const room = width - visibleWidth(right);
701
661
  const roomy = visibleWidth(left) <= room || room >= COMPACT_MIN_LEFT;
702
662
  const line = roomy ? truncateToWidth(left, Math.max(room, 0), "…") + right : truncate(left + right);
703
663
  const whole = roomy && visibleWidth(line) <= width;
664
+ const runs = runsOf(rows);
704
665
  frame.ticking = true;
705
- if (whole && evidence === "screen") {
706
- const marked = line + this.marker(lead.id);
666
+ if (whole && runs.length && evidence === "screen") {
667
+ const marked = line + this.marker(lead.key);
707
668
  for (const r of runs) frame.marked.set(r.id, marked);
708
669
  lines.push(marked);
709
670
  } else {
@@ -712,27 +673,36 @@ export class TodoOverlay {
712
673
  }
713
674
  }
714
675
 
676
+ /** The groups that got rows, each a heading then its rows; `closed` means the last one ends the panel. */
677
+ private drawGroups(groups: { group: Group; n: number }[], closed: boolean, draw: DrawContext, frame: Frame): string[] {
678
+ const drawn = groups.filter((g) => g.n > 0);
679
+ return drawn.flatMap(({ group, n }, i) => this.drawGroup(group, n, closed && i === drawn.length - 1, draw, frame));
680
+ }
681
+
715
682
  /**
716
- * The Other workers group: a heading row, then this session's runs bound to no
717
- * task, drawn and claimed like bound run rows. `closed` means it ends the panel.
683
+ * A group: a heading row, then its first `n` rows, runs drawn and claimed like bound run rows, and a row of a todo
684
+ * that has no row with that todo's number. `closed` means it ends the panel.
718
685
  */
719
- private drawGroup(runs: RunRow[], closed: boolean, draw: DrawContext, frame: Frame): string[] {
720
- if (!runs.length) return [];
686
+ private drawGroup(group: Group, n: number, closed: boolean, draw: DrawContext, frame: Frame): string[] {
721
687
  const { theme, truncate } = draw;
722
- const heading = `${theme.fg("dim", closed ? "└─" : "├─")} ${theme.fg("muted", t("overlay.others", OVERLAY_OTHERS))}`;
688
+ const heading = `${theme.fg("dim", closed ? "└─" : "├─")} ${theme.fg("muted", group.title)}`;
723
689
  if (draw.compact) {
724
690
  const lines: string[] = [];
725
- this.drawCompact(lines, heading, runs, draw, frame, true);
691
+ this.drawCompact(lines, heading, group.rows, draw, frame, group);
726
692
  return lines;
727
693
  }
728
694
  const lines = [truncate(heading)];
729
- for (const [j, r] of runs.entries())
730
- this.drawRun(lines, r, `${closed ? " " : "│"} ${j === runs.length - 1 ? "└" : "├"} ${draw.runOwners.has(r.id) ? `#${draw.runOwners.get(r.id)} ` : ''}`, draw, frame);
695
+ const rows = group.rows.slice(0, n);
696
+ for (const [j, l] of rows.entries()) {
697
+ const owner = l.kind === "run" ? draw.runOwners.get(l.run.id) : draw.owners.get(l.key);
698
+ const branch = `${closed ? " " : "│"} ${j === rows.length - 1 ? "└" : "├"} ${owner !== undefined ? `#${owner} ` : ""}`;
699
+ this.drawLive(lines, l, branch, draw, frame, group.kind === "ask");
700
+ }
731
701
  return lines;
732
702
  }
733
703
 
734
704
  /**
735
- * Draw task rows and, for the tasks in `withRuns`, their run rows; any other task
705
+ * Draw task rows and, for the tasks in `withRuns`, their live rows; any other task
736
706
  * with live runs shows `· N runs`. `closed` means nothing follows, so the last
737
707
  * task row takes `└─`.
738
708
  */
@@ -747,26 +717,27 @@ export class TodoOverlay {
747
717
  const lines: string[] = [];
748
718
  for (const [i, { task, row }] of entries.entries()) {
749
719
  const { older } = draw.bound.get(task.id) ?? history(undefined);
750
- const children = this.children(task, draw);
751
- const fits = !children.length || withRuns.has(task);
720
+ const rows = children(task, draw);
721
+ const runs = runsOf(rows);
722
+ const fits = !rows.length || withRuns.has(task);
752
723
  const last = closed && i === entries.length - 1;
753
724
  const display =
754
- fits && children.some((r) => r.name === task.owner)
725
+ fits && runs.some((r) => r.name === task.owner)
755
726
  ? { ...task, owner: undefined }
756
727
  : task;
757
- const count = !fits
758
- ? ` · ${children.length} ${t("run.count", "runs")}`
728
+ const count = !fits && runs.length
729
+ ? ` · ${runs.length} ${t("run.count", "runs")}`
759
730
  : "";
760
731
  const taskLine = `${theme.fg("dim", last ? "└─" : "├─")} ${formatPlanTaskLine(display, theme, showIds, row)}${count}${older && live ? ` +${older}` : ""}`;
761
- if (fits && children.length && draw.compact) {
762
- this.drawCompact(lines, taskLine, children, draw, frame);
732
+ if (fits && rows.length && draw.compact) {
733
+ this.drawCompact(lines, taskLine, rows, draw, frame);
763
734
  continue;
764
735
  }
765
736
  lines.push(truncate(taskLine));
766
737
  if (!fits) continue;
767
738
  const indent = " ".repeat(row?.depth ?? 0);
768
- for (const [j, r] of children.entries())
769
- this.drawRun(lines, r, `${last ? " " : "│"} ${indent}${j === children.length - 1 ? "└" : "├"} `, draw, frame);
739
+ for (const [j, l] of rows.entries())
740
+ this.drawLive(lines, l, `${last ? " " : "│"} ${indent}${j === rows.length - 1 ? "└" : "├"} `, draw, frame);
770
741
  }
771
742
  return lines;
772
743
  }
package/src/todo.ts CHANGED
@@ -56,20 +56,13 @@ export { TOOL_NAME } from "./tool/types.ts";
56
56
  // Tool registration
57
57
  // ---------------------------------------------------------------------------
58
58
 
59
- export const DEFAULT_PROMPT_SNIPPET = "Manage a task list to track multi-step progress";
59
+ export const DEFAULT_PROMPT_SNIPPET = "Track multi-step work in a task list";
60
60
  export const DEFAULT_PROMPT_GUIDELINES: string[] = [
61
- "Use `todo` for complex work with 3+ steps, when the user gives you a list of tasks, or immediately after receiving new instructions to capture requirements. Skip it for single trivial tasks and purely conversational requests.",
62
- "When starting a task from the todo list, mark it in_progress BEFORE beginning work. Mark it completed IMMEDIATELY when done — never batch completions. Exactly one task in_progress at a time.",
63
- "Never mark a task completed if tests are failing, the implementation is partial, or you hit unresolved errors — keep it in_progress and create a new task for the blocker instead.",
64
- "Task status is a 4-state machine: pending → in_progress → completed, plus deleted as a tombstone. Pass activeForm (present-continuous label, e.g. 'researching existing tool') when marking in_progress.",
65
- 'To change a task\'s status, call update with the task id and the target status, e.g. {"action":"update","id":3,"status":"completed"} or {"action":"update","id":3,"status":"in_progress","activeForm":"writing tests"}. status is the field that changes the task; an update without a mutable field (status or another) is rejected.',
66
- "Use blockedBy to express dependencies (A is blocked by B). On create, pass blockedBy as the initial set. On update, use addBlockedBy / removeBlockedBy (additive merge — do not resend the full array). Cycles are rejected.",
67
- "To create several independent tasks at once, pass create with tasks: [{subject}, ...]. Do not also pass subject. tasks[] cannot blockedBy each other (ids do not exist until the call commits); create the prerequisite first, then the dependent with blockedBy. Dependency chains stay single-create.",
68
- "Use import with a snapshot file path, or session (an earlier session's id), to restore a handed-over list into an empty session list.",
69
- "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
70
- "Subject must be short and imperative (e.g. 'Research existing tool'); description is for long-form detail. activeForm is a present-continuous label shown while in_progress.",
71
- "Optional bookkeeping fields: points (effort, 0 to 10), anchor (the check that shows the task is done, e.g. a test command), and evidence (runs of checks, each {command, sha?, result: pass|fail, at?}). On update, points and anchor replace; evidence is appended, never replaced.",
72
- "When a task waits on something outside your control (a person, CI, a train, a release window), mark it with waitsOn (what it waits on) and, if known, until (ISO time); it shows ⏸ and reminders leave it alone while it waits. To end a wait early, clear every field you set (waitsOn: null, until: null), since an until left in place keeps the task waiting; completing the task clears both.",
61
+ "Use todo for work with 3+ steps, a user task list, or immediately on new instructions to capture requirements. Skip single trivial tasks and conversation.",
62
+ "Mark one task in_progress before starting (with activeForm); mark it completed immediately when done, never in batches. With failing tests, partial work or unresolved errors, keep it in_progress and create a blocker task.",
63
+ "Set status with update and id: pending → in_progress → completed; deleted is a tombstone. update needs a mutable field.",
64
+ "For dependencies, create prerequisites first, then dependents with blockedBy. Update via addBlockedBy/removeBlockedBy, not a full set; cycles are rejected.",
65
+ "On external waits (person, CI, train, release window), set waitsOn and, if known, until. End a wait early with waitsOn: null and until: null for the fields you set; a future until still holds the wait.",
73
66
  ];
74
67
 
75
68
  export function registerTodoTool(pi: ExtensionAPI, finish: FinishCall): void {
@@ -77,8 +70,7 @@ export function registerTodoTool(pi: ExtensionAPI, finish: FinishCall): void {
77
70
  pi.registerTool({
78
71
  name: TOOL_NAME,
79
72
  label: TOOL_LABEL,
80
- description:
81
- "Manage a task list for tracking multi-step progress. Actions: create (new task, or several independent tasks at once via tasks[]), update (change status/fields/dependencies), list (all tasks, optionally filtered by status), get (single task details), delete (tombstone), clear (reset all), import (restore a snapshot file into an empty list). Status: pending → in_progress → completed, plus deleted tombstone. Use this to plan and track multi-step work like research, design, and implementation.",
73
+ description: "Track a plan and its progress: create, update, list, get, delete (tombstone), clear (reset all), or import a handoff into an empty list.",
82
74
  promptSnippet: guidance.promptSnippet ?? DEFAULT_PROMPT_SNIPPET,
83
75
  promptGuidelines: guidance.promptGuidelines ?? DEFAULT_PROMPT_GUIDELINES,
84
76
  parameters: TodoParamsSchema,
package/src/tool/types.ts CHANGED
@@ -151,135 +151,57 @@ export interface TaskMutationParams {
151
151
  }
152
152
 
153
153
  // ---------------------------------------------------------------------------
154
- // TypeBox parameter schema — every `description` doubles as LLM-facing prompt
155
- // copy. Field order and wording are pinned by registration tests.
154
+ // TypeBox parameter schema. Descriptions are prompt text: document shared
155
+ // fields once, on the top-level property rather than in each batch item.
156
156
  // ---------------------------------------------------------------------------
157
157
 
158
- const PointsSchema = (description: string) =>
159
- Type.Number({ minimum: POINTS_MIN, maximum: POINTS_MAX, description });
160
-
161
- const AnchorSchema = (description: string) => Type.String({ minLength: 1, description });
162
-
163
- const EvidenceInputSchema = Type.Object({
164
- ref: Type.Optional(Type.String({ minLength: 1, maxLength: 64, pattern: "^\\S*$", description: "Run or child:<id>" })),
165
- command: Type.String({ minLength: 1, description: "The check that ran, e.g. 'npm test -- replay'" }),
166
- sha: Type.Optional(Type.String({ description: "Revision the check ran on, e.g. a git commit SHA" })),
167
- result: StringEnum(["pass", "fail"] as const, { description: "How the run ended" }),
168
- at: Type.Optional(Type.String({ description: "ISO 8601 time of the run. Default: now" })),
169
- });
170
-
171
- const EvidenceSchema = (description: string) => Type.Array(EvidenceInputSchema, { description });
172
-
173
- const WAITS_ON_TEXT =
174
- "What this task waits on (a person, CI, a train to end); it shows ⏸, and close and stale reminders leave the task alone while it waits. Completing or deleting the task clears it; to end a wait early, clear both waitsOn and until";
175
- const UNTIL_TEXT = "ISO 8601 time the task waits until, e.g. 2027-01-15T09:00:00+08:00; once it passes, an until-only wait ends";
158
+ const PointsSchema = Type.Number({ minimum: POINTS_MIN, maximum: POINTS_MAX });
159
+ const AnchorSchema = Type.String({ minLength: 1 });
160
+ const EvidenceSchema = Type.Array(Type.Object({
161
+ ref: Type.Optional(Type.String({ minLength: 1, maxLength: 64, pattern: "^\\S*$" })),
162
+ command: Type.String({ minLength: 1 }),
163
+ sha: Type.Optional(Type.String()),
164
+ result: StringEnum(["pass", "fail"] as const),
165
+ at: Type.Optional(Type.String()),
166
+ }));
176
167
 
177
168
  const CreateTaskInputSchema = Type.Object({
178
- subject: Type.String({ description: "Task subject line" }),
179
- description: Type.Optional(Type.String({ description: "Long-form task description" })),
180
- activeForm: Type.Optional(
181
- Type.String({
182
- description: "Present-continuous spinner label shown while status is in_progress (e.g. 'writing tests')",
183
- }),
184
- ),
185
- blockedBy: Type.Optional(
186
- Type.Array(Type.Number(), {
187
- description:
188
- "Existing task ids this item waits on. Cannot name another item in this same batch; create the prerequisite first, then the dependent with blockedBy.",
189
- }),
190
- ),
191
- owner: Type.Optional(Type.String({ description: "Agent/owner assigned to this task" })),
192
- metadata: Type.Optional(
193
- Type.Record(Type.String(), Type.Unknown(), {
194
- description: "Arbitrary metadata",
195
- }),
196
- ),
197
- points: Type.Optional(PointsSchema("Effort points, 0 to 10")),
198
- anchor: Type.Optional(AnchorSchema("The check that shows this task is done, e.g. a test command")),
169
+ subject: Type.String(),
170
+ description: Type.Optional(Type.String()),
171
+ activeForm: Type.Optional(Type.String()),
172
+ blockedBy: Type.Optional(Type.Array(Type.Number())),
173
+ owner: Type.Optional(Type.String()),
174
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
175
+ points: Type.Optional(PointsSchema),
176
+ anchor: Type.Optional(AnchorSchema),
199
177
  graph: Type.Optional(Type.String()),
200
- evidence: Type.Optional(EvidenceSchema("Check runs already recorded for this task")),
201
- waitsOn: Type.Optional(Type.String({ minLength: 1, description: WAITS_ON_TEXT })),
202
- until: Type.Optional(Type.String({ description: UNTIL_TEXT })),
178
+ evidence: Type.Optional(EvidenceSchema),
179
+ waitsOn: Type.Optional(Type.String({ minLength: 1 })),
180
+ until: Type.Optional(Type.String()),
203
181
  });
204
182
 
205
183
  export const TodoParamsSchema = Type.Object({
206
184
  action: StringEnum(["create", "update", "list", "get", "delete", "clear", "import"] as const),
207
- path: Type.Optional(Type.String({ description: "Snapshot file (import only); relative to the session cwd" })),
208
- session: Type.Optional(Type.String({ description: "Or a session id, id prefix, or .jsonl (import only)" })),
209
- subject: Type.Optional(
210
- Type.String({
211
- description: "Task subject line (required for create unless tasks[] is set)",
212
- }),
213
- ),
214
- description: Type.Optional(Type.String({ description: "Long-form task description" })),
215
- activeForm: Type.Optional(
216
- Type.String({
217
- description: "Present-continuous spinner label shown while status is in_progress (e.g. 'writing tests')",
218
- }),
219
- ),
220
- status: Type.Optional(
221
- StringEnum(["pending", "in_progress", "completed", "deleted"] as const, {
222
- description:
223
- "Set this task's status (update): one of pending, in_progress, completed, deleted. When action is list, filters returned tasks by this status.",
224
- }),
225
- ),
226
- blockedBy: Type.Optional(
227
- Type.Array(Type.Number(), {
228
- description: "Initial blockedBy ids (create only)",
229
- }),
230
- ),
231
- addBlockedBy: Type.Optional(
232
- Type.Array(Type.Number(), {
233
- description: "Task ids to add to blockedBy (update only, additive merge)",
234
- }),
235
- ),
236
- removeBlockedBy: Type.Optional(
237
- Type.Array(Type.Number(), {
238
- description: "Task ids to remove from blockedBy (update only, additive merge)",
239
- }),
240
- ),
241
- owner: Type.Optional(Type.String({ description: "Agent/owner assigned to this task" })),
242
- metadata: Type.Optional(
243
- Type.Record(Type.String(), Type.Unknown(), {
244
- description: "Arbitrary metadata; pass null value for a key to delete that key on update",
245
- }),
246
- ),
247
- points: Type.Optional(PointsSchema("Effort points, 0 to 10 (create or update; update replaces)")),
248
- anchor: Type.Optional(
249
- AnchorSchema(
250
- "The check that shows this task is done, e.g. a test command (create or update; update replaces)",
251
- ),
252
- ),
253
- graph: Type.Optional(
254
- Type.Union([Type.String(), Type.Null()], {
255
- description: "single-loop, fan-out/fan-in, or orchestrator-worker; null clears",
256
- }),
257
- ),
258
- evidence: Type.Optional(
259
- EvidenceSchema(
260
- "Check runs to record: the initial list on create; on update, appended to the task's evidence (never replaced or removed)",
261
- ),
262
- ),
263
- waitsOn: Type.Optional(
264
- Type.Union([Type.String({ minLength: 1 }), Type.Null()], { description: `${WAITS_ON_TEXT}; null clears (update)` }),
265
- ),
266
- until: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: `${UNTIL_TEXT}; null clears (update)` })),
267
- id: Type.Optional(
268
- Type.Number({
269
- description: "Task id (required for update, get, delete)",
270
- }),
271
- ),
272
- includeDeleted: Type.Optional(
273
- Type.Boolean({
274
- description: "If true, list action returns deleted (tombstoned) tasks as well. Default: false.",
275
- }),
276
- ),
277
- tasks: Type.Optional(
278
- Type.Array(CreateTaskInputSchema, {
279
- description:
280
- "Batch create: independent tasks in one call, one-of with subject. The whole list is validated then committed together. Items cannot blockedBy each other; create the prerequisite first, then the dependent with blockedBy.",
281
- }),
282
- ),
185
+ path: Type.Optional(Type.String({ description: "Import snapshot, cwd-relative." })),
186
+ session: Type.Optional(Type.String({ description: "Import alternative: session ID, unique prefix or .jsonl." })),
187
+ subject: Type.Optional(Type.String({ description: "Short imperative title (create, unless tasks is set)." })),
188
+ description: Type.Optional(Type.String({ description: "Long-form detail." })),
189
+ activeForm: Type.Optional(Type.String({ description: "Present-continuous in_progress label, e.g. 'writing tests'." })),
190
+ status: Type.Optional(StringEnum(["pending", "in_progress", "completed", "deleted"] as const, { description: "Set on update; filter on list." })),
191
+ blockedBy: Type.Optional(Type.Array(Type.Number(), { description: "Existing prerequisite IDs (create)." })),
192
+ addBlockedBy: Type.Optional(Type.Array(Type.Number(), { description: "Update: add prerequisite IDs." })),
193
+ removeBlockedBy: Type.Optional(Type.Array(Type.Number(), { description: "Update: drop prerequisite IDs." })),
194
+ owner: Type.Optional(Type.String()),
195
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Update: null drops that key." })),
196
+ points: Type.Optional({ ...PointsSchema, description: "Effort; update replaces." }),
197
+ anchor: Type.Optional({ ...AnchorSchema, description: "Completion check, e.g. test command; update replaces." }),
198
+ graph: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "single-loop, fan-out/fan-in or orchestrator-worker; null clears." })),
199
+ evidence: Type.Optional({ ...EvidenceSchema, description: "Check runs: update only appends. ref: run or child:<id>; sha: tested revision; at: ISO 8601 (default now)." }),
200
+ waitsOn: Type.Optional(Type.Union([Type.String({ minLength: 1 }), Type.Null()], { description: "What is pending. Wait shows ⏸, suppresses close/stale reminders; complete/delete clears it. null clears on update." })),
201
+ until: Type.Optional(Type.Union([Type.String(), Type.Null()], { description: "ISO 8601 deadline; an until-only wait ends then. null clears on update." })),
202
+ id: Type.Optional(Type.Number({ description: "Required for update/get/delete." })),
203
+ includeDeleted: Type.Optional(Type.Boolean({ description: "list: include tombstones (default false)." })),
204
+ tasks: Type.Optional(Type.Array(CreateTaskInputSchema, { description: "Atomic batch create instead of subject; same fields, no dependencies within the batch." })),
283
205
  });
284
206
 
285
207
  export type TodoParams = Static<typeof TodoParamsSchema>;
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Which live rows belong to which todo, and which rows one budget gives: pure, for the panel (todo-overlay.ts) to draw.
3
+ * A live row is a run of the host (live-runs.ts), or a car or a question of pi-straw-boss (sb-rows.ts).
4
+ */
5
+ import { history } from "../ledger/herdr-runs.ts";
6
+ import { t } from "../state/i18n-bridge.ts";
7
+ import type { Task } from "../tool/types.ts";
8
+ import { type liveRows, type RunRow, runState } from "./live-runs.ts";
9
+ import { type AskRow, type AskRows, askNames, type CarRow, type CarRows, carNames } from "./sb-rows.ts";
10
+
11
+ const OVERLAY_OTHERS = "Other workers";
12
+ const OVERLAY_ASKS = "Waiting on you";
13
+ const OVERLAY_CARS = "Other cars";
14
+
15
+ /** One live row under a todo or in a group: a run of the host, or a car or an ask of sb (src/view/sb-rows.ts). `key` is unique on a panel. */
16
+ export type Live =
17
+ | { kind: "run"; key: string; run: RunRow }
18
+ | { kind: "car"; key: string; car: CarRow }
19
+ | { kind: "ask"; key: string; ask: AskRow };
20
+
21
+ /** A group of live rows whose todo has no row: the asks waiting on the boss, the Other workers, or a group of cars sb names. */
22
+ export interface Group {
23
+ kind: Live["kind"];
24
+ title: string;
25
+ rows: Live[];
26
+ }
27
+
28
+ /** The rows one budget gives, decided by rank (see allot). */
29
+ export interface Allotment {
30
+ /** Tasks that get a row, in display order. */
31
+ shown: Task[];
32
+ /** Shown tasks whose run rows are drawn; any other shown task with runs counts them on its row. */
33
+ withRuns: Set<Task>;
34
+ /** The groups, in display order, each with how many of its rows get a row under its heading (compact: all, on its one row). */
35
+ groups: { group: Group; n: number }[];
36
+ /** Rows the budget leaves unused. */
37
+ left: number;
38
+ }
39
+
40
+ /** What the attribution reads of one frame. */
41
+ export interface RowsContext {
42
+ bound: Map<number, ReturnType<typeof history>>;
43
+ live: ReturnType<typeof liveRows>;
44
+ /** sb's car rows, and the asks of this session waiting on the boss; none without sb. */
45
+ cars: CarRow[];
46
+ asks: AskRows;
47
+ runOwners: Map<string, number>;
48
+ /** The task each bound car or ask (by key) belongs to, for its row and the `#id` of a row in a group. */
49
+ owners: Map<string, number>;
50
+ }
51
+
52
+ /** Rows of a group that fit `rows`: the heading and at least one row, or none. */
53
+ const groupFit = (rows: number, runs: number) => (runs > 0 && rows >= 2 ? Math.min(runs, rows - 1) : 0);
54
+
55
+ /**
56
+ * How a live row ranks for the one spot on a compact row: a question waiting on the boss (the todo's blocker), a returned or dropped
57
+ * car, a working run, a run waiting for a reply or a car that warns, then the rest, idle runs last.
58
+ */
59
+ const ACTIVITY: Record<string, number> = { running: 0, waiting: 1, idle: 3 };
60
+ const CAR_RANK: Record<CarRow["tone"], number> = { bad: -1, warn: 1, wait: 2, ok: 2 };
61
+ const attention = (l: Live) =>
62
+ l.kind === "ask" ? -2 : l.kind === "car" ? CAR_RANK[l.car.tone] : (ACTIVITY[runState(l.run) ?? ""] ?? 2);
63
+ export const mostActive = (rows: readonly Live[]) => rows.reduce((best, l) => (attention(l) < attention(best) ? l : best));
64
+ export const runsOf = (rows: readonly Live[]) => rows.flatMap((l) => (l.kind === "run" ? [l.run] : []));
65
+
66
+ /** The task each car and ask belongs to (by `car:<id>`, `ask:<id>`), among the tasks the panel may show. */
67
+ export function attribute(tasks: readonly Task[], cars: CarRows, asks: AskRows): Map<string, number> {
68
+ const owners = new Map<string, number>();
69
+ for (const c of cars.rows) {
70
+ const owner = tasks.find((task) => carNames(c, task, cars.session));
71
+ if (owner) owners.set(`car:${c.id}`, owner.id);
72
+ }
73
+ for (const a of asks.rows) {
74
+ const owner = tasks.find((task) => askNames(a, task, asks.session));
75
+ if (owner) owners.set(`ask:${a.id}`, owner.id);
76
+ }
77
+ return owners;
78
+ }
79
+
80
+ /** Live rows of a task: the asks it is blocked on, its runs the host lists, then its cars (empty without either). */
81
+ export function children(task: Task, ctx: RowsContext): Live[] {
82
+ const { runs } = ctx.bound.get(task.id) ?? history(undefined);
83
+ return [
84
+ ...ctx.asks.rows.flatMap((ask): Live[] => (ctx.owners.get(`ask:${ask.id}`) === task.id ? [{ kind: "ask", key: `ask:${ask.id}`, ask }] : [])),
85
+ ...runs.flatMap((r): Live[] => {
86
+ const run = ctx.live?.get(r.id);
87
+ return run ? [{ kind: "run", key: `run:${run.id}`, run }] : [];
88
+ }),
89
+ ...ctx.cars.flatMap((car): Live[] => (ctx.owners.get(`car:${car.id}`) === task.id ? [{ kind: "car", key: `car:${car.id}`, car }] : [])),
90
+ ];
91
+ }
92
+
93
+ /**
94
+ * The groups for the tasks that got a row, in display order: the asks waiting on the boss, the Other workers, then the cars by
95
+ * the group sb names (a car whose todo has no row goes in Other cars). Each holds the rows of its kind whose task has no row.
96
+ */
97
+ function groupCandidates(visible: readonly Task[], ctx: RowsContext): Group[] {
98
+ const ids = new Set(visible.map((task) => task.id));
99
+ const orphan = (key: string) => !ids.has(ctx.owners.get(key) ?? -1);
100
+ const asks: Live[] = ctx.asks.rows.map((ask) => ({ kind: "ask" as const, key: `ask:${ask.id}`, ask })).filter((l) => orphan(l.key));
101
+ const runs: Live[] = [...(ctx.live?.values() ?? [])]
102
+ .filter((run) => !ids.has(ctx.runOwners.get(run.id) ?? -1))
103
+ .map((run) => ({ kind: "run" as const, key: `run:${run.id}`, run }));
104
+ const cars = new Map<string, Live[]>();
105
+ for (const car of ctx.cars) {
106
+ const key = `car:${car.id}`;
107
+ if (!orphan(key)) continue;
108
+ const title = (car.item === undefined && car.group) || t("overlay.cars", OVERLAY_CARS);
109
+ cars.set(title, [...(cars.get(title) ?? []), { kind: "car", key, car }]);
110
+ }
111
+ return [
112
+ { kind: "ask" as const, title: t("overlay.asks", OVERLAY_ASKS), rows: asks },
113
+ { kind: "run" as const, title: t("overlay.others", OVERLAY_OTHERS), rows: runs },
114
+ ...[...cars].map(([title, rows]) => ({ kind: "car" as const, title, rows })),
115
+ ].filter((g) => g.rows.length > 0);
116
+ }
117
+
118
+ /**
119
+ * Give `slots` rows to the candidates (in display order) by rank:
120
+ * 1. in-progress task rows;
121
+ * 2. live rows (runs, cars and asks), all of one task's together, with that task's row when it has none yet;
122
+ * 3. the groups, holding every live row whose task got no row;
123
+ * 4. open tasks without a live row;
124
+ * 5. completed tasks without a live row.
125
+ * A task with live rows that missed rank 2 gets no row, so its rows join the groups.
126
+ * An in-progress task whose rows do not fit keeps its row and counts its runs.
127
+ * `compact`: live rows take no rows of their own, and each group takes one row.
128
+ */
129
+ export function allot(candidates: readonly Task[], slots: number, ctx: RowsContext, compact: boolean): Allotment {
130
+ const chosen = new Set<Task>();
131
+ const withRuns = new Set<Task>();
132
+ let used = 0;
133
+ const take = (rows: number) => {
134
+ if (used + rows > slots) return false;
135
+ used += rows;
136
+ return true;
137
+ };
138
+ for (const task of candidates) if (task.status === "in_progress" && take(1)) chosen.add(task);
139
+ for (const task of candidates) {
140
+ const runs = children(task, ctx).length;
141
+ if (runs && take((compact ? 0 : runs) + Number(!chosen.has(task)))) {
142
+ chosen.add(task);
143
+ withRuns.add(task);
144
+ }
145
+ }
146
+ const groups = groupCandidates([...chosen], ctx).map((group) => {
147
+ if (compact) return { group, n: take(1) ? group.rows.length : 0 };
148
+ const n = groupFit(slots - used, group.rows.length);
149
+ used += n ? 1 + n : 0;
150
+ return { group, n };
151
+ });
152
+ for (const done of [false, true])
153
+ for (const task of candidates)
154
+ if ((task.status === "completed") === done && !chosen.has(task) && !children(task, ctx).length && take(1))
155
+ chosen.add(task);
156
+ return { shown: candidates.filter((task) => chosen.has(task)), withRuns, groups, left: slots - used };
157
+ }
158
+
159
+ /**
160
+ * The allotment for `rows` rows, keeping one for the summary when anything of `total` tasks or the groups is left out.
161
+ * `compact` is set when some live row would get no row of its own: each live row then joins its task's row, and each
162
+ * group takes one row.
163
+ */
164
+ export function budget(candidates: readonly Task[], total: number, rows: number, ctx: RowsContext) {
165
+ const cut = (a: Allotment) => a.shown.length < total || a.groups.some((g) => g.n < g.group.rows.length);
166
+ const fit = (compact: boolean) => {
167
+ const first = allot(candidates, rows, ctx, compact);
168
+ return cut(first)
169
+ ? { shown: allot(candidates, rows - 1, ctx, compact), summarized: true }
170
+ : { shown: first, summarized: false };
171
+ };
172
+ let { shown, summarized } = fit(false);
173
+ const compact =
174
+ shown.groups.some((g) => g.n < g.group.rows.length) ||
175
+ shown.shown.some((task) => children(task, ctx).length > 0 && !shown.withRuns.has(task));
176
+ if (compact) ({ shown, summarized } = fit(true));
177
+ return { shown, summarized, compact };
178
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * What pi-straw-boss (sb) knows of a session beyond its runs, read from its two probes on `pi.events`, as the run rows are read:
3
+ * the reader emits a plain object and sb's synchronous handler sets `rows` on it. With no sb loaded both are absent, and the panel
4
+ * draws nothing of them. sb writes every word of a car row; the ledger adds only the time.
5
+ * - `straw-boss:car-rows:v1`: the merge-train cars this session sent, or the trains it integrates (sb docs/specs/2026-11-28-car-rows.md).
6
+ * - `straw-boss:ask-rows:v1`: the open questions that wait on the boss (sb docs/specs/2026-11-28-boss-asks.md).
7
+ */
8
+ import { truncateToWidth } from "@earendil-works/pi-tui";
9
+ import { t } from "../state/i18n-bridge.ts";
10
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
11
+
12
+ export const CAR_ROWS_EVENT = "straw-boss:car-rows:v1";
13
+ export const ASK_ROWS_EVENT = "straw-boss:ask-rows:v1";
14
+
15
+ export type CarTone = "ok" | "wait" | "warn" | "bad";
16
+ export interface CarRow {
17
+ id: string;
18
+ /** The todo it goes under: its uid, else `<session8>#<id>`; absent exactly when `group` is set. */
19
+ item?: string;
20
+ group?: string;
21
+ tickets: string[];
22
+ phase: string;
23
+ tone: CarTone;
24
+ line: string;
25
+ wait?: string;
26
+ since: number;
27
+ }
28
+ export interface AskRow {
29
+ id: string;
30
+ subject: string;
31
+ asker: string;
32
+ where: string;
33
+ kind: string;
34
+ since: number;
35
+ /** The asker is this session or one of its subagents. */
36
+ mine: boolean;
37
+ /**
38
+ * The todo it blocks: the session whose list holds it (as `AskRows.session` names this one), its id there, and its uid when sb bound
39
+ * it with one. The ledger reuses ids after `clear`, so only the uid tells that todo from a new one.
40
+ */
41
+ item?: { session: string; id: number; uid?: string };
42
+ }
43
+ export interface CarRows {
44
+ /** This session's id: an item `<session8>#<id>` must start with its first eight characters. An older sb leaves it out. */
45
+ session?: string;
46
+ rows: CarRow[];
47
+ }
48
+ export interface AskRows {
49
+ /** This session's id as `item.session` names it; an older sb leaves it out, and then no ask is put under a todo. */
50
+ session?: string;
51
+ rows: AskRow[];
52
+ }
53
+
54
+ /** Emits a probe on sb's event and returns nothing; the handler fills the probe. */
55
+ export type SbQuery = (event: string, probe: object) => void;
56
+
57
+ function probe(query: SbQuery | undefined, event: string): { version?: unknown; session?: unknown; rows?: unknown } | undefined {
58
+ const p: { rows?: { version?: unknown; session?: unknown; rows?: unknown } } = {};
59
+ try {
60
+ query?.(event, p);
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ const rows = p.rows;
65
+ return rows && rows.version === 1 && Array.isArray(rows.rows) ? rows : undefined;
66
+ }
67
+
68
+ const TONES = new Set<string>(["ok", "wait", "warn", "bad"]);
69
+ const str = (v: unknown): v is string => typeof v === "string";
70
+
71
+ /** The car rows of this session, a row the contract does not allow left out; none without sb. */
72
+ export function carRows(query?: SbQuery): CarRows {
73
+ const answer = probe(query, CAR_ROWS_EVENT);
74
+ const rows = ((answer?.rows ?? []) as unknown[]).filter((r): r is CarRow => {
75
+ const c = r as Partial<CarRow> | null;
76
+ return !!c && str(c.id) && str(c.line) && str(c.phase) && Number.isFinite(c.since) &&
77
+ (c.item === undefined || str(c.item)) && (c.group === undefined || str(c.group)) && (c.wait === undefined || str(c.wait));
78
+ }).map((c) => ({ ...c, tone: TONES.has(c.tone) ? c.tone : "ok", tickets: Array.isArray(c.tickets) ? c.tickets.filter(str) : [] }));
79
+ return { ...(str(answer?.session) && answer.session ? { session: answer.session } : {}), rows };
80
+ }
81
+
82
+ /** The open asks of this session and its subagents (`mine`); another session's are on `/boss asks` and sb's GUI, not here. */
83
+ export function askRows(query?: SbQuery): AskRows {
84
+ const answer = probe(query, ASK_ROWS_EVENT);
85
+ const rows = ((answer?.rows ?? []) as unknown[]).filter((r): r is AskRow => {
86
+ const a = r as Partial<AskRow> | null;
87
+ return !!a && str(a.id) && str(a.subject) && str(a.kind) && Number.isFinite(a.since) && a.mine === true;
88
+ });
89
+ return { ...(str(answer?.session) && answer.session ? { session: answer.session } : {}), rows };
90
+ }
91
+
92
+ /**
93
+ * Whether an ask blocks this todo of this session: its item names this session, the todo's id, and the uid the todo has
94
+ * (carrows-review-F001). An item with no uid, or a todo with none, cannot be told from a todo that took the id later: neither matches.
95
+ */
96
+ export function askNames(ask: AskRow, task: { id: number; uid?: string }, session: string | undefined): boolean {
97
+ const item = ask.item;
98
+ return !!session && !!item && item.session === session && item.id === task.id && typeof item.uid === "string" && item.uid === task.uid;
99
+ }
100
+
101
+ /**
102
+ * Whether a car row's `item` names this todo: its uid, or `<session8>#<id>` with this session's own eight characters
103
+ * (carrows-review-F003). With no session from sb, only a uid places a car.
104
+ */
105
+ export function carNames(car: CarRow, task: { id: number; uid?: string }, session: string | undefined): boolean {
106
+ if (!car.item) return false;
107
+ if (task.uid && car.item === task.uid) return true;
108
+ return !!session && car.item === `${session.slice(0, 8)}#${task.id}`;
109
+ }
110
+
111
+ /** `42s`, `12m`, `1h05m`, as the run rows have it. */
112
+ export function duration(ms: number): string {
113
+ const s = Math.max(0, Math.floor(ms / 1000));
114
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m` : `${Math.floor(s / 3600)}h${String(Math.floor(s / 60) % 60).padStart(2, "0")}m`;
115
+ }
116
+
117
+ type Color = "dim" | "warning" | "error";
118
+ type Fg = (color: Color, text: string) => string;
119
+ const plain: Fg = (_, text) => text;
120
+ const TONE_COLOR: Record<CarTone, Color> = { ok: "dim", wait: "dim", warn: "warning", bad: "error" };
121
+
122
+ /** A car row as sb's contract draws it: `${line} ${duration}${wait ? " · " + wait : ""}`, coloured by its tone. */
123
+ export function carLine(car: CarRow, now: number, fg: Fg = plain): string {
124
+ const text = `${car.line} ${duration(now - car.since)}${car.wait ? ` · ${car.wait}` : ""}`;
125
+ return fg(TONE_COLOR[car.tone], sanitizeTerminalText(text));
126
+ }
127
+
128
+ /** The longest question an ask row shows; the rest is on `/boss asks`. */
129
+ export const ASK_SUBJECT_WIDTH = 48;
130
+ /**
131
+ * An ask row: `⏸ waits on you: <question> 5m` under its todo; in the group, whose heading already says so, `⏸ <question> 5m`.
132
+ */
133
+ export function askLine(ask: AskRow, now: number, fg: Fg = plain, grouped = false): string {
134
+ const subject = truncateToWidth(sanitizeTerminalText(ask.subject).replace(/\s+/g, " ").trim(), ASK_SUBJECT_WIDTH, "…");
135
+ const lead = grouped ? "" : t("ask.waits", "waits on you: ");
136
+ return fg("warning", `⏸ ${lead}${subject} ${duration(now - ask.since)}`);
137
+ }
138
+
139
+ /** What changed for the panel, to redraw it when sb's rows do (sb refreshes them every 15 s, between turns too). */
140
+ export function sbSignature(query?: SbQuery): string {
141
+ const cars = carRows(query);
142
+ const asks = askRows(query);
143
+ return JSON.stringify([cars.session, cars.rows.map((c) => [c.id, c.item, c.group, c.phase, c.tone, c.line, c.wait, c.since]), asks.session, asks.rows.map((a) => [a.id, a.subject, a.item?.session, a.item?.id, a.item?.uid])]);
144
+ }