@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/index.ts ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * rpiv-todo — Pi extension. Registers the `todo` tool, `/todos` slash
3
+ * command, and the persistent TodoOverlay widget.
4
+ *
5
+ * TUI chrome strings localize at render time via the i18n bridge. Strings are
6
+ * registered with rpiv-i18n here, once, at module init — but only when the
7
+ * SDK is actually installed. If `@juicesharp/rpiv-i18n` is missing (standalone
8
+ * install of just this package), the dynamic-load shim no-ops and the bridge's
9
+ * `t(key, fallback)` returns the inline English literal at every call site.
10
+ * The extension stays online either way.
11
+ *
12
+ * Adding a locale: drop `locales/<code>.json` next to en.json (mirroring the
13
+ * key set). No edit needed here — `registerLocalesFromDir` iterates
14
+ * `SUPPORTED_LOCALES` from the SDK. See `@juicesharp/rpiv-i18n` README →
15
+ * "Contributing translations" for the full convention.
16
+ *
17
+ * Extracted from rpiv-pi@7525a5d. Tool name "todo" and widget key
18
+ * "rpiv-todos" preserved verbatim so existing session history replays
19
+ * correctly after upgrade.
20
+ */
21
+
22
+ import type { ExtensionAPI, ExtensionUIContext } from "@earendil-works/pi-coding-agent";
23
+ import type { KeyId } from "@earendil-works/pi-tui";
24
+ import { COLLAPSE_KEY_OFF, resolveCollapseKey } from "./config.ts";
25
+ import { I18N_NAMESPACE } from "./state/i18n-bridge.ts";
26
+ import { replayFromBranch } from "./state/replay.ts";
27
+ import {
28
+ clearActiveRenderSession,
29
+ evictSession,
30
+ getActiveRenderSession,
31
+ getRenderState,
32
+ replaceState,
33
+ setActiveRenderSession,
34
+ sid,
35
+ } from "./state/store.ts";
36
+ import { registerTodosCommand, registerTodoTool, TOOL_NAME } from "./todo.ts";
37
+ import type { TodoOverlay } from "./todo-overlay.ts";
38
+
39
+ type I18nLoader = {
40
+ registerLocalesFromDir: (
41
+ namespace: string,
42
+ packageUrl: string,
43
+ options?: { label?: string },
44
+ ) => void;
45
+ };
46
+
47
+ /** Delay the overlay graph pre-warm until Pi's startup work has settled. */
48
+ export const PREWARM_DELAY_MS = 2000;
49
+
50
+ type TodoOverlayModule = typeof import("./todo-overlay.ts");
51
+ type TodoOverlayImporter = () => Promise<TodoOverlayModule>;
52
+
53
+ /**
54
+ * Marker shared by the loader's poisoned-namespace error and the
55
+ * `isStaleOverlayModuleError` predicate that lets handlers re-throw it while
56
+ * swallowing transient load failures.
57
+ */
58
+ const STALE_OVERLAY_MESSAGE = "Todo overlay module cache is stale; restart Pi";
59
+
60
+ /** True for the loader's latched poisoned-namespace error (see below). */
61
+ export function isStaleOverlayModuleError(e: unknown): boolean {
62
+ return String(e).includes(STALE_OVERLAY_MESSAGE);
63
+ }
64
+
65
+ /**
66
+ * Memoize the overlay graph after a successful load, but drop a rejected
67
+ * promise so a failed pre-warm does not permanently replay the same rejection.
68
+ * The export guard turns jiti's poisoned-namespace failure into a useful restart
69
+ * error instead of a bare "TodoOverlay is not a constructor" TypeError.
70
+ */
71
+ export function makeTodoOverlayLoader(
72
+ importOverlay: TodoOverlayImporter = () => import("./todo-overlay.ts"),
73
+ ): TodoOverlayImporter {
74
+ let memo: Promise<TodoOverlayModule> | undefined;
75
+
76
+ return async (): Promise<TodoOverlayModule> => {
77
+ memo ??= importOverlay();
78
+ const current = memo;
79
+ let mod: TodoOverlayModule;
80
+ try {
81
+ mod = await current;
82
+ } catch (error) {
83
+ // Clear only OUR rejected promise: a late catch from a concurrent
84
+ // awaiter must never clobber a fresh retry another caller installed.
85
+ if (memo === current) memo = undefined;
86
+ throw error;
87
+ }
88
+ if (typeof mod.TodoOverlay !== "function") {
89
+ // Deliberately latched: the memo keeps this resolved-but-poisoned
90
+ // namespace, so every subsequent load re-throws instead of retrying.
91
+ // Re-importing would hand back the same cached jiti namespace — a
92
+ // retry can never heal this; only the restart the error asks for can.
93
+ const keys = JSON.stringify(Object.keys(mod));
94
+ throw new Error(`${STALE_OVERLAY_MESSAGE} (resolved namespace keys: ${keys})`);
95
+ }
96
+ return mod;
97
+ };
98
+ }
99
+
100
+ // Dynamic import keeps `@juicesharp/rpiv-i18n` a soft optional peer: when the
101
+ // SDK is installed alongside this package the strings register and
102
+ // `/languages` flips them live; when it isn't, the import rejects here, we
103
+ // no-op, and the bridge's English-fallback shim keeps the extension online.
104
+ //
105
+ // The `/loader` subpath is used instead of the SDK entry so the i18n-ui +
106
+ // pi-tui modules are not pulled into our load graph just to register strings.
107
+ try {
108
+ const sdk = (await import("@juicesharp/rpiv-i18n/loader")) as I18nLoader;
109
+ sdk.registerLocalesFromDir(I18N_NAMESPACE, import.meta.url, { label: "rpiv-todo" });
110
+ } catch {
111
+ // SDK absent — extension still loads with English-only UI.
112
+ }
113
+
114
+ // pi-core's ExtensionRunner throws this exact phrase from an invalidated ctx
115
+ // proxy after session replacement/reload. Match the stable substring so genuine
116
+ // replay bugs still propagate instead of being silently swallowed.
117
+ function isStaleCtxError(e: unknown): boolean {
118
+ return /stale after session replacement/.test(String(e));
119
+ }
120
+
121
+ /**
122
+ * Render a caught `unknown` as a human-readable message — the `instanceof Error`
123
+ * dance collapsed to one place. Local copy of the `formatError` in
124
+ * packages/rpiv-workflow/internal-utils.ts:56-58 (that module disclaims its
125
+ * public surface, so the cross-package import is not available). M2 boundary
126
+ * duplication: tracked as a documented-constant seam.
127
+ */
128
+ function formatError(e: unknown): string {
129
+ return e instanceof Error ? e.message : String(e);
130
+ }
131
+
132
+ export default function (
133
+ pi: ExtensionAPI,
134
+ importOverlay: TodoOverlayImporter = () => import("./todo-overlay.ts"),
135
+ ) {
136
+ let todoOverlay: TodoOverlay | undefined;
137
+ const loadTodoOverlay = makeTodoOverlayLoader(importOverlay);
138
+ let uiCtx: ExtensionUIContext | undefined;
139
+ let lifecycleGeneration = 0;
140
+
141
+ async function updateTodoOverlay(
142
+ resetCompletedDisplayState = false,
143
+ generation = lifecycleGeneration,
144
+ ): Promise<void> {
145
+ const hasVisibleTasks = getRenderState().tasks.some((task) => task.status !== "deleted");
146
+ if (!uiCtx || (!todoOverlay && !hasVisibleTasks)) return;
147
+
148
+ const { TodoOverlay } = await loadTodoOverlay();
149
+ if (generation !== lifecycleGeneration || !uiCtx) return;
150
+
151
+ todoOverlay ??= new TodoOverlay();
152
+ todoOverlay.setUICtx(uiCtx);
153
+ if (resetCompletedDisplayState) todoOverlay.resetCompletedDisplayState();
154
+ todoOverlay.update();
155
+ }
156
+
157
+ registerTodoTool(pi);
158
+ registerTodosCommand(pi);
159
+
160
+ // Collapse/expand hotkey for the todo overlay. The key is resolved once at
161
+ // factory scope from config (register-once contract: a config change needs
162
+ // `/reload` to re-bind, same as lane-switcher's env hotkey) and the binding is
163
+ // skipped entirely when collapseKey is "off". The handler closes over the
164
+ // closure-local `todoOverlay` by reference and re-reads it at fire time, so an
165
+ // overlay loaded after shortcut registration is picked up. No-op in headless
166
+ // mode, before the overlay has loaded, or when the widget isn't currently
167
+ // registered (auto-hidden on an empty list).
168
+ const collapseKey = resolveCollapseKey();
169
+ if (collapseKey !== COLLAPSE_KEY_OFF) {
170
+ pi.registerShortcut(collapseKey as KeyId, {
171
+ description: "Collapse or expand the todo overlay",
172
+ handler: (ctx) => {
173
+ if (!ctx.hasUI || !todoOverlay?.isRegistered()) return;
174
+ todoOverlay.toggleCollapse();
175
+ },
176
+ });
177
+ }
178
+
179
+ // Re-key a session's slot from its branch, then refresh the overlay only when
180
+ // the refreshed session IS the foreground. Shared by session_compact and
181
+ // session_tree (verbatim-identical pre-extraction). A stale ctx (auto-compaction
182
+ // races session disposal: pi-core invalidates the runner while still emitting the
183
+ // event, so `ctx` may be a dead proxy whose getters throw) keeps current state —
184
+ // the replacement session's session_start replays it. Other errors are real replay
185
+ // bugs and must propagate. The render is sid-gated so a child never refreshes the
186
+ // foreground overlay.
187
+ const replayAndRefresh = async (
188
+ ctx: Parameters<typeof sid>[0] & Parameters<typeof replayFromBranch>[0],
189
+ ): Promise<void> => {
190
+ let isForeground = false;
191
+ try {
192
+ const id = sid(ctx);
193
+ replaceState(id, replayFromBranch(ctx));
194
+ isForeground = id === getActiveRenderSession();
195
+ } catch (e) {
196
+ if (!isStaleCtxError(e)) throw e;
197
+ }
198
+ if (isForeground) await updateTodoOverlay(true);
199
+ };
200
+
201
+ pi.on("session_start", async (_event, ctx) => {
202
+ let id: string;
203
+ try {
204
+ id = sid(ctx);
205
+ // Every session replays into its OWN data slot (Phase 1 isolation).
206
+ replaceState(id, replayFromBranch(ctx));
207
+ } catch (e) {
208
+ // Parity with compact/tree/shutdown: session_start is the fresh-ctx event
209
+ // so the stale risk is low, but a stale/throwing ctx has nothing to bind —
210
+ // swallow the known stale error and bail; let real replay bugs propagate.
211
+ if (!isStaleCtxError(e)) throw e;
212
+ return;
213
+ }
214
+ if (!ctx.hasUI) return;
215
+ // First UI-bearing session_start claims the foreground (the interactive
216
+ // launcher, by spawn-ordering) without eagerly loading the overlay.
217
+ if (getActiveRenderSession() === "") setActiveRenderSession(id);
218
+ // Only the foreground re-binds/refreshes the shared overlay. A child
219
+ // (distinct sid) is skipped — does not rebind to a relay/stale ui.
220
+ if (id !== getActiveRenderSession()) return;
221
+ const generation = ++lifecycleGeneration;
222
+ uiCtx = ctx.ui;
223
+ await updateTodoOverlay(true, generation);
224
+ });
225
+
226
+ pi.on("session_compact", async (_event, ctx) => {
227
+ await replayAndRefresh(ctx);
228
+ });
229
+
230
+ pi.on("session_tree", async (_event, ctx) => {
231
+ await replayAndRefresh(ctx);
232
+ });
233
+
234
+ pi.on("session_shutdown", async (_event, ctx) => {
235
+ // Best-effort sid: disposal can race a stale ctx (like compact). An
236
+ // unknown/stale sid resolves to "" and is treated as foreground — the
237
+ // safe pre-isolation default that disposes as before.
238
+ let s: string;
239
+ try {
240
+ s = sid(ctx);
241
+ } catch (e) {
242
+ if (!isStaleCtxError(e)) throw e;
243
+ s = "";
244
+ }
245
+ // The shutting-down session's own data slot is always evicted.
246
+ evictSession(s);
247
+ // Overlay teardown is sid-gated: a child shutdown (distinct sid) must not
248
+ // dispose the foreground's overlay. Only the foreground's own shutdown
249
+ // (or an unknown/stale sid) tears it down and clears the pointer.
250
+ if (s === "" || s === getActiveRenderSession()) {
251
+ // Invalidate pending imports before clearing the foreground binding so a
252
+ // replaced session cannot inherit the stale overlay or UI context.
253
+ lifecycleGeneration++;
254
+ uiCtx = undefined;
255
+ // `dispose()`'s first act is setWidget(KEY, undefined) on a possibly-stale
256
+ // ui proxy, which can throw. evictSession(s) above already deleted this
257
+ // slot, so leaving `activeRenderSession` pointing at it would resolve
258
+ // getRenderState() to a fresh EMPTY_STATE (overlay silently renders empty).
259
+ // try/finally guarantees the pointer-clear + overlay-drop run regardless.
260
+ try {
261
+ todoOverlay?.dispose();
262
+ } finally {
263
+ todoOverlay = undefined;
264
+ clearActiveRenderSession();
265
+ }
266
+ }
267
+ });
268
+
269
+ // Reads getTodos() at render time; do NOT call replayFromBranch here
270
+ // (branch is stale — message_end runs after tool_execution_end).
271
+ pi.on("tool_execution_end", async (event) => {
272
+ if (event.toolName !== TOOL_NAME || event.isError) return;
273
+ try {
274
+ await updateTodoOverlay();
275
+ } catch (e) {
276
+ // The tool itself succeeded — a transient overlay-load failure only
277
+ // costs this one refresh, and the loader's cleared memo lets the next
278
+ // update retry. Don't surface that as an extension error. The latched
279
+ // stale-namespace error still propagates: it never self-heals, and the
280
+ // user needs its restart guidance.
281
+ if (isStaleOverlayModuleError(e)) throw e;
282
+ console.warn(
283
+ `[rpiv-todo] overlay refresh failed (will retry on next update): ${formatError(e)}`,
284
+ );
285
+ }
286
+ });
287
+
288
+ // Evaluate the lazy graph after startup while Pi's boot-time dependency paths
289
+ // are still stable. This loads no widget and constructs no overlay; those stay
290
+ // deferred until a foreground session has visible tasks. A rejected pre-warm
291
+ // is intentionally swallowed after loadTodoOverlay clears its memo, allowing
292
+ // the first real update to retry. unref avoids holding an embedder open.
293
+ const prewarmTimer = setTimeout(
294
+ () => void loadTodoOverlay().catch(() => undefined),
295
+ PREWARM_DELAY_MS,
296
+ );
297
+ prewarmTimer.unref?.();
298
+
299
+ pi.on("agent_start", async () => {
300
+ todoOverlay?.hideCompletedTasksFromPreviousTurn();
301
+ });
302
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated. Note: 'overlay.more' renders as '+5 weitere' which is grammatically loose for plural agreement — accepted for badge brevity.",
3
+
4
+ "status.pending": "ausstehend",
5
+ "status.in_progress": "in Bearbeitung",
6
+ "status.completed": "erledigt",
7
+ "status.deleted": "gelöscht",
8
+
9
+ "overlay.heading": "Todos",
10
+ "overlay.more": "weitere",
11
+ "overlay.expandHint": "{key} zum Ausklappen",
12
+ "overlay.collapsed": "eingeklappt",
13
+
14
+ "command.no_todos": "Noch keine Todos. Bitte den Agenten, welche hinzuzufügen!",
15
+ "command.requires_interactive": "/todos erfordert den interaktiven Modus",
16
+ "command.section.pending": "── Ausstehend ──",
17
+ "command.section.in_progress": "── In Bearbeitung ──",
18
+ "command.section.completed": "── Erledigt ──"
19
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "status.pending": "pending",
3
+ "status.in_progress": "in progress",
4
+ "status.completed": "completed",
5
+ "status.deleted": "deleted",
6
+
7
+ "overlay.heading": "Todos",
8
+ "overlay.more": "more",
9
+ "overlay.expandHint": "{key} to expand",
10
+ "overlay.collapsed": "collapsed",
11
+
12
+ "command.no_todos": "No todos yet. Ask the agent to add some!",
13
+ "command.requires_interactive": "/todos requires interactive mode",
14
+ "command.section.pending": "── Pending ──",
15
+ "command.section.in_progress": "── In Progress ──",
16
+ "command.section.completed": "── Completed ──"
17
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "pendientes",
5
+ "status.in_progress": "en curso",
6
+ "status.completed": "completadas",
7
+ "status.deleted": "eliminada",
8
+
9
+ "overlay.heading": "Tareas",
10
+ "overlay.more": "más",
11
+ "overlay.expandHint": "{key} para expandir",
12
+ "overlay.collapsed": "contraído",
13
+
14
+ "command.no_todos": "Sin tareas aún. ¡Pídele al agente que añada algunas!",
15
+ "command.requires_interactive": "/todos requiere modo interactivo",
16
+ "command.section.pending": "── Pendientes ──",
17
+ "command.section.in_progress": "── En curso ──",
18
+ "command.section.completed": "── Completadas ──"
19
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "en attente",
5
+ "status.in_progress": "en cours",
6
+ "status.completed": "terminées",
7
+ "status.deleted": "supprimée",
8
+
9
+ "overlay.heading": "Tâches",
10
+ "overlay.more": "autres",
11
+ "overlay.expandHint": "{key} pour développer",
12
+ "overlay.collapsed": "réduit",
13
+
14
+ "command.no_todos": "Pas encore de tâches. Demandez à l'agent d'en ajouter !",
15
+ "command.requires_interactive": "/todos nécessite le mode interactif",
16
+ "command.section.pending": "── En attente ──",
17
+ "command.section.in_progress": "── En cours ──",
18
+ "command.section.completed": "── Terminées ──"
19
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "pendentes",
5
+ "status.in_progress": "em andamento",
6
+ "status.completed": "concluídas",
7
+ "status.deleted": "excluída",
8
+
9
+ "overlay.heading": "Tarefas",
10
+ "overlay.more": "mais",
11
+ "overlay.expandHint": "{key} para expandir",
12
+ "overlay.collapsed": "recolhido",
13
+
14
+ "command.no_todos": "Nenhuma tarefa ainda. Peça ao agente para adicionar algumas!",
15
+ "command.requires_interactive": "/todos requer modo interativo",
16
+ "command.section.pending": "── Pendentes ──",
17
+ "command.section.in_progress": "── Em andamento ──",
18
+ "command.section.completed": "── Concluídas ──"
19
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Auto-translated draft. Native-speaker review welcome via PR. Unicode box-drawing characters (──) stay untranslated.",
3
+
4
+ "status.pending": "pendentes",
5
+ "status.in_progress": "em curso",
6
+ "status.completed": "concluídas",
7
+ "status.deleted": "eliminada",
8
+
9
+ "overlay.heading": "Tarefas",
10
+ "overlay.more": "mais",
11
+ "overlay.expandHint": "{key} para expandir",
12
+ "overlay.collapsed": "recolhido",
13
+
14
+ "command.no_todos": "Sem tarefas ainda. Peça ao agente para adicionar algumas!",
15
+ "command.requires_interactive": "/todos requer modo interativo",
16
+ "command.section.pending": "── Pendentes ──",
17
+ "command.section.in_progress": "── Em curso ──",
18
+ "command.section.completed": "── Concluídas ──"
19
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Автоперевод. Приветствуется проверка носителем языка через PR. Символы юникода (──) не переводятся.",
3
+
4
+ "status.pending": "ожидание",
5
+ "status.in_progress": "в работе",
6
+ "status.completed": "выполнено",
7
+ "status.deleted": "удалена",
8
+
9
+ "overlay.heading": "Задачи",
10
+ "overlay.more": "ещё",
11
+ "overlay.expandHint": "{key} — развернуть",
12
+ "overlay.collapsed": "свёрнуто",
13
+
14
+ "command.no_todos": "Задач пока нет. Попросите агента добавить!",
15
+ "command.requires_interactive": "/todos требует интерактивного режима",
16
+ "command.section.pending": "── Ожидание ──",
17
+ "command.section.in_progress": "── В работе ──",
18
+ "command.section.completed": "── Выполнено ──"
19
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "Автопереклад. Привітна перевірка носієм мови через PR. Символи юнікоду (──) не перекладаються.",
3
+
4
+ "status.pending": "очікування",
5
+ "status.in_progress": "у роботі",
6
+ "status.completed": "виконано",
7
+ "status.deleted": "видалено",
8
+
9
+ "overlay.heading": "Завдання",
10
+ "overlay.more": "ще",
11
+ "overlay.expandHint": "{key} — розгорнути",
12
+ "overlay.collapsed": "згорнуто",
13
+
14
+ "command.no_todos": "Завдань поки немає. Попросіть агента додати!",
15
+ "command.requires_interactive": "/todos потребує інтерактивного режиму",
16
+ "command.section.pending": "── Очікування ──",
17
+ "command.section.in_progress": "── У роботі ──",
18
+ "command.section.completed": "── Виконано ──"
19
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "中文翻译。欢迎中文母语者通过 PR 审校。",
3
+
4
+ "status.pending": "待处理",
5
+ "status.in_progress": "进行中",
6
+ "status.completed": "已完成",
7
+ "status.deleted": "已删除",
8
+
9
+ "overlay.heading": "任务清单",
10
+ "overlay.more": "更多",
11
+ "overlay.expandHint": "按 {key} 展开",
12
+ "overlay.collapsed": "已折叠",
13
+
14
+ "command.no_todos": "暂无任务。可以让 agent 添加一些!",
15
+ "command.requires_interactive": "/todos 需要交互模式",
16
+ "command.section.pending": "── 待处理 ──",
17
+ "command.section.in_progress": "── 进行中 ──",
18
+ "command.section.completed": "── 已完成 ──"
19
+ }
package/package.json CHANGED
@@ -1,19 +1,89 @@
1
1
  {
2
2
  "name": "@indexyz/pi-todo",
3
- "version": "0.0.0",
4
- "description": "Bootstrap placeholder for configuring npm trusted publishing",
3
+ "version": "0.1.0",
4
+ "description": "A Pi todo tool and live task overlay with compact session persistence",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "task-list",
9
+ "todo"
10
+ ],
11
+ "homepage": "https://github.com/5aaee9/pi-agent-extensions/tree/main/pi-todo#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/5aaee9/pi-agent-extensions/issues"
14
+ },
5
15
  "license": "MIT",
