pi-todo-ledger 0.8.2 → 0.10.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.
@@ -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
+ }