@juicesharp/rpiv-todo 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.
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # rpiv-todo
2
+
3
+ Pi extension that registers the `todo` tool, `/todos` slash command, and a
4
+ persistent TodoOverlay widget above the editor. Replaces Claude Code's
5
+ TaskCreate/TaskUpdate tool family.
6
+
7
+ ## Installation
8
+
9
+ pi install npm:@juicesharp/rpiv-todo
10
+
11
+ Then restart your Pi session.
12
+
13
+ ## Tool
14
+
15
+ - **`todo`** — create / update / list / get / delete / clear tasks. 4-state
16
+ machine (pending → in_progress → completed, plus deleted tombstone).
17
+ Supports `blockedBy` dependency tracking with cycle detection. Tasks persist
18
+ via branch replay — survive session compact and `/reload`.
19
+
20
+ ## Commands
21
+
22
+ - **`/todos`** — print the current todo list grouped by status.
23
+
24
+ ## Overlay
25
+
26
+ The aboveEditor widget auto-renders whenever any non-deleted tasks exist.
27
+ 12-line collapse threshold; completed tasks drop first on overflow, pending
28
+ tasks truncate last. Auto-hides when the list is empty.
29
+
30
+ ## License
31
+
32
+ MIT
package/index.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * rpiv-todo — Pi extension
3
+ *
4
+ * Registers the `todo` tool, `/todos` slash command, and the five lifecycle
5
+ * hooks that manage branch-replay state reconstruction and the TodoOverlay
6
+ * persistent widget.
7
+ *
8
+ * Extracted from rpiv-pi@7525a5d. Tool name "todo" and widget key
9
+ * "rpiv-todos" preserved verbatim so existing session history replays
10
+ * correctly after upgrade.
11
+ */
12
+
13
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
14
+ import { registerTodoTool, registerTodosCommand, reconstructTodoState } from "./todo.js";
15
+ import { TodoOverlay } from "./todo-overlay.js";
16
+
17
+ export default function (pi: ExtensionAPI) {
18
+ // Todo overlay widget — constructed lazily at the first session_start with UI.
19
+ let todoOverlay: TodoOverlay | undefined;
20
+
21
+ registerTodoTool(pi);
22
+ registerTodosCommand(pi);
23
+
24
+ pi.on("session_start", async (_event, ctx) => {
25
+ reconstructTodoState(ctx);
26
+ if (ctx.hasUI) {
27
+ todoOverlay ??= new TodoOverlay();
28
+ todoOverlay.setUICtx(ctx.ui);
29
+ todoOverlay.update();
30
+ }
31
+ });
32
+
33
+ pi.on("session_compact", async (_event, ctx) => {
34
+ reconstructTodoState(ctx);
35
+ todoOverlay?.update();
36
+ });
37
+
38
+ pi.on("session_tree", async (_event, ctx) => {
39
+ reconstructTodoState(ctx);
40
+ todoOverlay?.update();
41
+ });
42
+
43
+ pi.on("session_shutdown", async () => {
44
+ todoOverlay?.dispose();
45
+ todoOverlay = undefined;
46
+ });
47
+
48
+ // Reads getTodos() at render time; do NOT call reconstructTodoState here
49
+ // (branch is stale — message_end runs after tool_execution_end).
50
+ pi.on("tool_execution_end", async (event) => {
51
+ if (event.toolName !== "todo" || event.isError) return;
52
+ todoOverlay?.update();
53
+ });
54
+ }
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@juicesharp/rpiv-todo",
3
+ "version": "0.1.0",
4
+ "description": "Pi extension: Claude-Code-parity todo tool + persistent overlay widget",
5
+ "keywords": ["pi-package", "pi-extension", "rpiv", "todo"],
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "author": "juicesharp",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/juicesharp/rpiv-todo.git"
12
+ },
13
+ "homepage": "https://github.com/juicesharp/rpiv-todo#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/juicesharp/rpiv-todo/issues"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "pi": {
21
+ "extensions": ["./index.ts"]
22
+ },
23
+ "peerDependencies": {
24
+ "@mariozechner/pi-ai": "*",
25
+ "@mariozechner/pi-coding-agent": "*",
26
+ "@mariozechner/pi-tui": "*",
27
+ "@sinclair/typebox": "*"
28
+ }
29
+ }
@@ -0,0 +1,245 @@
1
+ /**
2
+ * todo-overlay.ts — Persistent widget showing todo list above the editor.
3
+ *
4
+ * Mirrors @tintinweb/pi-subagents's AgentWidget shape: factory-form setWidget
5
+ * registration in widgetContainerAbove, register-once + requestRender() refresh,
6
+ * 12-line collapse-not-scroll, auto-hide when empty. No timer (todos have no
7
+ * animation), no status bar, no aging map.
8
+ *
9
+ * Data source is module-level getTodos() read at render time — NEVER
10
+ * reconstructTodoState from a tool_execution_end handler, since the persisted
11
+ * branch is stale at that point (message_end runs after the extension event).
12
+ */
13
+
14
+ import type {
15
+ ExtensionUIContext,
16
+ Theme,
17
+ } from "@mariozechner/pi-coding-agent";
18
+ import { truncateToWidth, type TUI } from "@mariozechner/pi-tui";
19
+ import { getTodos, type Task, type TaskStatus } from "./todo.js";
20
+
21
+ // ---- Constants ----
22
+
23
+ const WIDGET_KEY = "rpiv-todos";
24
+ /** Maximum rendered lines before overflow-collapse kicks in. Mirrors AgentWidget. */
25
+ const MAX_WIDGET_LINES = 12;
26
+
27
+ // ---- Helpers ----
28
+
29
+ function statusGlyph(status: TaskStatus, theme: Theme): string {
30
+ switch (status) {
31
+ case "pending":
32
+ return theme.fg("dim", "○");
33
+ case "in_progress":
34
+ return theme.fg("warning", "◐");
35
+ case "completed":
36
+ return theme.fg("success", "✓");
37
+ case "deleted":
38
+ return theme.fg("error", "✗");
39
+ }
40
+ }
41
+
42
+ // ---- Controller ----
43
+
44
+ export class TodoOverlay {
45
+ private uiCtx: ExtensionUIContext | undefined;
46
+ private widgetRegistered = false;
47
+ private tui: TUI | undefined;
48
+
49
+ /**
50
+ * Bind or rebind the UI context. Identity-compares the incoming ctx so
51
+ * subsequent session_start handlers are idempotent; on identity change
52
+ * (e.g. /reload) cached widgetRegistered/tui are invalidated so the next
53
+ * update() re-registers under the fresh context.
54
+ */
55
+ setUICtx(ctx: ExtensionUIContext): void {
56
+ if (ctx !== this.uiCtx) {
57
+ this.uiCtx = ctx;
58
+ this.widgetRegistered = false;
59
+ this.tui = undefined;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Idempotent refresh. Safe to call from session_start, session_compact,
65
+ * session_tree, and tool_execution_end. Reads live state via getTodos() —
66
+ * NEVER calls reconstructTodoState (branch is stale during tool events).
67
+ */
68
+ update(): void {
69
+ if (!this.uiCtx) return;
70
+
71
+ const visible = getTodos().filter((t) => t.status !== "deleted");
72
+
73
+ // Empty → unregister and clear cached refs.
74
+ if (visible.length === 0) {
75
+ if (this.widgetRegistered) {
76
+ this.uiCtx.setWidget(WIDGET_KEY, undefined);
77
+ this.widgetRegistered = false;
78
+ this.tui = undefined;
79
+ }
80
+ return;
81
+ }
82
+
83
+ // Non-empty → register once, then requestRender on subsequent updates.
84
+ if (!this.widgetRegistered) {
85
+ this.uiCtx.setWidget(
86
+ WIDGET_KEY,
87
+ (tui, theme) => {
88
+ this.tui = tui;
89
+ return {
90
+ render: (width: number) => this.renderWidget(theme, width),
91
+ invalidate: () => {
92
+ // Theme changed — force factory re-invocation to capture fresh theme.
93
+ this.widgetRegistered = false;
94
+ this.tui = undefined;
95
+ },
96
+ };
97
+ },
98
+ { placement: "aboveEditor" },
99
+ );
100
+ this.widgetRegistered = true;
101
+ } else {
102
+ this.tui?.requestRender();
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Build rendered rows. Called from the registered widget's render() closure,
108
+ * so it reads live state each time via getTodos() rather than capturing it.
109
+ * Preserves natural (insertion) order. On overflow, drops completed tasks
110
+ * first (in-place — remaining items stay in natural order), then truncates
111
+ * the non-completed tail if still overflowing.
112
+ */
113
+ private renderWidget(theme: Theme, width: number): string[] {
114
+ const all = getTodos().filter((t) => t.status !== "deleted");
115
+ if (all.length === 0) return [];
116
+
117
+ const truncate = (line: string): string => truncateToWidth(line, width);
118
+
119
+ const completedCount = all.filter((t) => t.status === "completed").length;
120
+ const totalVisible = all.length;
121
+ const hasActive = all.some(
122
+ (t) => t.status === "in_progress" || t.status === "pending",
123
+ );
124
+ // Show per-row ids only when at least one task has a blockedBy
125
+ // reference — otherwise the `⛓ #N` suffix on a dep row couldn't be
126
+ // resolved against any visible task.
127
+ const showIds = all.some((t) => t.blockedBy && t.blockedBy.length > 0);
128
+
129
+ const headingColor = hasActive ? "accent" : "dim";
130
+ const headingIcon = hasActive ? "●" : "○";
131
+ const headingText = `Todos (${completedCount}/${totalVisible})`;
132
+ const heading = truncate(
133
+ theme.fg(headingColor, headingIcon) +
134
+ " " +
135
+ theme.fg(headingColor, headingText),
136
+ );
137
+
138
+ const lines: string[] = [heading];
139
+ const maxBody = MAX_WIDGET_LINES - 1; // heading takes 1 row
140
+
141
+ // Happy path: everything fits in natural order.
142
+ if (all.length <= maxBody) {
143
+ for (const t of all) {
144
+ lines.push(
145
+ truncate(
146
+ theme.fg("dim", "├─") + " " + this.formatTaskLine(t, theme, showIds),
147
+ ),
148
+ );
149
+ }
150
+ const last = lines.length - 1;
151
+ lines[last] = lines[last].replace("├─", "└─");
152
+ return lines;
153
+ }
154
+
155
+ // Overflow path: reserve 1 line for the summary, drop completed first
156
+ // (in natural order), then truncate the non-completed tail if needed.
157
+ const budget = maxBody - 1;
158
+ const nonCompleted = all.filter((t) => t.status !== "completed");
159
+
160
+ let visible: Task[];
161
+ let truncatedTailCount = 0;
162
+ if (nonCompleted.length <= budget) {
163
+ // Dropping completed alone was enough. Fill remaining slots with
164
+ // completed tasks from `all` until the budget is hit, then re-sort
165
+ // into natural order.
166
+ const kept = new Set<Task>(nonCompleted);
167
+ for (const t of all) {
168
+ if (kept.size >= budget) break;
169
+ if (t.status === "completed") kept.add(t);
170
+ }
171
+ visible = all.filter((t) => kept.has(t));
172
+ } else {
173
+ // Even dropping all completed isn't enough — truncate the
174
+ // non-completed tail.
175
+ visible = nonCompleted.slice(0, budget);
176
+ truncatedTailCount = nonCompleted.length - budget;
177
+ }
178
+
179
+ for (const t of visible) {
180
+ lines.push(
181
+ truncate(
182
+ theme.fg("dim", "├─") + " " + this.formatTaskLine(t, theme, showIds),
183
+ ),
184
+ );
185
+ }
186
+
187
+ const shownCompleted = visible.filter(
188
+ (t) => t.status === "completed",
189
+ ).length;
190
+ const hiddenCompleted = completedCount - shownCompleted;
191
+ const totalHidden = hiddenCompleted + truncatedTailCount;
192
+ const overflowParts: string[] = [];
193
+ if (hiddenCompleted > 0) overflowParts.push(`${hiddenCompleted} completed`);
194
+ if (truncatedTailCount > 0) overflowParts.push(`${truncatedTailCount} pending`);
195
+ lines.push(
196
+ truncate(
197
+ theme.fg("dim", "└─") +
198
+ " " +
199
+ theme.fg(
200
+ "dim",
201
+ overflowParts.length > 0
202
+ ? `+${totalHidden} more (${overflowParts.join(", ")})`
203
+ : `+${totalHidden} more`,
204
+ ),
205
+ ),
206
+ );
207
+ return lines;
208
+ }
209
+
210
+ private formatTaskLine(t: Task, theme: Theme, showId: boolean): string {
211
+ const glyph = statusGlyph(t.status, theme);
212
+ const subjectColor =
213
+ t.status === "completed" || t.status === "deleted" ? "dim" : "text";
214
+ let subject = theme.fg(subjectColor, t.subject);
215
+ if (t.status === "completed" || t.status === "deleted") {
216
+ subject = theme.strikethrough(subject);
217
+ }
218
+ let line = `${glyph}`;
219
+ if (showId) {
220
+ line += ` ${theme.fg("accent", `#${t.id}`)}`;
221
+ }
222
+ line += ` ${subject}`;
223
+ if (t.status === "in_progress" && t.activeForm) {
224
+ line += " " + theme.fg("dim", `(${t.activeForm})`);
225
+ }
226
+ if (t.blockedBy && t.blockedBy.length > 0) {
227
+ line +=
228
+ " " +
229
+ theme.fg(
230
+ "dim",
231
+ `⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}`,
232
+ );
233
+ }
234
+ return line;
235
+ }
236
+
237
+ dispose(): void {
238
+ if (this.uiCtx) {
239
+ this.uiCtx.setWidget(WIDGET_KEY, undefined);
240
+ }
241
+ this.widgetRegistered = false;
242
+ this.tui = undefined;
243
+ this.uiCtx = undefined;
244
+ }
245
+ }
package/todo.ts ADDED
@@ -0,0 +1,768 @@
1
+ /**
2
+ * todo tool + /todos command — Claude-Code-parity Task management.
3
+ *
4
+ * State lives in this module and persists via the tool's AgentToolResult.details
5
+ * envelope. reconstructTodoState walks ctx.sessionManager.getBranch() and restores
6
+ * the last snapshot; the pure applyTaskMutation reducer is the single source of
7
+ * truth for invariants — state machine transitions, blockedBy cycle checks,
8
+ * dangling-reference rejection. Tool name is deliberately "todo" (not
9
+ * TaskCreate/etc.) to preserve the permissions entry at
10
+ * templates/pi-permissions.jsonc:26.
11
+ */
12
+
13
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
14
+ import { StringEnum } from "@mariozechner/pi-ai";
15
+ import { Text } from "@mariozechner/pi-tui";
16
+ import { Type } from "@sinclair/typebox";
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Types
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export type TaskStatus = "pending" | "in_progress" | "completed" | "deleted";
23
+
24
+ export type TaskAction = "create" | "update" | "list" | "get" | "delete" | "clear";
25
+
26
+ export interface Task {
27
+ id: number;
28
+ subject: string;
29
+ description?: string;
30
+ activeForm?: string;
31
+ status: TaskStatus;
32
+ blockedBy?: number[];
33
+ owner?: string;
34
+ metadata?: Record<string, unknown>;
35
+ }
36
+
37
+ export interface TaskDetails {
38
+ action: TaskAction;
39
+ params: Record<string, unknown>;
40
+ tasks: Task[];
41
+ nextId: number;
42
+ error?: string;
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // State machine
47
+ // ---------------------------------------------------------------------------
48
+
49
+ const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {
50
+ pending: new Set(["in_progress", "completed", "deleted"]),
51
+ in_progress: new Set(["pending", "completed", "deleted"]),
52
+ completed: new Set(["deleted"]),
53
+ deleted: new Set(),
54
+ };
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Module state
58
+ // ---------------------------------------------------------------------------
59
+
60
+ let tasks: Task[] = [];
61
+ let nextId = 1;
62
+
63
+ export function getTodos(): readonly Task[] {
64
+ return tasks;
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Pure helpers — no state mutation, no I/O
69
+ // ---------------------------------------------------------------------------
70
+
71
+ export function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {
72
+ if (from === to) return true;
73
+ return VALID_TRANSITIONS[from].has(to);
74
+ }
75
+
76
+ export function detectCycle(
77
+ taskList: readonly Task[],
78
+ taskId: number,
79
+ newBlockedBy: readonly number[],
80
+ ): boolean {
81
+ const edges = new Map<number, number[]>();
82
+ for (const t of taskList) {
83
+ if (t.id === taskId) {
84
+ const merged = new Set([...(t.blockedBy ?? []), ...newBlockedBy]);
85
+ edges.set(t.id, [...merged]);
86
+ } else {
87
+ edges.set(t.id, t.blockedBy ? [...t.blockedBy] : []);
88
+ }
89
+ }
90
+
91
+ const visiting = new Set<number>();
92
+ const visited = new Set<number>();
93
+ const hasCycleFrom = (node: number): boolean => {
94
+ if (visiting.has(node)) return true;
95
+ if (visited.has(node)) return false;
96
+ visiting.add(node);
97
+ for (const nb of edges.get(node) ?? []) {
98
+ if (hasCycleFrom(nb)) return true;
99
+ }
100
+ visiting.delete(node);
101
+ visited.add(node);
102
+ return false;
103
+ };
104
+
105
+ for (const node of edges.keys()) {
106
+ if (hasCycleFrom(node)) return true;
107
+ }
108
+ return false;
109
+ }
110
+
111
+ export function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {
112
+ const blocks = new Map<number, number[]>();
113
+ for (const t of taskList) {
114
+ for (const dep of t.blockedBy ?? []) {
115
+ const arr = blocks.get(dep) ?? [];
116
+ arr.push(t.id);
117
+ blocks.set(dep, arr);
118
+ }
119
+ }
120
+ return blocks;
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // Reducer — pure, single source of truth for invariants
125
+ // ---------------------------------------------------------------------------
126
+
127
+ interface ReducerState {
128
+ tasks: Task[];
129
+ nextId: number;
130
+ }
131
+
132
+ interface ReducerResult {
133
+ state: ReducerState;
134
+ details: TaskDetails;
135
+ content: Array<{ type: "text"; text: string }>;
136
+ }
137
+
138
+ interface TaskMutationParams {
139
+ [key: string]: unknown;
140
+ subject?: string;
141
+ description?: string;
142
+ activeForm?: string;
143
+ status?: TaskStatus;
144
+ blockedBy?: number[];
145
+ addBlockedBy?: number[];
146
+ removeBlockedBy?: number[];
147
+ owner?: string;
148
+ metadata?: Record<string, unknown>;
149
+ id?: number;
150
+ includeDeleted?: boolean;
151
+ }
152
+
153
+ function errorResult(
154
+ state: ReducerState,
155
+ action: TaskAction,
156
+ params: TaskMutationParams,
157
+ error: string,
158
+ ): ReducerResult {
159
+ return {
160
+ state,
161
+ details: {
162
+ action,
163
+ params: params as Record<string, unknown>,
164
+ tasks: state.tasks,
165
+ nextId: state.nextId,
166
+ error,
167
+ },
168
+ content: [{ type: "text", text: `Error: ${error}` }],
169
+ };
170
+ }
171
+
172
+ export function applyTaskMutation(
173
+ state: ReducerState,
174
+ action: TaskAction,
175
+ params: TaskMutationParams,
176
+ ): ReducerResult {
177
+ switch (action) {
178
+ case "create": {
179
+ if (!params.subject || !params.subject.trim()) {
180
+ return errorResult(state, action, params, "subject required for create");
181
+ }
182
+ if (params.blockedBy && params.blockedBy.length) {
183
+ for (const dep of params.blockedBy) {
184
+ const depTask = state.tasks.find((t) => t.id === dep);
185
+ if (!depTask) {
186
+ return errorResult(
187
+ state,
188
+ action,
189
+ params,
190
+ `blockedBy: #${dep} not found`,
191
+ );
192
+ }
193
+ if (depTask.status === "deleted") {
194
+ return errorResult(
195
+ state,
196
+ action,
197
+ params,
198
+ `blockedBy: #${dep} is deleted`,
199
+ );
200
+ }
201
+ }
202
+ }
203
+ const newTask: Task = {
204
+ id: state.nextId,
205
+ subject: params.subject,
206
+ status: "pending",
207
+ };
208
+ if (params.description) newTask.description = params.description;
209
+ if (params.activeForm) newTask.activeForm = params.activeForm;
210
+ if (params.blockedBy && params.blockedBy.length) {
211
+ newTask.blockedBy = [...params.blockedBy];
212
+ }
213
+ if (params.owner) newTask.owner = params.owner;
214
+ if (params.metadata) newTask.metadata = { ...params.metadata };
215
+
216
+ const newTasks = [...state.tasks, newTask];
217
+ const newState: ReducerState = { tasks: newTasks, nextId: state.nextId + 1 };
218
+ return {
219
+ state: newState,
220
+ details: {
221
+ action: "create",
222
+ params: params as Record<string, unknown>,
223
+ tasks: newTasks,
224
+ nextId: newState.nextId,
225
+ },
226
+ content: [
227
+ {
228
+ type: "text",
229
+ text: `Created #${newTask.id}: ${newTask.subject} (pending)`,
230
+ },
231
+ ],
232
+ };
233
+ }
234
+
235
+ case "update": {
236
+ if (params.id === undefined) {
237
+ return errorResult(state, action, params, "id required for update");
238
+ }
239
+ const idx = state.tasks.findIndex((t) => t.id === params.id);
240
+ if (idx === -1) {
241
+ return errorResult(state, action, params, `#${params.id} not found`);
242
+ }
243
+ const current = state.tasks[idx];
244
+
245
+ const hasMutation =
246
+ params.subject !== undefined ||
247
+ params.description !== undefined ||
248
+ params.activeForm !== undefined ||
249
+ params.status !== undefined ||
250
+ params.owner !== undefined ||
251
+ params.metadata !== undefined ||
252
+ (params.addBlockedBy && params.addBlockedBy.length > 0) ||
253
+ (params.removeBlockedBy && params.removeBlockedBy.length > 0);
254
+ if (!hasMutation) {
255
+ return errorResult(
256
+ state,
257
+ action,
258
+ params,
259
+ "update requires at least one mutable field",
260
+ );
261
+ }
262
+
263
+ let newStatus = current.status;
264
+ if (params.status !== undefined) {
265
+ if (!isTransitionValid(current.status, params.status)) {
266
+ return errorResult(
267
+ state,
268
+ action,
269
+ params,
270
+ `illegal transition ${current.status} → ${params.status}`,
271
+ );
272
+ }
273
+ newStatus = params.status;
274
+ }
275
+
276
+ let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];
277
+ if (params.removeBlockedBy && params.removeBlockedBy.length) {
278
+ const toRemove = new Set(params.removeBlockedBy);
279
+ newBlockedBy = newBlockedBy.filter((dep) => !toRemove.has(dep));
280
+ }
281
+ if (params.addBlockedBy && params.addBlockedBy.length) {
282
+ for (const dep of params.addBlockedBy) {
283
+ if (dep === current.id) {
284
+ return errorResult(
285
+ state,
286
+ action,
287
+ params,
288
+ `cannot block #${current.id} on itself`,
289
+ );
290
+ }
291
+ const depTask = state.tasks.find((t) => t.id === dep);
292
+ if (!depTask) {
293
+ return errorResult(
294
+ state,
295
+ action,
296
+ params,
297
+ `addBlockedBy: #${dep} not found`,
298
+ );
299
+ }
300
+ if (depTask.status === "deleted") {
301
+ return errorResult(
302
+ state,
303
+ action,
304
+ params,
305
+ `addBlockedBy: #${dep} is deleted`,
306
+ );
307
+ }
308
+ if (!newBlockedBy.includes(dep)) newBlockedBy.push(dep);
309
+ }
310
+ if (detectCycle(state.tasks, current.id, newBlockedBy)) {
311
+ return errorResult(
312
+ state,
313
+ action,
314
+ params,
315
+ "addBlockedBy would create a cycle in the blockedBy graph",
316
+ );
317
+ }
318
+ }
319
+
320
+ let newMetadata = current.metadata;
321
+ if (params.metadata !== undefined) {
322
+ const merged: Record<string, unknown> = { ...(current.metadata ?? {}) };
323
+ for (const [k, v] of Object.entries(params.metadata)) {
324
+ if (v === null) delete merged[k];
325
+ else merged[k] = v;
326
+ }
327
+ newMetadata = Object.keys(merged).length ? merged : undefined;
328
+ }
329
+
330
+ const updated: Task = { ...current, status: newStatus };
331
+ if (params.subject !== undefined) updated.subject = params.subject;
332
+ if (params.description !== undefined) updated.description = params.description;
333
+ if (params.activeForm !== undefined) updated.activeForm = params.activeForm;
334
+ if (params.owner !== undefined) updated.owner = params.owner;
335
+ if (newBlockedBy.length) {
336
+ updated.blockedBy = newBlockedBy;
337
+ } else {
338
+ delete updated.blockedBy;
339
+ }
340
+ if (newMetadata === undefined) {
341
+ delete updated.metadata;
342
+ } else {
343
+ updated.metadata = newMetadata;
344
+ }
345
+
346
+ const newTasks = [...state.tasks];
347
+ newTasks[idx] = updated;
348
+ const transition =
349
+ current.status !== newStatus
350
+ ? ` (${current.status} → ${newStatus})`
351
+ : "";
352
+ return {
353
+ state: { tasks: newTasks, nextId: state.nextId },
354
+ details: {
355
+ action: "update",
356
+ params: params as Record<string, unknown>,
357
+ tasks: newTasks,
358
+ nextId: state.nextId,
359
+ },
360
+ content: [
361
+ { type: "text", text: `Updated #${updated.id}${transition}` },
362
+ ],
363
+ };
364
+ }
365
+
366
+ case "list": {
367
+ const includeDeleted = params.includeDeleted === true;
368
+ const statusFilter = params.status;
369
+ let view = state.tasks;
370
+ if (!includeDeleted) {
371
+ view = view.filter((t) => t.status !== "deleted");
372
+ }
373
+ if (statusFilter) {
374
+ view = view.filter((t) => t.status === statusFilter);
375
+ }
376
+ const text =
377
+ view.length === 0
378
+ ? "No tasks"
379
+ : view
380
+ .map((t) => {
381
+ const block = t.blockedBy?.length
382
+ ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}`
383
+ : "";
384
+ const form =
385
+ t.status === "in_progress" && t.activeForm
386
+ ? ` (${t.activeForm})`
387
+ : "";
388
+ return `[${t.status}] #${t.id} ${t.subject}${form}${block}`;
389
+ })
390
+ .join("\n");
391
+ return {
392
+ state,
393
+ details: {
394
+ action: "list",
395
+ params: params as Record<string, unknown>,
396
+ tasks: state.tasks,
397
+ nextId: state.nextId,
398
+ },
399
+ content: [{ type: "text", text }],
400
+ };
401
+ }
402
+
403
+ case "get": {
404
+ if (params.id === undefined) {
405
+ return errorResult(state, action, params, "id required for get");
406
+ }
407
+ const task = state.tasks.find((t) => t.id === params.id);
408
+ if (!task) {
409
+ return errorResult(state, action, params, `#${params.id} not found`);
410
+ }
411
+ const blocks = deriveBlocks(state.tasks).get(task.id) ?? [];
412
+ const lines = [`#${task.id} [${task.status}] ${task.subject}`];
413
+ if (task.description) lines.push(` description: ${task.description}`);
414
+ if (task.activeForm) lines.push(` activeForm: ${task.activeForm}`);
415
+ if (task.blockedBy?.length) {
416
+ lines.push(
417
+ ` blockedBy: ${task.blockedBy.map((id) => `#${id}`).join(", ")}`,
418
+ );
419
+ }
420
+ if (blocks.length) {
421
+ lines.push(` blocks: ${blocks.map((id) => `#${id}`).join(", ")}`);
422
+ }
423
+ if (task.owner) lines.push(` owner: ${task.owner}`);
424
+ return {
425
+ state,
426
+ details: {
427
+ action: "get",
428
+ params: params as Record<string, unknown>,
429
+ tasks: state.tasks,
430
+ nextId: state.nextId,
431
+ },
432
+ content: [{ type: "text", text: lines.join("\n") }],
433
+ };
434
+ }
435
+
436
+ case "delete": {
437
+ if (params.id === undefined) {
438
+ return errorResult(state, action, params, "id required for delete");
439
+ }
440
+ const idx = state.tasks.findIndex((t) => t.id === params.id);
441
+ if (idx === -1) {
442
+ return errorResult(state, action, params, `#${params.id} not found`);
443
+ }
444
+ const current = state.tasks[idx];
445
+ if (current.status === "deleted") {
446
+ return errorResult(
447
+ state,
448
+ action,
449
+ params,
450
+ `#${current.id} is already deleted`,
451
+ );
452
+ }
453
+ const updated: Task = { ...current, status: "deleted" };
454
+ const newTasks = [...state.tasks];
455
+ newTasks[idx] = updated;
456
+ return {
457
+ state: { tasks: newTasks, nextId: state.nextId },
458
+ details: {
459
+ action: "delete",
460
+ params: params as Record<string, unknown>,
461
+ tasks: newTasks,
462
+ nextId: state.nextId,
463
+ },
464
+ content: [
465
+ { type: "text", text: `Deleted #${updated.id}: ${updated.subject}` },
466
+ ],
467
+ };
468
+ }
469
+
470
+ case "clear": {
471
+ const count = state.tasks.length;
472
+ return {
473
+ state: { tasks: [], nextId: 1 },
474
+ details: {
475
+ action: "clear",
476
+ params: params as Record<string, unknown>,
477
+ tasks: [],
478
+ nextId: 1,
479
+ },
480
+ content: [{ type: "text", text: `Cleared ${count} tasks` }],
481
+ };
482
+ }
483
+ }
484
+ }
485
+
486
+ // ---------------------------------------------------------------------------
487
+ // Persistence — snapshot-based replay with type-guard
488
+ // ---------------------------------------------------------------------------
489
+
490
+ function isTaskDetails(value: unknown): value is TaskDetails {
491
+ if (!value || typeof value !== "object") return false;
492
+ const v = value as Record<string, unknown>;
493
+ return Array.isArray(v.tasks) && typeof v.nextId === "number";
494
+ }
495
+
496
+ export function reconstructTodoState(ctx: any): void {
497
+ tasks = [];
498
+ nextId = 1;
499
+ for (const entry of ctx.sessionManager.getBranch()) {
500
+ if (entry.type !== "message") continue;
501
+ const msg = entry.message;
502
+ if (msg.role !== "toolResult" || msg.toolName !== "todo") continue;
503
+ const details: unknown = msg.details;
504
+ if (!isTaskDetails(details)) continue;
505
+ tasks = details.tasks.map((t) => ({ ...t }));
506
+ nextId = details.nextId;
507
+ }
508
+ }
509
+
510
+ // ---------------------------------------------------------------------------
511
+ // Rendering helpers
512
+ // ---------------------------------------------------------------------------
513
+
514
+ function formatStatus(status: TaskStatus): string {
515
+ switch (status) {
516
+ case "in_progress": return "in progress";
517
+ case "deleted": return "deleted";
518
+ default: return status;
519
+ }
520
+ }
521
+
522
+ const STATUS_GLYPH: Record<TaskStatus, string> = {
523
+ pending: "○",
524
+ in_progress: "◐",
525
+ completed: "●",
526
+ deleted: "⊘",
527
+ };
528
+
529
+ // Mirrors todo-overlay.ts:statusGlyph palette, but uses `muted` for deleted so
530
+ // a successful delete is visually distinct from the error branch (which uses
531
+ // `error` + `✗`).
532
+ const STATUS_COLOR: Record<TaskStatus, "dim" | "warning" | "success" | "muted"> = {
533
+ pending: "dim",
534
+ in_progress: "warning",
535
+ completed: "success",
536
+ deleted: "muted",
537
+ };
538
+
539
+ const ACTION_GLYPH: Record<TaskAction, string> = {
540
+ create: "+",
541
+ update: "→",
542
+ delete: "×",
543
+ get: "›",
544
+ list: "☰",
545
+ clear: "∅",
546
+ };
547
+
548
+ function taskSubject(id: number): string | undefined {
549
+ return tasks.find((t) => t.id === id)?.subject;
550
+ }
551
+
552
+ // ---------------------------------------------------------------------------
553
+ // Tool registration
554
+ // ---------------------------------------------------------------------------
555
+
556
+ const TodoParams = Type.Object({
557
+ action: StringEnum(["create", "update", "list", "get", "delete", "clear"] as const),
558
+ subject: Type.Optional(
559
+ Type.String({ description: "Task subject line (required for create)" }),
560
+ ),
561
+ description: Type.Optional(
562
+ Type.String({ description: "Long-form task description" }),
563
+ ),
564
+ activeForm: Type.Optional(
565
+ Type.String({
566
+ description:
567
+ "Present-continuous spinner label shown while status is in_progress (e.g. 'writing tests')",
568
+ }),
569
+ ),
570
+ status: Type.Optional(
571
+ StringEnum(["pending", "in_progress", "completed", "deleted"] as const, {
572
+ description: "Target status (update) or list filter (list)",
573
+ }),
574
+ ),
575
+ blockedBy: Type.Optional(
576
+ Type.Array(Type.Number(), {
577
+ description: "Initial blockedBy ids (create only)",
578
+ }),
579
+ ),
580
+ addBlockedBy: Type.Optional(
581
+ Type.Array(Type.Number(), {
582
+ description: "Task ids to add to blockedBy (update only, additive merge)",
583
+ }),
584
+ ),
585
+ removeBlockedBy: Type.Optional(
586
+ Type.Array(Type.Number(), {
587
+ description: "Task ids to remove from blockedBy (update only, additive merge)",
588
+ }),
589
+ ),
590
+ owner: Type.Optional(
591
+ Type.String({ description: "Agent/owner assigned to this task" }),
592
+ ),
593
+ metadata: Type.Optional(
594
+ Type.Record(Type.String(), Type.Unknown(), {
595
+ description:
596
+ "Arbitrary metadata; pass null value for a key to delete that key on update",
597
+ }),
598
+ ),
599
+ id: Type.Optional(
600
+ Type.Number({
601
+ description: "Task id (required for update, get, delete)",
602
+ }),
603
+ ),
604
+ includeDeleted: Type.Optional(
605
+ Type.Boolean({
606
+ description:
607
+ "If true, list action returns deleted (tombstoned) tasks as well. Default: false.",
608
+ }),
609
+ ),
610
+ });
611
+
612
+ export function registerTodoTool(pi: ExtensionAPI): void {
613
+ pi.registerTool({
614
+ name: "todo",
615
+ label: "Todo",
616
+ description:
617
+ "Manage a task list for tracking multi-step progress. Actions: create (new task), update (change status/fields/dependencies), list (all tasks, optionally filtered by status), get (single task details), delete (tombstone), clear (reset all). Status: pending → in_progress → completed, plus deleted tombstone. Use this to plan and track multi-step work like research, design, and implementation.",
618
+ promptSnippet: "Manage a Claude-Code-style task list to track multi-step progress",
619
+ promptGuidelines: [
620
+ "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.",
621
+ "When starting any task, mark it in_progress BEFORE beginning work. Mark it completed IMMEDIATELY when done — never batch completions. Exactly one task should be in_progress at a time.",
622
+ "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.",
623
+ "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.",
624
+ "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.",
625
+ "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
626
+ "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.",
627
+ ],
628
+ parameters: TodoParams,
629
+
630
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
631
+ const result = applyTaskMutation(
632
+ { tasks, nextId },
633
+ params.action,
634
+ params as TaskMutationParams,
635
+ );
636
+ tasks = result.state.tasks;
637
+ nextId = result.state.nextId;
638
+ return {
639
+ content: result.content,
640
+ details: result.details,
641
+ };
642
+ },
643
+
644
+ renderCall(args, theme, _context) {
645
+ const glyph = ACTION_GLYPH[args.action] ?? args.action;
646
+ let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", glyph);
647
+
648
+ if (args.action === "create" && args.subject) {
649
+ text += ` ${theme.fg("dim", args.subject)}`;
650
+ } else if (
651
+ (args.action === "update" || args.action === "get" || args.action === "delete") &&
652
+ args.id !== undefined
653
+ ) {
654
+ const subject = taskSubject(args.id);
655
+ text += ` ${theme.fg("accent", subject ?? `#${args.id}`)}`;
656
+ } else if (args.action === "list" && args.status) {
657
+ text += ` ${theme.fg("muted", formatStatus(args.status))}`;
658
+ } else if (args.action === "clear") {
659
+ // nothing extra
660
+ }
661
+ return new Text(text, 0, 0);
662
+ },
663
+
664
+ renderResult(result, _opts, theme, _context) {
665
+ if (result.isError) {
666
+ return new Text(theme.fg("error", "✗"), 0, 0);
667
+ }
668
+ const details = result.details as TaskDetails | undefined;
669
+ // Only create/update/delete advertise a status; list/get/clear render a
670
+ // plain ✓. This prevents list from rendering the last task's status as
671
+ // if it were the operation's result.
672
+ let status: TaskStatus | undefined;
673
+ if (details) {
674
+ const params = details.params as TaskMutationParams;
675
+ switch (details.action) {
676
+ case "create":
677
+ // New task is the last element of details.tasks.
678
+ status = details.tasks[details.tasks.length - 1]?.status;
679
+ break;
680
+ case "update":
681
+ status =
682
+ params.status ??
683
+ details.tasks.find((t) => t.id === params.id)?.status;
684
+ break;
685
+ case "delete":
686
+ status = details.tasks.find((t) => t.id === params.id)?.status;
687
+ break;
688
+ case "list":
689
+ case "get":
690
+ case "clear":
691
+ break;
692
+ }
693
+ }
694
+ if (status) {
695
+ return new Text(
696
+ theme.fg(STATUS_COLOR[status], `${STATUS_GLYPH[status]} ${formatStatus(status)}`),
697
+ 0,
698
+ 0,
699
+ );
700
+ }
701
+ return new Text(theme.fg("success", "✓"), 0, 0);
702
+ },
703
+ });
704
+ }
705
+
706
+ // ---------------------------------------------------------------------------
707
+ // /todos slash command
708
+ // ---------------------------------------------------------------------------
709
+
710
+ export function registerTodosCommand(pi: ExtensionAPI): void {
711
+ pi.registerCommand("todos", {
712
+ description: "Show all todos on the current branch, grouped by status",
713
+ handler: async (_args, ctx) => {
714
+ if (!ctx.hasUI) {
715
+ ctx.ui.notify("/todos requires interactive mode", "error");
716
+ return;
717
+ }
718
+ const visible = tasks.filter((t) => t.status !== "deleted");
719
+ if (visible.length === 0) {
720
+ ctx.ui.notify("No todos yet. Ask the agent to add some!", "info");
721
+ return;
722
+ }
723
+
724
+ const pending = visible.filter((t) => t.status === "pending");
725
+ const inProgress = visible.filter((t) => t.status === "in_progress");
726
+ const completed = visible.filter((t) => t.status === "completed");
727
+
728
+ const header: string[] = [];
729
+ if (completed.length > 0) {
730
+ header.push(`${completed.length}/${visible.length} completed`);
731
+ }
732
+ if (inProgress.length > 0) {
733
+ header.push(`${inProgress.length} ${formatStatus("in_progress")}`);
734
+ }
735
+ if (pending.length > 0) {
736
+ header.push(`${pending.length} pending`);
737
+ }
738
+
739
+ const lines: string[] = [header.join(" · ")];
740
+
741
+ const renderTask = (t: Task, glyph: string): string => {
742
+ const form =
743
+ t.status === "in_progress" && t.activeForm
744
+ ? ` (${t.activeForm})`
745
+ : "";
746
+ const block = t.blockedBy?.length
747
+ ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}`
748
+ : "";
749
+ return ` ${glyph} #${t.id} ${t.subject}${form}${block}`;
750
+ };
751
+
752
+ if (pending.length > 0) {
753
+ lines.push("── Pending ──");
754
+ for (const t of pending) lines.push(renderTask(t, "○"));
755
+ }
756
+ if (inProgress.length > 0) {
757
+ lines.push("── In Progress ──");
758
+ for (const t of inProgress) lines.push(renderTask(t, "◐"));
759
+ }
760
+ if (completed.length > 0) {
761
+ lines.push("── Completed ──");
762
+ for (const t of completed) lines.push(renderTask(t, "✓"));
763
+ }
764
+
765
+ ctx.ui.notify(lines.join("\n"), "info");
766
+ },
767
+ });
768
+ }