@riverai7z/pi-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/DESIGN.md ADDED
@@ -0,0 +1,79 @@
1
+ # Design
2
+
3
+ ## Scope
4
+
5
+ This release implements Claude Code's structured task-list domain:
6
+
7
+ - `TaskCreate`
8
+ - `TaskGet`
9
+ - `TaskList`
10
+ - `TaskUpdate`
11
+
12
+ Claude Code's `TaskOutput` and `TaskStop` operate on a different runtime registry containing background shells and subagents. Pi does not expose an equivalent shared registry to extensions. Those names remain reserved until a background-task producer and lifecycle contract are implemented; fake placeholder tools are deliberately avoided.
13
+
14
+ ## State model
15
+
16
+ ```text
17
+ TaskState
18
+ ├── nextId: number
19
+ └── tasks[]
20
+ ├── id, subject, description, activeForm?
21
+ ├── status: pending | in_progress | completed | deleted
22
+ ├── owner?
23
+ ├── blockedBy[]
24
+ └── metadata?
25
+ ```
26
+
27
+ `blocks` is derived as the inverse of `blockedBy`, preventing the two directions from drifting. `deleted` is a tombstone rather than physical removal, preserving monotonic IDs and historical dependency references.
28
+
29
+ Allowed status transitions:
30
+
31
+ ```text
32
+ pending ───────► in_progress ───────► completed ───────► deleted
33
+ ▲ ▲ │
34
+ │ └────────────────────┤
35
+ └───────────────────────────────────────┘
36
+
37
+ in_progress may return to pending when work is released. Completed work may be reopened as pending or in_progress when verification or new requirements reveal more work. Deleted is terminal.
38
+ ```
39
+
40
+ ## Persistence and branch semantics
41
+
42
+ No project task file is written. Every tool result stores a complete snapshot in `details`:
43
+
44
+ ```ts
45
+ {
46
+ action: "create" | "get" | "list" | "update",
47
+ tasks: Task[],
48
+ nextId: number,
49
+ error?: string
50
+ }
51
+ ```
52
+
53
+ On `session_start`, `session_compact`, and `session_tree`, the extension walks the active session branch and restores the latest valid snapshot from any of the four tools. This gives `/reload`, compaction, forks, and tree navigation the same state semantics as the conversation branch.
54
+
55
+ Live state is partitioned by Pi session ID. Only the foreground UI session owns the overlay, preventing child or detached sessions from replacing its widget.
56
+
57
+ ## Dependency invariants
58
+
59
+ - Dependencies must reference existing, non-deleted tasks.
60
+ - A task cannot depend on itself.
61
+ - Updates are applied to a candidate graph and rejected if a cycle appears.
62
+ - Completing or deleting a blocker resolves it for availability and display, while retaining the historical edge.
63
+
64
+ ## UI
65
+
66
+ The overlay is mounted above the editor only when visible tasks exist. When space is constrained it prioritizes recently completed work, `in_progress`, unblocked `pending`, blocked `pending`, then older completed work. Its height responds to the terminal, Pi's tool expansion mode reveals the full list, and overflow is summarized by status. Completed rows remain visible for their turn and are hidden from the next turn's overlay without deleting task history. `/tasks` provides the complete grouped view. `Ctrl+Shift+T` toggles the overlay's collapsed state. The active task's `activeForm` (falling back to its subject) drives Pi's working message.
67
+
68
+ ## Future background-task phase
69
+
70
+ A real `TaskOutput`/`TaskStop` phase should add:
71
+
72
+ 1. A producer tool for background shell or agent tasks.
73
+ 2. A process registry scoped to a Pi session.
74
+ 3. Abort-safe process-group termination.
75
+ 4. Output files with bounded reads and truncation.
76
+ 5. Completion notifications and shutdown cleanup.
77
+ 6. `TaskOutput` polling (`block`, `timeout`) and `TaskStop` validation matching Claude Code semantics.
78
+
79
+ That runtime registry should remain separate from the structured task list even if both use task-like IDs.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 River-Walras
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # pi-todo
2
+
3
+ Claude Code-style structured task management for Pi.
4
+
5
+ ## Features
6
+
7
+ - Four task-list tools with Claude Code-compatible responsibilities:
8
+ - `TaskCreate`
9
+ - `TaskGet`
10
+ - `TaskList`
11
+ - `TaskUpdate`
12
+ - Status workflow: `pending` → `in_progress` → `completed`, plus terminal `deleted` tombstones.
13
+ - Owners, metadata, `blocks`/`blockedBy` dependencies, cycle rejection, and unresolved-blocker filtering.
14
+ - Session-local state reconstructed from tool-result `details`, so `/reload`, compaction, `/tree`, and forks preserve branch semantics without project files.
15
+ - Live responsive task overlay above the editor, with blocked work deprioritized and categorized overflow.
16
+ - `activeForm` drives Pi's working message while a task is in progress.
17
+ - Completed rows are struck through, remain visible for the current turn, then leave the overlay without deleting history.
18
+ - `/tasks` command for the complete grouped list.
19
+ - `Ctrl+Shift+T` collapses or expands the overlay; Pi's tool expansion mode shows all tasks.
20
+
21
+ `TaskOutput` and `TaskStop` belong to Claude Code's separate background-process task system. They are intentionally reserved until this package gains a Pi background-task producer; registering non-functional placeholders would mislead the model.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pi install npm:@riverai7z/pi-todo
27
+ ```
28
+
29
+ From this directory:
30
+
31
+ ```bash
32
+ pi install .
33
+ ```
34
+
35
+ For development:
36
+
37
+ ```bash
38
+ pi -e ./index.ts
39
+ ```
40
+
41
+ ## Persistence model
42
+
43
+ Every tool result contains a complete task-state snapshot in `details`. On session start, compaction, or tree navigation, the extension walks the active branch and restores the latest valid snapshot. Each Pi session has an isolated in-memory state slot, while the foreground session owns the overlay.
44
+
45
+ ## Design references
46
+
47
+ - Claude Code `TaskCreate`, `TaskGet`, `TaskList`, and `TaskUpdate`
48
+ - Pi's stateful todo extension example
49
+ - `rpiv-mono/packages/rpiv-todo` session replay and overlay patterns
package/index.ts ADDED
@@ -0,0 +1,462 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI, ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
3
+ import { Text } from "@earendil-works/pi-tui";
4
+ import { type Static, Type } from "typebox";
5
+ import { formatTaskLine, TaskOverlay } from "./overlay.js";
6
+ import {
7
+ clearForegroundSession,
8
+ createTask,
9
+ deriveBlocks,
10
+ evictSession,
11
+ getForegroundSession,
12
+ getForegroundState,
13
+ getState,
14
+ getTask,
15
+ listTasks,
16
+ replayState,
17
+ replaceState,
18
+ sessionId,
19
+ setForegroundSession,
20
+ snapshot,
21
+ unresolvedBlockers,
22
+ updateTask,
23
+ type Task,
24
+ type TaskSnapshot,
25
+ type TaskStatus,
26
+ } from "./state.js";
27
+
28
+ const TASK_TOOL_NAMES = new Set(["TaskCreate", "TaskGet", "TaskList", "TaskUpdate"]);
29
+ const TaskCreateSchema = Type.Object({
30
+ subject: Type.String({ minLength: 1, description: "A brief title for the task" }),
31
+ description: Type.String({ minLength: 1, description: "What needs to be done" }),
32
+ activeForm: Type.Optional(
33
+ Type.String({ description: "Present continuous form shown in spinner when in_progress (e.g., \"Running tests\")" }),
34
+ ),
35
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Arbitrary metadata to attach to the task" })),
36
+ });
37
+
38
+ const TaskGetSchema = Type.Object({
39
+ taskId: Type.String({ description: "The ID of the task to retrieve" }),
40
+ });
41
+
42
+ const TaskListSchema = Type.Object({});
43
+
44
+ const TaskUpdateSchema = Type.Object({
45
+ taskId: Type.String({ description: "The ID of the task to update" }),
46
+ subject: Type.Optional(Type.String({ description: "New subject for the task" })),
47
+ description: Type.Optional(Type.String({ description: "New description for the task" })),
48
+ activeForm: Type.Optional(
49
+ Type.String({ description: "Present continuous form shown in spinner when in_progress (e.g., \"Running tests\")" }),
50
+ ),
51
+ status: Type.Optional(
52
+ StringEnum(["pending", "in_progress", "completed", "deleted"] as const, {
53
+ description: "New status for the task",
54
+ }),
55
+ ),
56
+ addBlocks: Type.Optional(Type.Array(Type.String(), { description: "Task IDs that this task blocks" })),
57
+ addBlockedBy: Type.Optional(Type.Array(Type.String(), { description: "Task IDs that block this task" })),
58
+ owner: Type.Optional(Type.String({ description: "New owner for the task" })),
59
+ metadata: Type.Optional(
60
+ Type.Record(Type.String(), Type.Unknown(), {
61
+ description: "Metadata keys to merge into the task. Set a key to null to delete it.",
62
+ }),
63
+ ),
64
+ });
65
+
66
+ type TaskUpdateParams = Static<typeof TaskUpdateSchema>;
67
+
68
+ const TASK_CREATE_DESCRIPTION = `Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
69
+ It also helps the user understand the progress of the task and overall progress of their requests.
70
+
71
+ ## When to Use This Tool
72
+
73
+ Use this tool proactively in these scenarios:
74
+
75
+ - Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
76
+ - Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
77
+ - Plan mode - When using plan mode, create a task list to track the work
78
+ - User explicitly requests todo list - When the user directly asks you to use the todo list
79
+ - User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
80
+ - After receiving new instructions - Immediately capture user requirements as tasks
81
+ - When you start working on a task - Mark it as in_progress BEFORE beginning work
82
+ - After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
83
+
84
+ ## When NOT to Use This Tool
85
+
86
+ Skip using this tool when:
87
+ - There is only a single, straightforward task
88
+ - The task is trivial and tracking it provides no organizational benefit
89
+ - The task can be completed in less than 3 trivial steps
90
+ - The task is purely conversational or informational
91
+
92
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
93
+
94
+ ## Task Fields
95
+
96
+ - **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")
97
+ - **description**: What needs to be done
98
+ - **activeForm** (optional): Present continuous form shown in the spinner when the task is in_progress (e.g., "Fixing authentication bug"). If omitted, the spinner shows the subject instead.
99
+
100
+ All tasks are created with status \`pending\`.
101
+
102
+ ## Tips
103
+
104
+ - Create tasks with clear, specific subjects that describe the outcome
105
+ - After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed
106
+ - Check TaskList first to avoid creating duplicate tasks`;
107
+
108
+ const TASK_GET_DESCRIPTION = `Use this tool to retrieve a task by its ID from the task list.
109
+
110
+ ## When to Use This Tool
111
+
112
+ - When you need the full description and context before starting work on a task
113
+ - To understand task dependencies (what it blocks, what blocks it)
114
+ - After being assigned a task, to get complete requirements
115
+
116
+ ## Output
117
+
118
+ Returns full task details:
119
+ - **subject**: Task title
120
+ - **description**: Detailed requirements and context
121
+ - **status**: 'pending', 'in_progress', or 'completed'
122
+ - **blocks**: Tasks waiting on this one to complete
123
+ - **blockedBy**: Tasks that must complete before this one can start
124
+
125
+ ## Tips
126
+
127
+ - After fetching a task, verify its blockedBy list is empty before beginning work.
128
+ - Use TaskList to see all tasks in summary form.`;
129
+
130
+ const TASK_LIST_DESCRIPTION = `Use this tool to list all tasks in the task list.
131
+
132
+ ## When to Use This Tool
133
+
134
+ - To see what tasks are available to work on (status: 'pending', no owner, not blocked)
135
+ - To check overall progress on the project
136
+ - To find tasks that are blocked and need dependencies resolved
137
+ - After completing a task, to check for newly unblocked work or claim the next available task
138
+ - **Prefer working on tasks in ID order** (lowest ID first) when multiple tasks are available, as earlier tasks often set up context for later ones
139
+
140
+ ## Output
141
+
142
+ Returns a summary of each task:
143
+ - **id**: Task identifier (use with TaskGet, TaskUpdate)
144
+ - **subject**: Brief description of the task
145
+ - **status**: 'pending', 'in_progress', or 'completed'
146
+ - **owner**: Agent ID if assigned, empty if available
147
+ - **blockedBy**: List of open task IDs that must be resolved first (tasks with blockedBy cannot be claimed until dependencies resolve)
148
+
149
+ Use TaskGet with a specific task ID to view full details including description and comments.`;
150
+
151
+ const TASK_UPDATE_DESCRIPTION = `Use this tool to update a task in the task list.
152
+
153
+ ## When to Use This Tool
154
+
155
+ **Mark tasks as resolved:**
156
+ - When you have completed the work described in a task
157
+ - When a task is no longer needed or has been superseded
158
+ - IMPORTANT: Always mark your assigned tasks as resolved when you finish them
159
+ - After resolving, call TaskList to find your next task
160
+
161
+ - ONLY mark a task as completed when you have FULLY accomplished it
162
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
163
+ - When blocked, create a new task describing what needs to be resolved
164
+ - Never mark a task as completed if:
165
+ - Tests are failing
166
+ - Implementation is partial
167
+ - You encountered unresolved errors
168
+ - You couldn't find necessary files or dependencies
169
+
170
+ **Delete tasks:**
171
+ - When a task is no longer relevant or was created in error
172
+ - Setting status to \`deleted\` hides the task as a terminal tombstone in this Pi extension
173
+
174
+ **Update task details:**
175
+ - When requirements change or become clearer
176
+ - When establishing dependencies between tasks
177
+
178
+ ## Fields You Can Update
179
+
180
+ - **status**: The task status (see Status Workflow below)
181
+ - **subject**: Change the task title (imperative form, e.g., "Run tests")
182
+ - **description**: Change the task description
183
+ - **activeForm**: Present continuous form shown in spinner when in_progress (e.g., "Running tests")
184
+ - **owner**: Change the task owner (agent name)
185
+ - **metadata**: Merge metadata keys into the task (set a key to null to delete it)
186
+ - **addBlocks**: Mark tasks that cannot start until this one completes
187
+ - **addBlockedBy**: Mark tasks that must complete before this one can start
188
+
189
+ ## Status Workflow
190
+
191
+ Status progresses: \`pending\` → \`in_progress\` → \`completed\`
192
+
193
+ Use \`deleted\` to hide a task as a terminal tombstone.
194
+
195
+ ## Staleness
196
+
197
+ Make sure to read a task's latest state using \`TaskGet\` before updating it.
198
+
199
+ ## Examples
200
+
201
+ Mark task as in progress when starting work:
202
+ \`\`\`json
203
+ {"taskId": "1", "status": "in_progress"}
204
+ \`\`\`
205
+
206
+ Mark task as completed after finishing work:
207
+ \`\`\`json
208
+ {"taskId": "1", "status": "completed"}
209
+ \`\`\`
210
+
211
+ Delete a task:
212
+ \`\`\`json
213
+ {"taskId": "1", "status": "deleted"}
214
+ \`\`\`
215
+
216
+ Claim a task by setting owner:
217
+ \`\`\`json
218
+ {"taskId": "1", "owner": "my-name"}
219
+ \`\`\`
220
+
221
+ Set up task dependencies:
222
+ \`\`\`json
223
+ {"taskId": "2", "addBlockedBy": ["1"]}
224
+ \`\`\``;
225
+
226
+ function textResult(text: string, details: TaskSnapshot) {
227
+ return { content: [{ type: "text" as const, text }], details };
228
+ }
229
+
230
+ function renderHeader(label: string, suffix: string, theme: Theme): Text {
231
+ return new Text(`${theme.fg("toolTitle", theme.bold(label))}${suffix ? ` ${theme.fg("muted", suffix)}` : ""}`, 0, 0);
232
+ }
233
+
234
+ function renderResult(result: { content: Array<{ type: string; text?: string }>; details?: unknown }, theme: Theme): Text {
235
+ const details = result.details as TaskSnapshot | undefined;
236
+ const raw = result.content.find((part) => part.type === "text")?.text ?? "";
237
+ return new Text(details?.error ? theme.fg("error", raw) : theme.fg("muted", raw), 0, 0);
238
+ }
239
+
240
+ function fullTaskText(task: Task, tasks: readonly Task[]): string {
241
+ const lines = [
242
+ `Task #${task.id}: ${task.subject}`,
243
+ `Status: ${task.status}`,
244
+ `Description: ${task.description}`,
245
+ ];
246
+ if (task.activeForm) lines.push(`Active form: ${task.activeForm}`);
247
+ if (task.owner) lines.push(`Owner: ${task.owner}`);
248
+ if (task.blockedBy.length) lines.push(`Blocked by: ${task.blockedBy.map((id) => `#${id}`).join(", ")}`);
249
+ const blocks = deriveBlocks(tasks, task.id);
250
+ if (blocks.length) lines.push(`Blocks: ${blocks.map((id) => `#${id}`).join(", ")}`);
251
+ if (task.metadata && Object.keys(task.metadata).length) lines.push(`Metadata: ${JSON.stringify(task.metadata)}`);
252
+ return lines.join("\n");
253
+ }
254
+
255
+ function hasUpdate(params: TaskUpdateParams): boolean {
256
+ return (
257
+ params.subject !== undefined ||
258
+ params.description !== undefined ||
259
+ params.activeForm !== undefined ||
260
+ params.status !== undefined ||
261
+ params.owner !== undefined ||
262
+ params.metadata !== undefined ||
263
+ (params.addBlocks?.length ?? 0) > 0 ||
264
+ (params.addBlockedBy?.length ?? 0) > 0
265
+ );
266
+ }
267
+
268
+ export default function (pi: ExtensionAPI): void {
269
+ const overlay = new TaskOverlay();
270
+ let foregroundUi: ExtensionUIContext | undefined;
271
+
272
+ const syncWorkingMessage = (): void => {
273
+ if (!foregroundUi) return;
274
+ const activeTask = getForegroundState().tasks.find((task) => task.status === "in_progress");
275
+ const message = activeTask ? activeTask.activeForm?.trim() || activeTask.subject : undefined;
276
+ foregroundUi.setWorkingMessage(message);
277
+ };
278
+
279
+ pi.registerTool({
280
+ name: "TaskCreate",
281
+ label: "TaskCreate",
282
+ description: TASK_CREATE_DESCRIPTION,
283
+ promptSnippet: "Create a task in the structured task list",
284
+ parameters: TaskCreateSchema,
285
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
286
+ const id = sessionId(ctx);
287
+ if (!params.subject.trim() || !params.description.trim()) {
288
+ throw new Error("TaskCreate requires non-empty subject and description");
289
+ }
290
+ const { state, task } = createTask(id, params);
291
+ return textResult(`Task #${task.id} created successfully: ${task.subject}`, snapshot("create", state));
292
+ },
293
+ renderCall(args, theme) {
294
+ return renderHeader("TaskCreate", args.subject ? `“${args.subject}”` : "", theme);
295
+ },
296
+ renderResult(result, _options, theme) {
297
+ return renderResult(result, theme);
298
+ },
299
+ });
300
+
301
+ pi.registerTool({
302
+ name: "TaskGet",
303
+ label: "TaskGet",
304
+ description: TASK_GET_DESCRIPTION,
305
+ promptSnippet: "Retrieve a task by ID",
306
+ parameters: TaskGetSchema,
307
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
308
+ const id = sessionId(ctx);
309
+ const state = getState(id);
310
+ const task = getTask(id, params.taskId);
311
+ if (!task) return textResult("Task not found", snapshot("get", state, "Task not found"));
312
+ return textResult(fullTaskText(task, state.tasks), snapshot("get", state));
313
+ },
314
+ renderCall(args, theme) {
315
+ return renderHeader("TaskGet", `#${args.taskId}`, theme);
316
+ },
317
+ renderResult(result, _options, theme) {
318
+ return renderResult(result, theme);
319
+ },
320
+ });
321
+
322
+ pi.registerTool({
323
+ name: "TaskList",
324
+ label: "TaskList",
325
+ description: TASK_LIST_DESCRIPTION,
326
+ promptSnippet: "List all structured tasks",
327
+ parameters: TaskListSchema,
328
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
329
+ const id = sessionId(ctx);
330
+ const state = getState(id);
331
+ const tasks = listTasks(id);
332
+ const content = tasks.length
333
+ ? tasks
334
+ .map((task) => {
335
+ const owner = task.owner ? ` (${task.owner})` : "";
336
+ const blockedBy = unresolvedBlockers(task, state.tasks);
337
+ const blocked = blockedBy.length ? ` [blocked by ${blockedBy.map((value) => `#${value}`).join(", ")}]` : "";
338
+ return `#${task.id} [${task.status}] ${task.subject}${owner}${blocked}`;
339
+ })
340
+ .join("\n")
341
+ : "No tasks found";
342
+ return textResult(content, snapshot("list", state));
343
+ },
344
+ renderCall(_args, theme) {
345
+ return renderHeader("TaskList", "", theme);
346
+ },
347
+ renderResult(result, _options, theme) {
348
+ return renderResult(result, theme);
349
+ },
350
+ });
351
+
352
+ pi.registerTool({
353
+ name: "TaskUpdate",
354
+ label: "TaskUpdate",
355
+ description: TASK_UPDATE_DESCRIPTION,
356
+ promptSnippet: "Update a task or its dependencies",
357
+ parameters: TaskUpdateSchema,
358
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
359
+ const id = sessionId(ctx);
360
+ if (!hasUpdate(params)) {
361
+ const state = getState(id);
362
+ const error = "TaskUpdate requires at least one field to change";
363
+ return textResult(error, snapshot("update", state, error));
364
+ }
365
+ const result = updateTask(id, params.taskId, params);
366
+ if (result.error) return textResult(result.error, snapshot("update", result.state, result.error));
367
+ const message = result.updatedFields.length
368
+ ? `Updated task #${params.taskId}: ${result.updatedFields.join(", ")}`
369
+ : `No change to task #${params.taskId}`;
370
+ return textResult(message, snapshot("update", result.state));
371
+ },
372
+ renderCall(args, theme) {
373
+ const status = args.status ? ` → ${args.status}` : "";
374
+ return renderHeader("TaskUpdate", `#${args.taskId}${status}`, theme);
375
+ },
376
+ renderResult(result, _options, theme) {
377
+ return renderResult(result, theme);
378
+ },
379
+ });
380
+
381
+ pi.registerCommand("tasks", {
382
+ description: "Show the current session's task list",
383
+ handler: async (_args, ctx) => {
384
+ const state = getState(sessionId(ctx));
385
+ const tasks = state.tasks.filter((task) => task.status !== "deleted");
386
+ if (tasks.length === 0) {
387
+ ctx.ui.notify("No tasks found", "info");
388
+ return;
389
+ }
390
+ const order: Exclude<TaskStatus, "deleted">[] = ["in_progress", "pending", "completed"];
391
+ const labels: Record<Exclude<TaskStatus, "deleted">, string> = {
392
+ in_progress: "In Progress",
393
+ pending: "Pending",
394
+ completed: "Completed",
395
+ };
396
+ const lines: string[] = [];
397
+ for (const status of order) {
398
+ const group = tasks.filter((task) => task.status === status);
399
+ if (!group.length) continue;
400
+ lines.push(`── ${labels[status]} ──`);
401
+ for (const task of group) lines.push(` ${formatTaskLine(task, state.tasks, ctx.ui.theme)}`);
402
+ }
403
+ ctx.ui.notify(lines.join("\n"), "info");
404
+ },
405
+ });
406
+
407
+ pi.registerShortcut("ctrl+shift+t", {
408
+ description: "Collapse or expand the task overlay",
409
+ handler: (ctx) => {
410
+ if (ctx.hasUI) overlay.toggle();
411
+ },
412
+ });
413
+
414
+ const replayAndRefresh = (ctx: Parameters<typeof sessionId>[0] & Parameters<typeof replayState>[0]): void => {
415
+ const id = sessionId(ctx);
416
+ replaceState(id, replayState(ctx));
417
+ if (id === getForegroundSession()) {
418
+ overlay.resetCompletedDisplayState();
419
+ overlay.update();
420
+ syncWorkingMessage();
421
+ }
422
+ };
423
+
424
+ pi.on("session_start", async (_event, ctx) => {
425
+ const id = sessionId(ctx);
426
+ replaceState(id, replayState(ctx));
427
+ if (!ctx.hasUI) return;
428
+ if (!getForegroundSession()) setForegroundSession(id);
429
+ if (id === getForegroundSession()) {
430
+ foregroundUi = ctx.ui;
431
+ overlay.bind(ctx.ui);
432
+ syncWorkingMessage();
433
+ }
434
+ });
435
+
436
+ pi.on("session_compact", async (_event, ctx) => replayAndRefresh(ctx));
437
+ pi.on("session_tree", async (_event, ctx) => replayAndRefresh(ctx));
438
+
439
+ pi.on("tool_execution_end", async (event) => {
440
+ if (!TASK_TOOL_NAMES.has(event.toolName) || event.isError) return;
441
+ overlay.update();
442
+ syncWorkingMessage();
443
+ });
444
+
445
+ pi.on("agent_start", async () => {
446
+ overlay.hideCompletedTasksFromPreviousTurn();
447
+ });
448
+
449
+ pi.on("session_shutdown", async (_event, ctx) => {
450
+ const id = sessionId(ctx);
451
+ evictSession(id);
452
+ if (id === getForegroundSession()) {
453
+ try {
454
+ foregroundUi?.setWorkingMessage();
455
+ overlay.dispose();
456
+ } finally {
457
+ foregroundUi = undefined;
458
+ clearForegroundSession();
459
+ }
460
+ }
461
+ });
462
+ }
package/overlay.ts ADDED
@@ -0,0 +1,234 @@
1
+ import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, type TUI } from "@earendil-works/pi-tui";
3
+ import { getForegroundState, unresolvedBlockers, type Task } from "./state.js";
4
+
5
+ const WIDGET_KEY = "pi-todo";
6
+ const MAX_LINES = 12;
7
+ const RESERVED_TERMINAL_ROWS = 12;
8
+
9
+ function sanitizeTerminalText(text: string): string {
10
+ return text
11
+ .replace(/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]/g, "")
12
+ .replace(/(?:\u001b\]|\u009d)[^\u0007\u009c\u001b]*(?:\u0007|\u009c|\u001b\\)?/g, "")
13
+ .replace(/\u001b./g, "")
14
+ .replace(/[\u2028\u2029]/g, " ")
15
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, (character) =>
16
+ character === "\n" || character === "\r" || character === "\t" ? " " : "",
17
+ )
18
+ .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "");
19
+ }
20
+
21
+ function statusGlyph(task: Task): string {
22
+ switch (task.status) {
23
+ case "pending":
24
+ return "○";
25
+ case "in_progress":
26
+ return "◐";
27
+ case "completed":
28
+ return "✓";
29
+ case "deleted":
30
+ return "×";
31
+ }
32
+ }
33
+
34
+ function statusColor(task: Task): "dim" | "accent" | "success" {
35
+ if (task.status === "in_progress") return "accent";
36
+ if (task.status === "completed") return "success";
37
+ return "dim";
38
+ }
39
+
40
+ export function formatTaskLine(task: Task, tasks: readonly Task[], theme: Theme, showId = true): string {
41
+ const blockers = unresolvedBlockers(task, tasks);
42
+ const id = showId ? `${theme.fg("accent", `#${task.id}`)} ` : "";
43
+ const owner = task.owner ? theme.fg("dim", ` @${sanitizeTerminalText(task.owner)}`) : "";
44
+ const blocked = blockers.length
45
+ ? theme.fg("warning", ` [blocked by ${blockers.map((value) => `#${value}`).join(", ")}]`)
46
+ : "";
47
+ const rawSubject = theme.fg(task.status === "completed" ? "dim" : "text", sanitizeTerminalText(task.subject));
48
+ const subject = task.status === "completed" ? theme.strikethrough(rawSubject) : rawSubject;
49
+ const activeForm =
50
+ task.status === "in_progress" && task.activeForm
51
+ ? theme.fg("dim", ` (${sanitizeTerminalText(task.activeForm)})`)
52
+ : "";
53
+ return `${theme.fg(statusColor(task), statusGlyph(task))} ${id}${subject}${activeForm}${owner}${blocked}`;
54
+ }
55
+
56
+ function byId(a: Task, b: Task): number {
57
+ return Number(a.id) - Number(b.id);
58
+ }
59
+
60
+ export class TaskOverlay {
61
+ private ui?: ExtensionUIContext;
62
+ private tui?: TUI;
63
+ private registered = false;
64
+ private collapsed = false;
65
+ private completedPendingHide = new Set<string>();
66
+ private hiddenCompleted = new Set<string>();
67
+ private recentCompleted = new Set<string>();
68
+ private previousStatuses = new Map<string, Task["status"]>();
69
+ private lastNextId?: number;
70
+
71
+ bind(ui: ExtensionUIContext): void {
72
+ if (this.ui !== ui) {
73
+ this.dispose();
74
+ this.ui = ui;
75
+ }
76
+ this.update();
77
+ }
78
+
79
+ update(): void {
80
+ if (!this.ui) return;
81
+ const visible = this.reconcileVisibleTasks();
82
+ if (visible.length === 0) {
83
+ if (this.registered) this.ui.setWidget(WIDGET_KEY, undefined);
84
+ this.registered = false;
85
+ this.tui = undefined;
86
+ return;
87
+ }
88
+
89
+ if (!this.registered) {
90
+ this.ui.setWidget(
91
+ WIDGET_KEY,
92
+ (tui, theme) => {
93
+ this.tui = tui;
94
+ return {
95
+ render: (width: number) => this.render(this.ui?.theme ?? theme, width),
96
+ invalidate: () => {},
97
+ };
98
+ },
99
+ { placement: "aboveEditor" },
100
+ );
101
+ this.registered = true;
102
+ } else {
103
+ this.tui?.requestRender();
104
+ }
105
+ }
106
+
107
+ toggle(): void {
108
+ if (!this.registered) return;
109
+ this.collapsed = !this.collapsed;
110
+ this.tui?.requestRender(true);
111
+ }
112
+
113
+ resetCompletedDisplayState(): void {
114
+ this.completedPendingHide.clear();
115
+ this.hiddenCompleted.clear();
116
+ this.recentCompleted.clear();
117
+ this.previousStatuses.clear();
118
+ this.lastNextId = undefined;
119
+ }
120
+
121
+ hideCompletedTasksFromPreviousTurn(): void {
122
+ if (this.completedPendingHide.size === 0) return;
123
+ for (const id of this.completedPendingHide) {
124
+ this.hiddenCompleted.add(id);
125
+ this.recentCompleted.delete(id);
126
+ }
127
+ this.completedPendingHide.clear();
128
+ this.update();
129
+ }
130
+
131
+ dispose(): void {
132
+ if (this.ui && this.registered) this.ui.setWidget(WIDGET_KEY, undefined);
133
+ this.ui = undefined;
134
+ this.tui = undefined;
135
+ this.registered = false;
136
+ this.collapsed = false;
137
+ this.resetCompletedDisplayState();
138
+ }
139
+
140
+ private reconcileVisibleTasks(): Task[] {
141
+ const state = getForegroundState();
142
+ if (this.lastNextId !== undefined && state.nextId < this.lastNextId) this.resetCompletedDisplayState();
143
+ this.lastNextId = state.nextId;
144
+
145
+ const currentIds = new Set(state.tasks.map((task) => task.id));
146
+ for (const task of state.tasks) {
147
+ const previous = this.previousStatuses.get(task.id);
148
+ if (task.status === "completed" && previous !== undefined && previous !== "completed") {
149
+ this.recentCompleted.add(task.id);
150
+ this.completedPendingHide.add(task.id);
151
+ }
152
+ if (task.status !== "completed") {
153
+ this.completedPendingHide.delete(task.id);
154
+ this.hiddenCompleted.delete(task.id);
155
+ this.recentCompleted.delete(task.id);
156
+ }
157
+ this.previousStatuses.set(task.id, task.status);
158
+ }
159
+ for (const id of this.previousStatuses.keys()) {
160
+ if (!currentIds.has(id)) this.previousStatuses.delete(id);
161
+ }
162
+
163
+ return state.tasks.filter((task) => task.status !== "deleted" && !this.hiddenCompleted.has(task.id));
164
+ }
165
+
166
+ private prioritized(tasks: Task[]): Task[] {
167
+ const recentCompleted = tasks.filter((task) => this.recentCompleted.has(task.id)).sort(byId);
168
+ const inProgress = tasks.filter((task) => task.status === "in_progress").sort(byId);
169
+ const pending = tasks
170
+ .filter((task) => task.status === "pending")
171
+ .sort((a, b) => {
172
+ const aBlocked = unresolvedBlockers(a, tasks).length > 0;
173
+ const bBlocked = unresolvedBlockers(b, tasks).length > 0;
174
+ return Number(aBlocked) - Number(bBlocked) || byId(a, b);
175
+ });
176
+ const olderCompleted = tasks
177
+ .filter((task) => task.status === "completed" && !this.recentCompleted.has(task.id))
178
+ .sort(byId);
179
+ return [...recentCompleted, ...inProgress, ...pending, ...olderCompleted];
180
+ }
181
+
182
+ private contentLineBudget(): number {
183
+ const rows = this.tui?.terminal.rows;
184
+ if (!rows) return MAX_LINES;
185
+ return Math.min(MAX_LINES, Math.max(3, rows - RESERVED_TERMINAL_ROWS));
186
+ }
187
+
188
+ private render(theme: Theme, width: number): string[] {
189
+ const tasks = this.reconcileVisibleTasks();
190
+ if (tasks.length === 0) return [];
191
+
192
+ const completed = tasks.filter((task) => task.status === "completed").length;
193
+ const active = tasks.some((task) => task.status === "pending" || task.status === "in_progress");
194
+ const heading = `${theme.fg(active ? "accent" : "dim", active ? "●" : "○")} ${theme.fg(
195
+ active ? "accent" : "dim",
196
+ `Tasks (${completed}/${tasks.length})`,
197
+ )}`;
198
+ const truncate = (line: string) => truncateToWidth(line, width, "…");
199
+ if (this.collapsed) return [truncate(heading), truncate(theme.fg("dim", "└─ ctrl+shift+t to expand")), ""];
200
+
201
+ const expanded = this.ui?.getToolsExpanded() === true;
202
+ const contentBudget = expanded ? tasks.length + 1 : this.contentLineBudget();
203
+ const bodyBudget = Math.max(1, contentBudget - 1);
204
+ const needsSummary = tasks.length > bodyBudget;
205
+ const shownCount = needsSummary ? Math.max(0, bodyBudget - 1) : tasks.length;
206
+ const ordered = needsSummary ? this.prioritized(tasks) : [...tasks].sort(byId);
207
+ const shown = ordered.slice(0, shownCount);
208
+ const hidden = ordered.slice(shownCount);
209
+
210
+ const lines = [truncate(heading)];
211
+ for (const task of shown) {
212
+ lines.push(truncate(`${theme.fg("dim", "├─")} ${formatTaskLine(task, tasks, theme)}`));
213
+ if (task.status === "completed") this.completedPendingHide.add(task.id);
214
+ }
215
+
216
+ if (hidden.length > 0) {
217
+ const parts: string[] = [];
218
+ const hiddenInProgress = hidden.filter((task) => task.status === "in_progress").length;
219
+ const hiddenPending = hidden.filter((task) => task.status === "pending").length;
220
+ const hiddenCompleted = hidden.filter((task) => task.status === "completed").length;
221
+ if (hiddenInProgress) parts.push(`${hiddenInProgress} in progress`);
222
+ if (hiddenPending) parts.push(`${hiddenPending} pending`);
223
+ if (hiddenCompleted) parts.push(`${hiddenCompleted} completed`);
224
+ lines.push(
225
+ truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", `+${hidden.length} more (${parts.join(", ")})`)}`),
226
+ );
227
+ } else if (lines.length > 1) {
228
+ lines[lines.length - 1] = lines[lines.length - 1].replace("├─", "└─");
229
+ }
230
+
231
+ lines.push("");
232
+ return lines;
233
+ }
234
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@riverai7z/pi-todo",
3
+ "version": "0.1.0",
4
+ "description": "Claude Code-style task list tools for Pi",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-extension",
10
+ "todo",
11
+ "task-management"
12
+ ],
13
+ "files": [
14
+ "index.ts",
15
+ "state.ts",
16
+ "overlay.ts",
17
+ "README.md",
18
+ "DESIGN.md"
19
+ ],
20
+ "pi": {
21
+ "extensions": [
22
+ "./index.ts"
23
+ ]
24
+ },
25
+ "scripts": {
26
+ "test": "vitest run",
27
+ "typecheck": "tsc --noEmit"
28
+ },
29
+ "peerDependencies": {
30
+ "@earendil-works/pi-ai": "*",
31
+ "@earendil-works/pi-coding-agent": "*",
32
+ "@earendil-works/pi-tui": "*"
33
+ },
34
+ "dependencies": {
35
+ "typebox": "^1.1.24"
36
+ },
37
+ "devDependencies": {
38
+ "@earendil-works/pi-ai": "^0.80.6",
39
+ "@earendil-works/pi-coding-agent": "^0.80.6",
40
+ "@earendil-works/pi-tui": "^0.80.6",
41
+ "typescript": "^5.9.3",
42
+ "vitest": "^4.1.11"
43
+ }
44
+ }
package/state.ts ADDED
@@ -0,0 +1,326 @@
1
+ export type TaskStatus = "pending" | "in_progress" | "completed" | "deleted";
2
+
3
+ export interface Task {
4
+ id: string;
5
+ subject: string;
6
+ description: string;
7
+ activeForm?: string;
8
+ status: TaskStatus;
9
+ owner?: string;
10
+ blockedBy: string[];
11
+ metadata?: Record<string, unknown>;
12
+ }
13
+
14
+ export interface TaskState {
15
+ tasks: Task[];
16
+ nextId: number;
17
+ }
18
+
19
+ export interface TaskSnapshot {
20
+ action: "create" | "get" | "list" | "update";
21
+ tasks: Task[];
22
+ nextId: number;
23
+ error?: string;
24
+ }
25
+
26
+ const EMPTY_STATE: TaskState = { tasks: [], nextId: 1 };
27
+ const TOOL_NAMES = new Set(["TaskCreate", "TaskGet", "TaskList", "TaskUpdate"]);
28
+ const sessions = new Map<string, TaskState>();
29
+ let foregroundSession = "";
30
+
31
+ const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {
32
+ pending: new Set(["in_progress", "completed", "deleted"]),
33
+ in_progress: new Set(["pending", "completed", "deleted"]),
34
+ completed: new Set(["pending", "in_progress", "deleted"]),
35
+ deleted: new Set(),
36
+ };
37
+
38
+ function cloneTask(task: Task): Task {
39
+ return {
40
+ ...task,
41
+ blockedBy: [...task.blockedBy],
42
+ ...(task.metadata ? { metadata: { ...task.metadata } } : {}),
43
+ };
44
+ }
45
+
46
+ function cloneState(state: TaskState): TaskState {
47
+ return { tasks: state.tasks.map(cloneTask), nextId: state.nextId };
48
+ }
49
+
50
+ function isTask(value: unknown): value is Task {
51
+ if (!value || typeof value !== "object") return false;
52
+ const task = value as Partial<Task>;
53
+ return (
54
+ typeof task.id === "string" &&
55
+ typeof task.subject === "string" &&
56
+ typeof task.description === "string" &&
57
+ ["pending", "in_progress", "completed", "deleted"].includes(task.status ?? "") &&
58
+ Array.isArray(task.blockedBy) &&
59
+ task.blockedBy.every((id) => typeof id === "string")
60
+ );
61
+ }
62
+
63
+ function isSnapshot(value: unknown): value is TaskSnapshot {
64
+ if (!value || typeof value !== "object") return false;
65
+ const snapshot = value as Partial<TaskSnapshot>;
66
+ return Array.isArray(snapshot.tasks) && snapshot.tasks.every(isTask) && Number.isInteger(snapshot.nextId);
67
+ }
68
+
69
+ export function sessionId(ctx: { sessionManager: { getSessionId(): string } }): string {
70
+ return ctx.sessionManager.getSessionId() ?? "";
71
+ }
72
+
73
+ export function getState(id: string): TaskState {
74
+ return sessions.get(id) ?? cloneState(EMPTY_STATE);
75
+ }
76
+
77
+ export function getForegroundState(): TaskState {
78
+ return getState(foregroundSession);
79
+ }
80
+
81
+ export function setForegroundSession(id: string): void {
82
+ foregroundSession = id;
83
+ }
84
+
85
+ export function getForegroundSession(): string {
86
+ return foregroundSession;
87
+ }
88
+
89
+ export function clearForegroundSession(): void {
90
+ foregroundSession = "";
91
+ }
92
+
93
+ export function evictSession(id: string): void {
94
+ sessions.delete(id);
95
+ }
96
+
97
+ export function replayState(ctx: { sessionManager: { getBranch(): Iterable<unknown> } }): TaskState {
98
+ let state = cloneState(EMPTY_STATE);
99
+ for (const rawEntry of ctx.sessionManager.getBranch()) {
100
+ const entry = rawEntry as {
101
+ type?: string;
102
+ message?: { role?: string; toolName?: string; details?: unknown };
103
+ };
104
+ if (entry.type !== "message" || entry.message?.role !== "toolResult") continue;
105
+ if (!entry.message.toolName || !TOOL_NAMES.has(entry.message.toolName)) continue;
106
+ if (isSnapshot(entry.message.details)) {
107
+ state = { tasks: entry.message.details.tasks.map(cloneTask), nextId: entry.message.details.nextId };
108
+ }
109
+ }
110
+ return state;
111
+ }
112
+
113
+ export function replaceState(id: string, state: TaskState): void {
114
+ sessions.set(id, cloneState(state));
115
+ }
116
+
117
+ export function snapshot(action: TaskSnapshot["action"], state: TaskState, error?: string): TaskSnapshot {
118
+ return {
119
+ action,
120
+ tasks: state.tasks.map(cloneTask),
121
+ nextId: state.nextId,
122
+ ...(error ? { error } : {}),
123
+ };
124
+ }
125
+
126
+ export function deriveBlocks(tasks: readonly Task[], taskId: string): string[] {
127
+ return tasks.filter((task) => task.blockedBy.includes(taskId)).map((task) => task.id);
128
+ }
129
+
130
+ export function unresolvedBlockers(task: Task, tasks: readonly Task[]): string[] {
131
+ const resolved = new Set(
132
+ tasks.filter((candidate) => candidate.status === "completed" || candidate.status === "deleted").map((candidate) => candidate.id),
133
+ );
134
+ return task.blockedBy.filter((id) => !resolved.has(id));
135
+ }
136
+
137
+ function graphHasCycle(tasks: readonly Task[]): boolean {
138
+ const edges = new Map(tasks.map((task) => [task.id, task.blockedBy] as const));
139
+ const visiting = new Set<string>();
140
+ const visited = new Set<string>();
141
+
142
+ const visit = (id: string): boolean => {
143
+ if (visiting.has(id)) return true;
144
+ if (visited.has(id)) return false;
145
+ visiting.add(id);
146
+ for (const dependency of edges.get(id) ?? []) {
147
+ if (visit(dependency)) return true;
148
+ }
149
+ visiting.delete(id);
150
+ visited.add(id);
151
+ return false;
152
+ };
153
+
154
+ return [...edges.keys()].some(visit);
155
+ }
156
+
157
+ function requireTask(tasks: readonly Task[], id: string, field: string): string | undefined {
158
+ const task = tasks.find((candidate) => candidate.id === id);
159
+ if (!task) return `${field}: task #${id} not found`;
160
+ if (task.status === "deleted") return `${field}: task #${id} is deleted`;
161
+ return undefined;
162
+ }
163
+
164
+ function mutateDependencies(
165
+ target: Task,
166
+ additions: readonly string[] = [],
167
+ removals: readonly string[] = [],
168
+ ): boolean {
169
+ const next = target.blockedBy.filter((dependency) => !removals.includes(dependency));
170
+ for (const dependency of additions) {
171
+ if (!next.includes(dependency)) next.push(dependency);
172
+ }
173
+ if (next.length === target.blockedBy.length && next.every((value, index) => value === target.blockedBy[index])) {
174
+ return false;
175
+ }
176
+ target.blockedBy = next;
177
+ return true;
178
+ }
179
+
180
+ export function createTask(
181
+ id: string,
182
+ input: {
183
+ subject: string;
184
+ description: string;
185
+ activeForm?: string;
186
+ metadata?: Record<string, unknown>;
187
+ },
188
+ ): { state: TaskState; task: Task } {
189
+ const current = getState(id);
190
+ const task: Task = {
191
+ id: String(current.nextId),
192
+ subject: input.subject.trim(),
193
+ description: input.description.trim(),
194
+ activeForm: input.activeForm?.trim() || undefined,
195
+ status: "pending",
196
+ blockedBy: [],
197
+ metadata: input.metadata ? { ...input.metadata } : undefined,
198
+ };
199
+ const state = { tasks: [...current.tasks.map(cloneTask), task], nextId: current.nextId + 1 };
200
+ sessions.set(id, state);
201
+ return { state, task };
202
+ }
203
+
204
+ export function getTask(id: string, taskId: string): Task | undefined {
205
+ return getState(id).tasks.find((task) => task.id === taskId);
206
+ }
207
+
208
+ export function listTasks(id: string, includeDeleted = false): Task[] {
209
+ return getState(id).tasks.filter((task) => includeDeleted || task.status !== "deleted");
210
+ }
211
+
212
+ export interface TaskUpdateInput {
213
+ subject?: string;
214
+ description?: string;
215
+ activeForm?: string;
216
+ status?: TaskStatus;
217
+ owner?: string;
218
+ addBlocks?: string[];
219
+ addBlockedBy?: string[];
220
+ removeBlocks?: string[];
221
+ removeBlockedBy?: string[];
222
+ metadata?: Record<string, unknown>;
223
+ }
224
+
225
+ export function updateTask(
226
+ session: string,
227
+ taskId: string,
228
+ input: TaskUpdateInput,
229
+ ): { state: TaskState; task?: Task; updatedFields: string[]; error?: string; statusChange?: { from: TaskStatus; to: TaskStatus } } {
230
+ const current = getState(session);
231
+ const tasks = current.tasks.map(cloneTask);
232
+ const index = tasks.findIndex((task) => task.id === taskId);
233
+ if (index < 0) return { state: current, updatedFields: [], error: "Task not found" };
234
+
235
+ const before = cloneTask(tasks[index]);
236
+ if (before.status === "deleted") {
237
+ return { state: current, task: before, updatedFields: [], error: `Task #${taskId} is deleted` };
238
+ }
239
+ if (input.subject !== undefined && !input.subject.trim()) {
240
+ return { state: current, task: before, updatedFields: [], error: "Task subject cannot be empty" };
241
+ }
242
+ if (input.description !== undefined && !input.description.trim()) {
243
+ return { state: current, task: before, updatedFields: [], error: "Task description cannot be empty" };
244
+ }
245
+ if (input.status && input.status !== before.status && !VALID_TRANSITIONS[before.status].has(input.status)) {
246
+ return {
247
+ state: current,
248
+ task: before,
249
+ updatedFields: [],
250
+ error: `Illegal status transition: ${before.status} → ${input.status}`,
251
+ };
252
+ }
253
+
254
+ for (const [field, ids] of [
255
+ ["addBlocks", input.addBlocks],
256
+ ["addBlockedBy", input.addBlockedBy],
257
+ ] as const) {
258
+ for (const dependencyId of ids ?? []) {
259
+ if (dependencyId === taskId) {
260
+ return { state: current, task: before, updatedFields: [], error: `Task #${taskId} cannot depend on itself` };
261
+ }
262
+ const error = requireTask(tasks, dependencyId, field);
263
+ if (error) return { state: current, task: before, updatedFields: [], error };
264
+ }
265
+ }
266
+
267
+ const updatedFields: string[] = [];
268
+ const task = tasks[index];
269
+ if (input.subject !== undefined && task.subject !== input.subject.trim()) {
270
+ task.subject = input.subject.trim();
271
+ updatedFields.push("subject");
272
+ }
273
+ if (input.description !== undefined && task.description !== input.description.trim()) {
274
+ task.description = input.description.trim();
275
+ updatedFields.push("description");
276
+ }
277
+ if (input.activeForm !== undefined && task.activeForm !== input.activeForm.trim()) {
278
+ task.activeForm = input.activeForm.trim();
279
+ updatedFields.push("activeForm");
280
+ }
281
+ if (input.owner !== undefined && task.owner !== input.owner.trim()) {
282
+ task.owner = input.owner.trim();
283
+ updatedFields.push("owner");
284
+ }
285
+
286
+ let statusChange: { from: TaskStatus; to: TaskStatus } | undefined;
287
+ if (input.status && input.status !== task.status) {
288
+ statusChange = { from: task.status, to: input.status };
289
+ task.status = input.status;
290
+ updatedFields.push("status");
291
+ }
292
+
293
+ if (mutateDependencies(task, input.addBlockedBy, input.removeBlockedBy)) updatedFields.push("blockedBy");
294
+
295
+ let blocksChanged = false;
296
+ for (const blockedId of input.addBlocks ?? []) {
297
+ const target = tasks.find((candidate) => candidate.id === blockedId)!;
298
+ if (mutateDependencies(target, [taskId])) blocksChanged = true;
299
+ }
300
+ for (const blockedId of input.removeBlocks ?? []) {
301
+ const target = tasks.find((candidate) => candidate.id === blockedId);
302
+ if (target && mutateDependencies(target, [], [taskId])) blocksChanged = true;
303
+ }
304
+ if (blocksChanged) updatedFields.push("blocks");
305
+
306
+ if (graphHasCycle(tasks)) {
307
+ return { state: current, task: before, updatedFields: [], error: "Dependency update would create a cycle" };
308
+ }
309
+
310
+ if (input.metadata !== undefined) {
311
+ const merged = { ...(task.metadata ?? {}) };
312
+ for (const [key, value] of Object.entries(input.metadata)) {
313
+ if (value === null) delete merged[key];
314
+ else merged[key] = value;
315
+ }
316
+ const next = Object.keys(merged).length ? merged : undefined;
317
+ if (JSON.stringify(next) !== JSON.stringify(task.metadata)) {
318
+ task.metadata = next;
319
+ updatedFields.push("metadata");
320
+ }
321
+ }
322
+
323
+ const state = { tasks, nextId: current.nextId };
324
+ sessions.set(session, state);
325
+ return { state, task: cloneTask(task), updatedFields, statusChange };
326
+ }