@indexyz/pi-todo 0.0.0 → 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/state/store.ts ADDED
@@ -0,0 +1,125 @@
1
+ import type { Task } from "../tool/types.ts";
2
+ import { EMPTY_STATE, type TaskState } from "./state.ts";
3
+
4
+ /**
5
+ * Per-session live state: a Map partitioned by session id, so a detached/child
6
+ * session (distinct sid) can never read or clobber another session's tasks.
7
+ *
8
+ * The Map is the single mutation seam — only `commitState` / `replaceState` /
9
+ * `evictSession` write it; the reducer (`state/state-reducer.ts`) stays pure.
10
+ */
11
+ const sessions = new Map<string, TaskState>();
12
+
13
+ /**
14
+ * Ctx-less render pointer: which slot do the ctx-free readers (the overlay's
15
+ * `getSnapshot()`, the tool's `renderCall()`) render? Set when the first UI
16
+ * session claims the foreground, before the overlay is loaded (creator-ownership
17
+ * — see `index.ts`). A *distinct* concept from the three task-state mutation
18
+ * seams; it is not a 4th writer of task state.
19
+ */
20
+ let activeRenderSession = "";
21
+
22
+ /**
23
+ * Session-id extractor. Structural ctx type (no Pi-runtime import) —
24
+ * mirrors `replay.ts`'s ctx shape so `state/` stays Pi-import-free. Returns
25
+ * `… ?? ""` so an unknown/empty session resolves to "" rather than undefined
26
+ * (keeps the key a plain string for callers and the `index.ts` sid-gate).
27
+ */
28
+ export function sid(ctx: { sessionManager: { getSessionId(): string } }): string {
29
+ return ctx.sessionManager.getSessionId() ?? "";
30
+ }
31
+
32
+ /** Fresh, non-aliasing EMPTY_STATE copy (never returns `EMPTY_STATE.tasks`). */
33
+ function freshState(): TaskState {
34
+ return { tasks: [...EMPTY_STATE.tasks], nextId: EMPTY_STATE.nextId };
35
+ }
36
+
37
+ /** Get-or-read a session's slot: the committed slot by identity, or a fresh
38
+ * EMPTY_STATE copy (not stored) when the slot is absent. */
39
+ function slotFor(sessionId: string): TaskState {
40
+ return sessions.get(sessionId) ?? freshState();
41
+ }
42
+
43
+ /**
44
+ * Live tasks accessor for a session. Returned `readonly Task[]` so callers
45
+ * (overlay render hook, `/todos` command, `renderCall` subject lookup) cannot
46
+ * mutate the live slot. Consumers must not cast back.
47
+ */
48
+ export function getTodos(sessionId: string): readonly Task[] {
49
+ return slotFor(sessionId).tasks;
50
+ }
51
+
52
+ export function getNextId(sessionId: string): number {
53
+ return slotFor(sessionId).nextId;
54
+ }
55
+
56
+ /** Snapshot accessor used by reducer callers to pass canonical state in. */
57
+ export function getState(sessionId: string): TaskState {
58
+ return slotFor(sessionId);
59
+ }
60
+
61
+ /**
62
+ * Replay seam. Lifecycle handlers in `index.ts` call this on
63
+ * `session_start` / `session_compact` / `session_tree` after
64
+ * `replayFromBranch` decodes the latest snapshot, keyed to the session.
65
+ */
66
+ export function replaceState(sessionId: string, next: TaskState): void {
67
+ sessions.set(sessionId, next);
68
+ }
69
+
70
+ /**
71
+ * Post-reducer commit seam. Tool `execute()` calls this with the reducer's
72
+ * `state` output to publish the new canonical state to live readers (overlay,
73
+ * `/todos`, `renderCall`), keyed to the calling session.
74
+ */
75
+ export function commitState(sessionId: string, next: TaskState): void {
76
+ sessions.set(sessionId, next);
77
+ }
78
+
79
+ /** Drop a session's slot on `session_shutdown`. No-op if the slot is absent. */
80
+ export function evictSession(sessionId: string): void {
81
+ sessions.delete(sessionId);
82
+ }
83
+
84
+ /**
85
+ * Ctx-less render reader: the slot the overlay / `renderCall` render.
86
+ * Resolves to the `activeRenderSession` slot, or a fresh EMPTY_STATE copy when
87
+ * no foreground has been set yet.
88
+ */
89
+ export function getRenderState(): TaskState {
90
+ return slotFor(activeRenderSession);
91
+ }
92
+
93
+ /** Set the ctx-less render pointer when the first UI session claims foreground. */
94
+ export function setActiveRenderSession(sessionId: string): void {
95
+ activeRenderSession = sessionId;
96
+ }
97
+
98
+ /**
99
+ * Reads the foreground render pointer — the sid the `index.ts` sid-gate compares
100
+ * against, and the slot `getRenderState()` resolves to. Distinct from
101
+ * `setActiveRenderSession` (the writer): the gate *reads* this pointer, and
102
+ * foreground teardown must *clear* it.
103
+ */
104
+ export function getActiveRenderSession(): string {
105
+ return activeRenderSession;
106
+ }
107
+
108
+ /**
109
+ * Foreground teardown (session_shutdown of the foreground session). Resets the
110
+ * pointer to "" so the next `hasUI` session_start reclaims the foreground.
111
+ */
112
+ export function clearActiveRenderSession(): void {
113
+ activeRenderSession = "";
114
+ }
115
+
116
+ /**
117
+ * Test-setup reset. Wired into the global `test/setup.ts` `beforeEach` via
118
+ * the existing `__resetState` import path. Signature unchanged ⇒ no
119
+ * `test/setup.ts` edit needed. Clears BOTH the session Map and the render
120
+ * pointer so filesystem/detect resets start from a clean state.
121
+ */
122
+ export function __resetState(): void {
123
+ sessions.clear();
124
+ activeRenderSession = "";
125
+ }
@@ -0,0 +1,61 @@
1
+ import type { Task } from "../tool/types.ts";
2
+
3
+ /**
4
+ * Detect whether merging `newBlockedBy` into `taskId`'s `blockedBy` set would
5
+ * introduce a cycle in the dependency graph.
6
+ *
7
+ * Pure of any module state; takes the existing `taskList` and the proposed
8
+ * additions explicitly so the reducer can ask "would this update cycle?"
9
+ * without mutating state first.
10
+ */
11
+ export function detectCycle(
12
+ taskList: readonly Task[],
13
+ taskId: number,
14
+ newBlockedBy: readonly number[],
15
+ ): boolean {
16
+ const edges = new Map<number, number[]>();
17
+ for (const t of taskList) {
18
+ if (t.id === taskId) {
19
+ const merged = new Set([...(t.blockedBy ?? []), ...newBlockedBy]);
20
+ edges.set(t.id, [...merged]);
21
+ } else {
22
+ edges.set(t.id, t.blockedBy ? [...t.blockedBy] : []);
23
+ }
24
+ }
25
+
26
+ const visiting = new Set<number>();
27
+ const visited = new Set<number>();
28
+ const hasCycleFrom = (node: number): boolean => {
29
+ if (visiting.has(node)) return true;
30
+ if (visited.has(node)) return false;
31
+ visiting.add(node);
32
+ for (const nb of edges.get(node) ?? []) {
33
+ if (hasCycleFrom(nb)) return true;
34
+ }
35
+ visiting.delete(node);
36
+ visited.add(node);
37
+ return false;
38
+ };
39
+
40
+ for (const node of edges.keys()) {
41
+ if (hasCycleFrom(node)) return true;
42
+ }
43
+ return false;
44
+ }
45
+
46
+ /**
47
+ * Build the inverse adjacency map: for each task `T`, which other tasks list
48
+ * `T` in their `blockedBy`. Consumed by `selectShowTaskIds` (overlay gating)
49
+ * and the `get` action's "blocks: #x, #y" suffix line.
50
+ */
51
+ export function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {
52
+ const blocks = new Map<number, number[]>();
53
+ for (const t of taskList) {
54
+ for (const dep of t.blockedBy ?? []) {
55
+ const arr = blocks.get(dep) ?? [];
56
+ arr.push(t.id);
57
+ blocks.set(dep, arr);
58
+ }
59
+ }
60
+ return blocks;
61
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * todo-overlay.ts — Persistent widget showing todo list above the editor.
3
+ *
4
+ * Lifecycle controller for Pi's `setWidget` contract: factory-form
5
+ * registration in widgetContainerAbove, register-once + requestRender()
6
+ * refresh, configurable collapse-not-scroll (default 12 content rows via
7
+ * getMaxWidgetLines(); plus a trailing spacer row so the widget renders up
8
+ * to 13 lines), Pi tool-output expansion awareness, auto-hide when empty.
9
+ *
10
+ * Reads live state via `getRenderState()` (the ctx-less foreground slot) at render
11
+ * time — NEVER `replayFromBranch` from `tool_execution_end` (branch is stale;
12
+ * `message_end` runs after).
13
+ */
14
+
15
+ import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
16
+ import { type TUI, truncateToWidth } from "@earendil-works/pi-tui";
17
+ import { COLLAPSE_KEY_OFF, getMaxWidgetLines, resolveCollapseKey } from "./config.ts";
18
+ import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
19
+ import {
20
+ selectHasActive,
21
+ selectOverlayLayout,
22
+ selectShowTaskIds,
23
+ selectTodoCounts,
24
+ } from "./state/selectors.ts";
25
+ import { getRenderState } from "./state/store.ts";
26
+ import { formatOverlayTaskLine } from "./view/format.ts";
27
+
28
+ const WIDGET_KEY = "rpiv-todos";
29
+
30
+ // English fallbacks for localized overlay chrome strings.
31
+ const OVERLAY_HEADING = "Todos";
32
+ const OVERLAY_MORE = "more";
33
+ const OVERLAY_EXPAND_HINT = "{key} to expand";
34
+ const OVERLAY_COLLAPSED = "collapsed";
35
+
36
+ export class TodoOverlay {
37
+ private uiCtx: ExtensionUIContext | undefined;
38
+ private widgetRegistered = false;
39
+ private tui: TUI | undefined;
40
+ private completedTaskIdsPendingHide = new Set<number>();
41
+ private hiddenCompletedTaskIds = new Set<number>();
42
+ private lastNextId: number | undefined;
43
+ private collapsed = false;
44
+
45
+ setUICtx(ctx: ExtensionUIContext): void {
46
+ // Identity-compare so repeat session_start handlers are idempotent;
47
+ // on identity change (/reload) invalidate so update() re-registers.
48
+ if (ctx !== this.uiCtx) {
49
+ this.uiCtx = ctx;
50
+ this.widgetRegistered = false;
51
+ this.tui = undefined;
52
+ }
53
+ }
54
+
55
+ update(): void {
56
+ if (!this.uiCtx) return;
57
+ const snapshot = this.getSnapshot();
58
+ const visible = this.selectOverlayTasks(snapshot);
59
+
60
+ if (visible.length === 0) {
61
+ if (this.widgetRegistered) {
62
+ this.uiCtx.setWidget(WIDGET_KEY, undefined);
63
+ this.widgetRegistered = false;
64
+ this.tui = undefined;
65
+ }
66
+ return;
67
+ }
68
+
69
+ if (!this.widgetRegistered) {
70
+ this.uiCtx.setWidget(
71
+ WIDGET_KEY,
72
+ (tui, factoryTheme) => {
73
+ this.tui = tui;
74
+ return {
75
+ render: (width: number) => this.renderWidget(this.uiCtx?.theme ?? factoryTheme, width),
76
+ invalidate: () => {
77
+ // No rendered strings are cached. Pi invalidates on theme changes;
78
+ // the next render reads uiCtx.theme.
79
+ },
80
+ };
81
+ },
82
+ { placement: "aboveEditor" },
83
+ );
84
+ this.widgetRegistered = true;
85
+ } else {
86
+ this.tui?.requestRender();
87
+ }
88
+ }
89
+
90
+ resetCompletedDisplayState(): void {
91
+ this.completedTaskIdsPendingHide.clear();
92
+ this.hiddenCompletedTaskIds.clear();
93
+ this.lastNextId = undefined;
94
+ }
95
+
96
+ hideCompletedTasksFromPreviousTurn(): void {
97
+ if (this.completedTaskIdsPendingHide.size === 0) return;
98
+ for (const taskId of this.completedTaskIdsPendingHide) {
99
+ this.hiddenCompletedTaskIds.add(taskId);
100
+ }
101
+ this.completedTaskIdsPendingHide.clear();
102
+ this.tui?.requestRender();
103
+ }
104
+
105
+ toggleCollapse(): void {
106
+ this.collapsed = !this.collapsed;
107
+ // Forced full redraw on the collapsed↔expanded height step, mirroring the
108
+ // lane-dock's requestRender(shapeChanged); distinct from the non-forced
109
+ // requestRender() refresh paths in update()/hideCompletedTasksFromPreviousTurn().
110
+ this.tui?.requestRender(true);
111
+ }
112
+
113
+ isRegistered(): boolean {
114
+ return this.widgetRegistered;
115
+ }
116
+
117
+ private getSnapshot() {
118
+ const state = getRenderState();
119
+ if (this.lastNextId !== undefined && state.nextId < this.lastNextId) {
120
+ this.resetCompletedDisplayState();
121
+ }
122
+ this.lastNextId = state.nextId;
123
+ const completedTaskIds = new Set(
124
+ state.tasks.filter((task) => task.status === "completed").map((task) => task.id),
125
+ );
126
+ for (const taskId of this.completedTaskIdsPendingHide) {
127
+ if (!completedTaskIds.has(taskId)) this.completedTaskIdsPendingHide.delete(taskId);
128
+ }
129
+ for (const taskId of this.hiddenCompletedTaskIds) {
130
+ if (!completedTaskIds.has(taskId)) this.hiddenCompletedTaskIds.delete(taskId);
131
+ }
132
+ return { tasks: [...state.tasks], nextId: state.nextId };
133
+ }
134
+
135
+ private selectOverlayTasks(snapshot: ReturnType<TodoOverlay["getSnapshot"]>) {
136
+ return snapshot.tasks.filter(
137
+ (task) => task.status !== "deleted" && !this.shouldHideCompletedTask(task),
138
+ );
139
+ }
140
+
141
+ private shouldHideCompletedTask(
142
+ task: ReturnType<TodoOverlay["getSnapshot"]>["tasks"][number],
143
+ ): boolean {
144
+ return task.status === "completed" && this.hiddenCompletedTaskIds.has(task.id);
145
+ }
146
+
147
+ private renderWidget(theme: Theme, width: number): string[] {
148
+ const snapshot = this.getSnapshot();
149
+ const overlayTasks = this.selectOverlayTasks(snapshot);
150
+ if (overlayTasks.length === 0) return [];
151
+
152
+ const overlayState = { tasks: overlayTasks, nextId: snapshot.nextId };
153
+ const truncate = (line: string): string => truncateToWidth(line, width, "…");
154
+ const counts = selectTodoCounts(overlayState);
155
+ const hasActive = selectHasActive(overlayState);
156
+ const showIds = selectShowTaskIds(overlayState);
157
+
158
+ const headingColor = hasActive ? "accent" : "dim";
159
+ const headingIcon = hasActive ? "●" : "○";
160
+ const headingText = `${t("overlay.heading", OVERLAY_HEADING)} (${counts.completed}/${counts.total})`;
161
+ const heading = truncate(
162
+ `${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}`,
163
+ );
164
+
165
+ // Collapsed view: just the heading + a dim "└─" expand hint, then the
166
+ // trailing spacer. Short-circuit before the budget math and the completed-
167
+ // display tracking — nothing is shown to track, and skipping the tracking
168
+ // when nothing is rendered is correctness, not optimization. The hint splices
169
+ // the resolved key into the {key} placeholder (per-render, like the row
170
+ // budget); a config edit needs /reload to re-bind the actual shortcut. The
171
+ // "off" sentinel is reachable here mid-session (config edited after the
172
+ // shortcut was bound and the overlay collapsed) — render a static collapsed
173
+ // label instead of splicing the sentinel into the placeholder.
174
+ if (this.collapsed) {
175
+ const key = resolveCollapseKey();
176
+ const hint =
177
+ key === COLLAPSE_KEY_OFF
178
+ ? t("overlay.collapsed", OVERLAY_COLLAPSED)
179
+ : t("overlay.expandHint", OVERLAY_EXPAND_HINT).replace("{key}", key);
180
+ return this.withTrailingSpacer([
181
+ heading,
182
+ truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", hint)}`),
183
+ ]);
184
+ }
185
+
186
+ const lines: string[] = [heading];
187
+ // Budget for content rows (heading + tasks/summary). The rendered widget is
188
+ // one line taller — withTrailingSpacer() appends a blank row below the panel.
189
+ // Pi's global tool-output expansion mode is read on every render so its
190
+ // expand/collapse shortcut also expands this live widget. Optional chaining
191
+ // preserves compatibility with hosts predating getToolsExpanded().
192
+ const bodyBudget =
193
+ this.uiCtx?.getToolsExpanded?.() === true ? overlayTasks.length : getMaxWidgetLines() - 1;
194
+ const layout = selectOverlayLayout(overlayState, bodyBudget);
195
+ for (const task of layout.visible) {
196
+ lines.push(
197
+ truncate(`${theme.fg("dim", "├─")} ${formatOverlayTaskLine(task, theme, showIds)}`),
198
+ );
199
+ }
200
+
201
+ const newlyDisplayedCompletedTaskIds = overlayTasks
202
+ .filter(
203
+ (task) =>
204
+ task.status === "completed" &&
205
+ !this.completedTaskIdsPendingHide.has(task.id) &&
206
+ !this.hiddenCompletedTaskIds.has(task.id),
207
+ )
208
+ .map((task) => task.id);
209
+ for (const taskId of newlyDisplayedCompletedTaskIds) {
210
+ this.completedTaskIdsPendingHide.add(taskId);
211
+ }
212
+
213
+ if (layout.hiddenCompleted === 0 && layout.truncatedTail === 0) {
214
+ const last = lines.length - 1;
215
+ lines[last] = lines[last].replace("├─", "└─");
216
+ return this.withTrailingSpacer(lines);
217
+ }
218
+
219
+ const totalHidden = layout.hiddenCompleted + layout.truncatedTail;
220
+ const overflowParts: string[] = [];
221
+ if (layout.hiddenCompleted > 0)
222
+ overflowParts.push(`${layout.hiddenCompleted} ${formatStatusLabel("completed")}`);
223
+ if (layout.truncatedTail > 0)
224
+ overflowParts.push(`${layout.truncatedTail} ${formatStatusLabel("pending")}`);
225
+ const more = t("overlay.more", OVERLAY_MORE);
226
+ const summary =
227
+ overflowParts.length > 0
228
+ ? `+${totalHidden} ${more} (${overflowParts.join(", ")})`
229
+ : `+${totalHidden} ${more}`;
230
+ lines.push(truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", summary)}`));
231
+ return this.withTrailingSpacer(lines);
232
+ }
233
+
234
+ /**
235
+ * Append a trailing blank line so the overlay isn't flush against the
236
+ * editor box. Pi's host adds a leading spacer above the widget but none
237
+ * below, which leaves the last "└─" row (or the "+N more" summary) glued
238
+ * to the input box. The empty string gives the "Todos" panel a little
239
+ * breathing room.
240
+ */
241
+ private withTrailingSpacer(lines: string[]): string[] {
242
+ if (lines.length === 0) return lines;
243
+ lines.push("");
244
+ return lines;
245
+ }
246
+
247
+ dispose(): void {
248
+ if (this.uiCtx) this.uiCtx.setWidget(WIDGET_KEY, undefined);
249
+ this.widgetRegistered = false;
250
+ this.tui = undefined;
251
+ this.uiCtx = undefined;
252
+ this.collapsed = false;
253
+ this.resetCompletedDisplayState();
254
+ }
255
+ }
package/todo.ts ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * todo tool + /todos command — thin registration shell.
3
+ *
4
+ * Tool/command identity, schema, types, reducer, store, replay, response
5
+ * envelope, selectors, and view formatters live in the layered modules under
6
+ * `tool/`, `state/`, and `view/`. This file is the package-root registration
7
+ * surface — it mirrors `packages/rpiv-ask-user-question/ask-user-question.ts`
8
+ * which keeps the tool registration at the package root.
9
+ *
10
+ * Public re-exports below preserve the package-root import surface so that
11
+ * `index.ts`, `todo-overlay.ts`, and the global `test/setup.ts` `beforeEach`
12
+ * continue to import from `./todo.js`.
13
+ */
14
+
15
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
+ import { loadConfig, validateGuidanceFields } from "./config.ts";
17
+ import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
18
+ import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
19
+ import { applyTaskMutation, changesState } from "./state/state-reducer.ts";
20
+ import { commitState, getRenderState, getState, sid } from "./state/store.ts";
21
+ import { prepareTodoArguments } from "./tool/normalize-params.ts";
22
+ import { buildToolResult } from "./tool/response-envelope.ts";
23
+ import {
24
+ COMMAND_NAME,
25
+ ERR_REQUIRES_INTERACTIVE,
26
+ MSG_NO_TODOS,
27
+ STATE_ENTRY_TYPE,
28
+ type TaskAction,
29
+ type TaskMutationParams,
30
+ TOOL_LABEL,
31
+ TOOL_NAME,
32
+ TodoParamsSchema,
33
+ } from "./tool/types.ts";
34
+ import { formatCommandTaskLine, renderTodoCall, renderTodoResult } from "./view/format.ts";
35
+
36
+ // English fallbacks for localized /todos section headers — the box-drawing
37
+ // decoration is part of the localized string so translators can adjust spacing.
38
+ const SECTION_PENDING = "── Pending ──";
39
+ const SECTION_IN_PROGRESS = "── In Progress ──";
40
+ const SECTION_COMPLETED = "── Completed ──";
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Public re-exports — existing consumers (overlay, tests, index.ts) keep
44
+ // importing from `./todo.js`. New code may opt into deeper imports.
45
+ // ---------------------------------------------------------------------------
46
+
47
+ export { isTransitionValid } from "./state/invariants.ts";
48
+ export { applyTaskMutation } from "./state/state-reducer.ts";
49
+ export { __resetState, getNextId, getTodos, setActiveRenderSession, sid } from "./state/store.ts";
50
+ export { deriveBlocks, detectCycle } from "./state/task-graph.ts";
51
+ export type { Task, TaskAction, TaskDetails, TaskStatus } from "./tool/types.ts";
52
+ export { TOOL_NAME } from "./tool/types.ts";
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Tool registration
56
+ // ---------------------------------------------------------------------------
57
+
58
+ export const DEFAULT_PROMPT_SNIPPET = "Manage a task list to track multi-step progress";
59
+ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
60
+ "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.",
61
+ "When starting a task from the todo list, mark it in_progress BEFORE beginning work. Mark it completed IMMEDIATELY when done — never batch completions. Exactly one task in_progress at a time.",
62
+ "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.",
63
+ "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.",
64
+ 'To change a task\'s status, call update with the task id and the target status, e.g. {"action":"update","id":3,"status":"completed"} or {"action":"update","id":3,"status":"in_progress","activeForm":"writing tests"}. status is the field that changes the task; an update without a mutable field (status or another) is rejected.',
65
+ "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.",
66
+ "To create several independent tasks at once, pass create with tasks: [{subject}, ...]. Do not also pass subject. tasks[] cannot blockedBy each other (ids do not exist until the call commits); create the prerequisite first, then the dependent with blockedBy. Dependency chains stay single-create.",
67
+ "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
68
+ "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.",
69
+ ];
70
+
71
+ export function registerTodoTool(pi: ExtensionAPI): void {
72
+ const guidance = validateGuidanceFields(loadConfig().guidance);
73
+ pi.registerTool({
74
+ name: TOOL_NAME,
75
+ label: TOOL_LABEL,
76
+ description:
77
+ "Manage a task list for tracking multi-step progress. Actions: create (new task, or several independent tasks at once via tasks[]), update (change status/fields/dependencies), list (all tasks, optionally filtered by status), get (single task details), delete (tombstone), clear (reset all). Status: pending → in_progress → completed, plus deleted tombstone. Use this to plan and track multi-step work like research, design, and implementation.",
78
+ promptSnippet: guidance.promptSnippet ?? DEFAULT_PROMPT_SNIPPET,
79
+ promptGuidelines: guidance.promptGuidelines ?? DEFAULT_PROMPT_GUIDELINES,
80
+ parameters: TodoParamsSchema,
81
+ // Undo a double-encoded tasks[] before Pi validates it (#244 shape).
82
+ prepareArguments: prepareTodoArguments,
83
+
84
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
85
+ const result = applyTaskMutation(
86
+ getState(sid(ctx)),
87
+ params.action as TaskAction,
88
+ params as TaskMutationParams,
89
+ );
90
+ commitState(sid(ctx), result.state);
91
+ const toolResult = buildToolResult(
92
+ params.action as TaskAction,
93
+ params as TaskMutationParams,
94
+ result.state,
95
+ result.op,
96
+ );
97
+ // Persist a compact operation record as a custom entry on the calling session's branch, however the
98
+ // tool was reached: a call made through another tool (`ctx.executeTool`, e.g. codemode)
99
+ // never lands as a standalone `toolResult`, so its `details` alone would not survive
100
+ // replay. Pi's own codemode persists its `store()` the same way.
101
+ if (changesState(result.op)) pi.appendEntry(STATE_ENTRY_TYPE, toolResult.details);
102
+ return toolResult;
103
+ },
104
+
105
+ // renderCall reflects the FOREGROUND slot, not the calling session's. Pi's
106
+ // `ToolRenderContext` carries no session identity (no sessionManager/sessionId),
107
+ // so this ctx-less hook cannot re-key by caller. For the foreground session's
108
+ // own transcript that is exactly right. A detached/child call rendered in the
109
+ // lane-transcript viewer whose task lives only in the child's slot misses the
110
+ // foreground lookup and falls back to `#<id>` (see renderTodoCall). That is the
111
+ // safe outcome: per-session ids restart at 1, so searching sibling slots could
112
+ // surface the WRONG subject — the `#<id>` fallback is intentional, not a gap.
113
+ renderCall(args, theme, _context) {
114
+ return renderTodoCall(args as never, theme, getRenderState());
115
+ },
116
+
117
+ renderResult(result, _opts, theme, context) {
118
+ return renderTodoResult(result, theme, context?.isError);
119
+ },
120
+ });
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // /todos slash command
125
+ // ---------------------------------------------------------------------------
126
+
127
+ export function registerTodosCommand(pi: ExtensionAPI): void {
128
+ pi.registerCommand(COMMAND_NAME, {
129
+ description: "Show all todos on the current branch, grouped by status",
130
+ handler: async (_args, ctx) => {
131
+ if (!ctx.hasUI) {
132
+ ctx.ui.notify(t("command.requires_interactive", ERR_REQUIRES_INTERACTIVE), "error");
133
+ return;
134
+ }
135
+ const state = getState(sid(ctx));
136
+ const visible = selectVisibleTasks(state);
137
+ if (visible.length === 0) {
138
+ ctx.ui.notify(t("command.no_todos", MSG_NO_TODOS), "info");
139
+ return;
140
+ }
141
+ const groups = selectTasksByStatus(state);
142
+ const counts = selectTodoCounts(state);
143
+
144
+ const header: string[] = [];
145
+ if (counts.completed > 0)
146
+ header.push(`${counts.completed}/${counts.total} ${formatStatusLabel("completed")}`);
147
+ if (counts.inProgress > 0)
148
+ header.push(`${counts.inProgress} ${formatStatusLabel("in_progress")}`);
149
+ if (counts.pending > 0) header.push(`${counts.pending} ${formatStatusLabel("pending")}`);
150
+
151
+ const lines: string[] = [header.join(" · ")];
152
+ if (groups.pending.length > 0) {
153
+ lines.push(t("command.section.pending", SECTION_PENDING));
154
+ for (const task of groups.pending) lines.push(formatCommandTaskLine(task, "○"));
155
+ }
156
+ if (groups.inProgress.length > 0) {
157
+ lines.push(t("command.section.in_progress", SECTION_IN_PROGRESS));
158
+ for (const task of groups.inProgress) lines.push(formatCommandTaskLine(task, "◐"));
159
+ }
160
+ if (groups.completed.length > 0) {
161
+ lines.push(t("command.section.completed", SECTION_COMPLETED));
162
+ for (const task of groups.completed) lines.push(formatCommandTaskLine(task, "✓"));
163
+ }
164
+
165
+ ctx.ui.notify(lines.join("\n"), "info");
166
+ },
167
+ });
168
+ }
@@ -0,0 +1,44 @@
1
+ import type { TodoParams } from "./types.ts";
2
+
3
+ /**
4
+ * Pi's `prepareArguments` hook: undo a double-encoded `tasks[]` before schema
5
+ * validation. Some tool-call parsers (vLLM/LiteLLM-served GLM/Qwen-class models)
6
+ * emit nested structures as JSON strings — `tasks` itself, or its items — the same
7
+ * shape rpiv-ask-user-question decodes for `questions` (#244). Only a string at an
8
+ * array/object position is decoded, and only when it parses to the expected shape;
9
+ * anything else is passed through untouched so validation still reports the real
10
+ * problem. Well-formed arguments are returned as-is.
11
+ */
12
+ export function prepareTodoArguments(args: unknown): TodoParams {
13
+ if (!isRecord(args) || args.tasks === undefined) return args as TodoParams;
14
+ const tasks = decodeArray(args.tasks);
15
+ if (!Array.isArray(tasks)) return args as TodoParams;
16
+ const decoded = tasks.map(decodeObject);
17
+ if (tasks === args.tasks && decoded.every((item, i) => item === tasks[i]))
18
+ return args as TodoParams;
19
+ return { ...args, tasks: decoded } as unknown as TodoParams;
20
+ }
21
+
22
+ function isRecord(value: unknown): value is Record<string, unknown> {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+
26
+ /** A JSON string holding an array → that array; anything else unchanged. */
27
+ function decodeArray(value: unknown): unknown {
28
+ const parsed = typeof value === "string" ? parseJson(value) : value;
29
+ return Array.isArray(parsed) ? parsed : value;
30
+ }
31
+
32
+ /** A JSON string holding an object → that object; anything else unchanged. */
33
+ function decodeObject(value: unknown): unknown {
34
+ const parsed = typeof value === "string" ? parseJson(value) : value;
35
+ return isRecord(parsed) ? parsed : value;
36
+ }
37
+
38
+ function parseJson(text: string): unknown {
39
+ try {
40
+ return JSON.parse(text);
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }