repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(superpowers): harden workflow lifecycle testing

27bbf6a92123fc1b28547e71fcf23f740ae405e4

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (9)

.pi/prompts/live-extension-test.md

Added
new file mode 100644
1 +---
2 +description: Live-test a Pi extension in observable terminal/tmux with real Pi
3 +argument-hint: "<extension-or-bundle> :: <scenario/use-case>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: high
6 +---
8 +# Live Pi Extension Test
10 +Test this Pi extension/use case like a human coding-harness engineer:
12 +```text
13 +$ARGUMENTS
14 +```
16 +Mission:
18 +- Open a fresh observable terminal split/window.
19 +- In it run a dedicated tmux server with exactly one tmux session and exactly one tmux window.
20 +- Use as many panes as needed inside that one window.
21 +- Drive real interactive `pi`, with real LLM models.
22 +- Prefer default configured model for main run. Do not use mocks/fake providers unless scenario explicitly demands it.
23 +- Load only the extension under test by default. Load support extensions only when the scenario requires their real UX interaction.
24 +- Act like a human using Pi, not like a unit-test harness.
25 +- Watch for bugs, perf issues, awkward UI/UX, confusing states, bad messages, lifecycle/reload bugs, visual glitches, terminal rendering issues, browser UI issues, and model/tool behavior problems.
26 +- Probe the user's active shell before sending commands; many users run Nushell/Fish/PowerShell, not Bash.
27 +- If an extension opens HTML/browser UI, treat that browser UI as part of the product and test it with Chrome CDP or Firefox BiDi skills.
28 +- Be brutal, skeptical, and distrustful of the Pi agent under test.
29 +- Never accept the nested Pi agent's claims, status text, final answer, or self-reported verification at face value.
30 +- Keep running notes in a temp markdown file while testing.
31 +- Finish with a concise findings report and path to the notes file.
33 +## Parse Scenario
35 +Extract from `$ARGUMENTS`:
37 +- target extension(s)
38 +- support extension(s), if any
39 +- exact user workflow/use case
40 +- project/cwd to test in
41 +- success criteria
42 +- risks to watch
44 +If target is ambiguous, inspect repo structure and choose the most likely extension path. If still ambiguous, ask one focused question.
46 +## Shell Probe
48 +Before creating or driving panes, identify the user's shell and terminal environment. Do not assume Bash syntax inside tmux panes.
50 +Probe:
52 +```sh
53 +USER_SHELL="$(basename "${SHELL:-unknown}")"
54 +TERM_ENV="WEZTERM_PANE=${WEZTERM_PANE-} GHOSTTY_RESOURCES_DIR=${GHOSTTY_RESOURCES_DIR-} KITTY_WINDOW_ID=${KITTY_WINDOW_ID-} ALACRITTY_SOCKET=${ALACRITTY_SOCKET-} TERM_PROGRAM=${TERM_PROGRAM-} WT_SESSION=${WT_SESSION-}"
55 +printf 'shell=%s\n%s\n' "$USER_SHELL" "$TERM_ENV"
56 +```
58 +Shell rules:
60 +- Nushell: use `;`, not `&&`; env vars use `$env.NAME`; avoid Bash snippets in the pane.
61 +- Fish: use `;` or `and`, not Bash-only constructs.
62 +- PowerShell: use `;`; env vars use `$env:NAME`.
63 +- Bash/Zsh/Sh: `&&`, `VAR=value cmd`, and POSIX snippets are OK.
64 +- If unsure, run complex setup from the agent's `bash` tool, not by pasting Bash into the user's pane.
65 +- When sending commands to tmux panes, prefer simple one-command lines or shell-specific forms.
67 +## Observable Terminal + tmux Setup
69 +Create a dedicated tmux socket so the test environment has exactly one session/window without touching the user's existing tmux:
71 +```sh
72 +RUN_ID="pi-ext-$(date +%Y%m%d-%H%M%S)"
73 +SOCKET="$RUN_ID"
74 +SESSION="live"
75 +NOTES="/tmp/$RUN_ID-findings.md"
76 +ROOT="$PWD"
77 +USER_SHELL="$(basename "${SHELL:-unknown}")"
79 +cat > "$NOTES" <<EOF
80 +# Live Pi Extension Test
82 +- run: $RUN_ID
83 +- cwd: $ROOT
84 +- scenario: $ARGUMENTS
85 +- started: $(date -Is)
86 +- shell: $USER_SHELL
88 +## Timeline
90 +EOF
92 +tmux -L "$SOCKET" new-session -d -s "$SESSION" -n main -c "$ROOT"
93 +tmux -L "$SOCKET" split-window -h -t "$SESSION:main" -c "$ROOT"
94 +tmux -L "$SOCKET" split-window -v -t "$SESSION:main.2" -c "$ROOT"
95 +tmux -L "$SOCKET" select-pane -t "$SESSION:main.1" -T "pi interactive"
96 +tmux -L "$SOCKET" select-pane -t "$SESSION:main.2" -T "notes"
97 +tmux -L "$SOCKET" select-pane -t "$SESSION:main.3" -T "observer"
98 +tmux -L "$SOCKET" send-keys -t "$SESSION:main.2" "tail -f '$NOTES'" C-m
99 +tmux -L "$SOCKET" send-keys -t "$SESSION:main.3" "printf 'observer pane ready\\nnotes: $NOTES\\nshell: $USER_SHELL\\n'" C-m
100 +tmux -L "$SOCKET" select-pane -t "$SESSION:main.1"
102 +PANE_SHELL="$(tmux -L "$SOCKET" display-message -p -t "$SESSION:main.1" '#{pane_current_command}')"
103 +echo "pane shell: $PANE_SHELL" >> "$NOTES"
105 +tmux -L "$SOCKET" list-sessions
106 +tmux -L "$SOCKET" list-windows -t "$SESSION"
107 +```
109 +Use a shell-aware pane launch command:
111 +```sh
112 +PI_CMD="pi --no-extensions --no-skills --no-prompt-templates --no-context-files -e ./extensions/<target>/index.ts"
113 +case "$PANE_SHELL" in
114 + nu|nu.exe|fish|pwsh|powershell.exe) PANE_LAUNCH="cd '$ROOT'; $PI_CMD" ;;
115 + *) PANE_LAUNCH="cd '$ROOT' && $PI_CMD" ;;
116 +esac
118 +tmux -L "$SOCKET" send-keys -t "$SESSION:main.1" "$PANE_LAUNCH" C-m
119 +```
121 +Invariant:
123 +- `tmux -L "$SOCKET" list-sessions` shows exactly one session: `live`
124 +- `tmux -L "$SOCKET" list-windows -t live` shows exactly one window: `main`
125 +- more panes are OK; more sessions/windows are not
127 +Open/attach that tmux session in the current terminal emulator, preferring an actual split over a new OS window:
129 +1. WezTerm:
131 +```sh
132 +wezterm cli split-pane --right --cwd "$ROOT" -- tmux -L "$SOCKET" attach -t "$SESSION"
133 +```
135 +2. Ghostty / Kitty / Alacritty / GNOME Terminal / Terminal.app / Windows Terminal / other popular terminals:
137 +- Detect via env and available commands: `WEZTERM_PANE`, `GHOSTTY_*`, `KITTY_WINDOW_ID`, `ALACRITTY_*`, `TERM_PROGRAM`, `WT_SESSION`, `TMUX`, `uname`.
138 +- Use the terminal's CLI to open a split/window attached to:
140 +```sh
141 +tmux -L "$SOCKET" attach -t "$SESSION"
142 +```
144 +3. If no terminal split/window can be controlled safely:
146 +- Keep the tmux server running.
147 +- Print the exact attach command prominently.
148 +- Do not continue hidden; ask the user to attach/open it.
150 +## Start Pi
152 +In pane 1, launch real Pi interactively.
154 +Default isolation:
156 +```sh
157 +pi --no-extensions --no-skills --no-prompt-templates --no-context-files -e ./extensions/<target>/index.ts
158 +```
160 +Adjust only when needed:
162 +- support extension: add another `-e ./extensions/<support>/index.ts`
163 +- local package extension path: use exact path
164 +- scenario requires skills/prompts/context: remove only the needed isolation flag
165 +- scenario requires previous session behavior: use normal session mode intentionally and note why
167 +Do not force a model unless scenario requires model-specific behavior. Default configured model is preferred. For very long validation, it is OK to perform one secondary run with another available real model if useful.
169 +## Critical Verification Rules
171 +The Pi agent inside tmux is the system under test. Treat it like an unreliable junior engineer trying to impress you.
173 +- Do not trust its claims of success, failure, verification, implementation, or UX quality.
174 +- Independently inspect files it says it changed.
175 +- Independently rerun commands it says passed.
176 +- Independently inspect browser/terminal screenshots for UI claims.
177 +- Check whether it ignored instructions, skipped workflows, invented evidence, hid errors, or reframed the task smaller.
178 +- Record every unsupported claim as a finding until verified.
179 +- Prefer hard evidence: file diffs, command output, screenshots, browser console/network logs, session JSONL, pane captures.
180 +- Be concise but harsh in notes. No praise unless evidence earned it.
182 +## Human-like Driving Rules
184 +Interact through Pi as a human would:
186 +- type commands/prompts into pane 1
187 +- wait for UI states to settle
188 +- read terminal output
189 +- use extension slash commands, shortcuts, reloads, session switches, browser UIs, or tools only as real users would
190 +- if browser UI opens, inspect it and record UX findings with browser automation, not just terminal logs
191 +- test happy path, rough path, cancel/abort, reload/session lifecycle, browser lifecycle, and one realistic long-running path
192 +- observe latency and visual stability; note jank, flicker, unclear status, noisy widgets, bad footer/status behavior, stale state, or confusing errors
193 +- avoid unit-test shortcuts unless using them only to understand implementation
195 +This is expected to take time. Be thorough.
197 +## Browser UI Testing
199 +Some Pi extensions open local HTML pages. If a page opens or a URL is printed, that page is part of the extension UX and must be tested.
201 +Browser protocol:
203 +1. Detect URL/browser from terminal output, server info files, `xdg-open`/`open` behavior, or extension docs.
204 +2. If Chrome/Chromium is open or appropriate, load the `chrome-cdp` skill and use it to inspect/drive the live page.
205 +3. If Firefox is open or appropriate, load the `firefox-bidi` skill and use it to inspect/drive the live page; launching a managed Firefox is OK when needed.
206 +4. Interact like a human: click controls, type fields, resize if relevant, reload, close/reopen, test stale sessions, and verify events flow back to Pi.
207 +5. Inspect console errors, failed network requests, DOM state, accessibility labels where practical, and visual layout.
208 +6. Record browser findings in the notes with URL, browser, steps, expected/actual, and evidence.
210 +Do not skip browser testing because terminal behavior passed. If browser automation is unavailable, mark the browser portion blocked and say exactly what is missing.
212 +## Notes Discipline
214 +Append findings while testing:
216 +```sh
217 +cat >> "$NOTES" <<'EOF'
219 +### <timestamp> <area>
221 +- observation:
222 +- steps:
223 +- expected:
224 +- actual:
225 +- severity: low|medium|high
226 +- evidence:
227 +EOF
228 +```
230 +Record:
232 +- command used to launch Pi
233 +- exact extension paths loaded
234 +- model/provider observed when visible
235 +- terminal emulator detected
236 +- user shell and tmux pane shell detected
237 +- tmux socket/session/window
238 +- browser used, URL tested, console/network issues, and browser skill used when applicable
239 +- screenshots/GIF paths only if created
240 +- every bug/UX issue with reproduction steps
241 +- non-bugs worth preserving
243 +## Completion Report
245 +When done:
247 +1. Do not kill the tmux server automatically.
248 +2. Leave tmux running for user inspection.
249 +3. Give attach and kill commands.
250 +4. Ask: `Do you want me to close the tmux session now?`
251 +5. Only run `tmux -L <socket> kill-server` after the user says yes.
252 +6. Ensure notes file has final summary.
253 +7. Report:
255 +```text
256 +LIVE_EXTENSION_TEST_DONE
257 +notes: /tmp/<file>.md
258 +tmux attach: tmux -L <socket> attach -t live
259 +tmux kill: tmux -L <socket> kill-server
260 +loaded extensions: ...
261 +model: default|...
262 +shell: user=<shell> pane=<shell>
263 +browser: none|chrome-cdp|firefox-bidi|blocked
264 +result: pass|issues found|blocked
265 +findings:
266 +- [severity] title — evidence/repro
267 +```
269 +If blocked by terminal control, auth/model config, missing extension path, or unsafe destructive scenario, stop and ask for the smallest missing input. If testing completes successfully, still leave tmux alive and ask whether to close it.

