@phi-code-admin/phi-code 0.82.3 → 0.84.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/docs/usage.md +1 -1
  3. package/extensions/phi/btw/LICENSE +21 -0
  4. package/extensions/phi/btw/btw-ui.ts +238 -0
  5. package/extensions/phi/btw/btw.ts +363 -0
  6. package/extensions/phi/btw/index.ts +17 -0
  7. package/extensions/phi/btw/prompts/btw-system.txt +9 -0
  8. package/extensions/phi/chrome/LICENSE +21 -0
  9. package/extensions/phi/chrome/browser-extension/manifest.json +26 -0
  10. package/extensions/phi/chrome/browser-extension/service_worker.js +2388 -0
  11. package/extensions/phi/chrome/browser-extension/snapshot_injected.js +677 -0
  12. package/extensions/phi/chrome/index.ts +1799 -0
  13. package/extensions/phi/goal/LICENSE +21 -0
  14. package/extensions/phi/goal/index.ts +784 -0
  15. package/extensions/phi/mcp/LICENSE +21 -0
  16. package/extensions/phi/mcp/callback-server.ts +263 -0
  17. package/extensions/phi/mcp/config.ts +195 -0
  18. package/extensions/phi/mcp/errors.ts +35 -0
  19. package/extensions/phi/mcp/index.ts +376 -0
  20. package/extensions/phi/mcp/oauth-provider.ts +367 -0
  21. package/extensions/phi/mcp/server-manager.ts +464 -0
  22. package/extensions/phi/mcp/tool-bridge.ts +494 -0
  23. package/extensions/phi/todo/LICENSE +21 -0
  24. package/extensions/phi/todo/config.ts +14 -0
  25. package/extensions/phi/todo/index.ts +113 -0
  26. package/extensions/phi/todo/locales/de.json +17 -0
  27. package/extensions/phi/todo/locales/en.json +15 -0
  28. package/extensions/phi/todo/locales/es.json +17 -0
  29. package/extensions/phi/todo/locales/fr.json +17 -0
  30. package/extensions/phi/todo/locales/pt-BR.json +17 -0
  31. package/extensions/phi/todo/locales/pt.json +17 -0
  32. package/extensions/phi/todo/locales/ru.json +17 -0
  33. package/extensions/phi/todo/locales/uk.json +17 -0
  34. package/extensions/phi/todo/rpiv-config/config.ts +223 -0
  35. package/extensions/phi/todo/rpiv-config/index.ts +12 -0
  36. package/extensions/phi/todo/state/i18n-bridge.ts +65 -0
  37. package/extensions/phi/todo/state/invariants.ts +20 -0
  38. package/extensions/phi/todo/state/replay.ts +38 -0
  39. package/extensions/phi/todo/state/selectors.ts +107 -0
  40. package/extensions/phi/todo/state/state-reducer.ts +187 -0
  41. package/extensions/phi/todo/state/state.ts +18 -0
  42. package/extensions/phi/todo/state/store.ts +54 -0
  43. package/extensions/phi/todo/state/task-graph.ts +57 -0
  44. package/extensions/phi/todo/todo-overlay.ts +194 -0
  45. package/extensions/phi/todo/todo.ts +146 -0
  46. package/extensions/phi/todo/tool/response-envelope.ts +94 -0
  47. package/extensions/phi/todo/tool/types.ts +128 -0
  48. package/extensions/phi/todo/view/format.ts +162 -0
  49. package/package.json +4 -2
