repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(superpowers): add workflow extension

7325bf33272570269503bd42262e1af8c69fccf4

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (35)

extensions/superpowers/README.md

Added
new file mode 100644
1 +# superpowers
3 +Background subagents and explicit workflow discipline for Pi.
5 +## Activation
7 +```bash
8 +pi -e ./extensions/superpowers/index.ts
9 +pi -e ./extensions/superpowers/index.ts --superpowers
10 +```
12 +`/superpowers` toggles strict upstream-style workflow discipline for the current session.
13 +`--superpowers` starts with that mode already enabled.
15 +Strict mode means future non-trivial coding turns must pick and follow the smallest applicable Superpowers workflow, then verify before claiming completion.
17 +Prompts/skills remain installed and manually callable when off. Off only disables automatic methodology pressure.
18 +No always-on activation unless you opt in. No hidden agents.
20 +## Commands
22 +```text
23 +/superpowers # toggle workflow discipline
24 +/superpowers on
25 +/superpowers off
26 +/superpowers run <agent> [args]
27 +/superpowers open <id>
28 +/superpowers branch <id>
29 +/superpowers return <summary>
30 +/superpowers abort <id>
31 +/superpowers status [id]
33 +# workflow aliases → background workers
34 +/superpowers design <args> # brainstorming
35 +/superpowers plan <args> # writing-plans
36 +/superpowers execute <args> # executing-plans
37 +/superpowers parallel <args> # dispatching-parallel-agents
38 +/superpowers review <args> # requesting-code-review
39 +/superpowers deslop <args> # requesting-code-review, focused on slop
40 +/superpowers compress <args> # requesting-code-review, focused on DRY/design compression
41 +/superpowers debug <args> # systematic-debugging
42 +/superpowers git <args> # using-git-worktrees
43 +/superpowers meta <args> # writing-skills
44 +/superpowers verify <args> # verification-before-completion
46 +# visual brainstorming companion
47 +/superpowers visual start
48 +/superpowers visual status
49 +/superpowers visual stop
50 +```
52 +Agents are normal Pi prompt templates:
54 +```text
55 +.pi/prompts/*.md
56 +~/.pi/agent/prompts/*.md
57 +```
59 +Use the same file either way:
61 +```text
62 +/review ...
63 +/superpowers run review ...
64 +```
66 +Supported frontmatter:
68 +```yaml
69 +tools: [read, grep]
70 +extensions: ["*", "-superpowers"]
71 +thinking: off
72 +model: provider/model
73 +```
75 +Bundled workflow skills + prompt entrypoints:
77 +```text
78 +/using-superpowers
79 +/brainstorming
80 +/writing-plans
81 +/executing-plans
82 +/dispatching-parallel-agents
83 +/subagent-driven-development
84 +/requesting-code-review
85 +/receiving-code-review
86 +/test-driven-development
87 +/systematic-debugging
88 +/verification-before-completion
89 +/using-git-worktrees
90 +/finishing-a-development-branch
91 +/writing-skills
92 +```
94 +`skills/*/SKILL.md` holds the methodology. `prompts/*.md` are normal Pi slash prompt wrappers around those skills.
96 +Same prompts work as background workers:
98 +```text
99 +/superpowers run systematic-debugging flaky test
100 +/superpowers run requesting-code-review current diff
101 +```
103 +Runtime state lives in the platform state dir, per project:
105 +```text
106 +Linux: ${XDG_STATE_HOME:-~/.local/state}/pi/superpowers/<project-hash>/
107 +macOS: ~/Library/Application Support/pi/superpowers/<project-hash>/
108 +Windows: %LOCALAPPDATA%\\pi\\superpowers\\<project-hash>\\
109 +```
111 +Project/VCS state is only written by workflows that intentionally create docs/specs, e.g. `docs/superpowers/specs/...`.
113 +`status` is optimized for tmux supervision: summaries include id, state,
114 +elapsed time, agent name, tool count, and first result line. `status <id>` shows
115 +prompt, parent/child sessions, and latest result without opening an editor.
117 +## Shape
119 +From `/tmp/pi-superpowers-proto/DESIGN.md`:
121 +```text
122 +run = background SDK agent
123 +open = inspect checkpoint/log
124 +branch = stop/promote into ctx.newSession({ parentSession })
125 +return = ctx.switchSession(parent)
126 +```
128 +No Pi subprocesses. Uses Pi SDK sessions/resource loading directly.

extensions/superpowers/__tests__/harness.test.ts

