pi-workfeed 0.0.0-stage → 0.1.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,359 @@
1
+ /**
2
+ * Replay layer — the architecture constraint in code.
3
+ *
4
+ * JSONL is the single truth. Everything the digest shows is recomputed from that
5
+ * file, never carried over from the process that happened to be collecting:
6
+ *
7
+ * JSONL → parseLog() → aggregate() → buildDigest()
8
+ *
9
+ * Consequences that this module is responsible for keeping true:
10
+ * - a digest can be deleted at any time and regenerated, including long after the
11
+ * session that produced it has exited;
12
+ * - a fresh process that reopens an existing session file renders the whole
13
+ * session, not just the part it witnessed;
14
+ * - no retention cap belongs here: caps are a UI concern, never a truth concern;
15
+ * - the same file yields byte-identical output (the timestamp is the last event's
16
+ * ts), so digests can be compared, checksummed and diffed.
17
+ *
18
+ * No pi API is imported, so this doubles as the offline replay entry point (there is no CLI:
19
+ * see the 0.1.0 entry in CHANGELOG.md).
20
+ */
21
+
22
+ import { readFileSync } from "node:fs";
23
+ import {
24
+ buildDigest,
25
+ type DigestInput,
26
+ type LogIntegrity,
27
+ type TaskStats,
28
+ type TodoItem,
29
+ type TokenBuckets,
30
+ type ToolRecord,
31
+ } from "./digest.ts";
32
+
33
+ /** One log line. Fields beyond the four join keys belong to the event type. */
34
+ export interface JournalEvent {
35
+ v?: number;
36
+ ts?: number;
37
+ sid?: string;
38
+ /** 1-based user-instruction index */
39
+ task?: number;
40
+ /** work item id (source-neutral: todo list, planner or external list) that was `in_progress` */
41
+ item?: number;
42
+ /** event type: session | prompt | turn | tool | todo | settle | … */
43
+ t?: string;
44
+ [k: string]: unknown;
45
+ }
46
+
47
+ const zeroTokens = (): TokenBuckets => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 });
48
+
49
+ function dayStamp(ts?: number): string {
50
+ const d = ts ? new Date(ts) : new Date();
51
+ const p = (n: number) => String(n).padStart(2, "0");
52
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
53
+ }
54
+
55
+ function tokensOf(raw: unknown): TokenBuckets {
56
+ const u = raw as Record<string, number> | undefined;
57
+ if (!u) return zeroTokens();
58
+ const input = u.input ?? 0;
59
+ const output = u.output ?? 0;
60
+ const cacheRead = u.cacheRead ?? 0;
61
+ const cacheWrite = u.cacheWrite ?? 0;
62
+ const sum = input + output + cacheRead + cacheWrite;
63
+ // A missing total arrives as 0 from self-hosted endpoints, so `??` never fires:
64
+ // take the reported value only when it is actually positive.
65
+ const reported = Math.max(u.totalTokens ?? 0, u.total ?? 0);
66
+ return { input, output, cacheRead, cacheWrite, total: reported > 0 ? reported : sum };
67
+ }
68
+
69
+ /** What a replay could not use, and why — see `digest.ts` for the field meanings. */
70
+ export type { LogIntegrity };
71
+
72
+ export interface ParsedLog {
73
+ events: JournalEvent[];
74
+ integrity: LogIntegrity;
75
+ }
76
+
77
+ const EVENT_TYPES = new Set([
78
+ "session",
79
+ "prompt",
80
+ "agent_start",
81
+ "turn",
82
+ "tool",
83
+ "todo",
84
+ "user_bash",
85
+ "provider",
86
+ "compact",
87
+ "compact_failed",
88
+ "settle",
89
+ "shutdown",
90
+ ]);
91
+
92
+ /** Envelope check from the protocol, kept here so a consumer can reuse it. */
93
+ function envelopeError(e: Record<string, unknown>): string | null {
94
+ if (e.v !== 1) return `v=${String(e.v)} (this reader understands v=1)`;
95
+ if (!Number.isInteger(e.ts) || (e.ts as number) < 0) return "ts is not a non-negative integer";
96
+ if (typeof e.sid !== "string" || e.sid.length === 0) return "sid is not a non-empty string";
97
+ if (!Number.isInteger(e.task) || (e.task as number) < 0) return "task is not a non-negative integer";
98
+ if (typeof e.t !== "string" || e.t.length === 0) return "t is not a non-empty string";
99
+ if (e.item !== undefined && (!Number.isInteger(e.item) || (e.item as number) < 1)) return "item is present but not an integer ≥ 1";
100
+ return null;
101
+ }
102
+
103
+ /**
104
+ * Parse a log file into events plus an account of what was dropped.
105
+ *
106
+ * A torn final line is expected (a process killed mid-append) and is reported as
107
+ * `tornTail`. Anything unreadable *before* the tail is corruption and is listed
108
+ * line by line. Envelope failures and unknown event types are kept separate:
109
+ * the first means the producer broke the protocol, the second is normal forward
110
+ * compatibility.
111
+ */
112
+ export function parseLogDetailed(text: string): ParsedLog {
113
+ const raw = text.split("\n");
114
+ const integrity: LogIntegrity = { lines: 0, tornTail: null, corrupt: [], badEnvelope: [], unknown: [] };
115
+ const events: JournalEvent[] = [];
116
+
117
+ let lastNonEmpty = -1;
118
+ for (let i = raw.length - 1; i >= 0; i -= 1) {
119
+ if (raw[i].trim() !== "") {
120
+ lastNonEmpty = i;
121
+ break;
122
+ }
123
+ }
124
+
125
+ for (let i = 0; i < raw.length; i += 1) {
126
+ const s = raw[i].trim();
127
+ if (!s) continue;
128
+ integrity.lines += 1;
129
+ let parsed: unknown;
130
+ try {
131
+ parsed = JSON.parse(s);
132
+ } catch {
133
+ if (i === lastNonEmpty) integrity.tornTail = i + 1;
134
+ else integrity.corrupt.push(i + 1);
135
+ continue;
136
+ }
137
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
138
+ integrity.badEnvelope.push({ line: i + 1, reason: "not a JSON object" });
139
+ continue;
140
+ }
141
+ const obj = parsed as Record<string, unknown>;
142
+ const reason = envelopeError(obj);
143
+ if (reason) {
144
+ integrity.badEnvelope.push({ line: i + 1, reason });
145
+ continue;
146
+ }
147
+ if (!EVENT_TYPES.has(String(obj.t))) integrity.unknown.push({ line: i + 1, t: String(obj.t) });
148
+ events.push(obj as JournalEvent);
149
+ }
150
+
151
+ return { events, integrity };
152
+ }
153
+
154
+ /** Events only — the shape every existing caller wants. */
155
+ export function parseLog(text: string): JournalEvent[] {
156
+ return parseLogDetailed(text).events;
157
+ }
158
+
159
+ /** Does the file need to be reported as damaged? Torn tail is expected, not damage. */
160
+ export function hasDamage(integrity: LogIntegrity): boolean {
161
+ return integrity.corrupt.length > 0 || integrity.badEnvelope.length > 0;
162
+ }
163
+
164
+ /** One-line human summary, used by the digest header and by callers that log. */
165
+ export function describeIntegrity(integrity: LogIntegrity): string {
166
+ const parts = [`${integrity.lines} lines`];
167
+ if (integrity.tornTail !== null) parts.push(`torn tail at line ${integrity.tornTail}`);
168
+ if (integrity.corrupt.length > 0) parts.push(`${integrity.corrupt.length} corrupt in the middle (lines ${integrity.corrupt.join(", ")})`);
169
+ if (integrity.badEnvelope.length > 0) parts.push(`${integrity.badEnvelope.length} violating the envelope`);
170
+ if (integrity.unknown.length > 0) parts.push(`${integrity.unknown.length} of unknown type (${[...new Set(integrity.unknown.map((u) => u.t))].join(", ")})`);
171
+ return parts.join(" · ");
172
+ }
173
+
174
+ /**
175
+ * Fold events into the digest input. Order matters only where the log itself is
176
+ * ordered (last todo snapshot wins); totals are order-independent.
177
+ */
178
+ export function aggregate(
179
+ events: JournalEvent[],
180
+ fallback: Partial<DigestInput> = {},
181
+ integrity?: LogIntegrity,
182
+ ): DigestInput {
183
+ const first = events[0];
184
+ const last = events[events.length - 1];
185
+
186
+ const tasks: TaskStats[] = [];
187
+ const tools: ToolRecord[] = [];
188
+ // Item ids are unique for the whole session (protocol I2), so every snapshot can be
189
+ // *merged* instead of replacing the previous one. Taking only the last snapshot made a
190
+ // `clear` erase the timing of items that tool calls still reference.
191
+ const itemsById = new Map<number, TodoItem>();
192
+ let prompts = 0;
193
+ let model = fallback.model;
194
+ let provider = fallback.provider;
195
+ let cwd = fallback.cwd ?? "";
196
+ const startIds = new Set<string>();
197
+ const endIds = new Set<string>();
198
+ // Compaction is reported, not inferred: a failed compaction leaves no trace in the
199
+ // task or tool tables, and "nothing in the tables" must not read as "nothing happened".
200
+ const compaction = {
201
+ runs: 0,
202
+ failed: 0,
203
+ skipped: 0,
204
+ lastError: undefined as string | undefined,
205
+ lastSkip: undefined as string | undefined,
206
+ };
207
+
208
+ for (const e of events) {
209
+ switch (e.t) {
210
+ case "session":
211
+ if (typeof e.model === "string") model = e.model;
212
+ if (typeof e.provider === "string") provider = e.provider;
213
+ if (typeof e.cwd === "string") cwd = e.cwd;
214
+ break;
215
+ case "prompt":
216
+ prompts += 1;
217
+ // a prompt after /model switch reflects the model actually used
218
+ if (typeof e.model === "string") model = e.model;
219
+ break;
220
+ case "tool": {
221
+ if (e.phase === "start") {
222
+ startIds.add(String(e.id ?? ""));
223
+ break;
224
+ }
225
+ if (e.phase !== "end") break;
226
+ endIds.add(String(e.id ?? ""));
227
+ tools.push({
228
+ name: String(e.name ?? "?"),
229
+ task: e.task ?? 0,
230
+ item: e.item,
231
+ ts: e.ts ?? 0,
232
+ durMs: typeof e.durMs === "number" ? e.durMs : undefined,
233
+ wallMs: typeof e.wallMs === "number" ? e.wallMs : undefined,
234
+ isError: !!e.isError,
235
+ exitCode: typeof e.exitCode === "number" ? e.exitCode : undefined,
236
+ outBytes: typeof e.outBytes === "number" ? e.outBytes : undefined,
237
+ });
238
+ break;
239
+ }
240
+ case "todo": {
241
+ const items = e.items as Array<Record<string, unknown>> | undefined;
242
+ if (!Array.isArray(items)) break;
243
+ const seen = new Set<number>();
244
+ items.forEach((it, i) => {
245
+ const id = typeof it.id === "number" ? it.id : i + 1;
246
+ seen.add(id);
247
+ const prev = itemsById.get(id);
248
+ itemsById.set(id, {
249
+ id,
250
+ text: typeof it.text === "string" ? it.text : prev?.text ?? "",
251
+ status: typeof it.status === "string" ? it.status : prev?.status ?? "pending",
252
+ elapsedMs: typeof it.elapsedMs === "number" ? it.elapsedMs : prev?.elapsedMs ?? 0,
253
+ dropped: false,
254
+ });
255
+ });
256
+ // An item that vanished from the list was cleared away; its timing is a fact
257
+ // that already happened, so it is marked rather than deleted (protocol I8).
258
+ for (const [id, it] of itemsById) if (!seen.has(id)) it.dropped = true;
259
+ break;
260
+ }
261
+ case "compact":
262
+ compaction.runs += 1;
263
+ break;
264
+ case "compact_failed": {
265
+ // pi answers a premature `/compact` with "Nothing to compact (session too
266
+ // small)" — that is an empty answer, not a breakage, and counting it as a
267
+ // failure puts "1 failed" on the first digest a new user ever reads. An
268
+ // abort is likewise a no-op. Only the rest is a real failure.
269
+ const err = typeof e.error === "string" && e.error ? e.error : undefined;
270
+ const noop = e.aborted === true || (err !== undefined && /nothing to compact/i.test(err));
271
+ if (noop) {
272
+ compaction.skipped += 1;
273
+ if (err) compaction.lastSkip = err;
274
+ } else {
275
+ compaction.failed += 1;
276
+ if (err) compaction.lastError = err;
277
+ }
278
+ break;
279
+ }
280
+ case "settle":
281
+ tasks.push({
282
+ index: e.task ?? tasks.length + 1,
283
+ ms: typeof e.taskMs === "number" ? e.taskMs : 0,
284
+ turns: typeof e.turns === "number" ? e.turns : 0,
285
+ tools: typeof e.tools === "number" ? e.tools : 0,
286
+ tokens: tokensOf(e.tokens),
287
+ aborted: !!e.aborted,
288
+ });
289
+ break;
290
+ }
291
+ }
292
+
293
+ return {
294
+ sid: first?.sid ?? fallback.sid ?? "unknown",
295
+ date: dayStamp(first?.ts),
296
+ // deterministic: same file => same digest bytes
297
+ generatedAt: last?.ts ?? Date.now(),
298
+ model,
299
+ provider,
300
+ cwd,
301
+ events: events.length,
302
+ tasks,
303
+ tools,
304
+ todos: [...itemsById.values()],
305
+ quality: {
306
+ started: startIds.size,
307
+ calls: tools.length,
308
+ unfinished: [...startIds].filter((id) => !endIds.has(id)).length,
309
+ attributed: tools.filter((t) => t.item !== undefined).length,
310
+ tasksWithTokens: tasks.filter((t) => t.tokens.total > 0).length,
311
+ // A prompt with no settle is a task that never closed (killed, crashed, still
312
+ // running). It is not zero-duration — it is unknown, and must be said out loud.
313
+ prompts,
314
+ unsettled: Math.max(0, prompts - tasks.length),
315
+ // Absent when no compaction happened at all, so "no line" means "no compaction"
316
+ // rather than a fabricated zero.
317
+ compaction: compaction.runs + compaction.failed + compaction.skipped > 0 ? compaction : undefined,
318
+ integrity,
319
+ },
320
+ };
321
+ }
322
+
323
+ /** What a fresh process needs from an existing log before it appends: the task counter. */
324
+ export interface ResumeState {
325
+ /** next task index this process must use */
326
+ nextTask: number;
327
+ tasks: number;
328
+ lastTaskMs: number;
329
+ }
330
+
331
+ export function resumeState(logPath: string): ResumeState {
332
+ const events = parseLog(readFileSync(logPath, "utf8"));
333
+ let maxTask = 0;
334
+ let tasks = 0;
335
+ let lastTaskMs = 0;
336
+ for (const e of events) {
337
+ if (typeof e.task === "number" && e.task > maxTask) maxTask = e.task;
338
+ if (e.t === "settle") {
339
+ tasks += 1;
340
+ lastTaskMs = typeof e.taskMs === "number" ? e.taskMs : lastTaskMs;
341
+ }
342
+ }
343
+ return { nextTask: maxTask + 1, tasks, lastTaskMs };
344
+ }
345
+
346
+ /** Rebuild the digest text from a JSONL path. Throws only if the file is unreadable. */
347
+ export function rebuildDigest(logPath: string, fallback: Partial<DigestInput> = {}): string {
348
+ return replayLog(logPath, fallback).text;
349
+ }
350
+
351
+ /**
352
+ * Replay a file and hand back both the rendered digest and the integrity report,
353
+ * so a caller (a slash command, a test) can warn about damage instead of printing a
354
+ * digest that looks complete.
355
+ */
356
+ export function replayLog(logPath: string, fallback: Partial<DigestInput> = {}): { text: string; integrity: LogIntegrity } {
357
+ const { events, integrity } = parseLogDetailed(readFileSync(logPath, "utf8"));
358
+ return { text: buildDigest(aggregate(events, fallback, integrity)), integrity };
359
+ }
@@ -0,0 +1,324 @@
1
+ /**
2
+ * pi-workfeed · todo — a todo tool with per-item timing.
3
+ *
4
+ * The list is model-facing state; it is persisted in two places on purpose:
5
+ * - tool result `details` → correct after /fork and /tree (branch replay)
6
+ * - `pi.appendEntry` custom → survives compaction, which drops old messages
7
+ *
8
+ * Every *state change* is published on the extension event bus as
9
+ * `workfeed:todo`, so the journal extension can attribute turns, tool calls and
10
+ * tokens to the item that was in progress at that moment. UI ticks (the 2s status
11
+ * line repaint) never publish: an unchanged list emits nothing.
12
+ *
13
+ * Environment:
14
+ * PI_WORKFEED_TODO_OFF=1 disable this extension
15
+ */
16
+
17
+ import { StringEnum } from "@earendil-works/pi-ai";
18
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { Text } from "@earendil-works/pi-tui";
20
+ import { Type } from "typebox";
21
+
22
+ type TodoStatus = "pending" | "in_progress" | "completed";
23
+
24
+ interface Todo {
25
+ id: number;
26
+ text: string;
27
+ status: TodoStatus;
28
+ /** start of the current in_progress stretch (ms), cleared when it ends */
29
+ startedAt?: number;
30
+ /** accumulated in_progress time (ms) */
31
+ elapsedMs: number;
32
+ }
33
+
34
+ interface TodoDetails {
35
+ action: "write" | "list" | "clear";
36
+ todos: Todo[];
37
+ nextId: number;
38
+ error?: string;
39
+ }
40
+
41
+ const CUSTOM_TYPE = "workfeed:todo";
42
+
43
+ const Params = Type.Object({
44
+ action: StringEnum(["write", "list", "clear"] as const),
45
+ todos: Type.Optional(
46
+ Type.Array(
47
+ Type.Object({
48
+ text: Type.String({ description: "One-line task description, verb first" }),
49
+ status: Type.Optional(StringEnum(["pending", "in_progress", "completed"] as const)),
50
+ }),
51
+ { description: "Complete list for action=write; missing status means pending" },
52
+ ),
53
+ ),
54
+ });
55
+
56
+ function fmtDur(ms: number | undefined): string {
57
+ if (!ms || ms < 0) return "0s";
58
+ const s = Math.floor(ms / 1000);
59
+ if (s < 60) return `${s}s`;
60
+ const m = Math.floor(s / 60);
61
+ if (m < 60) return `${m}m${String(s % 60).padStart(2, "0")}s`;
62
+ const h = Math.floor(m / 60);
63
+ return `${h}h${String(m % 60).padStart(2, "0")}m`;
64
+ }
65
+
66
+ /** Elapsed for one item: accumulated + the stretch still running. */
67
+ function itemElapsedMs(t: Todo, now = Date.now()): number {
68
+ const base = t.elapsedMs || 0;
69
+ return t.status === "in_progress" && t.startedAt ? base + (now - t.startedAt) : base;
70
+ }
71
+
72
+ /** Ids are join keys, so recovery falls back to max+1, never to length+1. */
73
+ function maxIdOf(todos: Todo[]): number {
74
+ return todos.reduce((m, t) => Math.max(m, t.id), 0);
75
+ }
76
+
77
+ function summarize(todos: Todo[], now = Date.now()): string {
78
+ if (todos.length === 0) return "todo list is empty";
79
+ const done = todos.filter((t) => t.status === "completed").length;
80
+ const active = todos.find((t) => t.status === "in_progress");
81
+ const total = todos.reduce((acc, t) => acc + itemElapsedMs(t, now), 0);
82
+ const head = `${done}/${todos.length} done · ${fmtDur(total)} accumulated`;
83
+ return active ? `${head} · in progress: ${active.text} (${fmtDur(itemElapsedMs(active, now))})` : head;
84
+ }
85
+
86
+ function listText(todos: Todo[], now = Date.now()): string {
87
+ if (todos.length === 0) return "todo list is empty";
88
+ const icon = (s: TodoStatus) => (s === "completed" ? "x" : s === "in_progress" ? ">" : "o");
89
+ const lines = todos.map((t) => {
90
+ const el = itemElapsedMs(t, now);
91
+ return `${icon(t.status)} #${t.id} ${t.text}${el ? ` (${fmtDur(el)})` : ""}`;
92
+ });
93
+ lines.push(summarize(todos, now));
94
+ return lines.join("\n");
95
+ }
96
+
97
+ export default function (pi: ExtensionAPI) {
98
+ if (process.env.PI_WORKFEED_TODO_OFF === "1") return;
99
+
100
+ let todos: Todo[] = [];
101
+ let nextId = 1;
102
+ let ticker: ReturnType<typeof setInterval> | undefined;
103
+ let lastCtx: ExtensionContext | undefined;
104
+ /** signature of the state last published; equality means "nothing changed" */
105
+ let lastSig = "";
106
+ /** monotonic snapshot counter; consumers can drop duplicates by it */
107
+ let rev = 0;
108
+
109
+ /** What consumers care about: ids, texts, statuses and closed timing stretches. */
110
+ const sigOf = () =>
111
+ JSON.stringify({ n: nextId, t: todos.map((t) => [t.id, t.text, t.status, t.startedAt ?? 0, t.elapsedMs]) });
112
+
113
+ /** An empty list is the resting state, not a change: startup stays silent. */
114
+ lastSig = sigOf();
115
+
116
+ /**
117
+ * Publish state so the journal can attribute events to an item.
118
+ * Emits only when the state actually changed — the consumer's view is exactly
119
+ * what was last emitted, so an identical snapshot would only add a duplicate
120
+ * line. Branch replay goes through the same rule.
121
+ */
122
+ const publish = (ctx: ExtensionContext) => {
123
+ const sig = sigOf();
124
+ if (sig === lastSig) return;
125
+ lastSig = sig;
126
+ rev += 1;
127
+ pi.events.emit("workfeed:todo", { todos: todos.map((t) => ({ ...t })), nextId, rev, sessionId: ctx.sessionManager.getSessionId?.() });
128
+ };
129
+
130
+ const persist = () => {
131
+ pi.appendEntry(CUSTOM_TYPE, { todos: todos.map((t) => ({ ...t })), nextId });
132
+ };
133
+
134
+ /**
135
+ * Rebuild from the active branch. Custom entries outrank tool details once
136
+ * they exist, because compaction drops messages but keeps custom entries.
137
+ */
138
+ const reconstruct = (ctx: ExtensionContext) => {
139
+ todos = [];
140
+ nextId = 1;
141
+ const branch = ctx.sessionManager.getBranch();
142
+ for (const entry of branch) {
143
+ if (entry.type === "custom" && entry.customType === CUSTOM_TYPE) {
144
+ const d = entry.data as { todos?: Todo[]; nextId?: number } | undefined;
145
+ if (d?.todos) {
146
+ todos = d.todos.map((t) => ({ ...t, elapsedMs: t.elapsedMs || 0 }));
147
+ nextId = d.nextId ?? maxIdOf(todos) + 1;
148
+ }
149
+ continue;
150
+ }
151
+ if (entry.type !== "message") continue;
152
+ const msg = entry.message as { role?: string; toolName?: string; details?: unknown };
153
+ if (msg.role !== "toolResult" || (msg.toolName !== "workfeed_todo" && msg.toolName !== "todo")) continue;
154
+ const d = msg.details as TodoDetails | undefined;
155
+ if (d?.todos) {
156
+ todos = d.todos.map((t) => ({ ...t, elapsedMs: t.elapsedMs || 0 }));
157
+ nextId = d.nextId ?? maxIdOf(todos) + 1;
158
+ }
159
+ }
160
+ renderStatus(ctx);
161
+ publish(ctx);
162
+ };
163
+
164
+ /** UI only: repaint the status line. Runs every 2s, so it must never emit events. */
165
+ const renderStatus = (ctx: ExtensionContext | undefined) => {
166
+ if (!ctx) return;
167
+ if (ctx.hasUI) {
168
+ if (todos.length === 0) {
169
+ ctx.ui.setStatus("workfeed-todo", "");
170
+ } else {
171
+ const done = todos.filter((t) => t.status === "completed").length;
172
+ const active = todos.find((t) => t.status === "in_progress");
173
+ const parts = [`${done}/${todos.length}`];
174
+ if (active) parts.push(`> ${active.text.slice(0, 28)} ${fmtDur(itemElapsedMs(active))}`);
175
+ ctx.ui.setStatus("workfeed-todo", parts.join(" · "));
176
+ }
177
+ }
178
+ };
179
+
180
+ const startTicker = (ctx: ExtensionContext) => {
181
+ lastCtx = ctx;
182
+ if (ticker || !ctx.hasUI) return;
183
+ ticker = setInterval(() => renderStatus(lastCtx), 2000);
184
+ };
185
+
186
+ const stopTicker = () => {
187
+ if (ticker) clearInterval(ticker);
188
+ ticker = undefined;
189
+ };
190
+
191
+ pi.on("session_start", async (_event, ctx) => {
192
+ reconstruct(ctx);
193
+ startTicker(ctx);
194
+ });
195
+ pi.on("session_tree", async (_event, ctx) => {
196
+ reconstruct(ctx);
197
+ });
198
+ pi.on("session_shutdown", async () => {
199
+ stopTicker();
200
+ });
201
+
202
+ pi.registerTool({
203
+ name: "workfeed_todo",
204
+ label: "Todo",
205
+ description:
206
+ "Maintain the task list and time each item automatically. action=write replaces the whole list (timing is kept for items whose text matches); action=list is read-only; action=clear empties it. Item ids keep counting up for the whole session and are never reused, so they stay unique join keys. Keep at most one item in_progress.",
207
+ promptSnippet: "Track multi-step work in a task list with per-item timing",
208
+ promptGuidelines: [
209
+ "Use workfeed_todo with action=write for work that needs 3+ steps, and update statuses as you go; keep exactly one item in_progress.",
210
+ "Write the list in a turn of its own, before the tools it tracks. A tool call made while no item is in_progress is recorded with no item, so bundling the todo write with a bash/read call in the same turn costs that call its attribution and lowers the digest's attribution rate.",
211
+ "Call workfeed_todo again after each meaningful step so progress is visible, and mark an item completed only once its result is verified.",
212
+ ],
213
+ parameters: Params,
214
+
215
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
216
+ const action = params.action;
217
+ const now = Date.now();
218
+
219
+ if (action === "list") {
220
+ renderStatus(ctx as ExtensionContext);
221
+ return {
222
+ content: [{ type: "text", text: listText(todos, now) }],
223
+ details: { action, todos: [...todos], nextId } as TodoDetails,
224
+ };
225
+ }
226
+
227
+ if (action === "clear") {
228
+ const count = todos.length;
229
+ todos = [];
230
+ // `nextId` deliberately survives a clear: item ids are join keys, so they
231
+ // must never be reused inside one session (a second list's #1 would
232
+ // collide with the first list's #1 in the journal).
233
+ persist();
234
+ renderStatus(ctx as ExtensionContext);
235
+ publish(ctx as ExtensionContext);
236
+ return {
237
+ content: [{ type: "text", text: `cleared ${count} item(s)` }],
238
+ details: { action, todos: [], nextId } as TodoDetails,
239
+ };
240
+ }
241
+
242
+ const incoming = params.todos ?? [];
243
+ if (incoming.length === 0) {
244
+ return {
245
+ content: [{ type: "text", text: "error: write needs a non-empty todos array (use clear to empty the list)" }],
246
+ details: { action, todos: [...todos], nextId, error: "empty todos" } as TodoDetails,
247
+ };
248
+ }
249
+
250
+ const prevByText = new Map(todos.map((t) => [t.text, t]));
251
+ const next: Todo[] = [];
252
+ for (const raw of incoming) {
253
+ const text = raw.text.trim();
254
+ if (!text) continue;
255
+ const status: TodoStatus = raw.status ?? "pending";
256
+ const prev = prevByText.get(text);
257
+ const item: Todo = prev ? { ...prev } : { id: nextId++, text, status, elapsedMs: 0 };
258
+
259
+ // leaving in_progress: close the running stretch
260
+ if (item.status === "in_progress" && item.startedAt && status !== "in_progress") {
261
+ item.elapsedMs = (item.elapsedMs || 0) + Math.max(0, now - item.startedAt);
262
+ item.startedAt = undefined;
263
+ }
264
+ // entering in_progress: open a stretch
265
+ if (status === "in_progress" && !item.startedAt) item.startedAt = now;
266
+ // rolling back to pending keeps the timing: history is for review
267
+ item.status = status;
268
+ next.push(item);
269
+ }
270
+
271
+ const actives = next.filter((t) => t.status === "in_progress");
272
+ todos = next;
273
+ persist();
274
+ renderStatus(ctx as ExtensionContext);
275
+ publish(ctx as ExtensionContext);
276
+
277
+ const warn = actives.length > 1 ? `\n(note: ${actives.length} items are in_progress; keep one)` : "";
278
+ return {
279
+ content: [{ type: "text", text: `${listText(todos, now)}${warn}` }],
280
+ details: { action, todos: [...todos], nextId } as TodoDetails,
281
+ };
282
+ },
283
+
284
+ renderCall(args, theme) {
285
+ let s = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action);
286
+ if (args.todos?.length) s += theme.fg("dim", ` (${args.todos.length} items)`);
287
+ return new Text(s, 0, 0);
288
+ },
289
+
290
+ renderResult(result, { expanded }, theme) {
291
+ const d = result.details as TodoDetails | undefined;
292
+ if (d?.error) return new Text(theme.fg("error", `error: ${d.error}`), 0, 0);
293
+ if (!d?.todos) {
294
+ const t = result.content[0];
295
+ return new Text(t?.type === "text" ? t.text : "", 0, 0);
296
+ }
297
+ const now = Date.now();
298
+ const done = d.todos.filter((t) => t.status === "completed").length;
299
+ const active = d.todos.find((t) => t.status === "in_progress");
300
+ const head =
301
+ theme.fg("success", `${done}/${d.todos.length}`) +
302
+ (active ? " " + theme.fg("accent", `> ${active.text}`) : "") +
303
+ " " +
304
+ theme.fg("dim", `${fmtDur(d.todos.reduce((a, t) => a + itemElapsedMs(t, now), 0))} accumulated`);
305
+ const show = expanded ? d.todos : d.todos.slice(-3);
306
+ const lines = show.map((t) => {
307
+ const glyph = t.status === "completed" ? theme.fg("success", "x") : t.status === "in_progress" ? theme.fg("accent", ">") : theme.fg("dim", "o");
308
+ const el = itemElapsedMs(t, now) ? theme.fg("dim", ` ${fmtDur(itemElapsedMs(t, now))}`) : "";
309
+ const txt = t.status === "completed" ? theme.fg("dim", t.text) : theme.fg("muted", t.text);
310
+ return `${glyph} ${theme.fg("accent", `#${t.id}`)} ${txt}${el}`;
311
+ });
312
+ return new Text([head, ...lines].join("\n"), 0, 0);
313
+ },
314
+ });
315
+
316
+ pi.registerCommand("wf-todos", {
317
+ description: "Show the task list with per-item timing",
318
+ handler: async (_args, ctx) => {
319
+ // branch navigation can leave memory stale; replay before showing
320
+ reconstruct(ctx);
321
+ ctx.ui.notify(listText(todos), "info");
322
+ },
323
+ });
324
+ }