docs/superpowers/specs/2026-05-29-branch-return-lifecycle-design.md

Added
new file mode 100644
1 +# Branch/Return Lifecycle Design
3 +## Goal
5 +Harden and prove `/superpowers branch` + `/superpowers return` as a complete takeover loop.
7 +## Contract
9 +- `/superpowers branch <id>` uses the task's persisted `parentSession`.
10 +- Branching marks the task `branched`.
11 +- Branching stops the selected live runtime if present.
12 +- Branching aborts peer live runtimes.
13 +- Branching opens a child session from `parentSession`.
14 +- The child session receives takeover instructions including `/superpowers return <summary>`.
15 +- The task snapshot records `childSession`.
16 +- `/superpowers return <summary>` switches back to `parentSession`.
17 +- The parent session receives a structured return entry.
18 +- The parent session receives a visible return message containing the summary and child session path.
20 +## Non-goals
22 +- No visual workflow changes.
23 +- No worker prompt changes.
24 +- No new task state machine.
25 +- No UI redesign.
27 +## Files
29 +- `extensions/superpowers/index.ts`
30 +- `extensions/superpowers/__tests__/harness.test.ts`
32 +## Test Plan
34 +Add one harness test for the full branch/return path:
36 +1. Seed `tasks.json` with a task containing `parentSession`.
37 +2. Run `/superpowers branch sp-7`.
38 +3. Assert task state is `branched`.
39 +4. Assert `childSession` is written.
40 +5. Assert child takeover message exists and contains `/superpowers return <summary>`.
41 +6. Run `/superpowers return done` from the child context.
42 +7. Assert parent receives a structured return entry:
43 + - `kind: "return"`
44 + - `taskId: "sp-7"`
45 + - `summary: "done"`
46 + - `childSession` present
47 +8. Assert parent visible return message contains the summary.
49 +## Acceptance
51 +- `bun test extensions/superpowers/__tests__/harness.test.ts`
52 +- `mise run test -- superpowers`
53 +- `mise run build -- superpowers`

docs/superpowers/specs/2026-05-29-visual-command-lifecycle-design.md