@@ -0,0 +1,17 @@
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
+
12
+ "command.no_todos": "Sin tareas aún. ¡Pídele al agente que añada algunas!",
13
+ "command.requires_interactive": "/todos requiere modo interactivo",
14
+ "command.section.pending": "── Pendientes ──",
15
+ "command.section.in_progress": "── En curso ──",
16
+ "command.section.completed": "── Completadas ──"
17
+ }
@@ -0,0 +1,17 @@
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
+
12
+ "command.no_todos": "Pas encore de tâches. Demandez à l'agent d'en ajouter !",
13
+ "command.requires_interactive": "/todos nécessite le mode interactif",
14
+ "command.section.pending": "── En attente ──",
15
+ "command.section.in_progress": "── En cours ──",
16
+ "command.section.completed": "── Terminées ──"
17
+ }
@@ -0,0 +1,17 @@
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
+
12
+ "command.no_todos": "Nenhuma tarefa ainda. Peça ao agente para adicionar algumas!",
13
+ "command.requires_interactive": "/todos requer modo interativo",
14
+ "command.section.pending": "── Pendentes ──",
15
+ "command.section.in_progress": "── Em andamento ──",
16
+ "command.section.completed": "── Concluídas ──"
17
+ }
@@ -0,0 +1,17 @@
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
+
12
+ "command.no_todos": "Sem tarefas ainda. Peça ao agente para adicionar algumas!",
13
+ "command.requires_interactive": "/todos requer modo interativo",
14
+ "command.section.pending": "── Pendentes ──",
15
+ "command.section.in_progress": "── Em curso ──",
16
+ "command.section.completed": "── Concluídas ──"
17
+ }
@@ -0,0 +1,17 @@
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
+
12
+ "command.no_todos": "Задач пока нет. Попросите агента добавить!",
13
+ "command.requires_interactive": "/todos требует интерактивного режима",
14
+ "command.section.pending": "── Ожидание ──",
15
+ "command.section.in_progress": "── В работе ──",
16
+ "command.section.completed": "── Выполнено ──"
17
+ }
@@ -0,0 +1,17 @@
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
+
12
+ "command.no_todos": "Завдань поки немає. Попросіть агента додати!",
13
+ "command.requires_interactive": "/todos потребує інтерактивного режиму",
14
+ "command.section.pending": "── Очікування ──",
15
+ "command.section.in_progress": "── У роботі ──",
16
+ "command.section.completed": "── Виконано ──"
17
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * rpiv-config — shared config I/O utilities for rpiv-mono sibling packages.
3
+ *
4
+ * Provides JSON config load/save with crash-resistant defaults, path resolution,
5
+ * guidance-field validation, env-var fallback, and TypeBox-driven schema validation.
6
+ * Stateless — no module-level singletons, no globalThis caches, no side effects.
7
+ */
8
+
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { dirname, join } from "node:path";
12
+ import { type Static, type TObject, Type } from "typebox";
13
+ import { Value } from "typebox/value";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Path resolution
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /**
20
+ * Resolve a config file path under `~/.config/<name>/`.
21
+ *
22
+ * @param name — package directory name (e.g. "rpiv-todo")
23
+ * @param file — config filename (defaults to "config.json")
24
+ * @returns absolute path to the config file
25
+ */
26
+ export function configPath(name: string, file: string = "config.json"): string {
27
+ return join(homedir(), ".config", name, file);
28
+ }
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // JSON config load — Variant A (with typeof guard) universally
32
+ // ---------------------------------------------------------------------------
33
+
34
+ /**
35
+ * Load and parse a JSON config file.
36
+ *
37
+ * Returns `{}` for missing files, malformed JSON, or non-plain-object values.
38
+ * The typeof guard fixes a latent bug where valid non-object JSON
39
+ * (e.g. `"hello"`, `42`, `null`) passes through the cast. Arrays are also
40
+ * rejected — `typeof [] === "object"` in JavaScript, but config files are
41
+ * always plain objects.
42
+ */
43
+ export function loadJsonConfig<T>(path: string): T {
44
+ if (!existsSync(path)) return {} as T;
45
+ try {
46
+ const parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
47
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {} as T;
48
+ return parsed as T;
49
+ } catch (err) {
50
+ // Diagnostic for malformed-JSON path. Silent save + silent load otherwise
51
+ // produce identical user-visible symptoms (state reverts on next start)
52
+ // with zero diagnostic surface — the user cannot tell "never saved" from
53
+ // "saved-but-unreadable." Warning is owner-only since the file lives in
54
+ // the user's HOME.
55
+ console.warn(`rpiv-config: invalid JSON at ${path}, using default ({}) — ${(err as Error).message}`);
56
+ return {} as T;
57
+ }
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // JSON config save — best-effort void
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /** File mode for config files (user read/write only). */
65
+ const CONFIG_FILE_MODE = 0o600;
66
+
67
+ /**
68
+ * Persist a config object as formatted JSON. Returns `true` on successful
69
+ * mkdir+write, `false` on filesystem failure (disk full, EACCES, EROFS, …).
70
+ *
71
+ * Every current rpiv-* save call site is user-initiated and shows a
72
+ * "Saved …" notification — callers MUST guard the success notification on
73
+ * the boolean return so a silent disk failure can't make the success message
74
+ * lie on disk-full / EACCES.
75
+ *
76
+ * The chmod step is best-effort and never affects the return value: some
77
+ * filesystems (tmpfs, network mounts, Windows-style perms) silently ignore
78
+ * chmod and there is no portable way to enforce 0600 perms across platforms.
79
+ * Callers that genuinely don't care about persistence outcome can discard
80
+ * the return — TypeScript does not warn on ignored `boolean`.
81
+ */
82
+ export function saveJsonConfig(path: string, data: unknown): boolean {
83
+ try {
84
+ mkdirSync(dirname(path), { recursive: true });
85
+ writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
86
+ } catch {
87
+ return false;
88
+ }
89
+ try {
90
+ chmodSync(path, CONFIG_FILE_MODE);
91
+ } catch {
92
+ // chmod may fail on some filesystems — best effort only, never gates success
93
+ }
94
+ return true;
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // GuidanceFields — extracted from 4 byte-identical copies
99
+ // ---------------------------------------------------------------------------
100
+
101
+ export interface GuidanceFields {
102
+ promptSnippet?: string;
103
+ promptGuidelines?: string[];
104
+ }
105
+
106
+ // TypeBox form of GuidanceFields. Mirrors the interface 1:1 — same fields,
107
+ // same optionality. `additionalProperties: true` lets consumers compose
108
+ // wrappers that may carry sibling-specific keys without those leaking back
109
+ // into rpiv-config. The runtime invariants (non-empty string, non-empty
110
+ // array of non-empty strings) are still enforced by `validateGuidanceFields`;
111
+ // the schema is a structural type-narrowing aid for callers that bake
112
+ // guidance into a larger TypeBox-validated config object.
113
+ export const GuidanceFieldsSchema = Type.Object(
114
+ {
115
+ promptSnippet: Type.Optional(Type.String()),
116
+ promptGuidelines: Type.Optional(Type.Array(Type.String())),
117
+ },
118
+ { additionalProperties: true },
119
+ );
120
+
121
+ /**
122
+ * Validate and extract guidance fields from an unknown value.
123
+ *
124
+ * Returns a clean `GuidanceFields` object with only valid entries.
125
+ * Byte-identical logic previously in rpiv-todo, rpiv-ask-user-question,
126
+ * rpiv-advisor, and rpiv-web-tools.
127
+ */
128
+ export function validateGuidanceFields(fields: unknown): GuidanceFields {
129
+ if (!fields || typeof fields !== "object") return {};
130
+ const g = fields as Record<string, unknown>;
131
+ const result: GuidanceFields = {};
132
+ if (typeof g.promptSnippet === "string" && g.promptSnippet.length > 0) {
133
+ result.promptSnippet = g.promptSnippet;
134
+ }
135
+ if (
136
+ Array.isArray(g.promptGuidelines) &&
137
+ g.promptGuidelines.length > 0 &&
138
+ g.promptGuidelines.every((s) => typeof s === "string" && s.length > 0)
139
+ ) {
140
+ result.promptGuidelines = g.promptGuidelines;
141
+ }
142
+ return result;
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // Model key codec — provider:id string ↔ { provider, modelId } object.
147
+ // ---------------------------------------------------------------------------
148
+
149
+ /**
150
+ * Parse a model key string into its components.
151
+ *
152
+ * Accepts EITHER separator on read:
153
+ * - "provider/modelId" — canonical form (emitted by modelKey and persisted
154
+ * by post-slash-canonical-migration consumers).
155
+ * - "provider:modelId" — legacy form (persisted by released rpiv-advisor
156
+ * 1.16+ before the migration). Auto-rewritten on the next save by any
157
+ * consumer that re-serialises via modelKey.
158
+ *
159
+ * Slash is preferred when present — a key like "provider:foo/bar" splits on
160
+ * `/`, so the modelId is "bar" rather than re-introducing the legacy
161
+ * interpretation. No current model id contains a `/` so this asymmetry has
162
+ * no real-world ambiguity.
163
+ */
164
+ export function parseModelKey(key: string): { provider: string; modelId: string } | undefined {
165
+ const slashIdx = key.indexOf("/");
166
+ if (slashIdx >= 1) return { provider: key.slice(0, slashIdx), modelId: key.slice(slashIdx + 1) };
167
+ const colonIdx = key.indexOf(":");
168
+ if (colonIdx >= 1) return { provider: key.slice(0, colonIdx), modelId: key.slice(colonIdx + 1) };
169
+ return undefined;
170
+ }
171
+
172
+ /**
173
+ * Compose the canonical "provider/modelId" string from provider and modelId
174
+ * components. Slash-only emission; paired with parseModelKey's tolerant read,
175
+ * legacy colon-form persisted values auto-migrate the next time any consumer
176
+ * re-serialises through this codec.
177
+ */
178
+ export function modelKey(m: { provider: string; id: string }): string {
179
+ return `${m.provider}/${m.id}`;
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // Env-var fallback
184
+ // ---------------------------------------------------------------------------
185
+
186
+ /**
187
+ * Read an environment variable with optional fallback.
188
+ *
189
+ * Trims whitespace from the env value. Returns `fallback` (or `undefined`)
190
+ * when the variable is unset or empty after trimming.
191
+ */
192
+ export function readEnvVar(key: string, fallback?: string): string | undefined {
193
+ return process.env[key]?.trim() || fallback;
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // TypeBox-driven schema validation
198
+ // ---------------------------------------------------------------------------
199
+
200
+ /**
201
+ * Validate and clean a config value against a TypeBox schema.
202
+ *
203
+ * 1. Guards against non-plain-object input (returns `{}` for primitives, arrays).
204
+ * 2. Clones the input (Value.Clean mutates).
205
+ * 3. Strips unknown properties via `Value.Clean`.
206
+ * 4. Applies schema defaults via `Value.Create` (spread merge: defaults
207
+ * provide base, cleaned value overrides).
208
+ * 5. Returns the validated, cleaned object typed as the schema's static type.
209
+ *
210
+ * Falls back to `{}` on any failure — same fail-soft contract as `loadJsonConfig`.
211
+ */
212
+ export function validateConfig<T extends TObject>(schema: T, value: unknown): Static<T> {
213
+ try {
214
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {} as Static<T>;
215
+ const cleaned = Value.Clean(schema, Value.Clone(value));
216
+ const defaults = Value.Create(schema);
217
+ // Merge: defaults as base, cleaned values override.
218
+ // Both are plain objects from TypeBox operations — safe spread via Record cast.
219
+ return { ...(defaults as Record<string, unknown>), ...(cleaned as Record<string, unknown>) } as Static<T>;
220
+ } catch {
221
+ return {} as Static<T>;
222
+ }
223
+ }
@@ -0,0 +1,12 @@
1
+ export {
2
+ configPath,
3
+ type GuidanceFields,
4
+ GuidanceFieldsSchema,
5
+ loadJsonConfig,
6
+ modelKey,
7
+ parseModelKey,
8
+ readEnvVar,
9
+ saveJsonConfig,
10
+ validateConfig,
11
+ validateGuidanceFields,
12
+ } from "./config.js";
@@ -0,0 +1,65 @@
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.js";
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 i18nSpecifier: string = "@juicesharp/rpiv-i18n";
41
+ const sdk = (await import(i18nSpecifier)) as I18nSDK;
42
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
43
+ } catch {
44
+ scopeImpl = (_key, fallback) => fallback;
45
+ }
46
+
47
+ export const t: ScopeFn = scopeImpl;
48
+
49
+ const STATUS_LABEL_PENDING = "pending";
50
+ const STATUS_LABEL_IN_PROGRESS = "in progress";
51
+ const STATUS_LABEL_COMPLETED = "completed";
52
+ const STATUS_LABEL_DELETED = "deleted";
53
+
54
+ export function formatStatusLabel(status: TaskStatus): string {
55
+ switch (status) {
56
+ case "pending":
57
+ return t("status.pending", STATUS_LABEL_PENDING);
58
+ case "in_progress":
59
+ return t("status.in_progress", STATUS_LABEL_IN_PROGRESS);
60
+ case "completed":
61
+ return t("status.completed", STATUS_LABEL_COMPLETED);
62
+ case "deleted":
63
+ return t("status.deleted", STATUS_LABEL_DELETED);
64
+ }
65
+ }
@@ -0,0 +1,20 @@
1
+ import type { TaskStatus } from "../tool/types.js";
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
+ }
@@ -0,0 +1,38 @@
1
+ import type { TaskDetails } from "../tool/types.js";
2
+ import { EMPTY_STATE, type TaskState } from "./state.js";
3
+
4
+ /**
5
+ * Discriminator for `details` envelopes that match the persisted `TaskDetails`
6
+ * shape. Defensive — branch entries from older or corrupt sessions are
7
+ * skipped silently.
8
+ */
9
+ export function isTaskDetails(value: unknown): value is TaskDetails {
10
+ if (!value || typeof value !== "object") return false;
11
+ const v = value as Record<string, unknown>;
12
+ return Array.isArray(v.tasks) && typeof v.nextId === "number";
13
+ }
14
+
15
+ /**
16
+ * Walk the current branch in chronological order; the LAST `toolResult` whose
17
+ * `toolName === "todo"` and whose `details` shape matches `TaskDetails` wins
18
+ * (last-write-wins). When no matching entry exists, returns `EMPTY_STATE`.
19
+ *
20
+ * Pure of module state — `index.ts` writes the returned snapshot into the
21
+ * store after this returns. The function explicitly does NOT touch the store
22
+ * cell.
23
+ */
24
+ export function replayFromBranch(ctx: { sessionManager: { getBranch(): Iterable<unknown> } }): TaskState {
25
+ let result: TaskState = { tasks: [...EMPTY_STATE.tasks], nextId: EMPTY_STATE.nextId };
26
+ for (const entry of ctx.sessionManager.getBranch()) {
27
+ const e = entry as { type?: string; message?: { role?: string; toolName?: string; details?: unknown } };
28
+ if (e.type !== "message") continue;
29
+ const msg = e.message;
30
+ if (msg?.role !== "toolResult" || msg.toolName !== "todo") continue;
31
+ if (!isTaskDetails(msg.details)) continue;
32
+ result = {
33
+ tasks: msg.details.tasks.map((t) => ({ ...t })),
34
+ nextId: msg.details.nextId,
35
+ };
36
+ }
37
+ return result;
38
+ }
@@ -0,0 +1,107 @@
1
+ import type { Task, TaskStatus } from "../tool/types.js";
2
+ import type { TaskState } from "./state.js";
3
+
4
+ /** Tasks excluding deleted tombstones — the canonical "what's visible". */
5
+ export function selectVisibleTasks(state: TaskState): readonly Task[] {
6
+ return state.tasks.filter((t) => t.status !== "deleted");
7
+ }
8
+
9
+ /**
10
+ * Group visible tasks by status. Iteration order at the call site uses
11
+ * (`completed`, `inProgress`, `pending`) to match the `/todos` header part
12
+ * order pinned by `todo.command.test.ts`.
13
+ */
14
+ export interface TasksByStatus {
15
+ pending: readonly Task[];
16
+ inProgress: readonly Task[];
17
+ completed: readonly Task[];
18
+ }
19
+ export function selectTasksByStatus(state: TaskState): TasksByStatus {
20
+ const visible = selectVisibleTasks(state);
21
+ return {
22
+ pending: visible.filter((t) => t.status === "pending"),
23
+ inProgress: visible.filter((t) => t.status === "in_progress"),
24
+ completed: visible.filter((t) => t.status === "completed"),
25
+ };
26
+ }
27
+
28
+ /** Total counts for the overlay heading (`Todos (n/m)`) and `/todos` header. */
29
+ export interface TodoCounts {
30
+ total: number;
31
+ pending: number;
32
+ inProgress: number;
33
+ completed: number;
34
+ }
35
+ export function selectTodoCounts(state: TaskState): TodoCounts {
36
+ const groups = selectTasksByStatus(state);
37
+ return {
38
+ total: groups.pending.length + groups.inProgress.length + groups.completed.length,
39
+ pending: groups.pending.length,
40
+ inProgress: groups.inProgress.length,
41
+ completed: groups.completed.length,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Whether any visible task carries a `blockedBy` reference. The overlay uses
47
+ * this to gate the `#id` prefix on per-task rows — without at least one
48
+ * `⛓ #N` suffix, the per-row id has no anchor.
49
+ */
50
+ export function selectShowTaskIds(state: TaskState): boolean {
51
+ return selectVisibleTasks(state).some((t) => t.blockedBy && t.blockedBy.length > 0);
52
+ }
53
+
54
+ /**
55
+ * Resolve a task's subject by id from the live state for renderCall's
56
+ * accent label. `undefined` when the id is unknown — caller falls back to
57
+ * `#id` plain rendering.
58
+ */
59
+ export function selectTaskSubjectById(state: TaskState, id: number): string | undefined {
60
+ return state.tasks.find((t) => t.id === id)?.subject;
61
+ }
62
+
63
+ /**
64
+ * Overlay layout decision. Encapsulates the "drop completed first, then
65
+ * truncate non-completed tail" rule pre-refactor lived in
66
+ * `todo-overlay.ts:144-188`. `budget` is the body-slot count (caller passes
67
+ * `MAX_WIDGET_LINES - 1` to reserve the heading row); on overflow the
68
+ * selector reserves one more slot internally for the summary row. Returns
69
+ * the visible task slice plus the overflow summary parts.
70
+ */
71
+ export interface OverlayLayout {
72
+ visible: readonly Task[];
73
+ hiddenCompleted: number;
74
+ truncatedTail: number;
75
+ }
76
+ export function selectOverlayLayout(state: TaskState, budget: number): OverlayLayout {
77
+ const all = selectVisibleTasks(state);
78
+ if (all.length <= budget) {
79
+ return { visible: all, hiddenCompleted: 0, truncatedTail: 0 };
80
+ }
81
+ const innerBudget = budget - 1;
82
+ const nonCompleted = all.filter((t) => t.status !== "completed");
83
+ const totalCompleted = all.length - nonCompleted.length;
84
+ if (nonCompleted.length <= innerBudget) {
85
+ const kept = new Set<Task>(nonCompleted);
86
+ for (const t of all) {
87
+ if (kept.size >= innerBudget) break;
88
+ if (t.status === "completed") kept.add(t);
89
+ }
90
+ const visible = all.filter((t) => kept.has(t));
91
+ const shownCompleted = visible.filter((t) => t.status === "completed").length;
92
+ return { visible, hiddenCompleted: totalCompleted - shownCompleted, truncatedTail: 0 };
93
+ }
94
+ const visible = nonCompleted.slice(0, innerBudget);
95
+ const truncatedTail = nonCompleted.length - innerBudget;
96
+ return { visible, hiddenCompleted: totalCompleted, truncatedTail };
97
+ }
98
+
99
+ /**
100
+ * Helper: whether any visible task is `pending` or `in_progress`. The overlay
101
+ * uses this to pick the heading icon (`accent`+`●` vs `dim`+`○`).
102
+ */
103
+ export function selectHasActive(state: TaskState): boolean {
104
+ return selectVisibleTasks(state).some((t) => t.status === "in_progress" || t.status === "pending");
105
+ }
106
+
107
+ export const ACTIVE_STATUSES: ReadonlySet<TaskStatus> = new Set(["pending", "in_progress"]);