Added
new file mode 100644
1 +import { afterEach, describe, expect, it } from "bun:test";
2 +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3 +import path from "node:path";
4 +import {
5 + createTestSession,
6 + type TestSession,
7 +} from "@marcfargas/pi-test-harness";
8 +import { __test } from "../index.ts";
10 +let t: TestSession | undefined;
11 +afterEach(() => {
12 + t?.dispose();
13 + t = undefined;
14 +});
16 +const extPath = () => path.resolve(import.meta.dir, "../index.ts");
17 +const command = () =>
18 + t!.session.extensionRunner.extensions[0].commands.get("superpowers")!;
19 +const ctx = () => t!.session.extensionRunner.createCommandContext();
20 +const notices = () =>
21 + t!.events.uiCallsFor("notify").map((c) => String(c.args[0]));
22 +const tasksPath = () => __test.tasksFile(t!.cwd);
23 +const tasks = () => JSON.parse(readFileSync(tasksPath(), "utf8"));
24 +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
26 +async function waitFor(fn: () => boolean) {
27 + for (let i = 0; i < 80; i++) {
28 + if (fn()) return;
29 + await sleep(25);
30 + }
31 + expect(fn()).toBe(true);
34 +describe("superpowers harness", () => {
35 + it("loads in real Pi runtime and registers command/flag", async () => {
36 + t = await createTestSession({ extensions: [extPath()] });
37 + const [extension] = t.session.extensionRunner.extensions;
38 + expect(extension.path).toBe(extPath());
39 + expect(extension.commands.has("superpowers")).toBe(true);
40 + expect(extension.flags.has("superpowers")).toBe(true);
41 + expect(typeof command().getArgumentCompletions).toBe("function");
42 + });
44 + it("toggles workflow mode and reports usage/status/open failures without agent calls", async () => {
45 + t = await createTestSession({ extensions: [extPath()] });
46 + await command().handler("", ctx());
47 + await command().handler("", ctx());
48 + await command().handler("on", ctx());
49 + await command().handler("off", ctx());
50 + await command().handler("help", ctx());
51 + await command().handler("agent", ctx());
52 + await command().handler("status", ctx());
53 + await command().handler("open sp-404", ctx());
54 + expect(notices()).toContain("superpowers on");
55 + expect(notices()).toContain("superpowers off");
56 + expect(notices().some((m) => m.includes("superpowers off\nno tasks"))).toBe(true);
57 + expect(notices().some((m) => m.includes("/superpowers agent"))).toBe(true);
58 + expect(notices()).toContain("usage: /superpowers agent <prompt>");
59 + expect(notices().some((m) => m.includes("no tasks"))).toBe(true);
60 + expect(notices()).toContain("no such task: sp-404");
61 + });
63 + it("review family aliases start requesting-code-review workers", async () => {
64 + t = await createTestSession({ extensions: [extPath()] });
65 + mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
66 + writeFileSync(
67 + path.join(t.cwd, ".pi/prompts/requesting-code-review.md"),
68 + "Review $ARGUMENTS",
69 + "utf8",
70 + );
71 + await command().handler("compress src", ctx());
72 + await waitFor(
73 + () =>
74 + existsSync(tasksPath()) &&
75 + ["done", "error"].includes(tasks()["sp-1"]?.status),
76 + );
77 + expect(tasks()["sp-1"].agent).toBe("requesting-code-review");
78 + expect(tasks()["sp-1"].prompt).toBe("Review src");
79 + });
81 + it("workflow aliases start matching prompt workers", async () => {
82 + t = await createTestSession({ extensions: [extPath()] });
83 + mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
84 + writeFileSync(
85 + path.join(t.cwd, ".pi/prompts/systematic-debugging.md"),
86 + "Debug $ARGUMENTS",
87 + "utf8",
88 + );
89 + await command().handler("debug flaky test", ctx());
90 + await waitFor(
91 + () =>
92 + existsSync(tasksPath()) &&
93 + ["done", "error"].includes(tasks()["sp-1"]?.status),
94 + );
95 + expect(tasks()["sp-1"].agent).toBe("systematic-debugging");
96 + expect(tasks()["sp-1"].prompt).toBe("Debug flaky test");
97 + });
99 + it("finds project prompt names for autocomplete", async () => {
100 + t = await createTestSession({ extensions: [extPath()] });
101 + mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
102 + writeFileSync(
103 + path.join(t.cwd, ".pi/prompts/review.md"),
104 + "Review $ARGUMENTS",
105 + "utf8",
106 + );
107 + expect(command().getArgumentCompletions("run re")).toContainEqual({
108 + value: "run review",
109 + label: "review",
110 + });
111 + expect(command().getArgumentCompletions("run review keep-args")).toEqual(
112 + [],
113 + );
114 + });
116 + it("starts an embedded SDK agent and persists task state", async () => {
117 + t = await createTestSession({ extensions: [extPath()] });
118 + mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
119 + writeFileSync(
120 + path.join(t.cwd, ".pi/prompts/echo.md"),
121 + "Say ok for $ARGUMENTS",
122 + "utf8",
123 + );
124 + await command().handler("run echo smoke", ctx());
125 + await waitFor(
126 + () =>
127 + existsSync(tasksPath()) &&
128 + ["done", "error"].includes(tasks()["sp-1"]?.status),
129 + );
130 + expect(tasks()["sp-1"].prompt).toBe("Say ok for smoke");
131 + expect(tasks()["sp-1"].log[0]).toContain("start echo");
132 + });
134 + it("continues task ids from persisted task store on session_start", async () => {
135 + t = await createTestSession({ extensions: [extPath()] });
136 + mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
137 + writeFileSync(path.join(t.cwd, ".pi/prompts/echo.md"), "Say ok", "utf8");
138 + mkdirSync(path.dirname(tasksPath()), { recursive: true });
139 + writeFileSync(
140 + tasksPath(),
141 + JSON.stringify({
142 + "sp-9": {
143 + id: "sp-9",
144 + agent: "old",
145 + prompt: "old",
146 + status: "done",
147 + startedAt: "a",
148 + updatedAt: "b",
149 + log: ["old"],
150 + },
151 + }),
152 + "utf8",
153 + );
154 + await t.session.extensionRunner.emit({
155 + type: "session_start",
156 + reason: "resume",
157 + });
158 + await command().handler("run echo", ctx());
159 + expect(tasks()["sp-10"].agent).toBe("echo");
160 + });
162 + it("opens persisted task logs in the Pi editor and reports detailed status", async () => {
163 + t = await createTestSession({ extensions: [extPath()] });
164 + mkdirSync(path.dirname(tasksPath()), { recursive: true });
165 + writeFileSync(
166 + tasksPath(),
167 + JSON.stringify({
168 + "sp-7": {
169 + id: "sp-7",
170 + agent: "demo",
171 + prompt: "demo prompt",
172 + status: "done",
173 + startedAt: "2026-01-01T00:00:00.000Z",
174 + updatedAt: "2026-01-01T00:00:03.000Z",
175 + parentSession: "/tmp/parent.jsonl",
176 + log: ["checkpoint"],
177 + result: "DONE\nmore",
178 + },
179 + }),
180 + "utf8",
181 + );
182 + expect(command().getArgumentCompletions("open sp")).toContainEqual({
183 + value: "open sp-7",
184 + label: "sp-7",
185 + });
186 + expect(command().getArgumentCompletions("status sp")).toContainEqual({
187 + value: "status sp-7",
188 + label: "sp-7",
189 + });
190 + await command().handler("open sp-7", ctx());
191 + expect(t.events.uiCallsFor("editor")[0].args[0]).toBe("superpowers sp-7");
192 + expect(String(t.events.uiCallsFor("editor")[0].args[1])).toContain(
193 + "checkpoint",
194 + );
195 + await command().handler("status sp-7", ctx());
196 + expect(notices().at(-1)).toContain("sp-7 done 3s demo — DONE");
197 + expect(notices().at(-1)).toContain("prompt:\ndemo prompt");
198 + });
200 + it("guards branch when harness has no persisted parent session", async () => {
201 + t = await createTestSession({ extensions: [extPath()] });
202 + mkdirSync(path.dirname(tasksPath()), { recursive: true });
203 + writeFileSync(
204 + tasksPath(),
205 + JSON.stringify({
206 + "sp-7": {
207 + id: "sp-7",
208 + agent: "demo",
209 + prompt: "demo",
210 + status: "done",
211 + startedAt: "a",
212 + updatedAt: "b",
213 + log: ["checkpoint"],
214 + },
215 + }),
216 + "utf8",
217 + );
218 + await command().handler("branch sp-7", ctx());
219 + expect(notices()).toContain(
220 + "/superpowers branch requires persisted parent session",
221 + );
222 + });
223 +});

extensions/superpowers/__tests__/helpers.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "bun:test";
2 +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3 +import os from "node:os";
4 +import path from "node:path";
5 +import { __test } from "../index.ts";
6 +import { startVisualServer } from "../visual";
8 +describe("superpowers helpers", () => {
9 + it("uses platform state dirs for runtime state", () => {
10 + expect(__test.platformStateDir("linux", {}, "/home/me")).toBe(
11 + "/home/me/.local/state/pi",
12 + );
13 + expect(__test.platformStateDir("linux", { XDG_STATE_HOME: "/state" }, "/home/me")).toBe("/state/pi");
14 + expect(__test.platformStateDir("darwin", {}, "/Users/me")).toBe(
15 + "/Users/me/Library/Application Support/pi",
16 + );
17 + expect(
18 + __test.platformStateDir(
19 + "win32",
20 + { LOCALAPPDATA: "C:\\Users\\me\\AppData\\Local" },
21 + "C:\\Users\\me",
22 + ),
23 + ).toBe("C:\\Users\\me\\AppData\\Local\\pi");
24 + expect(__test.dir("/tmp/project")).toContain(path.join("pi", "superpowers"));
25 + });
27 + it("ships workflow prompts and skills", () => {
28 + const root = path.resolve(import.meta.dir, "..");
29 + for (const name of [
30 + "brainstorming",
31 + "writing-plans",
32 + "executing-plans",
33 + "dispatching-parallel-agents",
34 + "subagent-driven-development",
35 + "requesting-code-review",
36 + "receiving-code-review",
37 + "test-driven-development",
38 + "systematic-debugging",
39 + "verification-before-completion",
40 + "using-git-worktrees",
41 + "finishing-a-development-branch",
42 + "writing-skills",
43 + "using-superpowers",
44 + ]) {
45 + const prompt = path.join(root, "prompts", `${name}.md`);
46 + const skill = path.join(root, "skills", name, "SKILL.md");
47 + expect(existsSync(prompt)).toBe(true);
48 + expect(existsSync(skill)).toBe(true);
49 + const promptText = readFileSync(prompt, "utf8");
50 + expect(promptText).toContain("argument-hint:");
51 + expect(promptText).toContain(`Use the \`${name}\` skill`);
52 + expect(readFileSync(skill, "utf8")).toContain(`name: ${name}`);
53 + }
54 + });
56 + it("brainstorming workflow has approval/spec gates", () => {
57 + const skill = readFileSync(
58 + path.resolve(import.meta.dir, "../skills/brainstorming/SKILL.md"),
59 + "utf8",
60 + );
61 + expect(skill).toContain("Hard gate");
62 + expect(skill).toContain("Write spec to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`");
63 + expect(skill).toContain("After approval, hand off only to `writing-plans`");
64 + });
66 + it("agent-facing prompts omit hidden visual debug commands", () => {
67 + const root = path.resolve(import.meta.dir, "..");
68 + const promptFiles = readdirSync(path.join(root, "prompts")).map((f) =>
69 + path.join(root, "prompts", f),
70 + );
71 + const skillFiles = readdirSync(path.join(root, "skills")).map((d) =>
72 + path.join(root, "skills", d, "SKILL.md"),
73 + );
74 + for (const file of [...promptFiles, ...skillFiles]) {
75 + expect(readFileSync(file, "utf8")).not.toContain("visual events");
76 + expect(readFileSync(file, "utf8")).not.toContain("hidden debug");
77 + }
78 + });
80 + it("skills retain vital upstream workflow gates", () => {
81 + const skill = (name: string) =>
82 + readFileSync(path.resolve(import.meta.dir, `../skills/${name}/SKILL.md`), "utf8");
83 + expect(skill("test-driven-development")).toContain("No production code without a failing test first");
84 + expect(skill("systematic-debugging")).toContain("root-cause evidence");
85 + expect(skill("verification-before-completion")).toContain("Evidence before claims");
86 + expect(skill("writing-plans")).toContain("No `TODO`/`TBD`");
87 + expect(skill("receiving-code-review")).toContain("Verify each finding against the codebase");
88 + expect(skill("using-git-worktrees")).toContain("If already in a linked worktree");
89 + });
91 + it("review workflow includes deslop and compression passes", () => {
92 + const skill = readFileSync(
93 + path.resolve(
94 + import.meta.dir,
95 + "../skills/requesting-code-review/SKILL.md",
96 + ),
97 + "utf8",
98 + );
99 + const prompt = readFileSync(
100 + path.resolve(import.meta.dir, "../prompts/requesting-code-review.md"),
101 + "utf8",
102 + );
103 + expect(skill).toContain("Deslop Gate");
104 + expect(skill).toContain("Compression Gate");
105 + expect(skill).toContain("Review only. Do not edit.");
106 + expect(prompt).toContain("tools: [read, bash, grep, find, ls]");
107 + });
109 + it("visual server serves latest screen and records events", async () => {
110 + const root = mkdtempSync(path.join(os.tmpdir(), "sp-visual-"));
111 + try {
112 + const visual = await startVisualServer({ root, preferredPort: 0 });
113 + writeFileSync(
114 + path.join(visual.contentDir, "001-options.html"),
115 + '<div class="option" data-choice="a" onclick="toggleSelect(this)">A</div>',
116 + );
117 + const html = await fetch(visual.url).then((r) => r.text());
118 + expect(html).toContain("Visual Brainstorming");
119 + expect(html).toContain('data-choice="a"');
120 + const eventUrl = new URL("/api/event", visual.url);
121 + eventUrl.search = new URL(visual.url).search;
122 + await fetch(eventUrl, {
123 + method: "POST",
124 + headers: { "content-type": "application/json" },
125 + body: JSON.stringify({ type: "click", choice: "a" }),
126 + });
127 + expect(readFileSync(visual.eventsFile, "utf8")).toContain('"choice":"a"');
128 + expect(html).not.toContain("event-count");
129 + visual.close();
130 + } finally {
131 + rmSync(root, { recursive: true, force: true });
133 + });
135 + it("package manifest ships extension, prompts, and skills", () => {
136 + const pkg = JSON.parse(
137 + readFileSync(path.resolve(import.meta.dir, "../package.json"), "utf8"),
138 + );
139 + expect(pkg.pi).toEqual({
140 + extensions: ["./index.ts"],
141 + prompts: ["./prompts"],
142 + skills: ["./skills"],
143 + });
144 + });
146 + it("parses frontmatter and substitutes arguments", () => {
147 + const parsed = __test.parseAgentFile(
148 + `---\ndescription: demo\ntools: [read, "grep"]\nextensions: ["*", -superpowers]\nthinking: off\nmodel: zai/glm-5.1\n---\nDo $ARGUMENTS now`,
149 + "work",
150 + );
151 + expect(parsed.prompt).toBe("Do work now");
152 + expect(parsed.options).toEqual({
153 + tools: ["read", "grep"],
154 + extensions: ["*", "-superpowers"],
155 + thinking: "off",
156 + model: "zai/glm-5.1",
157 + });
158 + });
160 + it("resolves include/exclude globs as sets", () => {
161 + expect(
162 + __test.resolveNames(["*", "-write", "-edit"], ["read", "write", "edit"]),
163 + ).toEqual(["read"]);
164 + expect(
165 + __test.resolveNames(["g*", "-grep"], ["grep", "goal", "read"]),
166 + ).toEqual(["goal"]);
167 + expect(__test.resolveNames(["*", "-superpowers"], ["superpowers"])).toEqual(
168 + [],
169 + );
170 + expect(
171 + __test.resolveNames(
172 + ["super*", "-superpowers"],
173 + ["superpowers", "supervisor"],
174 + ),
175 + ).toEqual(["supervisor"]);
176 + expect(__test.resolveNames(undefined, ["read"])).toBeUndefined();
177 + });
179 + it("formats branch injection context", () => {
180 + const text = __test.childPrompt({
181 + id: "sp-7",
182 + parentSession: "/tmp/main.jsonl",
183 + log: ["start", "done"],
184 + });
185 + expect(text).toContain("Superpowers takeover: sp-7");
186 + expect(text).toContain("/superpowers return <summary>");
187 + expect(text).toContain("start\ndone");
188 + });
190 + it("formats useful status summaries", () => {
191 + const abortedTask = {
192 + id: "sp-10",
193 + agent: "inline",
194 + prompt: "manual ui",
195 + status: "aborted" as const,
196 + startedAt: "2026-01-01T00:00:00.000Z",
197 + updatedAt: "2026-01-01T00:00:10.000Z",
198 + log: ["start", "2026-01-01T00:00:10.000Z aborted by user"],
199 + };
200 + expect(__test.summaryLine(abortedTask)).toBe(
201 + "sp-10 aborted 10s inline — 2026-01-01T00:00:10.000Z aborted by user",
202 + );
204 + const task = {
205 + id: "sp-9",
206 + agent: "inline",
207 + prompt: "do work",
208 + status: "done" as const,
209 + startedAt: "2026-01-01T00:00:00.000Z",
210 + updatedAt: "2026-01-01T00:01:05.000Z",
211 + parentSession: "/tmp/parent.jsonl",
212 + log: ["start", "2026-01-01T00:00:01.000Z tool read"],
213 + result: "DONE\nextra detail",
214 + };
215 + expect(__test.summaryLine(task)).toBe(
216 + "sp-9 done 1m5s inline tools:1 — DONE",
217 + );
218 + const detail = __test.taskDetails(task);
219 + expect(detail).toContain("prompt:\ndo work");
220 + expect(detail).toContain("parent: /tmp/parent.jsonl");
221 + expect(detail).toContain("latest:\nDONE\nextra detail");
222 + });
223 +});

extensions/superpowers/docs-visual-brainstorming.md

Added
new file mode 100644
1 +# Visual Brainstorming Research
3 +Source inspected: upstream `obra/superpowers` brainstorming skill and visual companion docs.
5 +## How upstream works
7 +Visual brainstorming is not a separate mode. It is an optional browser companion offered during brainstorming when upcoming questions are easier to answer visually.
9 +Flow:
11 +1. Brainstorming starts with text/context exploration.
12 +2. If visual questions are likely, agent sends a standalone consent message.
13 +3. If user agrees, agent starts a local browser server.
14 +4. Agent writes HTML fragments into a watched content directory.
15 +5. Browser always shows newest HTML screen.
16 +6. User clicks options/cards/mockups in browser and also responds in terminal.
17 +7. Browser events are stored as JSONL in a state directory.
18 +8. Agent reads events next turn and merges them with terminal feedback.
19 +9. For non-visual questions, agent pushes a waiting screen and continues in terminal.
21 +## UX rules
23 +- Offer visual companion once, in its own message.
24 +- Decide per question whether visual helps.
25 +- Use browser for mockups, wireframes, diagrams, layout/color/design comparisons.
26 +- Use terminal for requirements, scope, text tradeoffs, technical decisions.
27 +- User terminal response remains primary; click events are supporting evidence.
28 +- Each screen uses a new semantic filename.
29 +- Stale screens should be replaced with “Continuing in terminal…” when leaving visual mode.
31 +## Technical shape
33 +Upstream server:
35 +- zero-dependency Node server using built-ins
36 +- serves newest `.html` from screen dir
37 +- wraps HTML fragments in a frame template
38 +- injects helper JS
39 +- records clicks/selections to JSONL events file
40 +- uses WebSocket reload to update browser
41 +- stores session under project `.superpowers/brainstorm/...`
43 +Important directories:
45 +```text
46 +.superpowers/brainstorm/<session>/content/ # HTML screens
47 +.superpowers/brainstorm/<session>/state/ # events + server-info
48 +```
50 +## Design implications for Pi
52 +For our Pi Superpowers:
54 +- Keep visual brainstorming explicitly activated by brainstorming workflow.
55 +- Do not make it a hidden hook.
56 +- It should be an explicit `/superpowers visual ...` tool, not automatic strict-mode behavior.
57 +- 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 +- Use Pi UI notification and a visible session message to show URL and paths.
59 +- Use `read`/`write` tool workflow for screens/events.
60 +- Keep zero dependency: Node built-ins or Bun server only.
62 +## Recommended Pi UX
64 +```text
65 +/brainstorming improve dashboard UX
66 +```
68 +Agent:
70 +```text
71 +Some choices are visual. I can open a local browser companion for mockups and layout comparisons. Use it? (local URL)
72 +```
74 +If yes:
76 +```text
77 +/superpowers visual start
78 +```
80 +Then:
82 +```text
83 +Showing 3 dashboard layout options at http://localhost:NNNN.
84 +Click one if useful, then tell me what you think here.
85 +```
87 +Future command candidates:
89 +```text
90 +/superpowers visual start
91 +/superpowers visual show <html-fragment-file>
92 +/superpowers visual stop
93 +```
95 +## What not to copy blindly
97 +- Do not vendor dependencies.
98 +- Do not force browser for conceptual questions.
99 +- Do not let visual companion skip design approval/spec gates.
100 +- Do not store under non-Pi `.superpowers` unless intentionally matching upstream.
101 +- Do not make visual server start automatically on `/superpowers on`.

extensions/superpowers/index.ts

Added
new file mode 100644
1 +import { createHash } from "node:crypto";
2 +import {
3 + existsSync,
4 + mkdirSync,
5 + readdirSync,
6 + readFileSync,
7 + writeFileSync,
8 +} from "node:fs";
9 +import os from "node:os";
10 +import path from "node:path";
11 +import { getModel } from "@earendil-works/pi-ai";
12 +import {
13 + createAgentSession,
14 + DefaultResourceLoader,
15 + type ExtensionAPI,
16 + type ExtensionCommandContext,
17 + type ExtensionContext,
18 + getAgentDir,
19 + SessionManager,
20 + SettingsManager,
21 +} from "@earendil-works/pi-coding-agent";
22 +import { openBrowser, startVisualServer, type VisualSession } from "./visual";
24 +const ID = "superpowers";
25 +const WIDGET = "superpowers";
26 +const FLAG_PROMPT = `
28 +Superpowers active. Strict mode.
30 +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>.
37 +`;
38 +const COMMANDS = [
39 + "run",
40 + "agent",
41 + "open",
42 + "branch",
43 + "return",
44 + "abort",
45 + "status",
46 + "on",
47 + "off",
48 + "design",
49 + "plan",
50 + "execute",
51 + "parallel",
52 + "review",
53 + "deslop",
54 + "compress",
55 + "debug",
56 + "git",
57 + "meta",
58 + "verify",
59 + "visual",
60 + "help",
61 +];
62 +const ALIASES: Record<string, string> = {
63 + design: "brainstorming",
64 + plan: "writing-plans",
65 + execute: "executing-plans",
66 + parallel: "dispatching-parallel-agents",
67 + review: "requesting-code-review",
68 + deslop: "requesting-code-review",
69 + compress: "requesting-code-review",
70 + debug: "systematic-debugging",
71 + git: "using-git-worktrees",
72 + meta: "writing-skills",
73 + verify: "verification-before-completion",
74 +};
75 +type Status = "running" | "done" | "error" | "aborted" | "branched";
76 +type Options = {
77 + tools?: string[];
78 + extensions?: string[];
79 + thinking?: string;
80 + model?: string;
81 +};
82 +type Task = {
83 + id: string;
84 + agent: string;
85 + prompt: string;
86 + status: Status;
87 + startedAt: string;
88 + updatedAt: string;
89 + parentSession?: string;
90 + childSession?: string;
91 + log: string[];
92 + result?: string;
93 +};
94 +type Runtime = {
95 + cwd: string;
96 + task: Task;
97 + abort?: () => void;
98 + dispose?: () => void;
99 +};
100 +type Entry =
101 + | { kind: "task"; task: Task }
102 + | { kind: "child"; task: Task }
103 + | { kind: "return"; taskId: string; summary: string; childSession?: string };
105 +const live = new Map<string, Runtime>();
106 +let next = 1;
107 +let generation = 0;
108 +let currentCwd = process.cwd();
109 +let active = false;
110 +let visual: VisualSession | undefined;
112 +const now = () => new Date().toISOString();
113 +function platformStateDir(
114 + platform: NodeJS.Platform = process.platform,
115 + env: NodeJS.ProcessEnv = process.env,
116 + home = os.homedir(),
117 +) {
118 + const paths = platform === "win32" ? path.win32 : path.posix;
119 + if (platform === "win32")
120 + return paths.join(env.LOCALAPPDATA ?? paths.join(home, "AppData", "Local"), "pi");
121 + if (env.XDG_STATE_HOME) return paths.join(env.XDG_STATE_HOME, "pi");
122 + if (platform === "darwin") return paths.join(home, "Library", "Application Support", "pi");
123 + return paths.join(home, ".local", "state", "pi");
125 +function hashProjectRoot(cwd: string) {
126 + return createHash("sha256").update(path.resolve(cwd)).digest("hex");
128 +const dir = (cwd: string) => path.join(platformStateDir(), "superpowers", hashProjectRoot(cwd));
129 +const tasksFile = (cwd: string) => path.join(dir(cwd), "tasks.json");
130 +const sessionsDir = (cwd: string) => path.join(dir(cwd), "sessions");
131 +const ensure = (cwd: string) => mkdirSync(sessionsDir(cwd), { recursive: true });
132 +const text = (x: unknown): string =>
133 + typeof x === "string"
134 + ? x
135 + : Array.isArray(x)
136 + ? x
137 + .map((p) => (p?.type === "text" ? p.text : ""))
138 + .filter(Boolean)
139 + .join("\n")
140 + : "";
142 +function readTasks(cwd: string): Record<string, Task> {
143 + try {
144 + return JSON.parse(readFileSync(tasksFile(cwd), "utf8"));
145 + } catch {
146 + return {};
149 +function writeTask(cwd: string, task: Task) {
150 + ensure(cwd);
151 + const all = readTasks(cwd);
152 + all[task.id] = task;
153 + writeFileSync(tasksFile(cwd), `${JSON.stringify(all, null, "\t")}\n`);
155 +function append(ctx: ExtensionContext, entry: Entry) {
157 + ctx.sessionManager as unknown as {
158 + appendCustomEntry(t: string, d: unknown): string;
160 + ).appendCustomEntry(ID, entry);
162 +function notify(
163 + ctx: ExtensionContext,
164 + msg: string,
165 + kind: "info" | "warning" | "error" = "info",
166 +) {
167 + if (ctx.hasUI) ctx.ui.notify(msg, kind);
169 +function firstLine(s: string | undefined) {
170 + return (s ?? "").split("\n")[0]?.trim() ?? "";
172 +function elapsed(start: string, end: string) {
173 + const a = Date.parse(start);
174 + const b = Date.parse(end);
175 + if (!Number.isFinite(a) || !Number.isFinite(b)) return "?";
176 + const sec = Math.max(0, Math.round((b - a) / 1000));
177 + return sec < 60 ? `${sec}s` : `${Math.floor(sec / 60)}m${sec % 60}s`;
179 +function toolCount(t: Task) {
180 + return t.log.filter((l) => / tool \S+/.test(l)).length;
182 +function summaryLine(t: Task) {
183 + const tail = firstLine(t.result ?? t.log.at(-1));
184 + const tools = toolCount(t);
185 + return `${t.id} ${t.status} ${elapsed(t.startedAt, t.updatedAt)} ${t.agent}${tools ? ` tools:${tools}` : ""}${tail ? ` — ${tail}` : ""}`;
187 +function taskDetails(t: Task) {
188 + return [
189 + summaryLine(t),
190 + `started: ${t.startedAt}`,
191 + `updated: ${t.updatedAt}`,
192 + `parent: ${t.parentSession ?? "none"}`,
193 + `child: ${t.childSession ?? "none"}`,
194 + "",
195 + "prompt:",
196 + t.prompt,
197 + "",
198 + "latest:",
199 + t.result ?? t.log.at(-1) ?? "",
200 + ].join("\n");
202 +function widget(ctx: ExtensionContext) {
203 + if (!ctx.hasUI) return;
204 + const tasks = Object.values(readTasks(ctx.cwd)).slice(-5);
205 + ctx.ui.setWidget(
206 + WIDGET,
207 + tasks.length || active
208 + ? [`superpowers ${active ? "on" : "off"}`, ...tasks.map(summaryLine)]
209 + : undefined,
210 + );
213 +function parseList(raw: string): string[] | undefined {
214 + const s = raw.trim().replace(/^\[/, "").replace(/\]$/, "");
215 + const xs = s
216 + .split(",")
217 + .map((x) => x.trim().replace(/^['"]|['"]$/g, ""))
218 + .filter(Boolean);
219 + return xs.length ? xs : undefined;
221 +function parseAgentFile(
222 + raw: string,
223 + args = "",
224 +): { prompt: string; options: Options } {
225 + let body = raw;
226 + const meta: Record<string, string> = {};
227 + if (raw.startsWith("---\n")) {
228 + const end = raw.indexOf("\n---\n", 4);
229 + if (end >= 0) {
230 + body = raw.slice(end + 5);
231 + for (const line of raw.slice(4, end).split("\n")) {
232 + const i = line.indexOf(":");
233 + if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim();
237 + return {
238 + prompt: body.replace(/\$ARGUMENTS|\$@/g, args).trim(),
239 + options: {
240 + tools: meta.tools && parseList(meta.tools),
241 + extensions: meta.extensions && parseList(meta.extensions),
242 + thinking: meta.thinking?.replace(/^['"]|['"]$/g, ""),
243 + model: meta.model?.replace(/^['"]|['"]$/g, ""),
244 + },
245 + };
247 +function glob(pat: string, v: string) {
248 + return (
249 + pat === "*" ||
250 + (!pat.includes("*")
251 + ? pat === v
252 + : new RegExp(
253 + `^${pat.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*")}$`,
254 + ).test(v))
255 + );
257 +function resolveNames(
258 + patterns: string[] | undefined,
259 + names: string[],
260 +): string[] | undefined {
261 + if (!patterns) return undefined;
262 + const out = new Set<string>();
263 + for (const p of patterns.filter((x) => !x.startsWith("-")))
264 + for (const n of names) if (glob(p, n)) out.add(n);
265 + for (const p of patterns
266 + .filter((x) => x.startsWith("-"))
267 + .map((x) => x.slice(1)))
268 + for (const n of names) if (glob(p, n)) out.delete(n);
269 + return [...out];
271 +function promptDirs(cwd: string) {
272 + return [path.join(cwd, ".pi/prompts"), path.join(getAgentDir(), "prompts")];
274 +function agentNames(cwd: string) {
275 + return [
276 + ...new Set(
277 + promptDirs(cwd).flatMap((d) =>
278 + existsSync(d)
279 + ? readdirSync(d)
280 + .filter((f) => f.endsWith(".md"))
281 + .map((f) => f.slice(0, -3))
282 + : [],
283 + ),
284 + ),
285 + ].sort();
287 +function loadAgent(cwd: string, name: string, args: string) {
288 + if (!/^[\w-]+$/.test(name)) return;
289 + for (const d of promptDirs(cwd)) {
290 + const f = path.join(d, `${name}.md`);
291 + if (existsSync(f)) return parseAgentFile(readFileSync(f, "utf8"), args);
294 +function childPrompt(task: Pick<Task, "id" | "parentSession" | "log">) {
295 + return `Superpowers takeover: ${task.id}\n\nParent session: ${task.parentSession ?? "unknown"}\n\nCheckpoint/log:\n${task.log.join("\n")}\n\nInspect/steer here. Run /superpowers return <summary> when done.`;
297 +function latestChild(ctx: ExtensionContext): Task | undefined {
298 + let t: Task | undefined;
299 + for (const e of ctx.sessionManager.getBranch())
300 + if (
301 + e.type === "custom" &&
302 + e.customType === ID &&
303 + (e.data as Entry)?.kind === "child"
305 + t = (e.data as Extract<Entry, { kind: "child" }>).task;
306 + return t;
308 +function modelFrom(s: string | undefined, fallback: ExtensionContext["model"]) {
309 + const [provider, ...id] = s?.split("/") ?? [];
310 + return provider && id.length
311 + ? getModel(provider, id.join("/"))
312 + : (fallback ?? getModel("openai", "gpt-4o"));
314 +function extName(p: string) {
315 + return path.basename(p) === "index.ts"
316 + ? path.basename(path.dirname(p))
317 + : path.basename(p).replace(/\.[^.]+$/, "");
319 +function stopRuntime(r: Runtime, status: Status) {
320 + r.abort?.();
321 + r.dispose?.();
322 + r.task.status = status;
323 + r.task.updatedAt = now();
324 + writeTask(r.cwd, r.task);
327 +function stopAll(status: Status = "aborted") {
328 + for (const [id, r] of live) {
329 + if (r.task.status === "running") stopRuntime(r, status);
330 + live.delete(id);
334 +function stopPeers(keepId: string) {
335 + for (const [id, r] of live) {
336 + if (id === keepId) continue;
337 + if (r.task.status === "running") stopRuntime(r, "aborted");
338 + live.delete(id);
342 +async function startAgent(
343 + name: string,
344 + loaded: { prompt: string; options: Options },
345 + ctx: ExtensionCommandContext,
346 + pi: ExtensionAPI,
347 +) {
348 + const cwd = ctx.cwd;
349 + const parentSession = ctx.sessionManager.getSessionFile();
350 + const model = ctx.model;
351 + const modelRegistry = ctx.modelRegistry;
352 + const availableTools = pi.getAllTools().map((t) => t.name);
353 + const thinking = pi.getThinkingLevel();
354 + ensure(cwd);
355 + const id = `sp-${next++}`;
356 + const task: Task = {
357 + id,
358 + agent: name,
359 + prompt: loaded.prompt,
360 + status: "running",
361 + startedAt: now(),
362 + updatedAt: now(),
363 + parentSession,
364 + log: [`${now()} start ${name}`],
365 + };
366 + live.set(id, { cwd, task });
367 + writeTask(cwd, task);
368 + append(ctx, { kind: "task", task });
369 + widget(ctx);
370 + pi.sendMessage(
372 + customType: ID,
373 + display: true,
374 + content: `Superpowers ${id} started: ${name}`,
375 + details: { taskId: id },
376 + },
377 + { triggerTurn: false },
378 + );
379 + notify(ctx, `${id} started`, "info");
380 + const gen = generation;
381 + void (async () => {
382 + let session:
383 + | Awaited<ReturnType<typeof createAgentSession>>["session"]
384 + | undefined;
385 + try {
386 + const agentDir = getAgentDir();
387 + const settingsManager = SettingsManager.create(cwd, agentDir);
388 + const ext = loaded.options.extensions;
389 + const loader = new DefaultResourceLoader({
390 + cwd,
391 + agentDir,
392 + settingsManager,
393 + noExtensions: !ext,
394 + extensionsOverride: ext
395 + ? (base) => ({
396 + ...base,
397 + extensions: base.extensions.filter(
398 + (e) => (resolveNames(ext, [extName(e.path)])?.length ?? 0) > 0,
399 + ),
400 + })
401 + : undefined,
402 + });
403 + await loader.reload();
404 + const tools = resolveNames(loaded.options.tools, availableTools);
405 + const created = await createAgentSession({
406 + cwd,
407 + agentDir,
408 + model: modelFrom(loaded.options.model, model),
409 + modelRegistry,
410 + thinkingLevel: (loaded.options.thinking ?? thinking) as never,
411 + settingsManager,
412 + resourceLoader: loader,
413 + sessionManager: SessionManager.create(cwd, sessionsDir(cwd), {
414 + parentSession: task.parentSession,
415 + }),
416 + ...(tools ? { tools } : { noTools: "all" as const }),
417 + });
418 + session = created.session;
419 + const rt = live.get(id);
420 + if (rt) {
421 + rt.abort = () => void session?.abort();
422 + rt.dispose = () => session?.dispose();
424 + let answer = "";
425 + const off = session.subscribe((e) => {
426 + if (gen !== generation || task.status !== "running") return;
427 + if (e.type === "tool_execution_start") {
428 + task.log.push(`${now()} tool ${e.toolName}`);
429 + task.updatedAt = now();
430 + writeTask(cwd, task);
431 + widget(ctx);
432 + } else if (e.type === "message_end" && e.message.role === "assistant")
433 + answer = text(e.message.content).trim();
434 + });
435 + try {
436 + await session.prompt(loaded.prompt, {
437 + source: "extension",
438 + expandPromptTemplates: false,
439 + });
440 + } finally {
441 + off();
443 + if (gen !== generation || task.status !== "running") return;
444 + task.result = answer;
445 + task.status = "done";
446 + task.updatedAt = now();
447 + task.log.push(`${task.updatedAt} done\n${task.result}`);
448 + } catch (err) {
449 + if (task.status === "running") {
450 + task.status = "error";
451 + task.updatedAt = now();
452 + task.log.push(`${task.updatedAt} error ${(err as Error).message}`);
454 + } finally {
455 + session?.dispose();
456 + live.delete(id);
457 + writeTask(cwd, task);
458 + if (gen === generation) {
459 + append(ctx, { kind: "task", task });
460 + widget(ctx);
463 + })();
466 +async function runAgent(
467 + name: string,
468 + args: string,
469 + ctx: ExtensionCommandContext,
470 + pi: ExtensionAPI,
471 +) {
472 + const loaded = loadAgent(ctx.cwd, name, args);
473 + if (!loaded) return notify(ctx, `agent not found: ${name}`, "error");
474 + return startAgent(name, loaded, ctx, pi);
477 +async function inlineAgent(
478 + prompt: string,
479 + ctx: ExtensionCommandContext,
480 + pi: ExtensionAPI,
481 +) {
482 + if (!prompt.trim())
483 + return notify(ctx, "usage: /superpowers agent <prompt>", "error");
484 + return startAgent(
485 + "inline",
486 + { prompt, options: { tools: ["*"], thinking: "off" } },
487 + ctx,
488 + pi,
489 + );
492 +async function openTask(id: string, ctx: ExtensionCommandContext) {
493 + const t = readTasks(ctx.cwd)[id.trim()];
494 + if (!t) return notify(ctx, `no such task: ${id.trim()}`, "error");
495 + if (ctx.hasUI)
496 + await ctx.ui.editor(
497 + `superpowers ${t.id}`,
499 + `# ${t.id} ${t.status}`,
500 + `agent: ${t.agent}`,
501 + `parent: ${t.parentSession ?? "none"}`,
502 + "",
503 + ...t.log,
504 + ].join("\n"),
505 + );
507 +async function branchTask(id: string, ctx: ExtensionCommandContext) {
508 + const task = readTasks(ctx.cwd)[id.trim()];
509 + if (!task) return notify(ctx, `no such task: ${id.trim()}`, "error");
510 + if (!task.parentSession)
511 + return notify(
512 + ctx,
513 + "/superpowers branch requires persisted parent session",
514 + "error",
515 + );
516 + const rt = live.get(task.id);
517 + if (rt) {
518 + stopRuntime(rt, "branched");
519 + live.delete(task.id);
521 + stopPeers(task.id);
522 + task.status = "branched";
523 + task.updatedAt = now();
524 + task.log.push(`${task.updatedAt} branched`);
525 + writeTask(ctx.cwd, task);
526 + append(ctx, { kind: "task", task });
527 + await ctx.waitForIdle();
528 + const r = await ctx.newSession({
529 + parentSession: task.parentSession,
530 + withSession: async (child) => {
531 + task.childSession = child.sessionManager.getSessionFile();
532 + writeTask(child.cwd, task);
533 + append(child, { kind: "child", task });
534 + if (child.hasUI)
535 + child.ui.setWidget(WIDGET, [
536 + `superpowers child ${task.id}`,
537 + "/superpowers return <summary>",
538 + ]);
539 + await child.sendMessage(
541 + customType: ID,
542 + display: true,
543 + content: childPrompt(task),
544 + details: { taskId: task.id },
545 + },
546 + { triggerTurn: false },
547 + );
548 + },
549 + });
550 + if (r.cancelled) notify(ctx, "branch cancelled", "warning");
552 +async function returnTask(summary: string, ctx: ExtensionCommandContext) {
553 + const task = latestChild(ctx);
554 + if (!task?.parentSession)
555 + return notify(ctx, "not in a superpowers child", "warning");
556 + const childSession = ctx.sessionManager.getSessionFile();
557 + await ctx.switchSession(task.parentSession, {
558 + withSession: async (parent) => {
559 + append(parent, {
560 + kind: "return",
561 + taskId: task.id,
562 + summary,
563 + childSession,
564 + });
565 + if (parent.hasUI) parent.ui.setWidget(WIDGET, undefined);
566 + await parent.sendMessage(
568 + customType: ID,
569 + display: true,
570 + content: `Superpowers return ${task.id}\n\n${summary}\n\nChild session: ${childSession ?? "unknown"}`,
571 + details: { taskId: task.id, childSession },
572 + },
573 + { triggerTurn: false },
574 + );
575 + },
576 + });
578 +function status(ctx: ExtensionCommandContext, id = "") {
579 + const tasks = readTasks(ctx.cwd);
580 + const key = id.trim();
581 + if (key) {
582 + const t = tasks[key];
583 + notify(ctx, t ? taskDetails(t) : `no such task: ${key}`, t ? "info" : "error");
584 + widget(ctx);
585 + return;
587 + const xs = Object.values(tasks);
588 + notify(
589 + ctx,
590 + [activeMessage(), ...(xs.length ? xs.map(summaryLine) : ["no tasks"])].join(
591 + "\n",
592 + ),
593 + );
594 + widget(ctx);
596 +function activeMessage() {
597 + return active ? "superpowers on" : "superpowers off";
599 +function setActive(ctx: ExtensionCommandContext, value: boolean) {
600 + active = value;
601 + widget(ctx);
602 + notify(ctx, activeMessage());
604 +function toggle(ctx: ExtensionCommandContext) {
605 + setActive(ctx, !active);
607 +async function announceVisualSession(ctx: ExtensionCommandContext, session: VisualSession) {
608 + const agentMsg = [
609 + "Superpowers visual brainstorming",
610 + "",
611 + `visual live: ${session.url}`,
612 + `content: ${session.contentDir}`,
613 + `events file: ${session.eventsFile}`,
614 + "",
615 + "Agent: read the events file directly when interpreting browser feedback.",
616 + ].join("\n");
617 + await ctx.sendMessage(
619 + customType: ID,
620 + display: true,
621 + content: agentMsg,
622 + details: {
623 + url: session.url,
624 + contentDir: session.contentDir,
625 + eventsFile: session.eventsFile,
626 + },
627 + },
628 + { triggerTurn: false },
629 + );
632 +async function visualCommand(args: string, ctx: ExtensionCommandContext) {
633 + const [sub = "status"] = args.trim().split(/\s+/);
634 + if (sub === "start") {
635 + if (visual) {
636 + notify(ctx, `visual already live: ${visual.url}\ncontent: ${visual.contentDir}\nevents file: ${visual.eventsFile}`);
637 + await announceVisualSession(ctx, visual);
638 + return;
640 + visual = await startVisualServer({ root: dir(ctx.cwd) });
641 + const opened = await openBrowser(visual.url);
642 + const msg = [
643 + `visual live: ${visual.url}`,
644 + `content: ${visual.contentDir}`,
645 + `events file: ${visual.eventsFile}`,
646 + opened.ok ? `opened: ${opened.command}` : `open manually: ${opened.error}`,
647 + ].join("\n");
648 + notify(ctx, msg, opened.ok ? "info" : "warning");
649 + await announceVisualSession(ctx, visual);
650 + return;
652 + if (sub === "stop") {
653 + if (!visual) return notify(ctx, "no visual session", "warning");
654 + visual.close();
655 + visual = undefined;
656 + notify(ctx, "visual stopped");
657 + return;
659 + if (sub === "events") {
660 + if (!visual) return notify(ctx, "no visual session", "warning");
661 + const events = existsSync(visual.eventsFile) ? readFileSync(visual.eventsFile, "utf8") : "";
662 + if (ctx.hasUI) await ctx.ui.editor("superpowers visual events", events || "no events");
663 + else notify(ctx, events || "no events");
664 + return;
666 + 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}`);
670 +function help(ctx: ExtensionCommandContext) {
671 + notify(
672 + ctx,
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 + ),
681 + .join("\n"),
682 + );
685 +export default function (pi: ExtensionAPI) {
686 + pi.registerFlag("superpowers", {
687 + description: "Activate Superpowers workflow discipline for this Pi run",
688 + type: "boolean",
689 + default: false,
690 + });
691 + pi.on("before_agent_start", (event) => {
692 + if (!active && !pi.getFlag("superpowers")) return;
693 + if (event.systemPrompt.includes("Superpowers active. Strict mode.")) return;
694 + return { systemPrompt: event.systemPrompt + FLAG_PROMPT };
695 + });
696 + pi.on("session_start", async (_e, ctx) => {
697 + generation++;
698 + active = Boolean(pi.getFlag("superpowers"));
699 + currentCwd = ctx.cwd;
700 + const ids = Object.keys(readTasks(ctx.cwd))
701 + .map((id) => Number(id.slice(3)))
702 + .filter(Number.isFinite);
703 + next = Math.max(next, 1 + Math.max(0, ...ids));
704 + widget(ctx);
705 + });
706 + pi.on("session_shutdown", async () => {
707 + generation++;
708 + visual?.close();
709 + visual = undefined;
710 + stopAll();
711 + });
712 + pi.registerCommand("superpowers", {
713 + description: "Run background agents and branch into them",
714 + getArgumentCompletions(input: string) {
715 + const parts = input.trimStart().split(/\s+/);
716 + const [cmd = "", q = ""] = parts;
717 + if (parts.length === 1 && !input.endsWith(" "))
718 + return COMMANDS.filter((s) => s.startsWith(cmd)).map((s) => ({
719 + value: s,
720 + label: s,
721 + }));
722 + if (parts.length !== 2) return [];
723 + if (cmd === "run")
724 + return agentNames(currentCwd)
725 + .filter((n) => n.startsWith(q))
726 + .map((n) => ({ value: `run ${n}`, label: n }));
727 + if (["open", "branch", "abort", "status"].includes(cmd))
728 + return Object.keys(readTasks(currentCwd))
729 + .filter((id) => id.startsWith(q))
730 + .map((id) => ({ value: `${cmd} ${id}`, label: id }));
731 + return [];
732 + },
733 + async handler(args, ctx) {
734 + currentCwd = ctx.cwd;
735 + const raw = args.trim();
736 + if (!raw) return toggle(ctx);
737 + const [cmd = "", ...rest] = raw.split(/\s+/);
738 + const tail = rest.join(" ");
739 + if (cmd === "run") {
740 + const [name = "", ...xs] = rest;
741 + return runAgent(name, xs.join(" "), ctx, pi);
743 + if (cmd === "agent") return inlineAgent(tail, ctx, pi);
744 + if (cmd === "open") return openTask(tail, ctx);
745 + if (cmd === "branch") return branchTask(tail, ctx);
746 + if (cmd === "return") return returnTask(tail, ctx);
747 + if (cmd === "abort") {
748 + const t = live.get(tail.trim());
749 + if (!t)
750 + return notify(ctx, `no running task: ${tail.trim()}`, "warning");
751 + t.abort?.();
752 + t.dispose?.();
753 + t.task.status = "aborted";
754 + t.task.updatedAt = now();
755 + t.task.log.push(`${t.task.updatedAt} aborted by user`);
756 + writeTask(ctx.cwd, t.task);
757 + live.delete(t.task.id);
758 + widget(ctx);
759 + return notify(ctx, `aborted ${t.task.id}`);
761 + if (cmd === "on") return setActive(ctx, true);
762 + if (cmd === "off") return setActive(ctx, false);
763 + if (cmd === "visual") return visualCommand(tail, ctx);
764 + if (cmd in ALIASES) return runAgent(ALIASES[cmd], tail, ctx, pi);
765 + if (cmd === "help") return help(ctx);
766 + return status(ctx, tail);
767 + },
768 + });
771 +export const __test = {
772 + parseAgentFile,
773 + resolveNames,
774 + childPrompt,
775 + summaryLine,
776 + taskDetails,
777 + platformStateDir,
778 + hashProjectRoot,
779 + tasksFile,
780 + dir,

extensions/superpowers/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-superpowers",
3 + "type": "module",
4 + "main": "index.ts",
5 + "pi": {
6 + "extensions": ["./index.ts"],
7 + "prompts": ["./prompts"],
8 + "skills": ["./skills"]
9 + },
10 + "scripts": {
11 + "test": "bun test ./__tests__/*.test.ts",
12 + "test:harness": "bun test ./__tests__/harness.test.ts"
13 + },
14 + "peerDependencies": {
15 + "@earendil-works/pi-ai": "*",
16 + "@earendil-works/pi-coding-agent": "*"
17 + },
18 + "devDependencies": {
19 + "@marcfargas/pi-test-harness": "^0.6.1"
20 + },
21 + "license": "MIT",
22 + "description": "Background subagents and takeover sessions for Pi.",
23 + "keywords": [
24 + "pi",
25 + "pi-extension",
26 + "subagents"
27 + ],
28 + "private": true

extensions/superpowers/prompts/brainstorming.md

Added
new file mode 100644
1 +---
2 +description: Run enhanced Superpowers brainstorming: context, questions, options, section approval, spec, self-review, handoff to planning.
3 +argument-hint: "<goal-or-feature>"
4 +tools: [read, write, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `brainstorming` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/dispatching-parallel-agents.md

Added
new file mode 100644
1 +---
2 +description: Run the dispatching-parallel-agents Superpowers workflow.
3 +argument-hint: "<work-to-split>"
4 +tools: [read, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `dispatching-parallel-agents` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/executing-plans.md

Added
new file mode 100644
1 +---
2 +description: Run the executing-plans Superpowers workflow.
3 +argument-hint: "<plan-or-task>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `executing-plans` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/finishing-a-development-branch.md

Added
new file mode 100644
1 +---
2 +description: Run the finishing-a-development-branch Superpowers workflow.
3 +argument-hint: "<branch-or-worktree>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `finishing-a-development-branch` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/receiving-code-review.md

Added
new file mode 100644
1 +---
2 +description: Run the receiving-code-review Superpowers workflow.
3 +argument-hint: "<review-findings>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `receiving-code-review` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/requesting-code-review.md

Added
new file mode 100644
1 +---
2 +description: Run strict Superpowers review: correctness, proof, deslop, compression, security, perf, UX, docs.
3 +argument-hint: "<file|directory|diff|scope>"
4 +tools: [read, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `requesting-code-review` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/subagent-driven-development.md

Added
new file mode 100644
1 +---
2 +description: Run the subagent-driven-development Superpowers workflow.
3 +argument-hint: "<approved-plan>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `subagent-driven-development` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/systematic-debugging.md

Added
new file mode 100644
1 +---
2 +description: Run the systematic-debugging Superpowers workflow.
3 +argument-hint: "<bug-description-or-error>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `systematic-debugging` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/test-driven-development.md

Added
new file mode 100644
1 +---
2 +description: Run the test-driven-development Superpowers workflow.
3 +argument-hint: "<behavior-or-bug>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `test-driven-development` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/using-git-worktrees.md

Added
new file mode 100644
1 +---
2 +description: Run the using-git-worktrees Superpowers workflow.
3 +argument-hint: "<task-or-branch-name>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `using-git-worktrees` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/using-superpowers.md

Added
new file mode 100644
1 +---
2 +description: Run the using-superpowers Superpowers workflow.
3 +argument-hint: "[task-or-question]"
4 +tools: [read, grep, find, ls]
5 +thinking: off
6 +---
7 +Use the `using-superpowers` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/verification-before-completion.md

Added
new file mode 100644
1 +---
2 +description: Run the verification-before-completion Superpowers workflow.
3 +argument-hint: "<work-to-verify>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: off
6 +---
7 +Use the `verification-before-completion` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/writing-plans.md

Added
new file mode 100644
1 +---
2 +description: Run the writing-plans Superpowers workflow.
3 +argument-hint: "<approved-design-or-scope>"
4 +tools: [read, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `writing-plans` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/prompts/writing-skills.md

Added
new file mode 100644
1 +---
2 +description: Run the writing-skills Superpowers workflow.
3 +argument-hint: "<skill-name-or-purpose>"
4 +tools: [read, write, edit, bash, grep, find, ls]
5 +thinking: medium
6 +---
7 +Use the `writing-skills` skill. Apply it to:
9 +$ARGUMENTS

extensions/superpowers/skills/brainstorming/SKILL.md

Added
new file mode 100644
1 +---
2 +name: brainstorming
3 +description: Use for vague goals, new features, product decisions, UX/UI work, or architecture choices before implementation. Enforces design approval before code, writes a spec, self-reviews it, then hands off to writing-plans.
4 +---
6 +# Brainstorming
8 +Design before code. No exceptions for “simple” work.
10 +## Hard gate
12 +Do not implement, scaffold, edit production code, or invoke implementation workflows until:
14 +1. design was presented,
15 +2. user approved it,
16 +3. spec was written,
17 +4. spec self-review passed,
18 +5. user approved the written spec.
20 +Tiny tasks may have tiny designs. They still need approval.
22 +## Flow
24 +1. Explore project context.
25 + - read relevant docs/files
26 + - inspect current structure
27 + - note constraints and existing patterns
28 + - inspect recent commits if useful
29 +2. If visual questions are likely, offer visual companion in its own message.
30 +3. Ask clarifying questions one at a time.
31 +4. Propose 2-3 approaches with tradeoffs.
32 +5. Recommend one.
33 +6. Present design in small sections.
34 +7. Ask approval after each section.
35 +8. Write spec to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` unless project rules say otherwise.
36 +9. Self-review spec; fix placeholders, contradictions, ambiguity, overscope.
37 +10. Commit the spec when project workflow uses git and project rules allow it.
38 +11. Ask user to review spec file.
39 +12. After approval, hand off only to `writing-plans`.
41 +## Question rules
43 +- One question per message.
44 +- Multiple choice preferred.
45 +- Ask only blocking questions.
46 +- If request is too large, decompose first; brainstorm one subproject.
48 +## Design sections
50 +Scale section length to complexity. Cover only relevant sections:
52 +- goal and non-goals
53 +- UX/API behavior
54 +- architecture/components
55 +- data flow/state
56 +- component boundaries: single responsibility, clear interfaces, independent tests
57 +- errors/failure modes
58 +- testing/proof
59 +- migration/rollout, only if truly needed
61 +## Spec self-review
63 +Before user review, check:
65 +- `TODO`, `TBD`, placeholders
66 +- contradictions
67 +- unclear ownership or boundaries
68 +- requirements that can be interpreted two ways
69 +- scope too large for one implementation plan
70 +- missing verification strategy
72 +Fix inline before asking user.
74 +## Output checkpoints
76 +```text
77 +BRAINSTORM_CONTEXT
78 +- existing patterns: ...
79 +- constraints: ...
80 +- visual companion: useful | not useful
81 +```
83 +```text
84 +BRAINSTORM_OPTIONS
85 +- recommendation: ...
86 +- options:
87 + 1. ... tradeoff ...
88 + 2. ... tradeoff ...
89 +```
91 +```text
92 +DESIGN_SECTION n/N — <name>
93 +...
94 +Approve / edit?
95 +```
97 +```text
98 +SPEC_READY
99 +- path: docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md
100 +- self-review: passed
101 +- next after approval: /writing-plans <path>
102 +```
104 +## Anti-patterns
106 +- Coding during brainstorming.
107 +- Dumping a giant spec without section approval.
108 +- Asking five questions at once.
109 +- “This is too simple for design.”
110 +- Generic scalable/flexible fluff.
111 +- Unrelated refactors while touching existing code.
112 +- Writing a spec full of hedges instead of decisions.
114 +## Visual companion
116 +Use only when seeing beats reading: mockups, layouts, palettes, diagrams, side-by-side UX choices.
118 +Offer in its own message:
120 +```text
121 +Some of this may be easier to judge visually. I can open a local browser companion for mockups/diagrams/options. Use it?
122 +```
124 +If user accepts:
126 +1. Ask user to run `/superpowers visual start` if not already live.
127 +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.
134 +Visual state is ephemeral platform state, not project files. Specs/design docs remain project files when approved.

extensions/superpowers/skills/dispatching-parallel-agents/SKILL.md

Added
new file mode 100644
1 +---
2 +name: dispatching-parallel-agents
3 +description: Use when work splits into independent investigations or edits. Creates fair /superpowers worker prompts and a merge plan.
4 +---
6 +# Dispatching Parallel Agents
8 +Parallel only when independent. One worker per independent problem domain.
10 +## Independence test
12 +Tasks are parallelizable if:
14 +- no task needs another task's output
15 +- no two tasks edit same file/region
16 +- failures can be understood separately
18 +If not, run sequentially.
20 +## Worker prompt must include
22 +- shared context
23 +- exact scope
24 +- allowed files
25 +- forbidden files/actions
26 +- verification command
27 +- required return format
28 +- enough context so worker does not need session history
30 +## Output
32 +```text
33 +DISPATCH_PLAN
34 +- shared context: ...
35 +- workers:
36 + - /superpowers run <prompt> ...
37 +- merge order: ...
38 +- conflicts: ...
39 +- final verify: ...
40 +```
42 +After workers return: read summaries, inspect changed files, check conflicts, run final verification.
44 +## Law
46 +Benchmark prompts must stay fair/profile-neutral. Do not steer toward a tool just to make an extension look good.

extensions/superpowers/skills/executing-plans/SKILL.md

Added
new file mode 100644
1 +---
2 +name: executing-plans
3 +description: Use when an implementation plan exists. Executes small batches, verifies after each batch, and stops on failed checks or bad plan assumptions.
4 +---
6 +# Executing Plans
8 +Implement plan. Do not improvise silently.
10 +## Loop
12 +1. Read the whole plan.
13 +2. Review it critically for gaps, contradictions, missing files/commands.
14 +3. Inspect current state.
15 +4. Run baseline check if cheap.
16 +5. Execute 1-3 plan steps exactly.
17 +6. Run listed verification.
18 +7. Record changed files and evidence.
19 +8. Stop if verification fails.
20 +9. If plan is wrong, report exact mismatch and minimal correction.
22 +## Output per batch
24 +```text
25 +BATCH_DONE
26 +- tasks: ...
27 +- changed: ...
28 +- verify: command → result
29 +- next: ...
30 +```
32 +## Forbidden
34 +- Big-bang edits.
35 +- Claiming “done” without `verification-before-completion`.
36 +- Changing scope because it “seemed useful”.
37 +- Starting implementation on `main`/`master` without explicit user consent.
38 +- Guessing through blockers instead of asking.

extensions/superpowers/skills/finishing-a-development-branch/SKILL.md

Added
new file mode 100644
1 +---
2 +name: finishing-a-development-branch
3 +description: Use when a feature branch/worktree is complete. Verifies, summarizes, and offers merge/PR/keep/discard choices.
4 +---
6 +# Finishing a Development Branch
8 +Finish cleanly.
10 +## Steps
12 +1. Inspect `git status`, diff, recent commits, branch, and worktree state.
13 +2. Run full verification before offering completion choices.
14 +3. If tests fail, stop and report failures.
15 +4. Summarize changes and evidence.
16 +5. Present options exactly:
17 + - merge locally
18 + - push/open PR
19 + - keep branch/worktree
20 + - discard
21 +6. Cleanup only after explicit choice.
22 +7. For discard, require typed confirmation.
23 +8. Remove only worktrees this workflow owns; never delete harness-owned workspace.
25 +## Output
27 +```text
28 +BRANCH_FINISH
29 +- branch: ...
30 +- status: clean | dirty
31 +- changes: ...
32 +- verify: ...
33 +- risks: ...
34 +- options: merge | PR | keep | discard
35 +```

extensions/superpowers/skills/receiving-code-review/SKILL.md

Added
new file mode 100644
1 +---
2 +name: receiving-code-review
3 +description: Use after code review. Fixes BLOCKER/MAJOR findings with minimal edits, rejects bad findings with evidence, then reruns verification.
4 +---
6 +# Receiving Code Review
8 +Address review without churn.
10 +## Process
12 +1. Read all feedback before reacting.
13 +2. Restate or clarify unclear findings before implementing anything.
14 +3. Verify each finding against the codebase.
15 +4. List findings by severity.
16 +5. Fix BLOCKER and MAJOR first, one item at a time.
17 +6. Reject invalid findings only with evidence.
18 +7. Do not touch unrelated code.
19 +8. Add tests when behavior changes.
20 +9. Rerun verification.
22 +## Output
24 +```text
25 +REVIEW_RESPONSE
26 +- fixed: ...
27 +- rejected: finding → evidence
28 +- changed: ...
29 +- tests: ...
30 +- remaining: none | ...
31 +```
33 +## Anti-patterns
35 +- Performative agreement before checking: “absolutely right”, “great point”.
36 +- Blindly implementing external review without codebase verification.
37 +- Rewriting whole module to fix one finding.
38 +- “Addressed” without commit/file/test evidence.
39 +- Adding unused “professional” features instead of applying YAGNI.

extensions/superpowers/skills/requesting-code-review/SKILL.md

Added
new file mode 100644
1 +---
2 +name: requesting-code-review
3 +description: Use before accepting implementation or when reviewing code quality. Reviews spec, tests, slop/deslop patterns, compression/DRY opportunities, security, performance, UX, docs, and project rules with severity-ranked findings.
4 +---
6 +# Requesting Code Review
8 +Review only. Do not edit.
10 +No politeness tax. No generic praise. Findings need evidence.
12 +## Inputs
14 +Establish:
16 +- target files/diff/plan
17 +- base/head commit range when available
18 +- user objective
19 +- relevant project rules
20 +- tests or proof expected
22 +If target is ambiguous, inspect likely changed files and state scope.
24 +## Pass 1 — Correctness Gate
26 +Check:
28 +- requested behavior implemented
29 +- logic errors, race/order bugs, off-by-one, bad state transitions
30 +- error paths and failure modes
31 +- API/CLI/UI contract drift
32 +- docs match behavior
34 +## Pass 2 — Test/Proof Gate
36 +Check:
38 +- tests prove behavior, not implementation trivia
39 +- failing paths covered when important
40 +- manual/UI proof exists when requested
41 +- benchmark/profiling exists for perf claims
42 +- no completion claim without evidence
44 +## Pass 3 — Deslop Gate
46 +Find LLM slop:
48 +- plausible but unverified APIs or assumptions
49 +- needless traits/classes/wrappers/pass-through layers
50 +- generic soup, global state, vague config
51 +- duplicated near-identical code with renamed variables
52 +- stringly typed domains where enum/newtype/validated shape fits
53 +- `unwrap`/`expect`/panic/swallowed errors/vague catch-all errors
54 +- missing docs/tests for public behavior or risky failure paths
55 +- insecure input/path/shell/env handling
57 +## Pass 4 — Compression Gate
59 +Find design compression opportunities:
61 +- repeated command handlers, parsers, errors, tests, data shapes
62 +- boilerplate that should become a helper/table/enum/data-driven path
63 +- overbroad abstractions hiding simple control flow
64 +- under-abstracted repeated logic likely to drift
65 +- dead layers, needless adapters, repeated conversions
67 +Compression is not code golf. Prefer one good abstraction over many clever ones.
69 +## Pass 5 — Handmade UX/Style Gate
71 +Check:
73 +- direct code, small functions, explicit state
74 +- no legacy/compat sludge unless required
75 +- no edge-case theater
76 +- readable names and boring control flow
77 +- UI is usable, high-contrast, keyboard-friendly, not ugly
78 +- performance avoids obvious allocations/O(n²)/N+1/process churn
80 +## Severity
82 +- BLOCKER: incorrect, unsafe, untested critical path, violates spec, or fake completion.
83 +- MAJOR: likely bug, bad API, serious slop, duplicated design risk, missing important proof.
84 +- MINOR: cleanup, naming, small simplification.
85 +- NOTE: observation, no action required.
87 +## Output
89 +```text
90 +REVIEW
91 +- verdict: pass | fail
92 +- scope: ...
93 +- blockers:
94 + - file:line — issue — required fix
95 +- major:
96 + - ...
97 +- minor:
98 + - ...
99 +- slop:
100 + - pattern — evidence — severity
101 +- compression:
102 + - repeated shape — proposed simpler shape — risk
103 +- tests/proof:
104 + - present: ...
105 + - missing: ...
106 +- required fixes: ...
107 +- verify: ...
108 +```
110 +## Follow-up
112 +- Critical/BLOCKER and MAJOR findings must be fixed or explicitly rejected with evidence before proceeding.
113 +- If findings exist: use `receiving-code-review`.
114 +- If fixes are large: write a plan first.
115 +- If review passes: run `verification-before-completion` before claiming shipped.

extensions/superpowers/skills/subagent-driven-development/SKILL.md

Added
new file mode 100644
1 +---
2 +name: subagent-driven-development
3 +description: Use for implementing a plan through /superpowers workers with mandatory spec and quality review before integration.
4 +---
6 +# Subagent-Driven Development
8 +Workers implement. Parent owns quality. Continue task-by-task without “should I continue?” check-ins unless blocked.
10 +## Process
12 +1. Require approved spec/plan. If absent, use `brainstorming` or `writing-plans`.
13 +2. Extract each task with full text and needed context.
14 +3. Create one worker prompt per bounded task. Do not make worker read the whole plan if the task text can be provided.
15 +4. Run worker with `/superpowers run <prompt> ...`.
16 +5. Inspect result with `/superpowers status <id>` or `/superpowers open <id>`.
17 +6. Handle worker state: done → review; needs-context → provide context; blocked → change prompt/model/scope or escalate.
18 +7. Review twice, in order:
19 + - spec compliance
20 + - code quality/simplicity
21 +8. Fix concrete issues and re-review before next task.
22 +9. Run final verification.
24 +## Review gates
26 +- Spec miss → send back/fix before next task.
27 +- Overbuilt code → simplify.
28 +- No tests/evidence → incomplete.
29 +- Multiple implementation workers editing overlapping files → forbidden.
31 +## Return format
33 +```text
34 +SDD_DONE
35 +- workers: ...
36 +- accepted: ...
37 +- rejected/fixed: ...
38 +- tests: ...
39 +- evidence: ...
40 +```

extensions/superpowers/skills/systematic-debugging/SKILL.md

Added
new file mode 100644
1 +---
2 +name: systematic-debugging
3 +description: Use for bugs, regressions, flaky tests, or unexpected behavior. Requires reproduction, root-cause tracing, hypothesis testing, smallest fix, and verification.
4 +---
6 +# Systematic Debugging
8 +No fix before root-cause evidence.
10 +## Phases
12 +1. Reproduce: exact command/input and observed failure. If not reproducible, gather more data; do not guess.
13 +2. Read errors fully; check recent changes and relevant config/env.
14 +3. Pattern analysis: find working examples and compare exact differences.
15 +4. Trace: follow data/control flow to root cause.
16 +5. Hypothesis: one cause, one prediction, one test.
17 +6. Fix: smallest root-cause change, preferably after a failing regression test.
18 +7. Verify: original failure + nearby regression.
20 +## Three-strike rule
22 +After 3 failed fixes, stop. Request architecture/design review.
24 +## Output
26 +```text
27 +DEBUG_DONE
28 +- repro: ...
29 +- evidence: ...
30 +- root cause: ...
31 +- fix: ...
32 +- verify: ...
33 +- failed attempts: N
34 +```
36 +## Forbidden
38 +- Guess-and-patch.
39 +- “Maybe race condition” without trace.
40 +- Multiple changes at once while testing a hypothesis.
41 +- Broad rewrites before root cause.

extensions/superpowers/skills/test-driven-development/SKILL.md

Added
new file mode 100644
1 +---
2 +name: test-driven-development
3 +description: Use when adding or changing behavior with a testable contract. Enforces red/green/refactor and proof of expected failure before implementation.
4 +---
6 +# Test-Driven Development
8 +RED first. No production code without a failing test first.
10 +If production code was written first, delete it and restart from RED. Do not keep it as reference.
12 +## Loop
14 +1. Write smallest failing test.
15 +2. Run it. Confirm failure is expected.
16 +3. Implement smallest passing code.
17 +4. Run focused test. Green.
18 +5. Refactor only to simplify.
19 +6. Run focused test again.
20 +7. Run relevant full suite.
22 +## Stop if
24 +- Test passes before implementation → bad test.
25 +- Failure is unrelated → fix test/setup first.
26 +- Implementation grows abstractions → cut it down.
27 +- User explicitly forbids tests → state risk and use manual proof.
28 +- Test needs heavy mocks → simplify API/design first.
30 +## Output
32 +```text
33 +TDD_DONE
34 +- red: command + expected failure
35 +- green: command + pass
36 +- refactor: yes/no
37 +- full verify: ...
38 +- files: ...
39 +```

extensions/superpowers/skills/using-git-worktrees/SKILL.md

Added
new file mode 100644
1 +---
2 +name: using-git-worktrees
3 +description: Use for risky or isolated development where the current worktree should stay untouched. Records git state, creates a worktree, and verifies baseline.
4 +---
6 +# Using Git Worktrees
8 +Protect trunk. Isolate risk.
10 +## Before creating
12 +First detect existing isolation:
14 +```bash
15 +git rev-parse --git-dir
16 +git rev-parse --git-common-dir
17 +git rev-parse --show-superproject-working-tree 2>/dev/null
18 +```
20 +If already in a linked worktree and not a submodule, do not create another.
22 +Record:
24 +- current branch
25 +- HEAD
26 +- remote/upstream
27 +- dirty status
28 +- likely trunk (`main`, `master`, `trunk`, `develop`)
30 +If current worktree is dirty, do not hide it. Ask or choose a safe path.
32 +## Process
34 +1. Prefer host/native worktree tools if available.
35 +2. Pick branch name from task.
36 +3. Create worktree outside current directory.
37 +4. If using project-local `.worktrees/` or `worktrees/`, verify path is gitignored first.
38 +5. Run setup/baseline tests there.
39 +6. Do implementation only in worktree.
40 +7. Finish with `finishing-a-development-branch`.
42 +## Output
44 +```text
45 +WORKTREE_READY
46 +- trunk: ...
47 +- branch: ...
48 +- path: ...
49 +- baseline: command → result
50 +```

extensions/superpowers/skills/using-superpowers/SKILL.md

Added
new file mode 100644
1 +---
2 +name: using-superpowers
3 +description: Use when /superpowers or --superpowers is active. Selects the smallest applicable workflow skill and keeps work evidence-driven, simple, and explicit.
4 +---
6 +# Using Superpowers
8 +Superpowers = process discipline. Not vibes.
10 +## Rule
12 +Before non-trivial work, choose and follow one workflow skill:
14 +| Situation | Skill |
15 +|---|---|
16 +| fuzzy feature/design | `brainstorming` |
17 +| approved design → tasks | `writing-plans` |
18 +| plan exists → implement | `executing-plans` |
19 +| independent subtasks | `dispatching-parallel-agents` |
20 +| worker + review loop | `subagent-driven-development` |
21 +| code change with testable behavior | `test-driven-development` |
22 +| bug/regression/flake | `systematic-debugging` |
23 +| before saying done | `verification-before-completion` |
24 +| isolated branch needed | `using-git-worktrees` |
25 +| branch is complete | `finishing-a-development-branch` |
26 +| creating/revising skills | `writing-skills` |
28 +Load the selected skill before acting. If multiple skills apply, use the earliest lifecycle gate: brainstorming → writing-plans → execution/TDD/debug → review → verification → finishing.
30 +## Local style
32 +- Simplicity/minimalism/brutalism.
33 +- Evidence > claims.
34 +- Exact files/commands > summaries.
35 +- No legacy/compat/edge-case bloat unless required.
36 +- User instructions override skills unless unsafe/impossible.
38 +## Red flags
40 +Stop and load a workflow if you are about to:
42 +- implement a fuzzy request without design approval
43 +- fix a bug without root-cause evidence
44 +- claim done without fresh verification
45 +- accept worker/reviewer output without checking evidence
47 +## Superpowers workers
49 +Use normal prompt templates:
51 +```text
52 +/<prompt> ...
53 +/superpowers run <prompt> ...
54 +```
56 +Use workers for isolated investigation/implementation. Parent integrates.

extensions/superpowers/skills/verification-before-completion/SKILL.md

Added
new file mode 100644
1 +---
2 +name: verification-before-completion
3 +description: Use before claiming done, fixed, shipped, or working. Requires real checks and evidence paths; prevents redefining success smaller.
4 +---
6 +# Verification Before Completion
8 +No fresh proof → not done. Evidence before claims.
10 +## Checklist
12 +- Changed files match scope.
13 +- Relevant tests/build/lint were run fresh.
14 +- Full output/exit code was read, not assumed.
15 +- Manual/UI requirements were actually exercised.
16 +- Artifacts exist and are executable/readable when required.
17 +- Docs match behavior.
18 +- No stray debug processes/files unless intentional.
20 +## Output
22 +```text
23 +VERIFIED
24 +- verdict: complete | incomplete
25 +- commands: ...
26 +- evidence: ...
27 +- changed: ...
28 +- remaining: none | ...
29 +```
31 +## Forbidden
33 +- “Should work.”
34 +- “Looks good.”
35 +- Passing unit tests when manual criterion was required.
36 +- Redefining success smaller.
37 +- Trusting worker/agent success without checking diff and evidence.
38 +- Regression test claimed without red-green proof when applicable.

extensions/superpowers/skills/writing-plans/SKILL.md

Added
new file mode 100644
1 +---
2 +name: writing-plans
3 +description: Use after design approval for multi-file or multi-step work. Converts design into small verifiable tasks with exact files and commands.
4 +---
6 +# Writing Plans
8 +Plan for a fast careless implementer with zero project context.
10 +Save plans to `docs/superpowers/plans/YYYY-MM-DD-<feature>.md` unless project rules say otherwise.
12 +## Task requirements
14 +Each task must include:
16 +- exact files
17 +- concrete edit/action
18 +- complete code or command for the step
19 +- expected result/output
20 +- verification command
21 +- commit step when project workflow uses git
22 +- rollback/failure note if risky
24 +## Shape
26 +```text
27 +PLAN
28 +- scope: ...
29 +- invariants: ...
30 +- tasks:
31 + 1. files: ...
32 + action: ...
33 + verify: ...
34 +- checkpoints: ...
35 +- acceptance: ...
36 +```
38 +## Rules
40 +- 2-10 minute tasks.
41 +- Tests before behavior when possible.
42 +- Every batch leaves repo working.
43 +- Mark unknown decisions `[?]`; stop before passing them.
44 +- No `TODO`/`TBD`/`similar to task N`/`write tests for above` placeholders.
45 +- No “refactor architecture” without file-level detail.
46 +- Self-review plan against spec: coverage, placeholders, type/name consistency.
47 +- End by offering `subagent-driven-development` or `executing-plans`.

extensions/superpowers/skills/writing-skills/SKILL.md

Added
new file mode 100644
1 +---
2 +name: writing-skills
3 +description: Use when creating or revising Pi Agent Skills. Produces sharp descriptions, short operational bodies, examples, and trigger tests.
4 +---
6 +# Writing Skills
8 +Skills are operational memory. Keep them sharp.
10 +## Required shape
12 +```text
13 +skills/<name>/SKILL.md
14 +```
16 +Frontmatter:
18 +```yaml
19 +---
20 +name: lowercase-hyphen-name
21 +description: Use when <specific trigger>. Does <specific outcome>.
22 +---
23 +```
25 +## Body rules
27 +- Short enough to load.
28 +- Concrete steps.
29 +- Anti-patterns included.
30 +- Examples only when useful.
31 +- Link deeper refs instead of dumping.
32 +- Local style, not upstream prose.
34 +## Test
36 +Use TDD for skills: first write a case where current behavior would not load/follow the skill, then update the skill until it passes.
38 +Create trigger cases:
40 +- should use skill
41 +- should not use skill
42 +- ambiguous case
44 +## Description rules
46 +- Include concrete trigger keywords.
47 +- Do not put the whole workflow in the description.
48 +- Avoid vague descriptions like “useful for development”.
49 +- If reference material is long, put it in separate files and link it.
51 +## Output
53 +```text
54 +SKILL_DONE
55 +- path: ...
56 +- trigger: ...
57 +- body: ...
58 +- tests: ...
59 +```

extensions/superpowers/visual.ts

Added
new file mode 100644
1 +import { spawn } from "node:child_process";
2 +import { randomBytes, randomUUID } from "node:crypto";
3 +import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, appendFileSync } from "node:fs";
4 +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
5 +import path from "node:path";
7 +export type VisualSession = {
8 + id: string;
9 + url: string;
10 + contentDir: string;
11 + stateDir: string;
12 + eventsFile: string;
13 + serverInfoFile: string;
14 + close(): void;
15 +};
17 +type StartVisualOptions = {
18 + root: string;
19 + preferredPort?: number;
20 +};
22 +const COOKIE = "pi_superpowers_visual";
23 +const BODY_LIMIT = 64 * 1024;
25 +export async function startVisualServer({ root, preferredPort = 47718 }: StartVisualOptions): Promise<VisualSession> {
26 + const id = randomUUID();
27 + const token = randomBytes(32).toString("base64url");
28 + const sessionRoot = path.join(root, "visual", id);
29 + const contentDir = path.join(sessionRoot, "content");
30 + const stateDir = path.join(sessionRoot, "state");
31 + const eventsFile = path.join(stateDir, "events.jsonl");
32 + const serverInfoFile = path.join(stateDir, "server-info.json");
33 + mkdirSync(contentDir, { recursive: true });
34 + mkdirSync(stateDir, { recursive: true });
35 + writeFileSync(path.join(contentDir, "000-waiting.html"), waitingFragment());
37 + let server!: Server;
38 + const authorized = (req: IncomingMessage, url: URL) =>
39 + url.searchParams.get("token") === token ||
40 + req.headers.authorization === `Bearer ${token}` ||
41 + (req.headers.cookie ?? "").split(/;\s*/).includes(`${COOKIE}=${token}`);
43 + server = createServer((req, res) => {
44 + void (async () => {
45 + try {
46 + const url = new URL(req.url ?? "/", "http://127.0.0.1");
47 + if (!authorized(req, url)) return json(res, 401, { error: "unauthorized" });
48 + if (url.pathname === "/" && req.method === "GET") {
49 + res.setHeader("Set-Cookie", `${COOKIE}=${token}; SameSite=Strict; Path=/`);
50 + return html(res, frame(latestFragment(contentDir), latestStamp(contentDir)));
51 + }
52 + if (url.pathname === "/api/latest" && req.method === "GET")
53 + return json(res, 200, latestStamp(contentDir));
54 + if (url.pathname === "/api/events" && req.method === "GET")
55 + return text(res, existsSync(eventsFile) ? readFileSync(eventsFile, "utf8") : "");
56 + if (url.pathname === "/api/event" && req.method === "POST") {
57 + const body = await readBody(req);
58 + const event = JSON.parse(body || "{}");
59 + appendFileSync(eventsFile, `${JSON.stringify({ ...event, timestamp: Date.now() })}\n`);
60 + return json(res, 200, { ok: true });
61 + }
62 + return json(res, 404, { error: "not found" });
63 + } catch (err) {
64 + return json(res, 500, { error: err instanceof Error ? err.message : String(err) });
65 + }
66 + })();
67 + });
68 + await listen(server, preferredPort);
69 + const address = server.address();
70 + if (!address || typeof address === "string") throw new Error("visual server failed to bind");
71 + const url = `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`;
72 + const info = { id, url, contentDir, stateDir, eventsFile };
73 + writeFileSync(serverInfoFile, `${JSON.stringify(info, null, "\t")}\n`);
74 + return { ...info, serverInfoFile, close: () => server.close() };
77 +export async function openBrowser(url: string): Promise<{ ok: boolean; command?: string; error?: string }> {
78 + if (process.env.NODE_ENV === "test" || process.env.PI_SUPERPOWERS_NO_OPEN)
79 + return { ok: false, error: "browser opener disabled" };
80 + for (const candidate of openerCandidates(url)) {
81 + const result = await trySpawn(candidate.command, candidate.args);
82 + if (result.ok) return { ok: true, command: candidate.command };
83 + }
84 + return { ok: false, error: "no browser opener found" };
87 +function openerCandidates(url: string): Array<{ command: string; args: string[] }> {
88 + if (process.env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
89 + if (process.platform === "darwin") return [{ command: "open", args: [url] }];
90 + if (process.platform === "win32") return [{ command: "cmd.exe", args: ["/c", "start", "", url] }];
91 + return [
92 + { command: "xdg-open", args: [url] },
93 + { command: "wslview", args: [url] },
94 + { command: "gio", args: ["open", url] },
95 + ];
98 +function trySpawn(command: string, args: string[]): Promise<{ ok: boolean; error?: string }> {
99 + return new Promise((resolve) => {
100 + const child = spawn(command, args, { detached: true, stdio: "ignore" });
101 + let settled = false;
102 + const done = (ok: boolean, error?: string) => {
103 + if (settled) return;
104 + settled = true;
105 + resolve({ ok, error });
106 + };
107 + child.once("error", (err) => done(false, err.message));
108 + child.once("spawn", () => {
109 + child.unref();
110 + done(true);
111 + });
112 + setTimeout(() => done(false, "timeout"), 1500).unref();
113 + });
116 +function listen(server: Server, preferredPort: number) {
117 + return new Promise<void>((resolve, reject) => {
118 + const onError = (err: NodeJS.ErrnoException) => {
119 + server.off("error", onError);
120 + if (err.code !== "EADDRINUSE") return reject(err);
121 + server.listen(0, "127.0.0.1", () => resolve());
122 + };
123 + server.once("error", onError);
124 + server.listen(preferredPort, "127.0.0.1", () => {
125 + server.off("error", onError);
126 + resolve();
127 + });
128 + });
131 +function latestFiles(contentDir: string) {
132 + return readdirSync(contentDir)
133 + .filter((f) => f.endsWith(".html"))
134 + .map((name) => ({ name, path: path.join(contentDir, name), mtime: statSync(path.join(contentDir, name)).mtimeMs }))
135 + .sort((a, b) => b.mtime - a.mtime || b.name.localeCompare(a.name));
138 +function latestFragment(contentDir: string) {
139 + const file = latestFiles(contentDir)[0];
140 + return file ? readFileSync(file.path, "utf8") : waitingFragment();
143 +function latestStamp(contentDir: string) {
144 + const file = latestFiles(contentDir)[0];
145 + return file ? { name: file.name, mtime: file.mtime } : { name: "", mtime: 0 };
148 +function waitingFragment() {
149 + return `<div class="center"><p class="subtitle">Waiting for Pi to push a visual brainstorming screen…</p></div>`;
152 +function frame(fragment: string, stamp: { name: string; mtime: number }) {
153 + const body = /<html[\s>]/i.test(fragment) || /<!doctype/i.test(fragment) ? fragment : `<main id="main">${fragment}</main>`;
154 + return `<!doctype html>
155 +<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>
158 +<script>${js()}</script></body></html>`;
161 +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}}`;
165 +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);`;
169 +async function readBody(req: IncomingMessage) {
170 + let body = "";
171 + for await (const chunk of req) {
172 + body += String(chunk);
173 + if (Buffer.byteLength(body, "utf8") > BODY_LIMIT) throw new Error("request body too large");
175 + return body;
178 +function html(res: ServerResponse, body: string) {
179 + res.statusCode = 200;
180 + res.setHeader("content-type", "text/html; charset=utf-8");
181 + res.setHeader("cache-control", "no-store");
182 + res.end(body);
184 +function json(res: ServerResponse, status: number, data: unknown) {
185 + res.statusCode = status;
186 + res.setHeader("content-type", "application/json; charset=utf-8");
187 + res.end(JSON.stringify(data));
189 +function text(res: ServerResponse, body: string) {
190 + res.statusCode = 200;
191 + res.setHeader("content-type", "text/plain; charset=utf-8");
192 + res.end(body);
194 +function escapeHtml(s: string) {
195 + return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
197 +function escapeAttr(s: string) {
198 + return escapeHtml(s).replaceAll('"', "&quot;");