Added
new file mode 100644
1 +# Visual Command Lifecycle Design
3 +## Goal
5 +Prove `/superpowers visual start/status/stop` as an end-to-end command loop that starts a local visual session, announces agent-readable paths, re-announces an existing session, and shuts down cleanly.
7 +## Contract
9 +- `/superpowers visual start` starts a local server under platform state.
10 +- Start reports URL, content dir, events file, and browser-open result to the user.
11 +- Start inserts a visible custom message into the chat/session for the agent.
12 +- The agent-facing message includes only actionable session data:
13 + - URL
14 + - content dir
15 + - events file
16 + - instruction to read the events file directly
17 +- The agent-facing message does not mention hidden/debug commands.
18 +- Re-running start while live re-announces the same session instead of starting another one.
19 +- `/superpowers visual status` reports URL, content dir, and events file.
20 +- `/superpowers visual stop` closes the server and clears the live session.
22 +## Non-goals
24 +- No browser automation.
25 +- No visual UI redesign.
26 +- No visual screen component changes.
27 +- No event command docs or autocomplete.
28 +- No automatic server start from strict mode.
30 +## Files
32 +- `extensions/superpowers/index.ts`
33 +- `extensions/superpowers/__tests__/harness.test.ts`
35 +## Test Plan
37 +Add one harness test with `PI_SUPERPOWERS_NO_OPEN=1`:
39 +1. Run `/superpowers visual start`.
40 +2. Assert notice contains `visual live`, `content`, `events file`, and manual-open fallback.
41 +3. Assert chat custom message contains URL, content dir, events file, and direct-read instruction.
42 +4. Assert chat custom message does not contain `visual events` or `hidden debug`.
43 +5. Run `/superpowers visual start` again.
44 +6. Assert the same session URL is re-announced.
45 +7. Run `/superpowers visual status`.
46 +8. Assert status contains URL, content dir, and events file.
47 +9. Run `/superpowers visual stop`.
48 +10. Assert stopped notice.
50 +## Acceptance
52 +- `bun test extensions/superpowers/__tests__/harness.test.ts`
53 +- `bun test extensions/superpowers/__tests__/*.test.ts`
54 +- `mise run test -- superpowers`
55 +- `mise run build -- superpowers`

extensions/superpowers/__tests__/harness.test.ts