16
+ "author": "5aaee9",
6
17
  "repository": {
7
18
  "type": "git",
8
19
  "url": "git+https://github.com/5aaee9/pi-agent-extensions.git",
9
20
  "directory": "pi-todo"
10
21
  },
11
- "publishConfig": {
12
- "access": "public",
13
- "tag": "bootstrap"
14
- },
15
22
  "files": [
23
+ "config.ts",
24
+ "index.ts",
25
+ "locales/",
26
+ "todo.ts",
27
+ "todo-overlay.ts",
28
+ "LICENSE",
29
+ "docs/configuration.md",
30
+ "docs/overlay.md",
31
+ "docs/tool-schema.md",
16
32
  "README.md",
17
- "LICENSE"
18
- ]
33
+ "CHANGELOG.md",
34
+ "state/invariants.ts",
35
+ "state/i18n-bridge.ts",
36
+ "state/replay.ts",
37
+ "state/selectors.ts",
38
+ "state/state-reducer.ts",
39
+ "state/state.ts",
40
+ "state/store.ts",
41
+ "state/task-graph.ts",
42
+ "tool/normalize-params.ts",
43
+ "tool/response-envelope.ts",
44
+ "tool/sanitize.ts",
45
+ "tool/types.ts",
46
+ "view/format.ts"
47
+ ],
48
+ "type": "module",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "test": "vitest run",
54
+ "test:watch": "vitest",
55
+ "typecheck": "tsc --noEmit",
56
+ "check": "npm run typecheck && npm test",
57
+ "prepack": "npm run check"
58
+ },
59
+ "devDependencies": {
60
+ "@earendil-works/pi-ai": "1.5.0",
61
+ "@earendil-works/pi-coding-agent": "1.5.0",
62
+ "@earendil-works/pi-tui": "1.5.0",
63
+ "@juicesharp/rpiv-i18n": "2.15.0",
64
+ "@types/node": "^24.0.0",
65
+ "typebox": "1.3.7",
66
+ "typescript": "^7.0.2",
67
+ "vitest": "^4.1.10"
68
+ },
69
+ "peerDependencies": {
70
+ "@earendil-works/pi-ai": "*",
71
+ "@earendil-works/pi-coding-agent": "*",
72
+ "@earendil-works/pi-tui": "*",
73
+ "@juicesharp/rpiv-i18n": "*",
74
+ "typebox": "*"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@juicesharp/rpiv-i18n": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "engines": {
82
+ "node": ">=22.19.0"
83
+ },
84
+ "pi": {
85
+ "extensions": [
86
+ "./index.ts"
87
+ ]
88
+ }
19
89
  }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * i18n bridge for rpiv-todo — single thin import surface so every call site
