@juicesharp/rpiv-todo 2.1.0 → 2.3.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.
@@ -85,7 +85,7 @@ Examples: `alt+o`, `ctrl+shift+t`, `super+alt+f5`.
85
85
 
86
86
  `guidance.promptSnippet` (string) and `guidance.promptGuidelines` (array of
87
87
  strings) replace the prompt copy the `todo` tool advertises to the model. Both
88
- are absent by default, in which case the built-in snippet and the seven built-in
88
+ are absent by default, in which case the built-in snippet and the eight built-in
89
89
  guideline bullets are used.
90
90
 
91
91
  - `promptSnippet` must be a non-empty string; an empty string or a wrong type
@@ -38,7 +38,7 @@ todo({
38
38
  // update / get / delete
39
39
  id?: number,
40
40
 
41
- // update (target status) or list (filter)
41
+ // update (sets this task's status) or list (filters by status)
42
42
  status?: "pending" | "in_progress" | "completed" | "deleted",
43
43
 
44
44
  // list-only
@@ -132,7 +132,7 @@ that it was a no-op instead of a fresh `Updated #N`.
132
132
  | `blockedBy: #N is deleted` | `create` naming a tombstoned dependency. |
133
133
  | `id required for update` / `get` / `delete` | `id` omitted. |
134
134
  | `#N not found` | No task with that id. |
135
- | `update requires at least one mutable field` | `update` with only an `id`. |
135
+ | `update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy` | `update` with only an `id`. |
136
136
  | `illegal transition completed → in_progress` | Target status not reachable from the current one. |
137
137
  | `cannot block #N on itself` | `addBlockedBy` includes the task's own id. |
138
138
  | `addBlockedBy: #N not found` / `is deleted` | Unknown or tombstoned dependency. |
@@ -144,8 +144,9 @@ carries the bare message. Task state is unchanged.
144
144
 
145
145
  ## Prompt guidance
146
146
 
147
- The tool ships a `promptSnippet` and seven `promptGuidelines` bullets telling the
147
+ The tool ships a `promptSnippet` and eight `promptGuidelines` bullets telling the
148
148
  model when to open a list, to keep exactly one task `in_progress`, to mark work
149
- completed immediately rather than in batches, and never to complete a task with
150
- failing tests. Both are overridable — see
149
+ completed immediately rather than in batches, never to complete a task with
150
+ failing tests, and the literal `update {id, status}` call shape for changing a
151
+ task's status. Both are overridable — see
151
152
  [configuration.md](./configuration.md#guidance).
package/index.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  * correctly after upgrade.
20
20
  */
21
21
 
22
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
22
+ import type { ExtensionAPI, ExtensionUIContext } from "@earendil-works/pi-coding-agent";
23
23
  import type { KeyId } from "@earendil-works/pi-tui";
24
24
  import { COLLAPSE_KEY_OFF, resolveCollapseKey } from "./config.js";
25
25
  import { I18N_NAMESPACE } from "./state/i18n-bridge.js";
@@ -28,17 +28,71 @@ import {
28
28
  clearActiveRenderSession,
29
29
  evictSession,
30
30
  getActiveRenderSession,
31
+ getRenderState,
31
32
  replaceState,
32
33
  setActiveRenderSession,
33
34
  sid,
34
35
  } from "./state/store.js";
35
36
  import { registerTodosCommand, registerTodoTool, TOOL_NAME } from "./todo.js";
36
- import { TodoOverlay } from "./todo-overlay.js";
37
+ import type { TodoOverlay } from "./todo-overlay.js";
37
38
 
38
39
  type I18nLoader = {
39
40
  registerLocalesFromDir: (namespace: string, packageUrl: string, options?: { label?: string }) => void;
40
41
  };
41
42
 
43
+ /** Delay the overlay graph pre-warm until Pi's startup work has settled. */
44
+ export const PREWARM_DELAY_MS = 2000;
45
+
46
+ type TodoOverlayModule = typeof import("./todo-overlay.js");
47
+ type TodoOverlayImporter = () => Promise<TodoOverlayModule>;
48
+
49
+ /**
50
+ * Marker shared by the loader's poisoned-namespace error and the
51
+ * `isStaleOverlayModuleError` predicate that lets handlers re-throw it while
52
+ * swallowing transient load failures.
53
+ */
54
+ const STALE_OVERLAY_MESSAGE = "Todo overlay module cache is stale; restart Pi";
55
+
56
+ /** True for the loader's latched poisoned-namespace error (see below). */
57
+ export function isStaleOverlayModuleError(e: unknown): boolean {
58
+ return String(e).includes(STALE_OVERLAY_MESSAGE);
59
+ }
60
+
61
+ /**
62
+ * Memoize the overlay graph after a successful load, but drop a rejected
63
+ * promise so a failed pre-warm does not permanently replay the same rejection.
64
+ * The export guard turns jiti's poisoned-namespace failure into a useful restart
65
+ * error instead of a bare "TodoOverlay is not a constructor" TypeError.
66
+ */
67
+ export function makeTodoOverlayLoader(
68
+ importOverlay: TodoOverlayImporter = () => import("./todo-overlay.js"),
69
+ ): TodoOverlayImporter {
70
+ let memo: Promise<TodoOverlayModule> | undefined;
71
+
72
+ return async (): Promise<TodoOverlayModule> => {
73
+ memo ??= importOverlay();
74
+ const current = memo;
75
+ let mod: TodoOverlayModule;
76
+ try {
77
+ mod = await current;
78
+ } catch (error) {
79
+ // Clear only OUR rejected promise: a late catch from a concurrent
80
+ // awaiter must never clobber a fresh retry another caller installed.
81
+ if (memo === current) memo = undefined;
82
+ throw error;
83
+ }
84
+ if (typeof mod.TodoOverlay !== "function") {
85
+ // Deliberately latched: the memo keeps this resolved-but-poisoned
86
+ // namespace, so every subsequent load re-throws instead of retrying.
87
+ // Re-importing would hand back the same cached jiti namespace — a
88
+ // retry can never heal this; only the restart the error asks for can.
89
+ const keys = JSON.stringify(Object.keys(mod));
90
+ throw new Error(`${STALE_OVERLAY_MESSAGE} (resolved namespace keys: ${keys})`);
91
+ }
92
+ return mod;
93
+ };
94
+ }
95
+
42
96
  // Dynamic import keeps `@juicesharp/rpiv-i18n` a soft optional peer: when the
43
97
  // SDK is installed alongside this package the strings register and
44
98
  // `/languages` flips them live; when it isn't, the import rejects here, we
@@ -60,9 +114,38 @@ function isStaleCtxError(e: unknown): boolean {
60
114
  return /stale after session replacement/.test(String(e));
61
115
  }
62
116
 
63
- export default function (pi: ExtensionAPI) {
64
- // Todo overlay widget — constructed lazily at the first session_start with UI.
117
+ /**
118
+ * Render a caught `unknown` as a human-readable message — the `instanceof Error`
119
+ * dance collapsed to one place. Local copy of the `formatError` in
120
+ * packages/rpiv-workflow/internal-utils.ts:56-58 (that module disclaims its
121
+ * public surface, so the cross-package import is not available). M2 boundary
122
+ * duplication: tracked as a documented-constant seam.
123
+ */
124
+ function formatError(e: unknown): string {
125
+ return e instanceof Error ? e.message : String(e);
126
+ }
127
+
128
+ export default function (pi: ExtensionAPI, importOverlay: TodoOverlayImporter = () => import("./todo-overlay.js")) {
65
129
  let todoOverlay: TodoOverlay | undefined;
130
+ const loadTodoOverlay = makeTodoOverlayLoader(importOverlay);
131
+ let uiCtx: ExtensionUIContext | undefined;
132
+ let lifecycleGeneration = 0;
133
+
134
+ async function updateTodoOverlay(
135
+ resetCompletedDisplayState = false,
136
+ generation = lifecycleGeneration,
137
+ ): Promise<void> {
138
+ const hasVisibleTasks = getRenderState().tasks.some((task) => task.status !== "deleted");
139
+ if (!uiCtx || (!todoOverlay && !hasVisibleTasks)) return;
140
+
141
+ const { TodoOverlay } = await loadTodoOverlay();
142
+ if (generation !== lifecycleGeneration || !uiCtx) return;
143
+
144
+ todoOverlay ??= new TodoOverlay();
145
+ todoOverlay.setUICtx(uiCtx);
146
+ if (resetCompletedDisplayState) todoOverlay.resetCompletedDisplayState();
147
+ todoOverlay.update();
148
+ }
66
149
 
67
150
  registerTodoTool(pi);
68
151
  registerTodosCommand(pi);
@@ -71,10 +154,10 @@ export default function (pi: ExtensionAPI) {
71
154
  // factory scope from config (register-once contract: a config change needs
72
155
  // `/reload` to re-bind, same as lane-switcher's env hotkey) and the binding is
73
156
  // skipped entirely when collapseKey is "off". The handler closes over the
74
- // closure-local `todoOverlay` by reference and re-reads it at fire time, so a
75
- // session_start that (re)creates the overlay is picked up. No-op in headless
76
- // mode, when the overlay hasn't been created yet, or when the widget isn't
77
- // currently registered (auto-hidden on an empty list).
157
+ // closure-local `todoOverlay` by reference and re-reads it at fire time, so an
158
+ // overlay loaded after shortcut registration is picked up. No-op in headless
159
+ // mode, before the overlay has loaded, or when the widget isn't currently
160
+ // registered (auto-hidden on an empty list).
78
161
  const collapseKey = resolveCollapseKey();
79
162
  if (collapseKey !== COLLAPSE_KEY_OFF) {
80
163
  pi.registerShortcut(collapseKey as KeyId, {
@@ -94,7 +177,9 @@ export default function (pi: ExtensionAPI) {
94
177
  // the replacement session's session_start replays it. Other errors are real replay
95
178
  // bugs and must propagate. The render is sid-gated so a child never refreshes the
96
179
  // foreground overlay.
97
- const replayAndRefresh = (ctx: Parameters<typeof sid>[0] & Parameters<typeof replayFromBranch>[0]): void => {
180
+ const replayAndRefresh = async (
181
+ ctx: Parameters<typeof sid>[0] & Parameters<typeof replayFromBranch>[0],
182
+ ): Promise<void> => {
98
183
  let isForeground = false;
99
184
  try {
100
185
  const id = sid(ctx);
@@ -103,10 +188,7 @@ export default function (pi: ExtensionAPI) {
103
188
  } catch (e) {
104
189
  if (!isStaleCtxError(e)) throw e;
105
190
  }
106
- if (isForeground) {
107
- todoOverlay?.resetCompletedDisplayState();
108
- todoOverlay?.update();
109
- }
191
+ if (isForeground) await updateTodoOverlay(true);
110
192
  };
111
193
 
112
194
  pi.on("session_start", async (_event, ctx) => {
@@ -124,23 +206,23 @@ export default function (pi: ExtensionAPI) {
124
206
  }
125
207
  if (!ctx.hasUI) return;
126
208
  // First UI-bearing session_start claims the foreground (the interactive
127
- // launcher, by spawn-ordering). A child hitting a live overlay cannot
128
- // clobber the pointer — `todoOverlay` is already set.
129
- if (todoOverlay === undefined) {
130
- todoOverlay = new TodoOverlay();
131
- setActiveRenderSession(id);
132
- }
209
+ // launcher, by spawn-ordering) without eagerly loading the overlay.
210
+ if (getActiveRenderSession() === "") setActiveRenderSession(id);
133
211
  // Only the foreground re-binds/refreshes the shared overlay. A child
134
212
  // (distinct sid) is skipped — does not rebind to a relay/stale ui.
135
213
  if (id !== getActiveRenderSession()) return;
136
- todoOverlay.setUICtx(ctx.ui);
137
- todoOverlay.resetCompletedDisplayState();
138
- todoOverlay.update();
214
+ const generation = ++lifecycleGeneration;
215
+ uiCtx = ctx.ui;
216
+ await updateTodoOverlay(true, generation);
139
217
  });
140
218
 
141
- pi.on("session_compact", async (_event, ctx) => replayAndRefresh(ctx));
219
+ pi.on("session_compact", async (_event, ctx) => {
220
+ await replayAndRefresh(ctx);
221
+ });
142
222
 
143
- pi.on("session_tree", async (_event, ctx) => replayAndRefresh(ctx));
223
+ pi.on("session_tree", async (_event, ctx) => {
224
+ await replayAndRefresh(ctx);
225
+ });
144
226
 
145
227
  pi.on("session_shutdown", async (_event, ctx) => {
146
228
  // Best-effort sid: disposal can race a stale ctx (like compact). An
@@ -159,6 +241,10 @@ export default function (pi: ExtensionAPI) {
159
241
  // dispose the foreground's overlay. Only the foreground's own shutdown
160
242
  // (or an unknown/stale sid) tears it down and clears the pointer.
161
243
  if (s === "" || s === getActiveRenderSession()) {
244
+ // Invalidate pending imports before clearing the foreground binding so a
245
+ // replaced session cannot inherit the stale overlay or UI context.
246
+ lifecycleGeneration++;
247
+ uiCtx = undefined;
162
248
  // `dispose()`'s first act is setWidget(KEY, undefined) on a possibly-stale
163
249
  // ui proxy, which can throw. evictSession(s) above already deleted this
164
250
  // slot, so leaving `activeRenderSession` pointing at it would resolve
@@ -177,9 +263,27 @@ export default function (pi: ExtensionAPI) {
177
263
  // (branch is stale — message_end runs after tool_execution_end).
178
264
  pi.on("tool_execution_end", async (event) => {
179
265
  if (event.toolName !== TOOL_NAME || event.isError) return;
180
- todoOverlay?.update();
266
+ try {
267
+ await updateTodoOverlay();
268
+ } catch (e) {
269
+ // The tool itself succeeded — a transient overlay-load failure only
270
+ // costs this one refresh, and the loader's cleared memo lets the next
271
+ // update retry. Don't surface that as an extension error. The latched
272
+ // stale-namespace error still propagates: it never self-heals, and the
273
+ // user needs its restart guidance.
274
+ if (isStaleOverlayModuleError(e)) throw e;
275
+ console.warn(`[rpiv-todo] overlay refresh failed (will retry on next update): ${formatError(e)}`);
276
+ }
181
277
  });
182
278
 
279
+ // Evaluate the lazy graph after startup while Pi's boot-time dependency paths
280
+ // are still stable. This loads no widget and constructs no overlay; those stay
281
+ // deferred until a foreground session has visible tasks. A rejected pre-warm
282
+ // is intentionally swallowed after loadTodoOverlay clears its memo, allowing
283
+ // the first real update to retry. unref avoids holding an embedder open.
284
+ const prewarmTimer = setTimeout(() => void loadTodoOverlay().catch(() => undefined), PREWARM_DELAY_MS);
285
+ prewarmTimer.unref?.();
286
+
183
287
  pi.on("agent_start", async () => {
184
288
  todoOverlay?.hideCompletedTasksFromPreviousTurn();
185
289
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-todo",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "description": "Pi extension. A todo list for the model, rendered as a live overlay that survives /reload and conversation compaction.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -67,7 +67,7 @@
67
67
  }
68
68
  },
69
69
  "dependencies": {
70
- "@juicesharp/rpiv-config": "^2.1.0",
70
+ "@juicesharp/rpiv-config": "^2.3.0",
71
71
  "typebox": "^1.1.24"
72
72
  }
73
73
  }
@@ -121,7 +121,11 @@ export function applyTaskMutation(state: TaskState, action: TaskAction, params:
121
121
  params.metadata !== undefined ||
122
122
  (params.addBlockedBy && params.addBlockedBy.length > 0) ||
123
123
  (params.removeBlockedBy && params.removeBlockedBy.length > 0);
124
- if (!hasMutation) return errorResult(state, "update requires at least one mutable field");
124
+ if (!hasMutation)
125
+ return errorResult(
126
+ state,
127
+ "update requires at least one mutable field: subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy",
128
+ );
125
129
 
126
130
  let newStatus = current.status;
127
131
  if (params.status !== undefined) {
package/state/store.ts CHANGED
@@ -13,9 +13,9 @@ const sessions = new Map<string, TaskState>();
13
13
 
14
14
  /**
15
15
  * Ctx-less render pointer: which slot do the ctx-free readers (the overlay's
16
- * `getSnapshot()`, the tool's `renderCall()`) render? Set once at overlay
17
- * creation by the session that first built the overlay (creator-ownership —
18
- * see `index.ts`). A *distinct* concept from the three task-state mutation
16
+ * `getSnapshot()`, the tool's `renderCall()`) render? Set when the first UI
17
+ * session claims the foreground, before the overlay is loaded (creator-ownership
18
+ * — see `index.ts`). A *distinct* concept from the three task-state mutation
19
19
  * seams; it is not a 4th writer of task state.
20
20
  */
21
21
  let activeRenderSession = "";
@@ -91,7 +91,7 @@ export function getRenderState(): TaskState {
91
91
  return slotFor(activeRenderSession);
92
92
  }
93
93
 
94
- /** Set the ctx-less render pointer (called at overlay creation in `index.ts`). */
94
+ /** Set the ctx-less render pointer when the first UI session claims foreground. */
95
95
  export function setActiveRenderSession(sessionId: string): void {
96
96
  activeRenderSession = sessionId;
97
97
  }
package/todo.ts CHANGED
@@ -58,6 +58,7 @@ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
58
58
  "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.",
59
59
  "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.",
60
60
  "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.",
61
+ '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.',
61
62
  "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.",
62
63
  "list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
63
64
  "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.",
package/tool/types.ts CHANGED
@@ -89,7 +89,8 @@ export const TodoParamsSchema = Type.Object({
89
89
  ),
90
90
  status: Type.Optional(
91
91
  StringEnum(["pending", "in_progress", "completed", "deleted"] as const, {
92
- description: "Target status (update) or list filter (list)",
92
+ description:
93
+ "Set this task's status (update): one of pending, in_progress, completed, deleted. When action is list, filters returned tasks by this status.",
93
94
  }),
94
95
  ),
95
96
  blockedBy: Type.Optional(