Modified
23 23 const tasks = () => JSON.parse(readFileSync(tasksPath(), "utf8"));
24 24 const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
26 +function fakeCtx(cwd: string, sessionFile: string) {
27 + const entries: any[] = [];
28 + const messages: any[] = [];
29 + const widgets: any[] = [];
30 + const notices: string[] = [];
31 + let entrySeq = 0;
32 + const ctx: any = {
33 + cwd,
34 + hasUI: true,
35 + ui: {
36 + notify: (msg: string) => notices.push(String(msg)),
37 + setWidget: (_id: string, value: unknown) => widgets.push(value),
38 + },
39 + sessionManager: {
40 + getSessionFile: () => sessionFile,
41 + appendCustomEntry: (customType: string, data: unknown) => {
42 + const entry = { id: `e${++entrySeq}`, type: "custom", customType, data };
43 + entries.push(entry);
44 + return entry.id;
45 + },
46 + getBranch: () => entries,
47 + },
48 + waitForIdle: async () => {},
49 + sendMessage: async (message: unknown) => messages.push(message),
50 + };
51 + return { ctx, entries, messages, widgets, notices };
26 54 async function waitFor(fn: () => boolean) {
27 55 for (let i = 0; i < 80; i++) {
28 56 if (fn()) return;
78 106 expect(tasks()["sp-1"].prompt).toBe("Review src");
81 - it("workflow aliases start matching prompt workers", async () => {
109 + it("workflow aliases prefer project prompts when present", async () => {
82 110 t = await createTestSession({ extensions: [extPath()] });
83 111 mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
84 112 writeFileSync(
96 124 expect(tasks()["sp-1"].prompt).toBe("Debug flaky test");
127 + it("workflow aliases use bundled prompts without project prompt files", async () => {
128 + t = await createTestSession({ extensions: [extPath()] });
129 + await command().handler("debug flaky test", ctx());
130 + await waitFor(
131 + () =>
132 + existsSync(tasksPath()) &&
133 + ["done", "error"].includes(tasks()["sp-1"]?.status),
134 + );
135 + expect(tasks()["sp-1"].agent).toBe("systematic-debugging");
136 + expect(tasks()["sp-1"].prompt).toContain("Use the `systematic-debugging` skill");
137 + expect(tasks()["sp-1"].prompt).toContain("flaky test");
138 + });
99 140 it("finds project prompt names for autocomplete", async () => {
100 141 t = await createTestSession({ extensions: [extPath()] });
101 142 mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
197 238 expect(notices().at(-1)).toContain("prompt:\ndemo prompt");
241 + it("starts, announces, reannounces, reports, and stops visual session", async () => {
242 + t = await createTestSession({ extensions: [extPath()] });
243 + const prevNoOpen = process.env.PI_SUPERPOWERS_NO_OPEN;
244 + process.env.PI_SUPERPOWERS_NO_OPEN = "1";
245 + try {
246 + await command().handler("visual start", ctx());
247 + await waitFor(() => t!.events.messages.some((m: any) => m.customType === "superpowers"));
248 + const firstNotice = notices().at(-1)!;
249 + expect(firstNotice).toContain("visual live: http://127.0.0.1:");
250 + expect(firstNotice).toContain("content:");
251 + expect(firstNotice).toContain("events file:");
252 + expect(firstNotice).toContain("open manually: browser opener disabled");
253 + const firstMessage = t.events.messages.find((m: any) => m.customType === "superpowers") as any;
254 + expect(firstMessage.content).toContain("Superpowers visual brainstorming");
255 + expect(firstMessage.content).toContain("visual live: http://127.0.0.1:");
256 + expect(firstMessage.content).toContain("content:");
257 + expect(firstMessage.content).toContain("events file:");
258 + expect(firstMessage.content).toContain("Agent rules:");
259 + expect(firstMessage.content).toContain("Use visual only for active user decisions");
260 + expect(firstMessage.content).toContain("Do not use visual as progress reporting");
261 + expect(firstMessage.content).toContain("data-choice");
262 + expect(firstMessage.content).toContain("wait for terminal answer or browser event");
263 + expect(firstMessage.content).toContain("Read the events file directly");
264 + expect(firstMessage.content).toContain("Continuing in terminal");
265 + expect(firstMessage.content).not.toContain("visual events");
266 + expect(firstMessage.content).not.toContain("hidden debug");
267 + const url = firstMessage.details.url;
268 + const contentDir = firstMessage.details.contentDir;
269 + const eventsFile = firstMessage.details.eventsFile;
271 + await command().handler("visual start", ctx());
272 + await waitFor(() => t!.events.messages.filter((m: any) => m.customType === "superpowers").length >= 2);
273 + expect(notices().at(-1)).toContain(`visual already live: ${url}`);
274 + const secondMessage = t.events.messages.filter((m: any) => m.customType === "superpowers").at(-1) as any;
275 + expect(secondMessage.details.url).toBe(url);
276 + expect(secondMessage.details.contentDir).toBe(contentDir);
277 + expect(secondMessage.details.eventsFile).toBe(eventsFile);
279 + await command().handler("visual status", ctx());
280 + expect(notices().at(-1)).toContain(`visual live: ${url}`);
281 + expect(notices().at(-1)).toContain(`content: ${contentDir}`);
282 + expect(notices().at(-1)).toContain(`events file: ${eventsFile}`);
284 + await command().handler("visual stop", ctx());
285 + expect(notices().at(-1)).toBe("visual stopped");
286 + } finally {
287 + if (prevNoOpen === undefined) delete process.env.PI_SUPERPOWERS_NO_OPEN;
288 + else process.env.PI_SUPERPOWERS_NO_OPEN = prevNoOpen;
290 + });
292 + it("closes visual server on session shutdown", async () => {
293 + t = await createTestSession({ extensions: [extPath()] });
294 + const prevNoOpen = process.env.PI_SUPERPOWERS_NO_OPEN;
295 + process.env.PI_SUPERPOWERS_NO_OPEN = "1";
296 + try {
297 + await command().handler("visual start", ctx());
298 + await waitFor(() => t!.events.messages.some((m: any) => m.customType === "superpowers"));
299 + const message = t.events.messages.find((m: any) => m.customType === "superpowers") as any;
300 + const url = message.details.url;
301 + expect(await fetch(url).then((r) => r.status)).toBe(200);
302 + await t.session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
303 + for (let i = 0; i < 40; i++) {
304 + try {
305 + await fetch(url);
306 + } catch {
307 + return;
309 + await sleep(25);
311 + expect.unreachable("visual server still accepted requests after shutdown");
312 + } finally {
313 + if (prevNoOpen === undefined) delete process.env.PI_SUPERPOWERS_NO_OPEN;
314 + else process.env.PI_SUPERPOWERS_NO_OPEN = prevNoOpen;
316 + });
318 + it("branches into a child session and returns summary to parent", async () => {
319 + t = await createTestSession({ extensions: [extPath()] });
320 + const parentSession = path.join(t.cwd, "parent.jsonl");
321 + const childSession = path.join(t.cwd, "child.jsonl");
322 + mkdirSync(path.dirname(tasksPath()), { recursive: true });
323 + writeFileSync(
324 + tasksPath(),
325 + JSON.stringify({
326 + "sp-7": {
327 + id: "sp-7",
328 + agent: "demo",
329 + prompt: "demo prompt",
330 + status: "done",
331 + startedAt: "2026-01-01T00:00:00.000Z",
332 + updatedAt: "2026-01-01T00:00:03.000Z",
333 + parentSession,
334 + log: ["checkpoint"],
335 + result: "DONE",
336 + },
337 + }),
338 + "utf8",
339 + );
340 + const parent = fakeCtx(t.cwd, parentSession);
341 + const child = fakeCtx(t.cwd, childSession);
342 + parent.ctx.newSession = async (options: any) => {
343 + expect(options.parentSession).toBe(parentSession);
344 + await options.withSession(child.ctx);
345 + return { cancelled: false };
346 + };
347 + child.ctx.switchSession = async (sessionPath: string, options: any) => {
348 + expect(sessionPath).toBe(parentSession);
349 + await options.withSession(parent.ctx);
350 + return { cancelled: false };
351 + };
353 + await command().handler("branch sp-7", parent.ctx);
354 + expect(tasks()["sp-7"].status).toBe("branched");
355 + expect(tasks()["sp-7"].childSession).toBe(childSession);
356 + expect(child.entries.at(-1)?.data).toMatchObject({
357 + kind: "child",
358 + task: { id: "sp-7", childSession },
359 + });
360 + expect(child.messages.at(-1)?.content).toContain("Superpowers takeover: sp-7");
361 + expect(child.messages.at(-1)?.content).toContain("/superpowers return <summary>");
363 + await command().handler("return done", child.ctx);
364 + expect(parent.entries.at(-1)?.data).toMatchObject({
365 + kind: "return",
366 + taskId: "sp-7",
367 + summary: "done",
368 + childSession,
369 + });
370 + expect(parent.messages.at(-1)?.content).toContain("Superpowers return sp-7");
371 + expect(parent.messages.at(-1)?.content).toContain("done");
372 + expect(parent.messages.at(-1)?.content).toContain(childSession);
373 + });
200 375 it("guards branch when harness has no persisted parent session", async () => {
201 376 t = await createTestSession({ extensions: [extPath()] });
202 377 mkdirSync(path.dirname(tasksPath()), { recursive: true });

extensions/superpowers/__tests__/helpers.test.ts

Modified
63 63 expect(skill).toContain("After approval, hand off only to `writing-plans`");
66 + it("visual companion is decision UI, not reporting UI", () => {
67 + const skill = readFileSync(
68 + path.resolve(import.meta.dir, "../skills/brainstorming/SKILL.md"),
69 + "utf8",
70 + );
71 + const research = readFileSync(
72 + path.resolve(import.meta.dir, "../docs-visual-brainstorming.md"),
73 + "utf8",
74 + );
75 + for (const text of [skill, research]) {
76 + expect(text).toContain("active decision aid, not a reporting dashboard");
77 + expect(text).toContain("Do not use");
78 + expect(text).toContain("implementation summaries");
79 + expect(text).toContain("data-choice");
80 + expect(text).toContain("wait");
81 + expect(text).toContain("Continuing in terminal");
82 + }
83 + });
66 85 it("agent-facing prompts omit hidden visual debug commands", () => {
67 86 const root = path.resolve(import.meta.dir, "..");
68 87 const promptFiles = readdirSync(path.join(root, "prompts")).map((f) =>
99 + it("strict prompt protects brainstorming before planning", () => {
100 + const source = readFileSync(path.resolve(import.meta.dir, "../index.ts"), "utf8");
101 + expect(source).toContain("Use brainstorming first for vague goals, UX/UI work");
102 + expect(source).toContain("Do not use writing-plans unless an approved design/spec already exists");
103 + });
80 105 it("skills retain vital upstream workflow gates", () => {
81 106 const skill = (name: string) =>
82 107 readFileSync(path.resolve(import.meta.dir, `../skills/${name}/SKILL.md`), "utf8");
114 139 path.join(visual.contentDir, "001-options.html"),
115 140 '<div class="option" data-choice="a" onclick="toggleSelect(this)">A</div>',
142 + expect(existsSync(visual.eventsFile)).toBe(true);
143 + expect(readFileSync(visual.eventsFile, "utf8")).toBe("");
117 144 const html = await fetch(visual.url).then((r) => r.text());
118 145 expect(html).toContain("Visual Brainstorming");
146 + expect(html).toContain('<link rel="icon" href="data:,">');
147 + expect(html).toContain("[data-choice]");
119 148 expect(html).toContain('data-choice="a"');
120 149 const eventUrl = new URL("/api/event", visual.url);
121 150 eventUrl.search = new URL(visual.url).search;

extensions/superpowers/docs-visual-brainstorming.md

Modified
24 24 - Decide per question whether visual helps.
25 25 - Use browser for mockups, wireframes, diagrams, layout/color/design comparisons.
26 26 - Use terminal for requirements, scope, text tradeoffs, technical decisions.
27 +- Visual companion is an active decision aid, not a reporting dashboard.
28 +- Every visual screen must ask a question, present selectable options, or show a mockup/diagram the user is meant to judge.
29 +- Do not use visual screens for progress updates, implementation summaries, final reports, or proof-of-work slides.
30 +- Use `data-choice` for clickable options; browser JS auto-records clicks.
31 +- After writing a decision screen, wait for terminal response or browser event before implementing.
27 32 - User terminal response remains primary; click events are supporting evidence.
28 33 - Each screen uses a new semantic filename.
29 34 - Stale screens should be replaced with “Continuing in terminal…” when leaving visual mode.
35 +- End of visual phase: ask whether to leave browser open for inspection or stop it with `/superpowers visual stop`.
31 37 ## Technical shape
37 43 - wraps HTML fragments in a frame template
38 44 - injects helper JS
39 45 - records clicks/selections to JSONL events file
40 -- uses WebSocket reload to update browser
46 +- auto-records clicks on `[data-choice]` elements so agents do not need inline JS
47 +- uses polling reload to update browser
41 48 - stores session under project `.superpowers/brainstorm/...`
43 50 Important directories:
57 64 - Store ephemeral files under platform state, not the repo: `${XDG_STATE_HOME:-~/.local/state}/pi/superpowers/<project-hash>/visual/...` on Linux, native equivalents on macOS/Windows.
58 65 - Use Pi UI notification and a visible session message to show URL and paths.
59 66 - Use `read`/`write` tool workflow for screens/events.
67 +- Create the events JSONL file at start so agent reads never fail before the first browser click.
68 +- Close server on `/superpowers visual stop` and session shutdown.
60 69 - Keep zero dependency: Node built-ins or Bun server only.
62 71 ## Recommended Pi UX
82 91 ```text
83 92 Showing 3 dashboard layout options at http://localhost:NNNN.
93 +Question: which layout would you actually want to use all day?
84 94 Click one if useful, then tell me what you think here.
97 107 - Do not vendor dependencies.
98 108 - Do not force browser for conceptual questions.
109 +- Do not use visual companion as a status board or final report.
99 110 - Do not let visual companion skip design approval/spec gates.
100 111 - Do not store under non-Pi `.superpowers` unless intentionally matching upstream.
101 112 - Do not make visual server start automatically on `/superpowers on`.

extensions/superpowers/index.ts

Modified
8 8 } from "node:fs";
9 9 import os from "node:os";
10 10 import path from "node:path";
11 +import { fileURLToPath } from "node:url";
11 12 import { getModel } from "@earendil-works/pi-ai";
12 13 import {
13 14 createAgentSession,
15 16 type ExtensionAPI,
16 17 type ExtensionCommandContext,
17 18 type ExtensionContext,
19 + type ThemeColor,
18 20 getAgentDir,
19 21 SessionManager,
20 22 SettingsManager,
22 24 import { openBrowser, startVisualServer, type VisualSession } from "./visual";
24 26 const ID = "superpowers";
27 +const STATUS_ID = "superpowers";
25 28 const WIDGET = "superpowers";
29 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
30 +const FOOTER_SEGMENT = {
31 + id: STATUS_ID,
32 + icon: "⚡",
33 + zone: "workspace",
34 + order: 80,
35 +} as const;
36 +const EXT_DIR = path.dirname(fileURLToPath(import.meta.url));
26 37 const FLAG_PROMPT = `
28 39 Superpowers active. Strict mode.
30 41 For every non-trivial coding task:
31 -1. Pick the smallest applicable workflow skill: brainstorming, writing-plans, executing-plans, test-driven-development, systematic-debugging, requesting-code-review, receiving-code-review, using-git-worktrees, verification-before-completion.
32 -2. Load/follow that skill before acting. Do not skip to implementation when brainstorming/planning/debugging applies.
33 -3. Say which workflow you are using in one short line.
34 -4. Prefer simplicity/minimalism/brutalism. No legacy/compat/edge-case bloat unless explicitly required.
35 -5. Before claiming done/fixed/shipped, run verification and cite evidence.
36 -6. For isolated or parallel worker tasks, use or suggest /superpowers run <prompt> <args>.
42 +1. Pick the earliest applicable lifecycle workflow: brainstorming → writing-plans → executing-plans/test-driven-development/systematic-debugging → requesting-code-review/receiving-code-review → verification-before-completion.
43 +2. Use brainstorming first for vague goals, UX/UI work, architecture choices, new features, or broad refactors. Do not use writing-plans unless an approved design/spec already exists.
44 +3. Load/follow that skill before acting. Do not skip to implementation when brainstorming/planning/debugging applies.
45 +4. Say which workflow you are using in one short line.
46 +5. Prefer simplicity/minimalism/brutalism. No legacy/compat/edge-case bloat unless explicitly required.
47 +6. Before claiming done/fixed/shipped, run verification and cite evidence.
48 +7. For isolated or parallel worker tasks, use or suggest /superpowers run <prompt> <args>.
38 50 const COMMANDS = [
39 51 "run",
108 120 let currentCwd = process.cwd();
109 121 let active = false;
110 122 let visual: VisualSession | undefined;
123 +let api: ExtensionAPI | undefined;
112 125 const now = () => new Date().toISOString();
113 126 function platformStateDir(
167 180 if (ctx.hasUI) ctx.ui.notify(msg, kind);
182 +function hasFooter() {
183 + const footer = (globalThis as any)[FOOTER_KEY];
184 + return footer?.loaded === true && footer.version >= 1;
186 +function statusCounts(cwd: string) {
187 + const tasks = Object.values(readTasks(cwd));
188 + return {
189 + tasks,
190 + running: tasks.filter((t) => t.status === "running").length,
191 + errors: tasks.filter((t) => t.status === "error").length,
192 + };
194 +function uiStatusText(cwd: string) {
195 + const { running, errors } = statusCounts(cwd);
196 + if (!active && !running && !errors && !visual) return undefined;
197 + return [
198 + active ? "sp on" : "sp",
199 + running ? `${running} run` : "",
200 + errors ? `${errors} err` : "",
201 + visual ? "visual" : "",
203 + .filter(Boolean)
204 + .join(" · ");
206 +function publishStatus(ctx: ExtensionContext) {
207 + if (!ctx.hasUI) return;
208 + const message = uiStatusText(ctx.cwd);
209 + if (hasFooter() && api) {
210 + (ctx.ui as any).setStatus?.(STATUS_ID, undefined);
211 + api.events.emit(
212 + "footer:segment",
213 + message
214 + ? {
215 + ...FOOTER_SEGMENT,
216 + text: message,
217 + variants: [message.replace(/^sp /, "")],
218 + color: (active ? "accent" : "muted") as ThemeColor,
220 + : { id: STATUS_ID, text: undefined },
221 + );
222 + return;
224 + api?.events.emit("footer:segment", { id: STATUS_ID, text: undefined });
225 + (ctx.ui as any).setStatus?.(STATUS_ID, message);
227 +function compactTaskLine(t: Task) {
228 + return `${t.id} ${t.agent} ${elapsed(t.startedAt, t.updatedAt)}${toolCount(t) ? ` · ${toolCount(t)} tools` : ""}`;
169 230 function firstLine(s: string | undefined) {
170 231 return (s ?? "").split("\n")[0]?.trim() ?? "";
200 261 ].join("\n");
202 263 function widget(ctx: ExtensionContext) {
264 + publishStatus(ctx);
203 265 if (!ctx.hasUI) return;
204 - const tasks = Object.values(readTasks(ctx.cwd)).slice(-5);
205 - ctx.ui.setWidget(
266 + const running = Object.values(readTasks(ctx.cwd))
267 + .filter((t) => t.status === "running")
268 + .slice(-3);
269 + (ctx.ui as any).setWidget?.(
206 270 WIDGET,
207 - tasks.length || active
208 - ? [`superpowers ${active ? "on" : "off"}`, ...tasks.map(summaryLine)]
271 + running.length
272 + ? [`superpowers · ${running.length} running`, ...running.map(compactTaskLine)]
209 273 : undefined,
269 333 return [...out];
271 335 function promptDirs(cwd: string) {
272 - return [path.join(cwd, ".pi/prompts"), path.join(getAgentDir(), "prompts")];
336 + return [
337 + path.join(cwd, ".pi/prompts"),
338 + path.join(getAgentDir(), "prompts"),
339 + path.join(EXT_DIR, "prompts"),
340 + ];
274 342 function agentNames(cwd: string) {
275 343 return [
391 459 agentDir,
392 460 settingsManager,
461 + additionalSkillPaths: [path.join(EXT_DIR, "skills")],
462 + additionalPromptTemplatePaths: [path.join(EXT_DIR, "prompts")],
393 463 noExtensions: !ext,
394 464 extensionsOverride: ext
395 465 ? (base) => ({
532 602 writeTask(child.cwd, task);
533 603 append(child, { kind: "child", task });
534 604 if (child.hasUI)
535 - child.ui.setWidget(WIDGET, [
605 + (child.ui as any).setWidget?.(WIDGET, [
536 606 `superpowers child ${task.id}`,
537 - "/superpowers return <summary>",
607 + "return with: /superpowers return <summary>",
539 609 await child.sendMessage(
604 674 function toggle(ctx: ExtensionCommandContext) {
605 675 setActive(ctx, !active);
607 -async function announceVisualSession(ctx: ExtensionCommandContext, session: VisualSession) {
677 +async function announceVisualSession(pi: ExtensionAPI, session: VisualSession) {
608 678 const agentMsg = [
609 679 "Superpowers visual brainstorming",
612 682 `content: ${session.contentDir}`,
613 683 `events file: ${session.eventsFile}`,
615 - "Agent: read the events file directly when interpreting browser feedback.",
685 + "Agent rules:",
686 + "- Use visual only for active user decisions: options, mockups, diagrams, layouts.",
687 + "- Do not use visual as progress reporting, implementation summary, final report, or proof slide.",
688 + "- Every screen must ask a clear question or show something the user should judge.",
689 + "- Use data-choice on clickable choices; the browser records clicks automatically.",
690 + "- After writing a decision screen, wait for terminal answer or browser event before implementing.",
691 + "- Read the events file directly when interpreting browser feedback.",
692 + "- When done with visual decisions, write a waiting screen: Continuing in terminal…",
693 + "- Ask whether to leave the browser open for inspection or stop it.",
616 694 ].join("\n");
617 - await ctx.sendMessage(
695 + await Promise.resolve(pi.sendMessage(
619 697 customType: ID,
620 698 display: true,
628 706 { triggerTurn: false },
629 - );
707 + ));
632 -async function visualCommand(args: string, ctx: ExtensionCommandContext) {
710 +async function visualCommand(args: string, ctx: ExtensionCommandContext, pi: ExtensionAPI) {
633 711 const [sub = "status"] = args.trim().split(/\s+/);
634 712 if (sub === "start") {
635 713 if (visual) {
636 714 notify(ctx, `visual already live: ${visual.url}\ncontent: ${visual.contentDir}\nevents file: ${visual.eventsFile}`);
637 - await announceVisualSession(ctx, visual);
715 + await announceVisualSession(pi, visual);
638 716 return;
640 718 visual = await startVisualServer({ root: dir(ctx.cwd) });
719 + widget(ctx);
641 720 const opened = await openBrowser(visual.url);
642 721 const msg = [
643 722 `visual live: ${visual.url}`,
646 725 opened.ok ? `opened: ${opened.command}` : `open manually: ${opened.error}`,
647 726 ].join("\n");
648 727 notify(ctx, msg, opened.ok ? "info" : "warning");
649 - await announceVisualSession(ctx, visual);
728 + await announceVisualSession(pi, visual);
650 729 return;
652 731 if (sub === "stop") {
653 732 if (!visual) return notify(ctx, "no visual session", "warning");
654 733 visual.close();
655 734 visual = undefined;
735 + widget(ctx);
656 736 notify(ctx, "visual stopped");
657 737 return;
664 744 return;
666 746 if (!visual) return notify(ctx, "no visual session. use /superpowers visual start", "warning");
667 - notify(ctx, `visual live: ${visual.url}\ncontent: ${visual.contentDir}\nevents: ${visual.eventsFile}`);
747 + notify(ctx, `visual live: ${visual.url}\ncontent: ${visual.contentDir}\nevents file: ${visual.eventsFile}`);
670 750 function help(ctx: ExtensionCommandContext) {
671 751 notify(
674 - "/superpowers toggle strict workflow discipline",
675 - ...COMMANDS.filter((c) => c !== "help")
676 - .map(
677 - (c) =>
678 - `/superpowers ${c}${c === "run" ? " <agent> [args]" : c === "agent" ? " <prompt>" : c === "return" ? " <summary>" : ["open", "branch", "abort"].includes(c) ? " <id>" : c === "status" ? " [id]" : c in ALIASES ? " <args>" : ""}`,
679 - ),
680 - ]
681 - .join("\n"),
754 + "Superpowers",
755 + "mode: /superpowers | on | off | status [id]",
756 + "workers: run <agent> [args] | agent <prompt> | open/branch/abort <id> | return <summary>",
757 + "workflows: design | plan | execute | debug | review | verify | parallel | git | meta",
758 + "browser: visual start | visual status | visual events | visual stop",
759 + ].join("\n"),
685 763 export default function (pi: ExtensionAPI) {
764 + api = pi;
686 765 pi.registerFlag("superpowers", {
687 766 description: "Activate Superpowers workflow discipline for this Pi run",
688 767 type: "boolean",
708 787 visual?.close();
709 788 visual = undefined;
710 789 stopAll();
790 + pi.events.emit("footer:segment", { id: STATUS_ID, text: undefined });
712 792 pi.registerCommand("superpowers", {
713 793 description: "Run background agents and branch into them",
761 841 if (cmd === "on") return setActive(ctx, true);
762 842 if (cmd === "off") return setActive(ctx, false);
763 - if (cmd === "visual") return visualCommand(tail, ctx);
843 + if (cmd === "visual") return visualCommand(tail, ctx, pi);
764 844 if (cmd in ALIASES) return runAgent(ALIASES[cmd], tail, ctx, pi);
765 845 if (cmd === "help") return help(ctx);
766 846 return status(ctx, tail);

extensions/superpowers/skills/brainstorming/SKILL.md

Modified
116 116 Use only when seeing beats reading: mockups, layouts, palettes, diagrams, side-by-side UX choices.
118 +This is an active decision aid, not a reporting dashboard. Every visual screen must either ask a question, present selectable options, or show a mockup/diagram the user is meant to judge. Do not use it for progress updates, implementation summaries, final reports, or proof-of-work slides.
118 120 Offer in its own message:
120 122 ```text
126 128 1. Ask user to run `/superpowers visual start` if not already live.
127 129 2. Use returned `content` dir.
128 -3. Write one fresh `.html` fragment per screen.
129 -4. Tell user the URL and what is on screen.
130 -5. Ask user to click/select if useful and answer in terminal.
131 -6. Read the events file path announced by `/superpowers visual start` directly when interpreting browser feedback.
132 -7. Push a waiting screen before returning to text-only discussion.
130 +3. Write one fresh `.html` fragment per decision screen.
131 +4. Each screen must include a clear prompt/question and obvious clickable choices when choice is useful.
132 +5. Use `data-choice="..."` on clickable options; the browser records those clicks automatically.
133 +6. Tell user the URL and the exact decision you need from the screen.
134 +7. Ask user to click/select if useful and answer in terminal.
135 +8. Wait for a terminal answer or browser event before implementing from a visual decision screen.
136 +9. Read the events file path announced by `/superpowers visual start` directly when interpreting browser feedback.
137 +10. After the visual decision is resolved, push a waiting screen saying `Continuing in terminal…` before returning to text-only discussion.
138 +11. At the end of the visual phase, ask whether to leave the browser companion open for inspection or stop it with `/superpowers visual stop`.
134 140 Visual state is ephemeral platform state, not project files. Specs/design docs remain project files when approved.

extensions/superpowers/visual.ts

Modified
33 33 mkdirSync(contentDir, { recursive: true });
34 34 mkdirSync(stateDir, { recursive: true });
35 35 writeFileSync(path.join(contentDir, "000-waiting.html"), waitingFragment());
36 + writeFileSync(eventsFile, "");
37 38 let server!: Server;
38 39 const authorized = (req: IncomingMessage, url: URL) =>
148 149 function waitingFragment() {
149 - return `<div class="center"><p class="subtitle">Waiting for Pi to push a visual brainstorming screen…</p></div>`;
150 + return `<div class="center"><p class="subtitle">Waiting for Pi to write a visual screen…</p></div>`;
152 153 function frame(fragment: string, stamp: { name: string; mtime: number }) {
153 154 const body = /<html[\s>]/i.test(fragment) || /<!doctype/i.test(fragment) ? fragment : `<main id="main">${fragment}</main>`;
154 155 return `<!doctype html>
155 156 <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
156 -<title>Pi Superpowers Visual Brainstorming</title><style>${css()}</style></head><body data-stamp="${escapeAttr(JSON.stringify(stamp))}">
157 -<div id="app"><header id="topbar"><div class="brand"><div><h1>Visual Brainstorming</h1><div class="subtitle">Pi × Superpowers</div></div><label class="theme-label" aria-label="Theme mode"><span class="theme-icon">◐</span><select id="theme-mode" aria-label="Theme mode"><option value="system">system</option><option value="dark">dark</option><option value="light">light</option></select></label></div><div id="status" class="status-pill">Ready</div></header>${body}</div>
157 +<title>Pi Superpowers Visual Brainstorming</title><link rel="icon" href="data:,"><style>${css()}</style></head><body data-stamp="${escapeAttr(JSON.stringify(stamp))}">
158 +<div id="app"><header id="topbar"><div class="brand"><h1>Visual Brainstorming</h1><div class="subtitle">${escapeHtml(stamp.name || "waiting")}</div></div><div class="topbar-actions"><label class="theme-label" aria-label="Theme mode"><span class="theme-icon">◐</span><select id="theme-mode" aria-label="Theme mode"><option value="system">system</option><option value="dark">dark</option><option value="light">light</option></select></label><div id="status" class="status-pill">ready</div></div></header>${body}</div>
158 159 <script>${js()}</script></body></html>`;
161 162 function css() {
162 - return `:root{color-scheme:dark light;--nugu-info:#3ec5dd;--nugu-content-normal:#ededed;--nugu-content-backdrop:#121212;--nugu-ui-backdrop:#242424;--nugu-ui-accent:#d86dd8;--nugu-ui-minor:#9d9d9d;--nugu-ui-focus:#9aabae;--nugu-ui-unfocus:#6f6f6f;--bg:var(--nugu-content-backdrop);--panel:color-mix(in srgb,var(--nugu-ui-backdrop) 86%,var(--bg));--panel-2:var(--nugu-ui-backdrop);--fg:var(--nugu-content-normal);--muted:var(--nugu-ui-minor);--faint:var(--nugu-ui-unfocus);--accent:var(--nugu-ui-accent);--accent-2:var(--nugu-info);--focus:var(--nugu-ui-focus);--border:color-mix(in srgb,var(--fg) 14%,transparent);--radius:12px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:var(--bg);color:var(--fg)}:root[data-theme="light"]{color-scheme:light;--nugu-info:#13616e;--nugu-content-normal:#121212;--nugu-content-backdrop:#ededed;--nugu-ui-backdrop:#dbdbdb;--nugu-ui-accent:#922792;--nugu-ui-minor:#292929;--nugu-ui-focus:#15333b;--nugu-ui-unfocus:#5d5d5d;--panel:color-mix(in srgb,var(--nugu-ui-backdrop) 72%,white);--border:color-mix(in srgb,var(--fg) 16%,transparent)}*{box-sizing:border-box}html,body,#app{height:100%}body{margin:0;background:var(--bg)}button,select,input,textarea{font:inherit}code,pre{font-family:"JetBrains Mono","Fira Code",ui-monospace,Menlo,Consolas,monospace}button{cursor:pointer}#app{display:grid;grid-template-rows:auto minmax(0,1fr);overflow:hidden}#topbar{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--border);background:color-mix(in srgb,var(--panel) 95%,transparent)}#main{overflow:auto;padding:24px;max-width:1180px;width:100%;margin:0 auto}.brand{display:flex;align-items:center;gap:10px;min-width:0;margin-right:auto}.brand h1{font-size:16px;line-height:1.1;margin:0}.subtitle{color:var(--muted);margin:.15rem 0 0;font-size:12px}.theme-label{position:relative;display:inline-grid;place-items:center;width:30px;height:30px;min-width:30px;margin:0;padding:0;border:1px solid color-mix(in srgb,var(--border) 78%,transparent);border-radius:999px;background:color-mix(in srgb,var(--panel-2) 56%,transparent);box-shadow:inset 0 1px 0 color-mix(in srgb,var(--fg) 5%,transparent);opacity:.72}.theme-label:hover,.theme-label:focus-within{opacity:1}.theme-icon{display:grid;place-items:center;width:100%;height:100%;color:color-mix(in srgb,var(--fg) 70%,var(--muted));font-size:14px;font-weight:800;line-height:1;pointer-events:none}.theme-label select{position:absolute;inset:0;width:100%;height:100%;min-width:0;padding:0;border:0;border-radius:999px;background:transparent;color:transparent;opacity:0;cursor:pointer}.theme-label:focus-within{border-color:color-mix(in srgb,var(--focus) 52%,var(--border));box-shadow:0 0 0 3px color-mix(in srgb,var(--focus) 18%,transparent)}.theme-label select:focus{box-shadow:none}.card-title{font-weight:700;color:var(--accent-2)}select,.mock-input{background:var(--panel-2);color:var(--fg);border:1px solid var(--border);border-radius:8px;padding:6px 8px}.card,.option,.mockup{border:1px solid var(--border);background:var(--panel);border-radius:var(--radius);padding:16px;box-shadow:0 18px 60px color-mix(in srgb,#000 25%,transparent)}.card{margin-bottom:12px}.options,.cards{display:grid;gap:14px;margin:14px 0 22px}.option,.card[data-choice]{cursor:pointer}.option:hover,.card[data-choice]:hover{border-color:var(--focus);background:color-mix(in srgb,var(--focus) 10%,var(--panel))}.selected{outline:2px solid var(--accent);border-color:var(--accent)!important}.letter{display:inline-grid;place-items:center;width:28px;height:28px;margin-right:10px;border-radius:999px;background:var(--accent);color:var(--bg);font-weight:800}.split{display:grid;grid-template-columns:1fr 1fr;gap:18px}.mockup-header{color:var(--accent-2);font-weight:800;margin-bottom:12px}.mock-nav{background:var(--panel-2);border-radius:10px;padding:10px;margin-bottom:10px}.pros-cons{display:grid;grid-template-columns:1fr 1fr;gap:16px}.pros,.cons{padding:14px;border-radius:12px;background:color-mix(in srgb,var(--panel-2) 92%,var(--bg))}.mock-button{background:linear-gradient(180deg,color-mix(in srgb,var(--accent) 38%,var(--panel-2)),color-mix(in srgb,var(--accent) 20%,var(--panel-2)));color:var(--fg);border:1px solid color-mix(in srgb,var(--accent) 58%,var(--border));border-radius:10px;padding:8px 12px}.placeholder{border:1px dashed var(--border);border-radius:10px;padding:24px;text-align:center;color:var(--muted)}.center{min-height:55vh;display:grid;place-items:center}.status-pill{display:inline-flex;align-items:center;min-height:30px;border:1px solid var(--border);border-radius:999px;padding:4px 10px;color:var(--muted);background:color-mix(in srgb,var(--panel-2) 56%,transparent)}dialog{border:1px solid var(--border);border-radius:14px;background:var(--panel);color:var(--fg);padding:20px;max-width:420px}dialog::backdrop{background:rgba(0,0,0,.55)}@media(max-width:840px){#topbar{flex-wrap:wrap}.split,.pros-cons{grid-template-columns:1fr}#main{padding:16px}}`;
163 + return `:root{color-scheme:dark light;--nugu-info:#3ec5dd;--nugu-content-normal:#ededed;--nugu-content-backdrop:#121212;--nugu-ui-backdrop:#242424;--nugu-ui-accent:#d86dd8;--nugu-ui-minor:#9d9d9d;--nugu-ui-focus:#9aabae;--nugu-ui-unfocus:#6f6f6f;--bg:var(--nugu-content-backdrop);--panel:color-mix(in srgb,var(--nugu-ui-backdrop) 86%,var(--bg));--panel-2:var(--nugu-ui-backdrop);--fg:var(--nugu-content-normal);--muted:var(--nugu-ui-minor);--faint:var(--nugu-ui-unfocus);--accent:var(--nugu-ui-accent);--accent-2:var(--nugu-info);--focus:var(--nugu-ui-focus);--border:color-mix(in srgb,var(--fg) 14%,transparent);--radius:10px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:var(--bg);color:var(--fg)}:root[data-theme="light"]{color-scheme:light;--nugu-info:#13616e;--nugu-content-normal:#121212;--nugu-content-backdrop:#ededed;--nugu-ui-backdrop:#dbdbdb;--nugu-ui-accent:#922792;--nugu-ui-minor:#292929;--nugu-ui-focus:#15333b;--nugu-ui-unfocus:#5d5d5d;--panel:color-mix(in srgb,var(--nugu-ui-backdrop) 72%,white);--border:color-mix(in srgb,var(--fg) 16%,transparent)}*{box-sizing:border-box}html,body,#app{height:100%}body{margin:0;background:var(--bg)}button,select,input,textarea{font:inherit}code,pre{font-family:"JetBrains Mono","Fira Code",ui-monospace,Menlo,Consolas,monospace}button{cursor:pointer}#app{display:grid;grid-template-rows:auto minmax(0,1fr);overflow:hidden}#topbar{display:flex;align-items:center;gap:12px;padding:8px 12px;border-bottom:1px solid var(--border);background:color-mix(in srgb,var(--panel) 95%,transparent)}#main{overflow:auto;padding:18px;width:100%;height:100%}.brand{min-width:0;margin-right:auto}.brand h1{font-size:14px;line-height:1.1;margin:0}.subtitle{color:var(--muted);margin:.1rem 0 0;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.topbar-actions{display:flex;align-items:center;gap:8px}.theme-label{position:relative;display:inline-grid;place-items:center;width:28px;height:28px;min-width:28px;margin:0;padding:0;border:1px solid color-mix(in srgb,var(--border) 78%,transparent);border-radius:999px;background:color-mix(in srgb,var(--panel-2) 56%,transparent);opacity:.72}.theme-label:hover,.theme-label:focus-within{opacity:1}.theme-icon{display:grid;place-items:center;width:100%;height:100%;color:color-mix(in srgb,var(--fg) 70%,var(--muted));font-size:13px;font-weight:800;line-height:1;pointer-events:none}.theme-label select{position:absolute;inset:0;width:100%;height:100%;min-width:0;padding:0;border:0;border-radius:999px;background:transparent;color:transparent;opacity:0;cursor:pointer}.theme-label:focus-within{border-color:color-mix(in srgb,var(--focus) 52%,var(--border));box-shadow:0 0 0 3px color-mix(in srgb,var(--focus) 18%,transparent)}.theme-label select:focus{box-shadow:none}.card-title{font-weight:700;color:var(--accent-2)}select,.mock-input,textarea,input{background:var(--panel-2);color:var(--fg);border:1px solid var(--border);border-radius:8px;padding:6px 8px}.card,.option,.mockup{border:1px solid var(--border);background:var(--panel);border-radius:var(--radius);padding:14px}.card{margin-bottom:10px}.options,.cards{display:grid;gap:10px;margin:12px 0 18px}.option,.card[data-choice]{cursor:pointer}.option:hover,.card[data-choice]:hover{border-color:var(--focus);background:color-mix(in srgb,var(--focus) 10%,var(--panel))}.selected{outline:2px solid var(--accent);border-color:var(--accent)!important}.letter{display:inline-grid;place-items:center;width:24px;height:24px;margin-right:8px;border-radius:999px;background:var(--accent);color:var(--bg);font-weight:800}.split{display:grid;grid-template-columns:1fr 1fr;gap:12px}.mockup-header{color:var(--accent-2);font-weight:800;margin-bottom:10px}.mock-nav{background:var(--panel-2);border-radius:8px;padding:8px;margin-bottom:8px}.pros-cons{display:grid;grid-template-columns:1fr 1fr;gap:12px}.pros,.cons{padding:12px;border-radius:10px;background:color-mix(in srgb,var(--panel-2) 92%,var(--bg))}.mock-button{background:var(--panel-2);color:var(--fg);border:1px solid color-mix(in srgb,var(--accent) 58%,var(--border));border-radius:8px;padding:7px 10px}.placeholder{border:1px dashed var(--border);border-radius:10px;padding:18px;text-align:center;color:var(--muted)}.center{min-height:55vh;display:grid;place-items:center}.status-pill{display:inline-flex;align-items:center;min-height:28px;border:1px solid var(--border);border-radius:999px;padding:3px 9px;color:var(--muted);background:color-mix(in srgb,var(--panel-2) 56%,transparent);font-size:12px}dialog{border:1px solid var(--border);border-radius:12px;background:var(--panel);color:var(--fg);padding:16px;max-width:420px}dialog::backdrop{background:rgba(0,0,0,.55)}@media(max-width:840px){#topbar{flex-wrap:wrap}.split,.pros-cons{grid-template-columns:1fr}#main{padding:12px}}`;
165 166 function js() {
166 - return `const select=document.getElementById('theme-mode');const saved=localStorage.getItem('superpowers-visual-theme')||'system';function applyTheme(mode){const light=matchMedia('(prefers-color-scheme: light)').matches;document.documentElement.dataset.theme=mode==='system'?(light?'light':'dark'):mode;if(select)select.value=mode}applyTheme(saved);select?.addEventListener('change',()=>{localStorage.setItem('superpowers-visual-theme',select.value);applyTheme(select.value)});let stamp=JSON.parse(document.body.dataset.stamp||'{"mtime":0}');async function post(e){const status=document.getElementById('status');if(status)status.textContent='saved';await fetch('/api/event',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(e)}).catch(()=>{})}window.toggleSelect=(el)=>{const multi=el.closest('[data-multiselect]');if(!multi)document.querySelectorAll('.selected').forEach(x=>x.classList.remove('selected'));el.classList.toggle('selected');post({type:'click',choice:el.dataset.choice||'',text:el.innerText.trim()})};setInterval(async()=>{try{const n=await fetch('/api/latest').then(r=>r.json());if(n.mtime&&n.mtime!==stamp.mtime)location.reload()}catch{}},1000);`;
167 + return `const select=document.getElementById('theme-mode');const saved=localStorage.getItem('superpowers-visual-theme')||'system';function applyTheme(mode){const light=matchMedia('(prefers-color-scheme: light)').matches;document.documentElement.dataset.theme=mode==='system'?(light?'light':'dark'):mode;if(select)select.value=mode}applyTheme(saved);select?.addEventListener('change',()=>{localStorage.setItem('superpowers-visual-theme',select.value);applyTheme(select.value)});let stamp=JSON.parse(document.body.dataset.stamp||'{"mtime":0}');async function post(e){const status=document.getElementById('status');if(status)status.textContent='saved';await fetch('/api/event',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(e)}).catch(()=>{})}window.toggleSelect=(el)=>{const multi=el.closest('[data-multiselect]');if(!multi)document.querySelectorAll('.selected').forEach(x=>x.classList.remove('selected'));el.classList.toggle('selected');post({type:'click',choice:el.dataset.choice||'',text:el.innerText.trim()})};document.addEventListener('click',e=>{const el=e.target.closest?.('[data-choice]');if(!el||el.hasAttribute('onclick'))return;window.toggleSelect(el)});setInterval(async()=>{try{const n=await fetch('/api/latest').then(r=>r.json());if(n.mtime&&n.mtime!==stamp.mtime)location.reload()}catch{}},1000);`;
169 170 async function readBody(req: IncomingMessage) {