3
+ * routes through one module. Backed by `@juicesharp/rpiv-i18n`'s SDK when
4
+ * available; degrades to canonical-English fallbacks when not.
5
+ *
6
+ * - `t(key, fallback)` is `scope("@juicesharp/rpiv-todo")` if the SDK is
7
+ * installed (live `/languages` updates propagate). If the SDK is missing
8
+ * (standalone install without rpiv-i18n), `t` is an identity passthrough
9
+ * that returns the inline English fallback at every call site, so the
10
+ * extension stays online with English UI.
11
+ * - `formatStatusLabel(status)` resolves a TaskStatus to its locale-aware
12
+ * label via the canonical `status.*` namespace, with the English literal
13
+ * as fallback so nothing renders blank if the namespace isn't registered.
14
+ * This is the SINGLE point of localization for status words — overlay,
15
+ * /todos header, /todos render-call all route through here.
16
+ *
17
+ * Strings are registered ONCE at extension load (see ../index.ts). Call sites
18
+ * MUST use this module at render time — never bake the result into a top-level
19
+ * `const X = formatStatusLabel(...)`.
20
+ */
21
+
22
+ import type { TaskStatus } from "../tool/types.ts";
23
+
24
+ export const I18N_NAMESPACE = "@juicesharp/rpiv-todo";
25
+
26
+ type ScopeFn = (key: string, fallback: string) => string;
27
+ type I18nSDK = { scope: (namespace: string) => ScopeFn };
28
+
29
+ // Prefer the live SDK if installed: closures it returns track the active
30
+ // locale, so /languages picker propagates to our render call sites. If the
31
+ // SDK isn't installed (standalone install of this extension without
32
+ // rpiv-i18n), the dynamic import fails, every t(key, fallback) returns the
33
+ // canonical English literal, and the extension stays online.
34
+ //
35
+ // Top-level await is required so a synchronous `t(...)` call from any
36
+ // downstream module sees the resolved scope; ESM module loading awaits this
37
+ // before evaluating any importer.
38
+ let scopeImpl: ScopeFn;
39
+ try {
40
+ const sdk = (await import("@juicesharp/rpiv-i18n")) as I18nSDK;
41
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
42
+ } catch {
43
+ scopeImpl = (_key, fallback) => fallback;
44
+ }
45
+
46
+ export const t: ScopeFn = scopeImpl;
47
+
48
+ const STATUS_LABEL_PENDING = "pending";
49
+ const STATUS_LABEL_IN_PROGRESS = "in progress";
50
+ const STATUS_LABEL_COMPLETED = "completed";
51
+ const STATUS_LABEL_DELETED = "deleted";
52
+
53
+ export function formatStatusLabel(status: TaskStatus): string {
54
+ switch (status) {
55
+ case "pending":
56
+ return t("status.pending", STATUS_LABEL_PENDING);
57
+ case "in_progress":
58
+ return t("status.in_progress", STATUS_LABEL_IN_PROGRESS);
59
+ case "completed":
60
+ return t("status.completed", STATUS_LABEL_COMPLETED);
61
+ case "deleted":
62
+ return t("status.deleted", STATUS_LABEL_DELETED);
63
+ }
64
+ }
@@ -0,0 +1,20 @@
1
+ import type { TaskStatus } from "../tool/types.ts";
2
+
3
+ /**
4
+ * Allowed forward transitions per source status. `completed` is one-way to
5
+ * `deleted` (never back to `in_progress`); `deleted` is terminal.
6
+ *
7
+ * Idempotent same→same is checked separately in `isTransitionValid` so this
8
+ * table only enumerates actual transitions.
9
+ */
10
+ export const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {
11
+ pending: new Set(["in_progress", "completed", "deleted"]),
12
+ in_progress: new Set(["pending", "completed", "deleted"]),
13
+ completed: new Set(["deleted"]),
14
+ deleted: new Set(),
15
+ };
16
+
17
+ export function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {
18
+ if (from === to) return true;
19
+ return VALID_TRANSITIONS[from].has(to);
20
+ }