repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Created pandoc skill with SKILL.md (15 sections covering format conversion, PDF, HTML, docx, presentations, Lua filters, templates, citations, defaults files, agent pipelines), 4 helper scripts (batch-convert, md-to-pdf, web-to-md, wordcount), 6 Lua filter examples (strong-to-smallcaps, center-images, meta-vars, extract-headings, add-meta-date, remove-empty-paras). All 10 validation tests pass.

a06d45c4e068f87524405144f91a19da4672a97b

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Result: {"status":"keep","skill_quality":9}

Changed files (67)

.pi/autoresearch/session.jsonl

Added
new file mode 100644
1 +{"type":"config","name":"Pandoc Skill Creation","metricName":"skill_quality","metricUnit":"score","bestDirection":"lower"}

.tsc-baseline.txt

Added
new file mode 100644
1 +extensions/context-size/index.ts(144,9): error TS2769: No overload matches this call.
2 +extensions/context-size/index.ts(144,27): error TS7006: Parameter '_event' implicitly has an 'any' type.
3 +extensions/context-size/index.ts(144,35): error TS7006: Parameter 'ctx' implicitly has an 'any' type.
4 +extensions/cost/index.ts(431,9): error TS2769: No overload matches this call.
5 +extensions/cost/index.ts(431,27): error TS7006: Parameter '_event' implicitly has an 'any' type.
6 +extensions/cost/index.ts(431,35): error TS7006: Parameter 'ctx' implicitly has an 'any' type.
7 +extensions/cost/index.ts(435,9): error TS2769: No overload matches this call.
8 +extensions/cost/index.ts(435,27): error TS7006: Parameter '_event' implicitly has an 'any' type.
9 +extensions/cost/index.ts(435,35): error TS7006: Parameter 'ctx' implicitly has an 'any' type.
10 +extensions/diff-review/browser/index.ts(1,8): error TS2882: Cannot find module or type declarations for side-effect import of './style.css'.
11 +extensions/diff-review/index.ts(68,74): error TS2339: Property 'url' does not exist on type 'never'.
12 +extensions/forget/index.ts(325,19): error TS2352: Conversion of type 'SessionEntry[]' to type 'BranchEntry[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
13 +extensions/git-safe/index.ts(190,15): error TS2339: Property 'isError' does not exist on type 'AgentToolResult<unknown>'.
14 +extensions/git-safe/index.ts(225,15): error TS2345: Argument of type '{ content: { type: "text"; text: string; }[]; }' is not assignable to parameter of type 'AgentToolResult<unknown>'.
15 +extensions/git-safe/spawn.ts(45,44): error TS2774: This condition will always return true since this function is always defined. Did you mean to call it instead?
16 +extensions/goal/index.ts(1374,41): error TS2345: Argument of type 'string | (TextContent | ImageContent)[]' is not assignable to parameter of type 'string'.
17 +extensions/goal/index.ts(1382,43): error TS2345: Argument of type 'string | (TextContent | ImageContent)[]' is not assignable to parameter of type 'string'.
18 +extensions/goal/index.ts(1570,52): error TS2345: Argument of type 'GoalState | undefined' is not assignable to parameter of type 'GoalState'.
19 +extensions/goal/index.ts(1749,3): error TS2322: Type '(args: string, ctx: ExtensionCommandContext) => void' is not assignable to type '(args: string, ctx: ExtensionCommandContext) => Promise<void>'.
20 +extensions/goal/index.ts(1896,4): error TS2322: Type '(args: string, ctx: ExtensionCommandContext) => void' is not assignable to type '(args: string, ctx: ExtensionCommandContext) => Promise<void>'.
21 +extensions/neko/index.ts(4,7): error TS2305: Module '"@earendil-works/pi-coding-agent"' has no exported member 'AutocompleteItem'.
22 +extensions/neko/index.ts(211,7): error TS2415: Class 'NekoEditor' incorrectly extends base class 'CustomEditor'.
23 +extensions/nu-bang/index.ts(325,28): error TS2345: Argument of type 'ChildProcessByStdio<null, Readable, Readable>' is not assignable to parameter of type 'ChildProcessWithoutNullStreams'.
24 +extensions/pulse/index.ts(16,2): error TS2305: Module '"@earendil-works/pi-coding-agent"' has no exported member 'AutocompleteItem'.
25 +extensions/pulse/index.ts(153,5): error TS2352: Conversion of type 'ExtensionAPI' to type 'Record<string, unknown>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
26 +extensions/pulse/index.ts(277,58): error TS2345: Argument of type 'unknown[]' is not assignable to parameter of type 'AgentMessage[]'.
27 +extensions/pulse/index.ts(296,16): error TS2345: Argument of type 'string' is not assignable to parameter of type 'KnownProvider'.
28 +extensions/pulse/index.ts(1291,44): error TS2554: Expected 1-2 arguments, but got 3.
29 +extensions/pulse/index.ts(1441,14): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
30 +extensions/pulse/index.ts(1449,54): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
31 +extensions/pulse/index.ts(1458,27): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
32 +extensions/pulse/index.ts(1465,26): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
33 +extensions/pulse/index.ts(1485,16): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
34 +extensions/pulse/index.ts(1487,22): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
35 +extensions/pulse/index.ts(1489,15): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
36 +extensions/pulse/index.ts(1491,13): error TS2345: Argument of type 'ExtensionContext' is not assignable to parameter of type 'ExtensionCommandContext'.
37 +extensions/quota/index.ts(665,45): error TS2345: Argument of type 'string' is not assignable to parameter of type 'ThemeColor'.
38 +extensions/quota/index.ts(665,80): error TS2345: Argument of type 'string' is not assignable to parameter of type 'ThemeColor'.
39 +extensions/quota/index.ts(672,27): error TS2345: Argument of type 'string' is not assignable to parameter of type 'ThemeColor'.
40 +extensions/quota/index.ts(672,62): error TS2345: Argument of type 'string' is not assignable to parameter of type 'ThemeColor'.
41 +extensions/session-rename/index.ts(255,4): error TS2322: Type '{ mode: "auto"; name: string; latestMarker: MarkerData | undefined; }' is not assignable to type 'TitleState'.
42 +extensions/ssh-tools/index.ts(188,3): error TS2322: Type '(path: string) => string | null' is not assignable to type '(absolutePath: string) => Promise<string | null | undefined>'.
43 +extensions/ssh-tools/index.ts(195,4): error TS2322: Type 'Promise<Buffer<ArrayBufferLike>>' is not assignable to type 'Promise<void>'.
44 +extensions/ssh-tools/index.ts(227,35): error TS1225: Cannot find parameter 'target'.
45 +extensions/ssh-tools/index.ts(236,69): error TS2345: Argument of type 'string' is not assignable to parameter of type '"ssh_read" | "ssh_write" | "ssh_edit" | "ssh_bash"'.
46 +extensions/ssh-tools/index.ts(241,36): error TS2339: Property 'bold' does not exist on type '{ fg: (c: string, s: string) => string; }'.
47 +extensions/ssh-tools/index.ts(269,6): error TS2339: Property 'ui' does not exist on type 'ExtensionAPI'.
48 +extensions/ssh-tools/index.ts(271,7): error TS2339: Property 'ui' does not exist on type 'ExtensionAPI'.
49 +extensions/ssh-tools/index.ts(273,6): error TS2339: Property 'ui' does not exist on type 'ExtensionAPI'.
50 +extensions/ssh-tools/index.ts(280,6): error TS2339: Property 'ui' does not exist on type 'ExtensionAPI'.
51 +extensions/ssh-tools/index.ts(281,6): error TS2339: Property 'ui' does not exist on type 'ExtensionAPI'.
52 +extensions/ssh-tools/index.ts(302,4): error TS2322: Type '(id: string, params: { offset?: number | undefined; limit?: number | undefined; path: string; } | { path: string; edits: { oldText: string; newText: string; }[]; } | { path: string; content: string; }, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<...> | undefined) => Promise<...> | Promise<...>' is not assignable to type '(toolCallId: string, params: { offset?: number | undefined; limit?: number | undefined; path: string; } | { path: string; edits: { oldText: string; newText: string; }[]; } | { path: string; content: string; }, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<...> | undefined, ctx: ExtensionContext)...'.
53 +extensions/ssh-tools/index.ts(303,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation.
54 +extensions/ssh-tools/index.ts(304,33): error TS2322: Type 'ReadOperations | WriteOperations | EditOperations' is not assignable to type '(ReadOperations & WriteOperations & EditOperations) | undefined'.
55 +extensions/ssh-tools/index.ts(304,61): error TS2554: Expected 5 arguments, but got 4.
56 +extensions/ssh-tools/index.ts(311,4): error TS2322: Type '(args: unknown, theme: { fg: (c: string, s: string) => string; }) => Text' is not assignable to type '(args: { offset?: number | undefined; limit?: number | undefined; path: string; } | { path: string; edits: { oldText: string; newText: string; }[]; } | { path: string; content: string; }, theme: Theme, context: ToolRenderContext<...>) => Component'.
57 +extensions/ssh-tools/index.ts(311,44): error TS2339: Property 'path' does not exist on type '{}'.
58 +extensions/ssh-tools/index.ts(312,4): error TS2322: Type '((result: AgentToolResult<EditToolDetails | undefined>, options: ToolRenderResultOptions, theme: Theme, context: ToolRenderContext<...>) => Component) | ((result: AgentToolResult<...>, options: ToolRenderResultOptions, theme: Theme, context: ToolRenderContext<...>) => Component) | ((result: AgentToolResult<...>, opt...' is not assignable to type '((result: AgentToolResult<undefined>, options: ToolRenderResultOptions, theme: Theme, context: ToolRenderContext<EditRenderState, { ...; } | ... 1 more ... | { ...; }>) => Component) | undefined'.
59 +extensions/ssh-tools/index.ts(324,4): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation.
60 +extensions/ssh-tools/index.ts(327,7): error TS2554: Expected 5 arguments, but got 4.
61 +extensions/tldr/index.ts(207,31): error TS2769: No overload matches this call.
62 +extensions/usage/index.ts(263,5): error TS2322: Type 'unknown' is not assignable to type 'string'.
63 +extensions/usage/index.ts(266,20): error TS2339: Property 'role' does not exist on type '{}'.
64 +extensions/usage/index.ts(268,37): error TS2345: Argument of type '{}' is not assignable to parameter of type 'Record<string, unknown>'.
65 +extensions/usage/index.ts(326,13): error TS2339: Property 'sessions' does not exist on type 'BaseStats'.
66 +extensions/usage/index.ts(326,45): error TS2339: Property 'sessions' does not exist on type 'BaseStats'.
67 +extensions/usage/index.ts(480,28): error TS2339: Property 'sessionId' does not exist on type 'GlobalSessionSpan'.
68 +extensions/web/index.ts(437,4): error TS2322: Type 'string | 0' is not assignable to type 'string | false | undefined'.
69 +extensions/web/index.ts(449,3): error TS2322: Type 'ImageSummary' is not assignable to type 'Record<string, unknown>'.
70 +extensions/web/index.ts(486,4): error TS2322: Type 'string | 0 | undefined' is not assignable to type 'string | false | undefined'.
71 +extensions/web/index.ts(500,3): error TS2322: Type 'MediaSummary' is not assignable to type 'Record<string, unknown>'.
72 +extensions/web/index.ts(697,38): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
73 +extensions/web/index.ts(720,2): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
74 +extensions/web/index.ts(803,20): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
75 +extensions/web/index.ts(824,15): error TS2339: Property 'isError' does not exist on type 'AgentToolResult<unknown>'.
76 +extensions/web/index.ts(830,20): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
77 +extensions/web/index.ts(963,9): error TS2322: Type '(_toolCallId: string, params: { timeout?: number | undefined; format?: "text" | "raw" | "html" | "json" | "markdown" | undefined; maxChars?: number | undefined; url: string; }, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<...> | undefined, ctx: ExtensionContext) => Promise<...>' is not assignable to type '(toolCallId: string, params: { timeout?: number | undefined; format?: "text" | "raw" | "html" | "json" | "markdown" | undefined; maxChars?: number | undefined; url: string; }, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<...> | undefined, ctx: ExtensionContext) => Promise<...>'.
78 +extensions/web/index.ts(971,15): error TS2345: Argument of type '{ content: { type: "text"; text: string; }[]; }' is not assignable to parameter of type 'AgentToolResult<unknown>'.
79 +extensions/web/index.ts(995,15): error TS2345: Argument of type '{ content: { type: "text"; text: string; }[]; }' is not assignable to parameter of type 'AgentToolResult<unknown>'.
80 +extensions/web/index.ts(1128,20): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
81 +extensions/web/index.ts(1131,15): error TS2339: Property 'isError' does not exist on type 'AgentToolResult<unknown>'.
82 +extensions/web/index.ts(1131,42): error TS2339: Property 'error' does not exist on type '{}'.
83 +extensions/web/index.ts(1133,6): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
84 +extensions/web/index.ts(1135,25): error TS2345: Argument of type 'AgentToolResult<unknown>' is not assignable to parameter of type '{ isError?: boolean | undefined; details?: Record<string, unknown> | undefined; content: { type: string; text?: string | undefined; }[]; }'.
85 +extensions/web/index.ts(1144,47): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
86 +extensions/web/index.ts(1171,15): error TS2345: Argument of type '{ content: { type: "text"; text: string; }[]; }' is not assignable to parameter of type 'AgentToolResult<unknown>'.
87 +extensions/web/index.ts(1291,20): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
88 +extensions/web/index.ts(1294,15): error TS2339: Property 'isError' does not exist on type 'AgentToolResult<unknown>'.
89 +extensions/web/index.ts(1294,42): error TS2339: Property 'error' does not exist on type '{}'.
90 +extensions/web/index.ts(1296,6): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
91 +extensions/web/index.ts(1298,25): error TS2345: Argument of type 'AgentToolResult<unknown>' is not assignable to parameter of type '{ isError?: boolean | undefined; details?: Record<string, unknown> | undefined; content: { type: string; text?: string | undefined; }[]; }'.
92 +extensions/web/index.ts(1305,49): error TS2345: Argument of type 'Theme' is not assignable to parameter of type '{ fg: (style: string, text: string) => string; }'.
93 +extensions/web/index.ts(1312,47): error TS2345: Argument of type '"expandTools"' is not assignable to parameter of type 'keyof Keybindings'.
94 +extensions/web/index.ts(1343,15): error TS2345: Argument of type '{ content: { type: "text"; text: string; }[]; }' is not assignable to parameter of type 'AgentToolResult<unknown>'.

extensions/autoresearch/__tests__/unit.test.ts

Modified
1 +import { DEFAULT_MAX_LINES } from "@earendil-works/pi-coding-agent";
1 2 import { describe, expect, it } from "bun:test";
2 3 import { __test } from "../index.ts";
3 4 import {
212 +// ── DEFAULT_MAX_LINES import regression ───────────────────────────────────
213 +// https://github.com/earendil-works/pi-ext/issues/XXX
214 +// ReferenceError: DEFAULT_MAX_LINES is not defined at runtime
216 +describe("DEFAULT_MAX_LINES is defined", () => {
217 + it("is a positive number", () => {
218 + // Regression: DEFAULT_MAX_LINES was used but never imported.
219 + // If the import is missing again, this file fails to load.
220 + // Additionally verify the value is sane.
221 + expect(typeof DEFAULT_MAX_LINES).toBe("number");
222 + expect(DEFAULT_MAX_LINES).toBeGreaterThan(0);
223 + });
224 +});
211 226 // ── Hook script path ──────────────────────────────────────────────────────
213 228 describe("hookScriptPath", () => {

extensions/autoresearch/index.ts

Modified
13 13 SessionBeforeCompactEvent,
14 14 Theme,
15 15 } from "@earendil-works/pi-coding-agent";
16 -import { truncateTail, DEFAULT_MAX_BYTES, formatSize } from "@earendil-works/pi-coding-agent";
16 +import { truncateTail, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES, formatSize } from "@earendil-works/pi-coding-agent";
17 17 import { StringEnum } from "@earendil-works/pi-ai";
18 18 import { Text, truncateToWidth, matchesKey, visibleWidth } from "@earendil-works/pi-tui";
19 19 import { Type } from "typebox";
1971 1971 const runtime = getRuntime(ctx);
1972 1972 const state = runtime.state;
1973 1973 const cwd = ctx.cwd;
1974 - const secondaryMetrics = params.metrics ?? {};
1974 + const secondaryMetrics = (params.metrics ?? {}) as Record<string, number>;
1976 1976 // Gate: prevent "keep" when checks failed
1977 1977 if (params.status === "keep" && runtime.lastRunChecks && !runtime.lastRunChecks.pass) {
2328 2328 // ── Shortcuts ───────────────────────────────────────────────────────
2330 2330 if (shortcuts.toggleDashboard) {
2331 - pi.registerShortcut(shortcuts.toggleDashboard, {
2331 + pi.registerShortcut(shortcuts.toggleDashboard as Parameters<typeof pi.registerShortcut>[0], {
2332 2332 description: "Toggle autoresearch dashboard",
2333 2333 handler: async (ctx) => {
2334 2334 const runtime = getRuntime(ctx);
2345 2345 if (shortcuts.fullscreenDashboard) {
2346 - pi.registerShortcut(shortcuts.fullscreenDashboard, {
2346 + pi.registerShortcut(shortcuts.fullscreenDashboard as Parameters<typeof pi.registerShortcut>[0], {
2347 2347 description: "Fullscreen autoresearch dashboard",
2348 2348 handler: async (ctx) => {
2349 2349 const runtime = getRuntime(ctx);

extensions/context-size/index.ts

Modified
147 147 for (const eventName of UPDATE_EVENTS) {
148 - pi.on(eventName, async (_event, ctx) => updateSegment(ctx));
148 + pi.on(eventName as any, async (_event: any, ctx: any) => updateSegment(ctx));
151 151 pi.on("session_shutdown", async (_event, ctx) => {

extensions/cost/index.ts

Modified
433 433 for (const eventName of UPDATE_EVENTS) {
434 - pi.on(eventName, async (_event, ctx) => syncBestEffort(ctx));
434 + pi.on(eventName as any, async (_event: any, ctx: any) => syncBestEffort(ctx));
437 437 for (const eventName of RESET_SIGNATURE_EVENTS) {
438 - pi.on(eventName, async (_event, ctx) => {
438 + pi.on(eventName as any, async (_event: any, ctx: any) => {
439 439 lastSignature = "";
440 440 await syncBestEffort(ctx);

extensions/diff-review/browser/index.ts

Added
new file mode 100644
1 +// @ts-expect-error — CSS side-effect import for bundler
2 +import "./style.css";
3 +import type {
4 + DiffLineAnnotation,
5 + FileDiff,
6 + FileDiffMetadata,
7 + SelectedLineRange,
8 +} from "@pierre/diffs";
9 +import type {
10 + FileTree,
11 + FileTreeRowDecorationRenderer,
12 + GitStatusEntry,
13 +} from "@pierre/trees";
14 +import {
15 + HEARTBEAT_INTERVAL_MS,
16 + REVIEW_POLL_INTERVAL_MS,
17 +} from "../constants.js";
18 +import type {
19 + FindingDraft,
20 + ReviewCategory,
21 + ReviewPayload,
22 + ReviewSeverity,
23 + ReviewSide,
24 +} from "../types.js";
25 +import { DIFF_FONT_CSS, TREE_CSS } from "./shadow-css.js";
26 +import { NUGU_CODE_THEME, registerNuguCodeTheme } from "./theme.js";
28 +type FindingMeta = {
29 + findingId: string;
30 + severity: ReviewSeverity;
31 + category: ReviewCategory;
32 + comment: string;
33 +};
34 +type ThemeMode = "system" | "dark" | "light";
35 +type PaneSide = "left" | "right";
36 +type ReviewSelection = {
37 + file: string;
38 + side: ReviewSide;
39 + startLine: number;
40 + endLine: number;
41 +};
42 +type ViewPoint = { x: number; y: number };
43 +type SearchEntry = {
44 + file: string;
45 + side: "additions" | "deletions";
46 + line: number;
47 + text: string;
48 +};
49 +type SearchMatch = SearchEntry & { matchStart: number; matchEnd: number };
51 +type Elements = {
52 + app: HTMLElement;
53 + meta: HTMLElement;
54 + summary: HTMLElement;
55 + findingCount: HTMLElement;
56 + drawerCount: HTMLElement;
57 + tree: HTMLElement;
58 + diffs: HTMLElement;
59 + inlineFinding: HTMLElement;
60 + selection: HTMLElement;
61 + severity: HTMLSelectElement;
62 + severitySub: HTMLElement;
63 + category: HTMLSelectElement;
64 + categorySub: HTMLElement;
65 + comment: HTMLTextAreaElement;
66 + add: HTMLButtonElement;
67 + inlineCancel: HTMLButtonElement;
68 + findings: HTMLElement;
69 + notes: HTMLTextAreaElement;
70 + search: HTMLInputElement;
71 + searchClear: HTMLButtonElement;
72 + searchResults: HTMLElement;
73 + cancel: HTMLButtonElement;
74 + submit: HTMLButtonElement;
75 + status: HTMLElement;
76 + themeMode: HTMLSelectElement;
77 + leftSplitter: HTMLElement;
78 + rightSplitter: HTMLElement;
79 + toggleLeft: HTMLButtonElement;
80 + toggleRight: HTMLButtonElement;
81 +};
83 +const ROUTES = {
84 + review: "/api/review",
85 + heartbeat: "/api/heartbeat",
86 + cancel: "/api/cancel",
87 + validateFinding: "/api/finding/validate",
88 + submit: "/api/submit",
89 +} as const;
90 +const THEME_STORAGE_KEY = "diff-review-theme";
91 +const LAYOUT_STORAGE_KEY = "diff-review-layout";
92 +const REVIEW_CATEGORIES = [
93 + "bug",
94 + "style",
95 + "perf",
96 + "question",
97 +] as const satisfies readonly ReviewCategory[];
98 +const REVIEW_SEVERITIES = [
99 + "high",
100 + "medium",
101 + "low",
102 +] as const satisfies readonly ReviewSeverity[];
103 +const THEME_MODES = [
104 + "system",
105 + "dark",
106 + "light",
107 +] as const satisfies readonly ThemeMode[];
108 +const SEVERITY_SUBS: Record<string, string> = {
109 + high: "ship it to prod, coward",
110 + medium: "suspicious little gremlin",
111 + low: "tiny crime, still crime",
113 +const CATEGORY_SUBS: Record<string, string> = {
114 + bug: "exquisite disaster",
115 + style: "crimes against taste",
116 + perf: "artisanal slowness",
117 + question: "explain yourself",
119 +const PANE_LIMITS = {
120 + left: { min: 180, max: 560, fallback: 288 },
121 + right: { min: 280, max: 680, fallback: 382 },
122 +} as const;
124 +type LayoutState = {
125 + left: number;
126 + right: number;
127 + leftCollapsed: boolean;
128 + rightCollapsed: boolean;
131 +const token = new URLSearchParams(location.search).get("token") ?? "";
132 +const els: Elements = {
133 + app: must("app"),
134 + meta: must("meta"),
135 + summary: must("summary"),
136 + findingCount: must("finding-count"),
137 + drawerCount: must("drawer-count"),
138 + tree: must("tree"),
139 + diffs: must("diffs"),
140 + inlineFinding: must("inline-finding"),
141 + selection: must("selection"),
142 + severity: mustSelect("severity"),
143 + severitySub: must("severity-sub"),
144 + category: mustSelect("category"),
145 + categorySub: must("category-sub"),
146 + comment: mustText("comment"),
147 + add: mustButton("add"),
148 + inlineCancel: mustButton("inline-cancel"),
149 + findings: must("findings"),
150 + notes: mustText("notes"),
151 + search: must("search") as HTMLInputElement,
152 + searchClear: mustButton("search-clear"),
153 + searchResults: must("search-results"),
154 + cancel: mustButton("cancel"),
155 + submit: mustButton("submit"),
156 + status: must("status"),
157 + themeMode: mustSelect("theme-mode"),
158 + leftSplitter: must("left-splitter"),
159 + rightSplitter: must("right-splitter"),
160 + toggleLeft: mustButton("toggle-left"),
161 + toggleRight: mustButton("toggle-right"),
164 +const findings: FindingDraft[] = [];
165 +const diffViews = new Map<string, FileDiff<FindingMeta>>();
166 +const systemTheme = window.matchMedia("(prefers-color-scheme: light)");
167 +let fileTree: FileTree | undefined;
168 +let selectedFile: string | undefined;
169 +let selected: ReviewSelection | undefined;
170 +let lastDiffPointer: ViewPoint | undefined;
171 +let searchIndex: SearchEntry[] = [];
172 +let searchResults: SearchMatch[] = [];
173 +let searchActiveIndex = -1;
174 +let searchDebounce: number | undefined;
175 +let diffsModule: typeof import("@pierre/diffs") | undefined;
176 +let treesModule: typeof import("@pierre/trees") | undefined;
177 +let heartbeat: number | undefined;
178 +let reviewPoll: number | undefined;
179 +let reviewHash = "";
180 +let renderGeneration = 0;
181 +let searchIndexing = false;
182 +let notesGrowFrame: number | undefined;
183 +let closing = false;
184 +let themeMode: ThemeMode = readThemeMode();
186 +applyThemeMode(themeMode);
187 +els.themeMode.value = themeMode;
188 +applyLayout(readLayout());
190 +main().catch((err) => setDisconnectedStatus(err));
191 +window.addEventListener("pagehide", closeFromBrowser);
192 +systemTheme.addEventListener("change", () => {
193 + if (themeMode === "system") applyThemeMode(themeMode);
194 +});
196 +async function main() {
197 + if (!token) throw new Error("Missing review token");
198 + setStatus("Loading review…");
199 + const reviewPromise = api<ReviewPayload>(ROUTES.review);
200 + setStatus("Loading diff renderer…");
201 + await loadRendererModules();
202 + const review = await reviewPromise;
203 + startHeartbeat();
204 + startReviewPolling();
205 + wireActions();
206 + await renderReview(review);
207 + setStatus("Ready");
210 +async function loadRendererModules() {
211 + if (diffsModule && treesModule) return;
212 + const [diffs, trees] = await Promise.all([
213 + import("@pierre/diffs"),
214 + import("@pierre/trees"),
215 + ]);
216 + diffsModule = diffs;
217 + treesModule = trees;
218 + registerNuguCodeTheme(diffs.registerCustomCSSVariableTheme);
221 +function diffs() {
222 + if (!diffsModule) throw new Error("Diff renderer not loaded");
223 + return diffsModule;
226 +function trees() {
227 + if (!treesModule) throw new Error("File tree renderer not loaded");
228 + return treesModule;
231 +async function renderReview(review: ReviewPayload) {
232 + const generation = ++renderGeneration;
233 + reviewHash = hashReview(review);
234 + renderMeta(review);
235 + renderTree(review);
236 + const fileDiffs = await renderDiffs(review, generation);
237 + if (!fileDiffs || generation !== renderGeneration) return;
238 + renderAnnotations();
239 + void buildSearchIndex(fileDiffs, generation);
242 +function renderMeta(review: ReviewPayload) {
243 + const totals = review.files.reduce(
244 + (sum, file) => ({
245 + additions: sum.additions + file.additions,
246 + deletions: sum.deletions + file.deletions,
247 + }),
248 + { additions: 0, deletions: 0 },
249 + );
250 + els.meta.replaceChildren(
251 + metaChip("round", String(review.round)),
252 + metaChip("reviewing", sourceLabel(review.source)),
253 + );
255 + els.summary.replaceChildren();
256 + const stats = document.createElement("span");
257 + stats.className = "summary-stats";
258 + stats.textContent = `${review.files.length} files · +${totals.additions} −${totals.deletions}`;
259 + els.summary.appendChild(stats);
260 + if (review.skippedFiles.length > 0) {
261 + const skipped = document.createElement("span");
262 + skipped.className = "summary-skipped";
263 + skipped.textContent = `skipped ${review.skippedFiles.length} oversized/binary file${review.skippedFiles.length === 1 ? "" : "s"}`;
264 + els.summary.appendChild(skipped);
266 + const hint = document.createElement("span");
267 + hint.className = "summary-hint";
268 + hint.textContent =
269 + "Click a changed line, describe issue, send findings to Pi.";
270 + els.summary.appendChild(hint);
271 + updateFindingCount();
274 +function sourceLabel(source: ReviewPayload["source"]): string {
275 + const scope = source.files?.length
276 + ? ` · ${source.files.length} path${source.files.length === 1 ? "" : "s"}`
277 + : "";
278 + if (source.kind === "working-tree") return `unstaged changes${scope}`;
279 + if (source.kind === "staged") return `staged changes${scope}`;
280 + return `changes vs ${source.base}${scope}`;
283 +function metaChip(label: string, value: string) {
284 + const chip = document.createElement("span");
285 + chip.className = `meta-chip meta-${label}`;
286 + const labelNode = document.createElement("span");
287 + labelNode.className = "meta-label";
288 + labelNode.textContent = label;
289 + const valueNode = document.createElement("span");
290 + valueNode.className = "meta-value";
291 + valueNode.textContent = value;
292 + chip.append(labelNode, valueNode);
293 + return chip;
296 +function renderTree(review: ReviewPayload) {
297 + fileTree?.cleanUp();
298 + const skipped = skippedFilesByPath(review);
299 + const reviewPaths = review.files.flatMap((file) =>
300 + file.prevPath && file.prevPath !== file.path
301 + ? [file.prevPath, file.path]
302 + : [file.path],
303 + );
304 + const paths = [
305 + ...reviewPaths,
306 + ...[...skipped.keys()].filter((path) => !reviewPaths.includes(path)),
307 + ];
308 + fileTree = new (trees().FileTree)({
309 + paths,
310 + search: true,
311 + unsafeCSS: TREE_CSS,
312 + initialExpansion: "open",
313 + initialSelectedPaths:
314 + selectedFile && review.files.some((file) => file.path === selectedFile)
315 + ? [selectedFile]
316 + : [],
317 + gitStatus: [
318 + ...review.files.flatMap((file) => treeGitStatusEntries(file)),
319 + ...[...skipped.keys()].map((path) => ({
320 + path,
321 + status: "ignored" as const,
322 + })),
323 + ] satisfies GitStatusEntry[],
324 + renderRowDecoration: treeRowDecoration(review, skipped),
325 + onSelectionChange: ([path]) => {
326 + const renamedTarget = path
327 + ? renamedTargetForPrevPath(review, path)
328 + : undefined;
329 + if (renamedTarget) {
330 + fileTree?.getItem(path)?.deselect();
331 + fileTree?.getItem(renamedTarget)?.select();
332 + selectFile(renamedTarget, true);
333 + return;
335 + if (path && skipped.has(path)) {
336 + fileTree?.getItem(path)?.deselect();
337 + if (selectedFile) fileTree?.getItem(selectedFile)?.select();
338 + setStatus(`Skipped ${path}: ${skipped.get(path)}`);
339 + return;
341 + selectFile(path, true);
342 + },
343 + });
344 + fileTree.render({ fileTreeContainer: els.tree });
345 + wireTreeSearchClear(fileTree);
348 +function treeGitStatusEntries(
349 + file: ReviewPayload["files"][number],
350 +): GitStatusEntry[] {
351 + if (file.status === "renamed" && file.prevPath && file.prevPath !== file.path)
352 + return [
353 + { path: file.prevPath, status: "deleted" },
354 + { path: file.path, status: "renamed" },
355 + ];
356 + return [{ path: file.path, status: toGitStatus(file.status) }];
359 +function renamedTargetForPrevPath(review: ReviewPayload, path: string) {
360 + return review.files.find(
361 + (file) => file.status === "renamed" && file.prevPath === path,
362 + )?.path;
365 +function treeRowDecoration(
366 + review: ReviewPayload,
367 + skipped: ReadonlyMap<string, string>,
368 +): FileTreeRowDecorationRenderer {
369 + return ({ row }) => {
370 + if (row.kind !== "file") return null;
371 + const reason = skipped.get(row.path);
372 + if (reason) return { text: "skip", title: reason };
373 + const renameSource = review.files.find(
374 + (file) => file.status === "renamed" && file.prevPath === row.path,
375 + );
376 + if (renameSource)
377 + return { text: "from", title: `renamed to ${renameSource.path}` };
378 + const renameTarget = review.files.find(
379 + (file) =>
380 + file.status === "renamed" && file.path === row.path && file.prevPath,
381 + );
382 + if (renameTarget?.prevPath)
383 + return { text: "to", title: `renamed from ${renameTarget.prevPath}` };
384 + return null;
385 + };
388 +function wireTreeSearchClear(tree: FileTree) {
389 + const root = els.tree.shadowRoot;
390 + if (!root) return;
392 + const sync = () => {
393 + const container = root.querySelector<HTMLElement>(
394 + "[data-file-tree-search-container]",
395 + );
396 + const input = root.querySelector<HTMLInputElement>(
397 + "[data-file-tree-search-input]",
398 + );
399 + if (!container || !input || container.querySelector(".tree-search-clear"))
400 + return;
401 + const clear = document.createElement("button");
402 + clear.type = "button";
403 + clear.className = "tree-search-clear";
404 + clear.textContent = "×";
405 + clear.setAttribute("aria-label", "Clear file search");
406 + clear.addEventListener("pointerdown", (event) => event.preventDefault());
407 + clear.addEventListener("click", (event) => {
408 + event.preventDefault();
409 + tree.setSearch("");
410 + input.value = "";
411 + input.focus();
412 + });
413 + container.appendChild(clear);
414 + };
416 + sync();
417 + const observer = new MutationObserver(sync);
418 + observer.observe(root, { childList: true, subtree: true });
419 + const cleanup = tree.cleanUp.bind(tree);
420 + tree.cleanUp = () => {
421 + observer.disconnect();
422 + cleanup();
423 + };
426 +function skippedFilesByPath(review: ReviewPayload): Map<string, string> {
427 + const skipped = new Map<string, string>();
428 + for (const entry of review.skippedFiles) {
429 + const { path, reason } = parseSkippedFile(entry);
430 + skipped.set(path, reason);
432 + return skipped;
435 +function parseSkippedFile(entry: string): { path: string; reason: string } {
436 + const match = /^(.*) \(([^()]*)\)$/.exec(entry);
437 + if (!match) return { path: entry, reason: "oversized/binary" };
438 + return { path: match[1], reason: match[2] };
441 +async function renderDiffs(
442 + review: ReviewPayload,
443 + generation: number,
444 +): Promise<FileDiffMetadata[] | undefined> {
445 + for (const view of diffViews.values()) view.cleanUp();
446 + diffViews.clear();
447 + els.diffs.replaceChildren();
448 + clearSelection(false);
450 + const files = diffs()
451 + .parsePatchFiles(review.diffText, `diff-review-${review.round}`, true)
452 + .flatMap((patch) => patch.files);
453 + for (let index = 0; index < files.length; index++) {
454 + if (generation !== renderGeneration) return undefined;
455 + renderFileDiff(files[index]);
456 + if (files.length > 1)
457 + setStatus(`Rendering ${index + 1}/${files.length} files…`);
458 + await yieldToBrowser();
460 + return files;
463 +function renderFileDiff(fileDiff: FileDiffMetadata) {
464 + const section = fileSection(fileDiff);
465 + const view = new (diffs().FileDiff)<FindingMeta>({
466 + theme: { dark: NUGU_CODE_THEME, light: NUGU_CODE_THEME },
467 + diffStyle: "split",
468 + overflow: "scroll",
469 + enableLineSelection: true,
470 + enableGutterUtility: true,
471 + lineHoverHighlight: "both",
472 + themeType: themeMode,
473 + unsafeCSS: DIFF_FONT_CSS,
474 + onLineSelected: (range) =>
475 + setSelection(fileDiff.name, range, lastDiffPointer),
476 + onGutterUtilityClick: (range) =>
477 + setSelection(fileDiff.name, range, lastDiffPointer),
478 + onLineClick: ({ lineNumber, annotationSide, event }) =>
479 + setSelection(
480 + fileDiff.name,
481 + singleLineRange(lineNumber, annotationSide),
482 + eventPoint(event),
483 + ),
484 + onLineNumberClick: ({ lineNumber, annotationSide, event }) =>
485 + setSelection(
486 + fileDiff.name,
487 + singleLineRange(lineNumber, annotationSide),
488 + eventPoint(event),
489 + ),
490 + renderAnnotation: renderAnnotation,
491 + });
492 + view.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
493 + diffViews.set(fileDiff.name, view);
496 +function fileSection(fileDiff: FileDiffMetadata) {
497 + const section = document.createElement("section");
498 + section.className = "file-section";
499 + section.dataset.fileSection = fileDiff.name;
500 + if (fileDiff.name === selectedFile) section.dataset.selectedFile = "true";
502 + const title = document.createElement("h2");
503 + title.className = "file-title";
504 + title.textContent = fileTitle(fileDiff);
505 + section.appendChild(title);
506 + els.diffs.appendChild(section);
507 + return section;
510 +function fileTitle(fileDiff: FileDiffMetadata) {
511 + return fileDiff.prevName && fileDiff.prevName !== fileDiff.name
512 + ? `${fileDiff.prevName} → ${fileDiff.name}`
513 + : fileDiff.name;
516 +function renderAnnotation(annotation: DiffLineAnnotation<FindingMeta>) {
517 + const chip = document.createElement("div");
518 + chip.className = "finding-chip";
519 + chip.textContent = `[${annotation.metadata.severity}][${annotation.metadata.category}] ${annotation.metadata.comment}`;
520 + return chip;
523 +function setSelection(
524 + file: string,
525 + range: SelectedLineRange | null,
526 + point?: ViewPoint,
527 +) {
528 + const next = normalizeSelection(file, range);
529 + if (!next) {
530 + clearSelection(false);
531 + return;
533 + selected = next;
534 + els.add.disabled = false;
535 + els.selection.className = "selection-active";
536 + els.selection.textContent = selectionLabel(next);
537 + showFindingForm(next, point);
540 +function showFindingForm(selection: ReviewSelection, point?: ViewPoint) {
541 + const anchor = point ?? lineAnchor(selection) ?? centerPoint();
542 + els.inlineFinding.hidden = false;
543 + els.inlineFinding.dataset.open = "true";
544 + positionFindingForm(anchor);
545 + requestAnimationFrame(() => {
546 + positionFindingForm(anchor);
547 + els.comment.focus();
548 + });
551 +function hideFindingForm() {
552 + els.inlineFinding.hidden = true;
553 + delete els.inlineFinding.dataset.open;
556 +function positionFindingForm(point: ViewPoint) {
557 + const margin = 12;
558 + const gap = 14;
559 + const rect = els.inlineFinding.getBoundingClientRect();
560 + const width = rect.width || 360;
561 + const height = rect.height || 280;
562 + let left = point.x + gap;
563 + let top = point.y - 22;
564 + if (left + width + margin > window.innerWidth) left = point.x - width - gap;
565 + left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));
566 + top = Math.max(margin, Math.min(top, window.innerHeight - height - margin));
567 + els.inlineFinding.style.left = `${Math.round(left)}px`;
568 + els.inlineFinding.style.top = `${Math.round(top)}px`;
571 +function lineAnchor(selection: ReviewSelection): ViewPoint | undefined {
572 + const section = document.querySelector<HTMLElement>(
573 + `[data-file-section="${cssEscape(selection.file)}"]`,
574 + );
575 + const container = section?.querySelector(
576 + "diffs-container",
577 + ) as HTMLElement | null;
578 + const root = container?.shadowRoot;
579 + const line = root?.querySelector<HTMLElement>(
580 + `[data-${selection.side}] [data-line="${selection.startLine}"]`,
581 + );
582 + if (!line) return undefined;
583 + const rect = line.getBoundingClientRect();
584 + return { x: rect.left + 24, y: rect.top + rect.height / 2 };
587 +function centerPoint(): ViewPoint {
588 + return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
591 +function eventPoint(event: MouseEvent | PointerEvent): ViewPoint {
592 + return { x: event.clientX, y: event.clientY };
595 +function normalizeSelection(
596 + file: string,
597 + range: SelectedLineRange | null,
598 +): ReviewSelection | undefined {
599 + if (!range) return undefined;
600 + const side = range.side;
601 + const endSide = range.endSide ?? side;
602 + if (!isReviewSide(side) || endSide !== side) return undefined;
603 + return {
604 + file,
605 + side,
606 + startLine: Math.min(range.start, range.end),
607 + endLine: Math.max(range.start, range.end),
608 + };
611 +function singleLineRange(
612 + lineNumber: number,
613 + side: SelectedLineRange["side"],
614 +): SelectedLineRange | null {
615 + return side
616 + ? { start: lineNumber, end: lineNumber, side, endSide: side }
617 + : null;
620 +function selectionLabel(selection: ReviewSelection) {
621 + const { file, startLine, endLine, side } = selection;
622 + return `${file}:${startLine}${startLine === endLine ? "" : `-${endLine}`} ${side}`;
625 +function wireActions() {
626 + els.themeMode.addEventListener("change", updateThemeMode);
627 + els.severity.addEventListener("change", () => {
628 + els.severitySub.textContent = SEVERITY_SUBS[els.severity.value] ?? "";
629 + });
630 + els.category.addEventListener("change", () => {
631 + els.categorySub.textContent = CATEGORY_SUBS[els.category.value] ?? "";
632 + });
633 + els.add.addEventListener("click", addFinding);
634 + els.submit.addEventListener("click", submitReview);
635 + els.cancel.addEventListener("click", cancelReview);
636 + els.toggleLeft.addEventListener("click", () => togglePane("left"));
637 + els.toggleRight.addEventListener("click", () => togglePane("right"));
638 + els.leftSplitter.addEventListener("pointerdown", (event) =>
639 + startPaneResize("left", event),
640 + );
641 + els.rightSplitter.addEventListener("pointerdown", (event) =>
642 + startPaneResize("right", event),
643 + );
644 + els.diffs.addEventListener(
645 + "pointerdown",
646 + (event) => {
647 + lastDiffPointer = eventPoint(event);
648 + },
649 + true,
650 + );
651 + els.diffs.addEventListener(
652 + "pointerup",
653 + (event) => {
654 + lastDiffPointer = eventPoint(event);
655 + },
656 + true,
657 + );
658 + els.inlineCancel.addEventListener("click", () => {
659 + clearFindingForm();
660 + clearSelection(true);
661 + });
662 + els.comment.addEventListener("keydown", (event) => {
663 + if ((event.metaKey || event.ctrlKey) && event.key === "Enter")
664 + void addFinding();
665 + if (event.key === "Escape") clearSelection(true);
666 + });
667 + els.notes.addEventListener("input", () => scheduleNotesAutoGrow());
668 + scheduleNotesAutoGrow();
669 + els.search.addEventListener("input", () => {
670 + window.clearTimeout(searchDebounce);
671 + searchDebounce = window.setTimeout(runSearch, 120);
672 + });
673 + els.searchClear.addEventListener("click", () => clearCodeSearch(true));
674 + els.search.addEventListener("search", () => {
675 + if (!els.search.value.trim()) clearCodeSearch(false);
676 + });
677 + els.search.addEventListener("keydown", (event) => {
678 + if (isEscapeKey(event)) {
679 + event.preventDefault();
680 + event.stopPropagation();
681 + closeCodeSearchPopup();
682 + return;
684 + if (event.key === "ArrowDown" || event.key === "ArrowUp") {
685 + event.preventDefault();
686 + navigateSearch(event.key === "ArrowDown" ? 1 : -1);
687 + return;
689 + if (event.key === "Enter") {
690 + event.preventDefault();
691 + if (searchResults.length === 0) return;
692 + const idx = searchActiveIndex >= 0 ? searchActiveIndex : 0;
693 + jumpToMatch(searchResults[idx], idx);
694 + hideSearch();
696 + });
697 + document.addEventListener(
698 + "keydown",
699 + (event) => {
700 + if (!isEscapeKey(event) || els.searchResults.hidden) return;
701 + event.preventDefault();
702 + event.stopPropagation();
703 + closeCodeSearchPopup();
704 + },
705 + true,
706 + );
707 + document.addEventListener("click", (event) => {
708 + if (
709 + !els.searchResults.contains(event.target as Node) &&
710 + event.target !== els.search
712 + hideSearch();
713 + });
716 +function scheduleNotesAutoGrow() {
717 + if (notesGrowFrame !== undefined) return;
718 + notesGrowFrame = requestAnimationFrame(() => {
719 + notesGrowFrame = undefined;
720 + autoGrowTextarea(els.notes);
721 + });
724 +function autoGrowTextarea(textarea: HTMLTextAreaElement) {
725 + textarea.style.height = "auto";
726 + textarea.style.height = `${textarea.scrollHeight}px`;
729 +function yieldToBrowser() {
730 + return new Promise<void>((resolve) => {
731 + const requestIdle = window.requestIdleCallback as
732 + | ((callback: () => void, options?: { timeout: number }) => number)
733 + | undefined;
734 + if (requestIdle) requestIdle(() => resolve(), { timeout: 80 });
735 + else requestAnimationFrame(() => resolve());
736 + });
739 +function updateThemeMode() {
740 + themeMode = themeModeFromValue(els.themeMode.value);
741 + localStorage.setItem(THEME_STORAGE_KEY, themeMode);
742 + applyThemeMode(themeMode);
743 + for (const view of diffViews.values()) view.setThemeType(themeMode);
746 +function togglePane(side: PaneSide) {
747 + const layout = readLayout();
748 + if (side === "left") layout.leftCollapsed = !layout.leftCollapsed;
749 + else layout.rightCollapsed = !layout.rightCollapsed;
750 + applyLayout(layout);
751 + writeLayout(layout);
754 +function startPaneResize(side: PaneSide, event: PointerEvent) {
755 + if ((event.target as HTMLElement).closest("button")) return;
756 + event.preventDefault();
757 + const layout = readLayout();
758 + if (side === "left") layout.leftCollapsed = false;
759 + else layout.rightCollapsed = false;
760 + els.app.dataset.resizing = side;
761 + try {
762 + els.app.setPointerCapture?.(event.pointerId);
763 + } catch {}
765 + const move = (moveEvent: PointerEvent) => {
766 + const next = { ...layout };
767 + if (side === "left") next.left = clampPane("left", moveEvent.clientX);
768 + else next.right = clampPane("right", window.innerWidth - moveEvent.clientX);
769 + applyLayout(next);
770 + writeLayout(next);
771 + };
772 + const stop = () => {
773 + delete els.app.dataset.resizing;
774 + window.removeEventListener("pointermove", move);
775 + window.removeEventListener("pointerup", stop);
776 + window.removeEventListener("pointercancel", stop);
777 + };
779 + window.addEventListener("pointermove", move);
780 + window.addEventListener("pointerup", stop, { once: true });
781 + window.addEventListener("pointercancel", stop, { once: true });
784 +function readLayout(): LayoutState {
785 + const stored = localStorage.getItem(LAYOUT_STORAGE_KEY);
786 + if (!stored) return defaultLayout();
787 + try {
788 + const value = JSON.parse(stored) as Partial<LayoutState>;
789 + return {
790 + left: clampPane("left", value.left),
791 + right: clampPane("right", value.right),
792 + leftCollapsed: value.leftCollapsed === true,
793 + rightCollapsed: value.rightCollapsed === true,
794 + };
795 + } catch {
796 + return defaultLayout();
800 +function writeLayout(layout: LayoutState) {
801 + localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(layout));
804 +function defaultLayout(): LayoutState {
805 + return {
806 + left: PANE_LIMITS.left.fallback,
807 + right: PANE_LIMITS.right.fallback,
808 + leftCollapsed: false,
809 + rightCollapsed: false,
810 + };
813 +function applyLayout(layout: LayoutState) {
814 + els.app.style.setProperty(
815 + "--left-pane",
816 + `${layout.leftCollapsed ? 0 : layout.left}px`,
817 + );
818 + els.app.style.setProperty(
819 + "--right-pane",
820 + `${layout.rightCollapsed ? 0 : layout.right}px`,
821 + );
822 + els.app.dataset.leftCollapsed = String(layout.leftCollapsed);
823 + els.app.dataset.rightCollapsed = String(layout.rightCollapsed);
824 + els.toggleLeft.textContent = layout.leftCollapsed ? "›" : "‹";
825 + els.toggleRight.textContent = layout.rightCollapsed ? "‹" : "›";
826 + els.toggleLeft.setAttribute(
827 + "aria-label",
828 + layout.leftCollapsed ? "Expand file tree" : "Collapse file tree",
829 + );
830 + els.toggleRight.setAttribute(
831 + "aria-label",
832 + layout.rightCollapsed ? "Expand review panel" : "Collapse review panel",
833 + );
836 +function clampPane(side: PaneSide, value: unknown) {
837 + const limits = PANE_LIMITS[side];
838 + const width =
839 + typeof value === "number" && Number.isFinite(value)
840 + ? value
841 + : limits.fallback;
842 + return Math.min(limits.max, Math.max(limits.min, Math.round(width)));
845 +async function addFinding() {
846 + const draft = draftFromSelection();
847 + if (!draft) return;
848 + els.add.disabled = true;
849 + try {
850 + await api(ROUTES.validateFinding, postJson(draft));
851 + findings.push(draft);
852 + clearFindingForm();
853 + clearSelection(true);
854 + renderFindings();
855 + renderAnnotations();
856 + setStatus("Finding added");
857 + } catch (err) {
858 + setStatus(errorMessage(err), "error");
859 + } finally {
860 + els.add.disabled = !selected;
864 +function draftFromSelection(): FindingDraft | undefined {
865 + if (!selected) return undefined;
866 + const comment = els.comment.value.trim();
867 + if (!comment) {
868 + setStatus("Comment required", "error");
869 + return undefined;
871 + return {
872 + ...selected,
873 + category: categoryFromValue(els.category.value),
874 + severity: severityFromValue(els.severity.value),
875 + comment,
876 + };
879 +async function submitReview() {
880 + if (
881 + findings.length === 0 &&
882 + !els.notes.value.trim() &&
883 + !confirm("Send empty review to Pi?")
885 + return;
886 + setDoneButtonsDisabled(true);
887 + try {
888 + await api(ROUTES.submit, postJson({ notes: els.notes.value, findings }));
889 + findings.splice(0);
890 + els.notes.value = "";
891 + renderFindings();
892 + renderAnnotations();
893 + setStatus("Sent to Pi — keep reviewing or close tab to end", "ok");
894 + } catch (err) {
895 + setStatus(errorMessage(err), "error");
896 + } finally {
897 + setDoneButtonsDisabled(false);
901 +async function cancelReview() {
902 + closing = true;
903 + setDoneButtonsDisabled(true);
904 + await api(ROUTES.cancel, postJson({})).catch(() => undefined);
905 + cleanup();
906 + setStatus("Closed — return to Pi");
909 +function setDoneButtonsDisabled(disabled: boolean) {
910 + els.submit.disabled = disabled;
911 + els.cancel.disabled = disabled;
914 +function clearFindingForm() {
915 + els.comment.value = "";
918 +function clearSelection(clearViews: boolean) {
919 + selected = undefined;
920 + els.add.disabled = true;
921 + els.selection.className = "selection-empty";
922 + els.selection.textContent = "Click an added or deleted line.";
923 + hideFindingForm();
924 + if (clearViews)
925 + for (const view of diffViews.values()) view.setSelectedLines(null);
928 +function renderFindings() {
929 + els.findings.replaceChildren();
930 + els.findings.className = findings.length === 0 ? "empty-list" : "";
931 + if (findings.length === 0) {
932 + els.findings.textContent = "No findings yet.";
933 + updateFindingCount();
934 + return;
936 + findings.forEach((finding, index) =>
937 + els.findings.appendChild(findingItem(finding, index)),
938 + );
939 + updateFindingCount();
942 +function findingItem(finding: FindingDraft, index: number) {
943 + const item = document.createElement("div");
944 + item.className = `finding-item severity-${finding.severity}`;
945 + item.tabIndex = 0;
946 + item.addEventListener("click", () => selectFile(finding.file, true));
947 + item.addEventListener("keydown", (event) => {
948 + if (event.key === "Enter") selectFile(finding.file, true);
949 + });
951 + const head = document.createElement("div");
952 + head.className = "finding-item-head";
954 + const number = document.createElement("span");
955 + number.className = "finding-number";
956 + number.textContent = String(index + 1);
958 + const severity = document.createElement("span");
959 + severity.className = `finding-pill ${finding.severity}`;
960 + severity.textContent = finding.severity;
962 + const category = document.createElement("span");
963 + category.className = "finding-pill category";
964 + category.textContent = finding.category;
966 + const remove = document.createElement("button");
967 + remove.className = "remove-finding";
968 + remove.type = "button";
969 + remove.textContent = "×";
970 + remove.title = "Remove finding";
971 + remove.addEventListener("click", (event) => {
972 + event.stopPropagation();
973 + removeFinding(index);
974 + });
976 + const location = document.createElement("div");
977 + location.className = "finding-location";
978 + location.textContent = selectionLabel(finding);
980 + const text = document.createElement("div");
981 + text.className = "finding-comment";
982 + text.textContent = finding.comment;
984 + head.append(number, severity, category, remove);
985 + item.append(head, location, text);
986 + return item;
989 +function removeFinding(index: number) {
990 + findings.splice(index, 1);
991 + renderFindings();
992 + renderAnnotations();
995 +function updateFindingCount() {
996 + els.findingCount.textContent = `${findings.length} finding${findings.length === 1 ? "" : "s"}`;
997 + els.drawerCount.textContent = String(findings.length);
1000 +function renderAnnotations() {
1001 + for (const [file, view] of diffViews) {
1002 + view.setLineAnnotations(annotationsFor(file));
1003 + view.rerender();
1007 +async function buildSearchIndex(
1008 + fileDiffs: FileDiffMetadata[],
1009 + generation: number,
1010 +) {
1011 + searchIndexing = true;
1012 + searchIndex = [];
1013 + const restoreStatus =
1014 + els.status.textContent === "Ready" ? "Ready" : undefined;
1015 + const entries: SearchEntry[] = [];
1016 + for (let index = 0; index < fileDiffs.length; index++) {
1017 + if (generation !== renderGeneration) {
1018 + searchIndexing = false;
1019 + return;
1021 + entries.push(...searchEntriesForFile(fileDiffs[index]));
1022 + if (fileDiffs.length > 1)
1023 + setStatus(`Indexing search ${index + 1}/${fileDiffs.length} files…`);
1024 + await yieldToBrowser();
1026 + if (generation !== renderGeneration) {
1027 + searchIndexing = false;
1028 + return;
1030 + searchIndex = entries;
1031 + searchIndexing = false;
1032 + if (els.search.value.trim()) runSearch();
1033 + if (restoreStatus && els.status.textContent.startsWith("Indexing search"))
1034 + setStatus(restoreStatus);
1037 +function searchEntriesForFile(fileDiff: FileDiffMetadata): SearchEntry[] {
1038 + const entries: SearchEntry[] = [];
1039 + for (const hunk of fileDiff.hunks) {
1040 + let additionLine = hunk.additionStart;
1041 + let deletionLine = hunk.deletionStart;
1042 + for (const content of hunk.hunkContent) {
1043 + if (content.type === "context") {
1044 + for (let i = 0; i < content.lines; i++) {
1045 + const text = fileDiff.additionLines[content.additionLineIndex + i];
1046 + if (text !== undefined)
1047 + entries.push({
1048 + file: fileDiff.name,
1049 + side: "additions",
1050 + line: additionLine + i,
1051 + text,
1052 + });
1054 + additionLine += content.lines;
1055 + deletionLine += content.lines;
1056 + } else {
1057 + for (let i = 0; i < content.deletions; i++) {
1058 + const text = fileDiff.deletionLines[content.deletionLineIndex + i];
1059 + if (text !== undefined)
1060 + entries.push({
1061 + file: fileDiff.name,
1062 + side: "deletions",
1063 + line: deletionLine + i,
1064 + text,
1065 + });
1067 + for (let i = 0; i < content.additions; i++) {
1068 + const text = fileDiff.additionLines[content.additionLineIndex + i];
1069 + if (text !== undefined)
1070 + entries.push({
1071 + file: fileDiff.name,
1072 + side: "additions",
1073 + line: additionLine + i,
1074 + text,
1075 + });
1077 + deletionLine += content.deletions;
1078 + additionLine += content.additions;
1082 + return entries;
1085 +function runSearch() {
1086 + const query = els.search.value.trim();
1087 + if (!query) {
1088 + searchResults = [];
1089 + searchActiveIndex = -1;
1090 + hideSearch();
1091 + return;
1093 + if (searchIndexing) {
1094 + els.searchResults.hidden = false;
1095 + els.searchResults.replaceChildren();
1096 + const empty = document.createElement("div");
1097 + empty.className = "search-empty";
1098 + empty.textContent = "Indexing search…";
1099 + els.searchResults.appendChild(empty);
1100 + return;
1102 + searchResults = searchCode(query);
1103 + searchActiveIndex = -1;
1104 + if (searchResults.length === 0) {
1105 + els.searchResults.hidden = false;
1106 + els.searchResults.replaceChildren();
1107 + const empty = document.createElement("div");
1108 + empty.className = "search-empty";
1109 + empty.textContent = "No matches.";
1110 + els.searchResults.appendChild(empty);
1111 + updateSearchBadge();
1112 + return;
1114 + renderSearchResults();
1115 + updateSearchBadge();
1118 +function renderSearchResults() {
1119 + els.searchResults.hidden = false;
1120 + els.searchResults.replaceChildren();
1121 + const max = Math.min(searchResults.length, 200);
1122 + for (let i = 0; i < max; i++)
1123 + els.searchResults.appendChild(searchResultItem(searchResults[i], i));
1124 + if (searchResults.length > max) {
1125 + const more = document.createElement("div");
1126 + more.className = "search-more";
1127 + more.textContent = `${searchResults.length - max} more matches`;
1128 + els.searchResults.appendChild(more);
1132 +function navigateSearch(delta: 1 | -1) {
1133 + if (searchResults.length === 0) return;
1134 + searchActiveIndex =
1135 + searchActiveIndex < 0
1136 + ? 0
1137 + : Math.max(
1138 + 0,
1139 + Math.min(searchResults.length - 1, searchActiveIndex + delta),
1140 + );
1141 + const items =
1142 + els.searchResults.querySelectorAll<HTMLElement>(".search-result");
1143 + items.forEach((el, i) =>
1144 + el.classList.toggle("search-result-active", i === searchActiveIndex),
1145 + );
1146 + const active = items[searchActiveIndex];
1147 + active?.scrollIntoView({ block: "nearest" });
1148 + jumpToMatch(searchResults[searchActiveIndex], searchActiveIndex);
1149 + updateSearchBadge();
1152 +function updateSearchBadge() {
1153 + const badge = document.querySelector<HTMLElement>("#search-badge");
1154 + if (!badge) return;
1155 + if (searchResults.length === 0) {
1156 + badge.hidden = true;
1157 + return;
1159 + badge.hidden = false;
1160 + badge.textContent =
1161 + searchActiveIndex >= 0
1162 + ? `${searchActiveIndex + 1}/${searchResults.length}`
1163 + : `${searchResults.length}`;
1166 +function searchCode(query: string): SearchMatch[] {
1167 + const hits: SearchMatch[] = [];
1168 + const isRegex = query.startsWith("/") && query.endsWith("/");
1169 + const pattern = isRegex
1170 + ? query.slice(1, -1)
1171 + : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1172 + let re: RegExp;
1173 + try {
1174 + re = new RegExp(pattern, "i");
1175 + } catch {
1176 + return hits;
1178 + for (const entry of searchIndex) {
1179 + const m = re.exec(entry.text);
1180 + if (m && m.index >= 0) {
1181 + hits.push({
1182 + ...entry,
1183 + matchStart: m.index,
1184 + matchEnd: m.index + m[0].length,
1185 + });
1186 + if (hits.length >= 500) break;
1189 + return hits;
1192 +function searchResultItem(match: SearchMatch, index: number) {
1193 + const item = document.createElement("div");
1194 + item.className = "search-result";
1195 + item.tabIndex = -1;
1196 + item.addEventListener("click", () => {
1197 + searchActiveIndex = index;
1198 + jumpToMatch(match, index);
1199 + renderSearchResults();
1200 + updateSearchBadge();
1201 + });
1203 + const file = document.createElement("span");
1204 + file.className = "search-result-file";
1205 + file.textContent = match.file;
1207 + const loc = document.createElement("span");
1208 + loc.className = "search-result-loc";
1209 + loc.textContent = `:${match.line} ${match.side === "additions" ? "+" : "-"}`;
1211 + const preview = document.createElement("div");
1212 + preview.className = "search-result-preview";
1213 + const before = match.text.slice(
1214 + Math.max(0, match.matchStart - 20),
1215 + match.matchStart,
1216 + );
1217 + const matched = match.text.slice(match.matchStart, match.matchEnd);
1218 + const after = match.text.slice(match.matchEnd, match.matchEnd + 40);
1219 + preview.textContent = before;
1220 + const mark = document.createElement("mark");
1221 + mark.textContent = matched;
1222 + preview.appendChild(mark);
1223 + preview.append(after);
1225 + item.append(file, loc, preview);
1226 + return item;
1229 +function jumpToMatch(match: SearchMatch, index: number) {
1230 + selectFile(match.file, false);
1231 + requestAnimationFrame(() => {
1232 + const section = document.querySelector<HTMLElement>(
1233 + `[data-file-section="${cssEscape(match.file)}"]`,
1234 + );
1235 + const container = section?.querySelector(
1236 + "diffs-container",
1237 + ) as HTMLElement | null;
1238 + const root = container?.shadowRoot;
1239 + const sideRoot = root?.querySelector<HTMLElement>(
1240 + match.side === "additions" ? "[data-additions]" : "[data-deletions]",
1241 + );
1242 + const line = sideRoot?.querySelector<HTMLElement>(
1243 + `[data-line="${match.line}"]`,
1244 + );
1245 + if (line) {
1246 + const lineIndex = line.getAttribute("data-line-index");
1247 + const gutter = lineIndex
1248 + ? sideRoot?.querySelector<HTMLElement>(
1249 + `[data-column-number][data-line-index="${cssEscape(lineIndex)}"]`,
1251 + : sideRoot?.querySelector<HTMLElement>(
1252 + `[data-column-number="${match.line}"]`,
1253 + );
1254 + scrollDiffLineIntoView(line);
1255 + flashSearchHighlight([line, gutter]);
1257 + });
1260 +function scrollDiffLineIntoView(line: HTMLElement) {
1261 + const scroller = els.diffs;
1262 + const lineRect = line.getBoundingClientRect();
1263 + const scrollerRect = scroller.getBoundingClientRect();
1264 + const nextTop =
1265 + scroller.scrollTop +
1266 + lineRect.top -
1267 + scrollerRect.top -
1268 + scrollerRect.height / 2 +
1269 + lineRect.height / 2;
1270 + scroller.scrollTo({ top: Math.max(0, nextTop), behavior: "smooth" });
1273 +function flashSearchHighlight(elements: Array<HTMLElement | undefined | null>) {
1274 + const targets = elements.filter((element): element is HTMLElement =>
1275 + Boolean(element),
1276 + );
1277 + for (const target of targets) target.classList.remove("search-highlight");
1278 + if (targets[0]) void targets[0].offsetWidth;
1279 + for (const target of targets) target.classList.add("search-highlight");
1282 +function isEscapeKey(event: KeyboardEvent) {
1283 + return event.key === "Escape" || event.key === "Esc";
1286 +function cancelPendingSearch() {
1287 + window.clearTimeout(searchDebounce);
1288 + searchDebounce = undefined;
1291 +function closeCodeSearchPopup() {
1292 + cancelPendingSearch();
1293 + searchActiveIndex = -1;
1294 + hideSearch();
1297 +function clearCodeSearch(refocus: boolean) {
1298 + cancelPendingSearch();
1299 + els.search.value = "";
1300 + searchResults = [];
1301 + searchActiveIndex = -1;
1302 + hideSearch();
1303 + updateSearchBadge();
1304 + if (refocus) els.search.focus();
1307 +function hideSearch() {
1308 + els.searchResults.hidden = true;
1309 + updateSearchBadge();
1312 +function annotationsFor(file: string): DiffLineAnnotation<FindingMeta>[] {
1313 + return findings
1314 + .filter((finding) => finding.file === file)
1315 + .map((finding, index) => ({
1316 + side: finding.side,
1317 + lineNumber: finding.startLine,
1318 + metadata: {
1319 + findingId: String(index),
1320 + severity: finding.severity,
1321 + category: finding.category,
1322 + comment: finding.comment,
1323 + },
1324 + }));
1327 +async function api<T = unknown>(
1328 + path: string,
1329 + init: RequestInit = {},
1330 +): Promise<T> {
1331 + const res = await fetch(path, {
1332 + ...init,
1333 + headers: {
1334 + Authorization: `Bearer ${token}`,
1335 + "Content-Type": "application/json",
1336 + ...(init.headers ?? {}),
1337 + },
1338 + });
1339 + const body = await res.text();
1340 + const data = body ? JSON.parse(body) : undefined;
1341 + if (!res.ok)
1342 + throw new Error(errorPayload(data) ?? `${res.status} ${res.statusText}`);
1343 + return data as T;
1346 +function postJson(body: unknown): RequestInit {
1347 + return { method: "POST", body: JSON.stringify(body) };
1350 +function errorPayload(value: unknown) {
1351 + return value &&
1352 + typeof value === "object" &&
1353 + "error" in value &&
1354 + typeof value.error === "string"
1355 + ? value.error
1356 + : undefined;
1359 +function startHeartbeat() {
1360 + heartbeat = window.setInterval(
1361 + () => api(ROUTES.heartbeat, postJson({})).catch(() => undefined),
1362 + HEARTBEAT_INTERVAL_MS,
1363 + );
1366 +function startReviewPolling() {
1367 + reviewPoll = window.setInterval(refreshReview, REVIEW_POLL_INTERVAL_MS);
1370 +async function refreshReview() {
1371 + try {
1372 + const review = await api<ReviewPayload>(ROUTES.review);
1373 + const nextHash = hashReview(review);
1374 + if (nextHash === reviewHash) return;
1375 + await renderReview(review);
1376 + setStatus("Diff updated", "ok");
1377 + } catch (err) {
1378 + setDisconnectedStatus(err);
1382 +function hashReview(review: ReviewPayload) {
1383 + return `${review.diffText}\0${review.skippedFiles.join("\0")}`;
1386 +function stopHeartbeat() {
1387 + if (heartbeat !== undefined) window.clearInterval(heartbeat);
1388 + heartbeat = undefined;
1391 +function stopReviewPolling() {
1392 + if (reviewPoll !== undefined) window.clearInterval(reviewPoll);
1393 + reviewPoll = undefined;
1396 +function cleanup() {
1397 + stopHeartbeat();
1398 + stopReviewPolling();
1399 + fileTree?.cleanUp();
1400 + for (const view of diffViews.values()) view.cleanUp();
1403 +function closeFromBrowser() {
1404 + if (closing) return;
1405 + closing = true;
1406 + navigator.sendBeacon?.(
1407 + ROUTES.cancel,
1408 + new Blob(["{}"], { type: "application/json" }),
1409 + );
1410 + cleanup();
1413 +function setStatus(text: string, tone: "neutral" | "error" | "ok" = "neutral") {
1414 + els.status.textContent = text;
1415 + els.status.className = tone === "neutral" ? "" : tone;
1418 +function setDisconnectedStatus(err: unknown) {
1419 + const message = errorMessage(err);
1420 + const disconnected =
1421 + /networkerror|failed to fetch|load failed|fetch resource/i.test(message);
1422 + setStatus(
1423 + disconnected ? "Disconnected. Run /diff-review, then refresh." : message,
1424 + "error",
1425 + );
1428 +function readThemeMode(): ThemeMode {
1429 + return themeModeFromValue(localStorage.getItem(THEME_STORAGE_KEY));
1432 +function applyThemeMode(mode: ThemeMode) {
1433 + document.documentElement.dataset.theme =
1434 + mode === "system" ? (systemTheme.matches ? "light" : "dark") : mode;
1435 + document.documentElement.dataset.themeMode = mode;
1436 + const icon = document.querySelector<HTMLElement>(".theme-icon");
1437 + if (icon)
1438 + icon.textContent = mode === "dark" ? "☾" : mode === "light" ? "☼" : "◐";
1441 +function selectFile(path: string | undefined, scroll: boolean) {
1442 + selectedFile = path;
1443 + applySelectedFileEmphasis();
1444 + if (scroll) scrollToFile(path);
1447 +function applySelectedFileEmphasis() {
1448 + for (const section of els.diffs.querySelectorAll<HTMLElement>(
1449 + "[data-file-section]",
1450 + )) {
1451 + const active = section.dataset.fileSection === selectedFile;
1452 + if (active) section.dataset.selectedFile = "true";
1453 + else delete section.dataset.selectedFile;
1457 +function scrollToFile(path: string | undefined) {
1458 + if (!path) return;
1459 + const section = document.querySelector<HTMLElement>(
1460 + `[data-file-section="${cssEscape(path)}"]`,
1461 + );
1462 + if (!section) return;
1463 + const scroller = els.diffs;
1464 + const top =
1465 + section.getBoundingClientRect().top -
1466 + scroller.getBoundingClientRect().top +
1467 + scroller.scrollTop;
1468 + scroller.scrollTo({ top: Math.max(0, top - 2), behavior: "smooth" });
1471 +function toGitStatus(
1472 + status: ReviewPayload["files"][number]["status"],
1473 +): GitStatusEntry["status"] {
1474 + if (status === "added" || status === "deleted" || status === "renamed")
1475 + return status;
1476 + return "modified";
1479 +function themeModeFromValue(value: unknown): ThemeMode {
1480 + return isOneOf(value, THEME_MODES) ? value : "system";
1483 +function categoryFromValue(value: unknown): ReviewCategory {
1484 + if (isOneOf(value, REVIEW_CATEGORIES)) return value;
1485 + throw new Error(`Invalid category: ${String(value)}`);
1488 +function severityFromValue(value: unknown): ReviewSeverity {
1489 + if (isOneOf(value, REVIEW_SEVERITIES)) return value;
1490 + throw new Error(`Invalid severity: ${String(value)}`);
1493 +function isReviewSide(value: unknown): value is ReviewSide {
1494 + return value === "additions" || value === "deletions";
1497 +function isOneOf<T extends string>(
1498 + value: unknown,
1499 + choices: readonly T[],
1500 +): value is T {
1501 + return typeof value === "string" && choices.includes(value as T);
1504 +function must(id: keyof Elements | string) {
1505 + const el = document.getElementById(id);
1506 + if (!el) throw new Error(`Missing #${id}`);
1507 + return el;
1510 +function mustButton(id: string) {
1511 + return must(id) as HTMLButtonElement;
1513 +function mustSelect(id: string) {
1514 + return must(id) as HTMLSelectElement;
1516 +function mustText(id: string) {
1517 + return must(id) as HTMLTextAreaElement;
1520 +function cssEscape(value: string) {
1521 + return CSS.escape(value);
1524 +function errorMessage(err: unknown) {
1525 + return err instanceof Error ? err.message : String(err);

extensions/diff-review/index.ts

Modified
67 67 if (restored) {
68 68 ctx.ui.notify(
69 69 `diff-review restored. Refresh existing browser tab. URL: ${restored.url}`,
70 71 "info",
72 73 return;

extensions/forget/index.ts

Added
new file mode 100644
1 +import { StringEnum } from "@earendil-works/pi-ai";
2 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3 +import { Text } from "@earendil-works/pi-tui";
4 +import { Type } from "typebox";
6 +const TOOL = "forget";
7 +const DETAILS_KIND = "forget";
8 +const REMINDER =
9 + "Context hygiene: use forget for safe prefix cuts in long mixed-task sessions. current_user=new task; previous_user=keep immediate setup. Skip if prior context may be needed.";
11 +type ForgetTarget = "current_user" | "previous_user";
13 +interface ForgetParams {
14 + target?: ForgetTarget | string;
15 + reason?: string;
18 +interface BranchEntry {
19 + type?: string;
20 + id?: string;
21 + message?: { role?: string; content?: unknown };
22 + [key: string]: unknown;
25 +interface TargetResolution {
26 + ok: boolean;
27 + target: ForgetTarget;
28 + offset: 0 | 1;
29 + index: number;
30 + userCount: number;
31 + entry?: BranchEntry;
32 + code?: string;
33 + hint?: string;
36 +interface ForgetResultDetails {
37 + kind?: typeof DETAILS_KIND;
38 + version?: number;
39 + code?: string;
40 + skipped?: boolean;
41 + compactionId?: string;
42 + target?: ForgetTarget | string;
43 + offset?: 0 | 1;
44 + keptFromEntryId?: string;
45 + keptPreview?: string;
46 + forgottenBefore?: number;
47 + reason?: string;
50 +function textResult(text: string, details?: Record<string, unknown>) {
51 + return { content: [{ type: "text" as const, text }], details };
54 +function errorResult(
55 + code: string,
56 + hint: string,
57 + details?: Record<string, unknown>,
58 +) {
59 + return {
60 + content: [{ type: "text" as const, text: `${code}. ${hint}` }],
61 + isError: true,
62 + details: { kind: DETAILS_KIND, code, ...details },
63 + };
66 +function compactWhitespace(text: string): string {
67 + return text.replace(/\s+/g, " ").trim();
70 +function safeInline(text: unknown): string {
71 + return compactWhitespace(
72 + String(text ?? "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""),
73 + );
76 +function contentText(content: unknown): string {
77 + if (typeof content === "string") return content;
78 + if (Array.isArray(content)) {
79 + return content
80 + .map((part) => {
81 + if (typeof part === "string") return part;
82 + if (part && typeof part === "object" && "text" in part) {
83 + const text = (part as { text?: unknown }).text;
84 + return typeof text === "string" ? text : "";
85 + }
86 + return "";
87 + })
88 + .filter(Boolean)
89 + .join(" ");
90 + }
91 + return "";
94 +function entryPreview(
95 + entry: BranchEntry | undefined,
96 + max = 180,
97 +): string | undefined {
98 + const text = safeInline(contentText(entry?.message?.content));
99 + if (!text) return undefined;
100 + return text.length > max ? `${text.slice(0, max - 1)}…` : text;
103 +function firstText(result: {
104 + content?: Array<{ type?: string; text?: string }>;
105 +}) {
106 + return result.content?.find((part) => part?.type === "text")?.text ?? "";
109 +function userIndexes(branch: BranchEntry[]): number[] {
110 + const indexes: number[] = [];
111 + for (let i = 0; i < branch.length; i++) {
112 + const entry = branch[i];
113 + if (entry?.type === "message" && entry.message?.role === "user")
114 + indexes.push(i);
116 + return indexes;
119 +function normalizeTarget(target: unknown): ForgetTarget | undefined {
120 + if (target === undefined || target === null || target === "")
121 + return "current_user";
122 + if (target === "current_user" || target === "previous_user") return target;
123 + if (target === "current" || target === "latest" || target === "user:0")
124 + return "current_user";
125 + if (target === "previous" || target === "prev" || target === "user:1")
126 + return "previous_user";
127 + return undefined;
130 +function resolveTarget(
131 + branch: BranchEntry[],
132 + rawTarget?: unknown,
133 +): TargetResolution {
134 + const target = normalizeTarget(rawTarget);
135 + if (!target)
136 + return {
137 + ok: false,
138 + target: "current_user",
139 + offset: 0,
140 + index: -1,
141 + userCount: 0,
142 + code: "bad_target",
143 + hint: "use current_user or previous_user",
144 + };
145 + const offset = target === "current_user" ? 0 : 1;
146 + const users = userIndexes(branch);
147 + const position = users.length - 1 - offset;
148 + if (position < 0)
149 + return {
150 + ok: false,
151 + target,
152 + offset,
153 + index: -1,
154 + userCount: users.length,
155 + code: "no_boundary",
156 + hint:
157 + offset === 1
158 + ? "no previous user; use current_user or skip"
159 + : "no current user",
160 + };
161 + const index = users[position];
162 + return {
163 + ok: true,
164 + target,
165 + offset,
166 + index,
167 + userCount: users.length,
168 + entry: branch[index],
169 + };
172 +function forgetSummary(resolution: TargetResolution, reason?: string): string {
173 + return [
174 + "[Forget] Earlier conversation context intentionally removed from active LLM context.",
175 + `Kept from ${resolution.target} entry ${resolution.entry?.id ?? "?"}.`,
176 + `Reason: ${reason?.trim() || "context budget"}.`,
177 + "History remains append-only/recoverable; active prompt context changed only.",
178 + ].join("\n");
181 +function countTokensBefore(ctx: {
182 + getContextUsage?: () => { tokens?: number | null } | undefined;
183 +}): number {
184 + const tokens = ctx.getContextUsage?.()?.tokens;
185 + return typeof tokens === "number" && Number.isFinite(tokens) ? tokens : 0;
188 +function appendForgetCompaction(
189 + ctx: unknown,
190 + resolution: TargetResolution,
191 + reason?: string,
192 +): string {
193 + const sessionManager = (ctx as { sessionManager?: unknown })
194 + .sessionManager as {
195 + appendCompaction?: (
196 + summary: string,
197 + firstKeptEntryId: string,
198 + tokensBefore: number,
199 + details?: unknown,
200 + fromHook?: boolean,
201 + ) => string;
202 + };
203 + if (typeof sessionManager?.appendCompaction !== "function")
204 + throw new Error(
205 + "SessionManager appendCompaction unavailable in this Pi runtime",
206 + );
207 + return sessionManager.appendCompaction(
208 + forgetSummary(resolution, reason),
209 + resolution.entry?.id ?? "",
210 + countTokensBefore(
211 + ctx as { getContextUsage?: () => { tokens?: number | null } | undefined },
212 + ),
214 + kind: DETAILS_KIND,
215 + version: 2,
216 + target: resolution.target,
217 + keptFromEntryId: resolution.entry?.id,
218 + forgottenBefore: resolution.index,
219 + reason,
220 + },
221 + true,
222 + );
225 +function renderForgetCall(args: ForgetParams, theme: any) {
226 + const target =
227 + normalizeTarget(args.target) ?? safeInline(args.target ?? "current_user");
228 + let text = theme.fg("toolTitle", theme.bold("◌ forget "));
229 + text += theme.fg("accent", target);
230 + const reason = safeInline(args.reason);
231 + if (reason) text += theme.fg("dim", ` — ${reason}`);
232 + return new Text(text, 0, 0);
235 +function renderForgetResult(
236 + result: {
237 + content?: Array<{ type?: string; text?: string }>;
238 + details?: unknown;
239 + isError?: boolean;
240 + },
241 + options: { expanded?: boolean; isPartial?: boolean },
242 + theme: any,
243 +) {
244 + if (options.isPartial)
245 + return new Text(theme.fg("warning", "◌ forgetting context…"), 0, 0);
247 + const details = result.details as ForgetResultDetails | undefined;
248 + if (result.isError || details?.code) {
249 + const msg = safeInline(
250 + firstText(result) || details?.code || "forget failed",
251 + );
252 + return new Text(theme.fg("error", `✗ ${msg}`), 0, 0);
255 + if (details?.skipped) {
256 + let text = theme.fg("muted", "↷ nothing to forget");
257 + if (details.target) text += theme.fg("dim", ` · ${details.target}`);
258 + return new Text(text, 0, 0);
261 + let text = theme.fg("success", "✓ ");
262 + text += theme.fg("accent", `kept ${details?.target ?? "boundary"}`);
263 + if (typeof details?.forgottenBefore === "number")
264 + text += theme.fg("dim", ` · dropped ${details.forgottenBefore} entries`);
266 + if (details?.keptPreview)
267 + text += `\n ${theme.fg("muted", "↳ kept context:")} ${theme.fg("dim", details.keptPreview)}`;
269 + if (options.expanded) {
270 + if (details?.reason)
271 + text += `\n ${theme.fg("muted", "reason:")} ${theme.fg("dim", safeInline(details.reason))}`;
272 + if (details?.keptFromEntryId)
273 + text += `\n ${theme.fg("muted", "entry:")} ${theme.fg("dim", details.keptFromEntryId)}`;
274 + if (details?.compactionId)
275 + text += `\n ${theme.fg("muted", "compaction:")} ${theme.fg("dim", details.compactionId)}`;
276 + text += `\n ${theme.fg("muted", "history append-only; active context prefix-cut only")}`;
279 + return new Text(text, 0, 0);
282 +export const __test = {
283 + appendForgetCompaction,
284 + entryPreview,
285 + forgetSummary,
286 + normalizeTarget,
287 + REMINDER,
288 + renderForgetCall,
289 + renderForgetResult,
290 + resolveTarget,
291 + userIndexes,
294 +export default function (pi: ExtensionAPI) {
295 + pi.on("before_agent_start", (event) => {
296 + if (event.systemPrompt.includes(REMINDER)) return undefined;
297 + return { systemPrompt: `${event.systemPrompt}\n\n${REMINDER}` };
298 + });
300 + pi.registerTool({
301 + name: TOOL,
302 + label: "Forget",
303 + description:
304 + "Context-budget tool. Drops older active context before current_user or previous_user. Not privacy deletion.",
305 + promptSnippet:
306 + "forget(target?, reason?) — prefix-cut active context before current_user or previous_user",
307 + promptGuidelines: [
308 + "target=current_user: latest user starts an independent new task; drop older context.",
309 + "target=previous_user: latest request depends on immediate prior setup; keep that setup and drop older context.",
310 + "Skip forget if prior discussion may be needed or no safe prefix cut exists.",
311 + ],
312 + parameters: Type.Object({
313 + target: Type.Optional(
314 + StringEnum(["current_user", "previous_user"] as const, {
315 + description: "Prefix-cut boundary. Defaults to current_user.",
316 + }),
317 + ),
318 + reason: Type.Optional(
319 + Type.String({ description: "Short reason for context compaction" }),
320 + ),
321 + }),
322 + renderCall: renderForgetCall,
323 + renderResult: renderForgetResult,
324 + async execute(_toolCallId, params: ForgetParams, _signal, _onUpdate, ctx) {
325 + const branch = ctx.sessionManager.getBranch() as unknown as BranchEntry[];
326 + const resolution = resolveTarget(branch, params.target);
327 + if (!resolution.ok)
328 + return errorResult(
329 + resolution.code ?? "invalid",
330 + resolution.hint ?? "skip forget",
331 + { target: params.target },
332 + );
333 + if (resolution.target === "current_user" && resolution.userCount <= 1)
334 + return textResult("already_first. nothing to forget", {
335 + kind: DETAILS_KIND,
336 + version: 3,
337 + skipped: true,
338 + target: resolution.target,
339 + keptFromEntryId: resolution.entry?.id,
340 + keptPreview: entryPreview(resolution.entry),
341 + forgottenBefore: 0,
342 + });
343 + const compactionId = appendForgetCompaction(
344 + ctx,
345 + resolution,
346 + params.reason,
347 + );
348 + return textResult(
349 + `done. kept=${resolution.target} dropped_entries=${resolution.index}`,
351 + kind: DETAILS_KIND,
352 + version: 3,
353 + compactionId,
354 + target: resolution.target,
355 + offset: resolution.offset,
356 + keptFromEntryId: resolution.entry?.id,
357 + keptPreview: entryPreview(resolution.entry),
358 + forgottenBefore: resolution.index,
359 + reason: params.reason,
360 + },
361 + );
362 + },
363 + });

extensions/git-safe/__tests__/spawn.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { spawnExpect, spawnWithTimeout, SpawnTimeoutError } from "../spawn";
4 +describe("spawnWithTimeout", () => {
5 + it("marks timed-out processes as killed", async () => {
6 + const result = await spawnWithTimeout(
7 + process.execPath,
8 + ["-e", "setTimeout(() => {}, 10_000)"],
9 + { timeout: 50 },
10 + );
12 + expect(result.killed).toBe(true);
13 + expect(result.code).not.toBe(0);
14 + });
16 + it("does not mark successful processes as killed", async () => {
17 + const result = await spawnWithTimeout(
18 + process.execPath,
19 + ["-e", "process.stdout.write(process.env.GIT_TERMINAL_PROMPT ?? '')"],
20 + { timeout: 1_000 },
21 + );
23 + expect(result).toMatchObject({ stdout: "0", code: 0, killed: false });
24 + });
26 + it("throws SpawnTimeoutError through spawnExpect", async () => {
27 + await expect(
28 + spawnExpect(process.execPath, ["-e", "setTimeout(() => {}, 10_000)"], {
29 + timeout: 50,
30 + }),
31 + ).rejects.toBeInstanceOf(SpawnTimeoutError);
32 + });
33 +});

extensions/git-safe/index.ts

Modified
193 193 : `${bytes}B`;
195 195 // Error or missing structured details — render from content text
196 - if (result.isError || !details?.url) {
196 + if ((result as any).isError || !details?.url) {
197 197 const content = result.content[0];
198 198 const msg = content?.type === "text" ? content.text : "Clone failed";
199 199 const lines = msg.split("\n").slice(0, 4);
235 235 content: [
236 236 { type: "text", text: `Cloning ${params.url} with safety checks...` },
238 + details: {},

extensions/git-safe/spawn.ts

Modified
33 33 const proc = spawn(cmd, args, { cwd, env: env as Record<string, string> });
34 34 let stdout = "";
35 35 let stderr = "";
36 + let timedOut = false;
37 + let settled = false;
39 + const finish = (result: SpawnResult) => {
40 + if (settled) return;
41 + settled = true;
42 + clearTimeout(timer);
43 + resolve(result);
44 + };
37 46 const timer = setTimeout(() => {
47 + timedOut = true;
38 48 proc.kill("SIGKILL");
39 49 }, timeout);
41 51 proc.stdout.on("data", (d: Buffer) => (stdout += d));
42 52 proc.stderr.on("data", (d: Buffer) => (stderr += d));
43 53 proc.on("close", (code) => {
44 - clearTimeout(timer);
45 - resolve({ stdout, stderr, code, killed: false });
54 + finish({ stdout, stderr, code, killed: timedOut });
47 56 proc.on("error", (err) => {
48 - clearTimeout(timer);
49 - resolve({ stdout, stderr: err.message, code: null, killed: false });
57 + finish({ stdout, stderr: err.message, code: null, killed: timedOut });

extensions/goal/index.ts

Modified
2156 2156 ? "warning"
2157 2157 : "accent";
2158 2158 return new Text(
2159 - theme.fg(color, goalJudgeMessageLine(message.content)),
2159 + theme.fg(color, goalJudgeMessageLine(typeof message.content === "string" ? message.content : JSON.stringify(message.content))),
2165 2165 pi.registerMessageRenderer(GOAL_EVENT_ENTRY, (message, _options, theme) => {
2166 2166 return new Text(
2167 - theme.fg("muted", goalJudgeMessageLine(message.content)),
2167 + theme.fg("muted", goalJudgeMessageLine(typeof message.content === "string" ? message.content : JSON.stringify(message.content))),
2412 2412 "warning",
2414 2414 setTimeout(
2415 - () => scheduleContinuation(pi, ctx, state, continuation),
2415 + () => scheduleContinuation(pi, ctx, state!, continuation),
2416 2416 Math.min(30000, 2000 * retries),
2418 2418 return;
2606 2606 description: "Persistent goal loop. Usage: /goal <objective>",
2607 2607 getArgumentCompletions: (argumentPrefix) =>
2608 2608 goalArgumentCompletions(argumentPrefix, state),
2609 - handler: (args, ctx) => {
2609 + handler: async (args, ctx) => {
2610 2610 const input = args.trim();
2611 2611 const firstSpace = input.search(/\s/);
2612 2612 const cmd = firstSpace === -1 ? input : input.slice(0, firstSpace);
2749 2749 if (process.env.PI_GOAL_PROBE === "1") {
2750 2750 pi.registerCommand("goal-probe", {
2751 2751 description: "Internal /goal continuation scheduling probe",
2752 - handler: (args, ctx) => {
2752 + handler: async (args, ctx) => {
2753 2753 const mode = parseProbeMode(args);
2754 2754 if (!mode)
2755 2755 return ctx.ui.notify(

extensions/neko/index.ts

Modified
1 1 import { existsSync, readFileSync, writeFileSync } from "node:fs";
2 2 import { join } from "node:path";
3 3 import {
4 +// @ts-expect-error — AutocompleteItem removed from upstream but used at runtime
4 5 type AutocompleteItem,
5 6 CustomEditor,
6 7 type ExtensionAPI,
208 209 return " ".repeat(left) + frame.text + " ".repeat(right);
212 +// @ts-expect-error — private paddingX conflicts with base class CustomEditor
211 213 class NekoEditor extends CustomEditor {
212 214 private noseX = 2;
213 215 private targetNoseX = 2;

extensions/superpowers/README.md

Deleted
deleted 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
13 -session.
14 -`--superpowers` starts with that mode already enabled.
16 -Strict mode means future non-trivial coding turns must pick and follow the
17 -smallest applicable Superpowers workflow, then verify before claiming
18 -completion.
20 -Prompts/skills remain installed and manually callable when off.
21 -Off only disables automatic methodology pressure.
22 -No always-on activation unless you opt in.
23 -No hidden agents.
25 -## Commands
27 -```text
28 -/superpowers # toggle workflow discipline
29 -/superpowers on
30 -/superpowers off
31 -/superpowers run <agent> [args] [--share]
32 -/superpowers open <id>
33 -/superpowers branch <id>
34 -/superpowers return <summary>
35 -/superpowers abort <id>
36 -/superpowers status [id]
38 -# workflow aliases → background workers
39 -/superpowers design <args> # brainstorming
40 -/superpowers plan <args> # writing-plans
41 -/superpowers execute <args> # executing-plans
42 -/superpowers parallel <args> # dispatching-parallel-agents
43 -/superpowers review <args> # requesting-code-review
44 -/superpowers deslop <args> # requesting-code-review, focused on slop
45 -/superpowers compress <args> # requesting-code-review, focused on DRY/design compression
46 -/superpowers debug <args> # systematic-debugging
47 -/superpowers git <args> # using-git-worktrees
48 -/superpowers meta <args> # writing-skills
49 -/superpowers verify <args> # verification-before-completion
51 -# visual brainstorming companion
52 -/superpowers visual start
53 -/superpowers status
54 -/superpowers visual stop
55 -```
57 -## Prompt frontmatter
59 -Agents are normal Pi prompt templates (`prompts/*.md`).
60 -Supported frontmatter:
62 -```yaml
63 -description: Run a focused code review
64 -argument-hint: "<file|directory|diff|scope>"
65 -tools: [read, bash, grep, find, ls]
66 -extensions: ["*", "-superpowers"]
67 -thinking: medium
68 -model: provider/model
69 -accent: syntaxKeyword
70 -```
72 -| Field | Purpose |
73 -| --------------- | ------------------------------------------------------------------ |
74 -| `description` | Shown in autocomplete and status |
75 -| `argument-hint` | Autocomplete hint for arguments |
76 -| `tools` | Tool allowlist for the subagent |
77 -| `extensions` | Extension filter (`*` = all, `-name` = exclude) |
78 -| `thinking` | Thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh` |
79 -| `model` | Override model: `provider/id` |
80 -| `accent` | Theme color for footer/widget/status rendering (see below) |
82 -### `accent` — workflow color
84 -Controls the visual identity of a worker in the footer, widget, and status
85 -output.
86 -Value is a `ThemeColor` name from Pi's theme system.
87 -The color resolves to whatever the active theme defines for that semantic role,
88 -so it adapts to light/dark themes automatically.
90 -**Recommended accents per workflow:**
92 -| Workflow | Accent | Visual feel |
93 -| -------------------------------- | ---------------- | ----------------------- |
94 -| `brainstorming` | `accent` | purple — creative |
95 -| `writing-plans` | `dim` | quiet — preparation |
96 -| `executing-plans` | `success` | green — building |
97 -| `test-driven-development` | `syntaxString` | green tint — test-first |
98 -| `systematic-debugging` | `warning` | yellow — caution |
99 -| `requesting-code-review` | `syntaxKeyword` | amber — critical eye |
100 -| `receiving-code-review` | `syntaxFunction` | blue — integration |
101 -| `verification-before-completion` | `toolTitle` | cyan — verification |
102 -| `dispatching-parallel-agents` | `syntaxVariable` | distinct — multi-agent |
103 -| `using-git-worktrees` | `muted` | gray — infrastructure |
104 -| `writing-skills` | `syntaxFunction` | blue — meta-work |
106 -**Full `ThemeColor` palette** (51 names, all valid for `accent`):
108 -```text
109 -# Semantic roles — the useful ones for accent
110 -accent # primary brand color (purple in most themes)
111 -success # positive / done
112 -warning # caution / attention
113 -error # failure / blocker
114 -muted # secondary / quiet
115 -dim # lowest prominence
116 -text # default text color
118 -# Syntax highlighting — good for workflow identity
119 -syntaxKeyword # amber/orange — keywords, review, attention
120 -syntaxFunction # blue — functions, integration
121 -syntaxVariable # teal — variables, parallel
122 -syntaxString # green — strings, tests
123 -syntaxNumber # numeric literals
124 -syntaxType # type names
125 -syntaxOperator # operators
126 -syntaxPunctuation # brackets, commas
127 -syntaxComment # comments
129 -# Markdown rendering
130 -mdHeading # heading color
131 -mdLink # link color
132 -mdCode # inline code
133 -mdCodeBlock # code block text
134 -mdCodeBlockBorder # code block border
135 -mdListBullet # bullet points
137 -# Tool output
138 -toolTitle # tool name color (cyan-ish)
139 -toolOutput # tool result text
140 -toolDiffAdded # diff + lines
141 -toolDiffRemoved # diff - lines
142 -toolDiffContext # diff context lines
144 -# Thinking levels
145 -thinkingText # assistant thinking text
146 -thinkingOff # off state
147 -thinkingMinimal # minimal
148 -thinkingLow # low
149 -thinkingMedium # medium
150 -thinkingHigh # high
151 -thinkingXhigh # extra-high
153 -# Message types
154 -userMessageText # user message
155 -customMessageText # extension/custom message
156 -customMessageLabel # custom message label
158 -# Borders
159 -border # default border
160 -borderAccent # accent border
161 -borderMuted # muted border
163 -# Other
164 -bashMode # bash mode indicator
165 -selectedBg # (ThemeBg, not ThemeColor — for backgrounds)
166 -```
168 -Without an `accent` field, workers default to the extension's accent color
169 -(amber `syntaxKeyword` for review, etc.).
171 -## Bundled workflows
173 -```text
174 -/using-superpowers
175 -/brainstorming
176 -/writing-plans
177 -/executing-plans
178 -/dispatching-parallel-agents
179 -/subagent-driven-development
180 -/requesting-code-review
181 -/receiving-code-review
182 -/test-driven-development
183 -/systematic-debugging
184 -/verification-before-completion
185 -/using-git-worktrees
186 -/finishing-a-development-branch
187 -/writing-skills
188 -```
190 -`skills/*/SKILL.md` holds the methodology.
191 -`prompts/*.md` are normal Pi slash prompt wrappers with the full skill inlined —
192 -no runtime skill discovery needed.
194 -Same prompts work as background workers:
196 -```text
197 -/superpowers run systematic-debugging flaky test
198 -/superpowers run requesting-code-review current diff
199 -```
201 -## Worktree isolation
203 -By default, `/superpowers run` and workflow aliases create an isolated
204 -worktree/workspace for the subagent.
205 -This prevents filesystem collisions between concurrent tasks and keeps the
206 -parent working copy clean.
208 -| Repo type | Isolation mechanism | Path |
209 -| ----------------------- | ------------------- | --------------------- |
210 -| Git standard checkout | `git worktree add` | `.git/wt-<id>` |
211 -| Git bare (co/wt layout) | `git worktree add` | `<root>/<id>` |
212 -| Jujutsu (jj) | `jj workspace add` | `.jj/workspaces/<id>` |
213 -| No repo detected | in-place fallback | — |
215 -Use `--share` to run the subagent in the current working copy instead:
217 -```text
218 -/superpowers run implement fix-bug --share
219 -```
221 -Isolation is skipped when:
223 -- `--share` is passed explicitly
224 -- No supported repo is detected
225 -- Worktree/workspace creation fails (falls back to in-place with a notice)
227 -On abort, isolated worktrees are cleaned up automatically.
228 -On successful completion, they are left for inspection — remove them manually or
229 -with `git worktree remove` / `jj workspace forget`.
231 -## Status display
233 -The footer and widget use compact, scannable formatting:
235 -**Footer** (status bar):
237 -```text
238 -on # strict mode active
239 -on 1↑ # 1 worker running
240 -on eye # visual brainstorming active
241 -1↑ # worker running, strict mode off
242 -```
244 -**Widget** (above editor, when workers run):
246 -```text
247 -2 workers running
248 -▶ sp-5 review 12s · 5 tools
249 -▶ sp-6 debug 1m3s · 8 tools
250 -```
252 -**Status icons:**
254 -```text
255 -▶ running ✓ done ⊘ aborted ✗ error ⤴ branched
256 -```
258 -**Agent short names:**
260 -```text
261 -review fix design plan exec debug verify tdd parallel git skill finish sp sub
262 -```
264 -`/superpowers status` lists all tasks.
265 -`/superpowers status <id>` shows full details.
267 -## State
269 -Runtime state lives in the platform state dir, per project:
271 -```text
272 -Linux: ${XDG_STATE_HOME:-~/.local/state}/pi/superpowers/<project-hash>/
273 -macOS: ~/Library/Application Support/pi/superpowers/<project-hash>/
274 -Windows: %LOCALAPPDATA%\\pi\\superpowers\\<project-hash>\\
275 -```
277 -Contents:
279 -```text
280 -tasks.json # all tasks (running, done, aborted, error, branched)
281 -runs.jsonl # append-only audit log: one JSON line per completed task
282 -sessions/ # subagent session files
283 -visual/ # visual brainstorming state (ephemeral)
284 -```
286 -Stale tasks (orphaned when the parent Pi session dies) are reaped on next
287 -session start.
289 -Project/VCS state is only written by workflows that intentionally create
290 -docs/specs, e.g. `docs/superpowers/specs/...`.
292 -## Architecture
294 -```text
295 -run = background SDK agent
296 -open = inspect checkpoint/log
297 -branch = stop/promote into ctx.newSession({ parentSession })
298 -return = ctx.switchSession(parent)
299 -```
301 -No Pi subprocesses.
302 -Uses Pi SDK sessions/resource loading directly.
304 -No Pi subprocesses.
305 -Uses Pi SDK sessions/resource loading directly.

extensions/superpowers/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { execSync } from "node:child_process";
2 -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3 -import path from "node:path";
4 -import { afterEach, describe, expect, it } from "vitest";
5 -import {
6 - createTestSession,
7 - sandboxEnv,
8 - type TestSession,
9 - withProcessEnvSync,
10 -} from "../../../test/harness";
11 -import { __test } from "../index.ts";
13 -let t: TestSession | undefined;
14 -afterEach(() => {
15 - t?.dispose();
16 - t = undefined;
17 -});
19 -const extPath = () => path.resolve(import.meta.dirname, "../index.ts");
20 -function command() {
21 - const cmd =
22 - t?.session.extensionRunner.extensions[0]?.commands.get("superpowers");
23 - if (!cmd) throw new Error("superpowers command not registered");
24 - return cmd;
26 -function ctx() {
27 - if (!t) throw new Error("test session not initialized");
28 - return t.session.extensionRunner.createCommandContext();
30 -const notices = () =>
31 - t?.events.uiCallsFor("notify").map((c) => String(c.args[0]));
32 -const tasksPath = () => {
33 - if (!t) throw new Error("test session not initialized");
34 - return withProcessEnvSync(t.env, () => __test.tasksFile(t.cwd));
35 -};
36 -const tasks = () => JSON.parse(readFileSync(tasksPath(), "utf8"));
37 -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
38 -function env() {
39 - if (!t) throw new Error("test session not initialized");
40 - return sandboxEnv(t.cwd);
42 -function initGitRepo() {
43 - if (!t) throw new Error("test session not initialized");
44 - const gitEnv = env();
45 - execSync("git init --initial-branch=trunk --quiet", {
46 - cwd: t.cwd,
47 - env: gitEnv,
48 - });
49 - execSync("git config user.email test@test.com", { cwd: t.cwd, env: gitEnv });
50 - execSync("git config user.name Test", { cwd: t.cwd, env: gitEnv });
51 - execSync("git config branch.autoSetupMerge false", {
52 - cwd: t.cwd,
53 - env: gitEnv,
54 - });
55 - writeFileSync(path.join(t.cwd, "file.txt"), "hello");
56 - execSync("git add .", { cwd: t.cwd, env: gitEnv });
57 - execSync("git commit -m init --quiet", { cwd: t.cwd, env: gitEnv });
58 - return gitEnv;
61 -function fakeCtx(cwd: string, sessionFile: string) {
62 - const entries: any[] = [];
63 - const messages: any[] = [];
64 - const widgets: any[] = [];
65 - const notices: string[] = [];
66 - let entrySeq = 0;
67 - const ctx: any = {
68 - cwd,
69 - hasUI: true,
70 - ui: {
71 - notify: (msg: string) => notices.push(String(msg)),
72 - setWidget: (_id: string, value: unknown) => widgets.push(value),
73 - },
74 - sessionManager: {
75 - getSessionFile: () => sessionFile,
76 - appendCustomEntry: (customType: string, data: unknown) => {
77 - const entry = {
78 - id: `e${++entrySeq}`,
79 - type: "custom",
80 - customType,
81 - data,
82 - };
83 - entries.push(entry);
84 - return entry.id;
85 - },
86 - getBranch: () => entries,
87 - },
88 - waitForIdle: async () => {},
89 - sendMessage: async (message: unknown) => messages.push(message),
90 - };
91 - return { ctx, entries, messages, widgets, notices };
94 -async function waitFor(
95 - fn: () => boolean,
96 - { timeoutMs = 8_000, message = "condition" } = {},
97 -) {
98 - const deadline = Date.now() + timeoutMs;
99 - while (Date.now() < deadline) {
100 - if (fn()) return;
101 - await sleep(25);
102 - }
103 - throw new Error(`timed out waiting for ${message}`);
106 -describe("superpowers harness", () => {
107 - it("loads in real Pi runtime and registers command/flag", async () => {
108 - t = await createTestSession({ extensions: [extPath()] });
109 - const [extension] = t.session.extensionRunner.extensions;
110 - expect(extension.path).toBe(extPath());
111 - expect(extension.commands.has("superpowers")).toBe(true);
112 - expect(extension.flags.has("superpowers")).toBe(true);
113 - expect(typeof command().getArgumentCompletions).toBe("function");
114 - });
116 - it("toggles workflow mode and reports usage/status/open failures without agent calls", async () => {
117 - t = await createTestSession({ extensions: [extPath()] });
118 - await command().handler("", ctx());
119 - await command().handler("", ctx());
120 - await command().handler("on", ctx());
121 - await command().handler("off", ctx());
122 - await command().handler("help", ctx());
123 - await command().handler("agent", ctx());
124 - await command().handler("status", ctx());
125 - await command().handler("open sp-404", ctx());
126 - expect(notices()).toContain("superpowers on");
127 - expect(notices()).toContain("superpowers off");
128 - expect(notices().some((m) => m.includes("superpowers off\nno tasks"))).toBe(
129 - true,
130 - );
131 - expect(notices().some((m) => m.includes("/superpowers agent"))).toBe(true);
132 - expect(notices()).toContain("usage: /superpowers agent <prompt>");
133 - expect(notices().some((m) => m.includes("no tasks"))).toBe(true);
134 - expect(notices()).toContain("no such task: sp-404");
135 - });
137 - it("review family aliases start requesting-code-review workers", async () => {
138 - t = await createTestSession({ extensions: [extPath()] });
139 - mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
140 - writeFileSync(
141 - path.join(t.cwd, ".pi/prompts/requesting-code-review.md"),
142 - "Review $ARGUMENTS",
143 - "utf8",
144 - );
145 - await command().handler("compress src", ctx());
146 - await waitFor(
147 - () =>
148 - existsSync(tasksPath()) &&
149 - ["done", "error"].includes(tasks()["sp-1"]?.status),
150 - );
151 - expect(tasks()["sp-1"].agent).toBe("requesting-code-review");
152 - expect(tasks()["sp-1"].prompt).toBe("Review src");
153 - });
155 - it("workflow aliases prefer project prompts when present", async () => {
156 - t = await createTestSession({ extensions: [extPath()] });
157 - mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
158 - writeFileSync(
159 - path.join(t.cwd, ".pi/prompts/systematic-debugging.md"),
160 - "Debug $ARGUMENTS",
161 - "utf8",
162 - );
163 - await command().handler("debug flaky test", ctx());
164 - await waitFor(
165 - () =>
166 - existsSync(tasksPath()) &&
167 - ["done", "error"].includes(tasks()["sp-1"]?.status),
168 - );
169 - expect(tasks()["sp-1"].agent).toBe("systematic-debugging");
170 - expect(tasks()["sp-1"].prompt).toBe("Debug flaky test");
171 - });
173 - it("workflow aliases use bundled prompts without project prompt files", async () => {
174 - t = await createTestSession({ extensions: [extPath()] });
175 - await command().handler("debug flaky test", ctx());
176 - await waitFor(
177 - () =>
178 - existsSync(tasksPath()) &&
179 - ["done", "error"].includes(tasks()["sp-1"]?.status),
180 - );
181 - expect(tasks()["sp-1"].agent).toBe("systematic-debugging");
182 - expect(tasks()["sp-1"].prompt).toContain(
183 - "No fix before root-cause evidence",
184 - );
185 - expect(tasks()["sp-1"].prompt).toContain("flaky test");
186 - });
188 - it("finds project prompt names for autocomplete", async () => {
189 - t = await createTestSession({ extensions: [extPath()] });
190 - mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
191 - writeFileSync(
192 - path.join(t.cwd, ".pi/prompts/review.md"),
193 - "Review $ARGUMENTS",
194 - "utf8",
195 - );
196 - expect(command().getArgumentCompletions("run re")).toContainEqual({
197 - value: "run review",
198 - label: "review",
199 - });
200 - expect(command().getArgumentCompletions("run review keep-args")).toEqual(
201 - [],
202 - );
203 - });
205 - it("starts an embedded SDK agent and persists task state", async () => {
206 - t = await createTestSession({ extensions: [extPath()] });
207 - mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
208 - writeFileSync(
209 - path.join(t.cwd, ".pi/prompts/echo.md"),
210 - "Say ok for $ARGUMENTS",
211 - "utf8",
212 - );
213 - await command().handler("run echo smoke", ctx());
214 - await waitFor(
215 - () =>
216 - existsSync(tasksPath()) &&
217 - ["done", "error"].includes(tasks()["sp-1"]?.status),
218 - );
219 - expect(tasks()["sp-1"].prompt).toBe("Say ok for smoke");
220 - expect(tasks()["sp-1"].log[0]).toContain("start echo");
221 - });
223 - it("continues task ids from persisted task store on session_start", async () => {
224 - t = await createTestSession({ extensions: [extPath()] });
225 - mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
226 - writeFileSync(path.join(t.cwd, ".pi/prompts/echo.md"), "Say ok", "utf8");
227 - mkdirSync(path.dirname(tasksPath()), { recursive: true });
228 - writeFileSync(
229 - tasksPath(),
230 - JSON.stringify({
231 - "sp-9": {
232 - id: "sp-9",
233 - agent: "old",
234 - prompt: "old",
235 - status: "done",
236 - startedAt: "a",
237 - updatedAt: "b",
238 - log: ["old"],
239 - },
240 - }),
241 - "utf8",
242 - );
243 - await t.session.extensionRunner.emit({
244 - type: "session_start",
245 - reason: "resume",
246 - });
247 - await command().handler("run echo", ctx());
248 - expect(tasks()["sp-10"].agent).toBe("echo");
249 - });
251 - it("reaps stale running tasks on session_start", async () => {
252 - t = await createTestSession({ extensions: [extPath()] });
253 - mkdirSync(path.dirname(tasksPath()), { recursive: true });
254 - writeFileSync(
255 - tasksPath(),
256 - JSON.stringify({
257 - "sp-1": {
258 - id: "sp-1",
259 - agent: "old",
260 - prompt: "stale",
261 - status: "running",
262 - startedAt: "2026-01-01T00:00:00.000Z",
263 - updatedAt: "2026-01-01T00:00:01.000Z",
264 - log: ["start"],
265 - },
266 - "sp-2": {
267 - id: "sp-2",
268 - agent: "old",
269 - prompt: "done",
270 - status: "done",
271 - startedAt: "2026-01-01T00:00:00.000Z",
272 - updatedAt: "2026-01-01T00:00:01.000Z",
273 - log: ["start", "done"],
274 - },
275 - }),
276 - "utf8",
277 - );
278 - await t.session.extensionRunner.emit({
279 - type: "session_start",
280 - reason: "resume",
281 - });
282 - expect(tasks()["sp-1"].status).toBe("aborted");
283 - expect(tasks()["sp-2"].status).toBe("done");
284 - expect(tasks()["sp-1"].log.at(-1)).toContain("reaped");
285 - });
287 - it("opens persisted task logs in the Pi editor and reports detailed status", async () => {
288 - t = await createTestSession({ extensions: [extPath()] });
289 - mkdirSync(path.dirname(tasksPath()), { recursive: true });
290 - writeFileSync(
291 - tasksPath(),
292 - JSON.stringify({
293 - "sp-7": {
294 - id: "sp-7",
295 - agent: "demo",
296 - prompt: "demo prompt",
297 - status: "done",
298 - startedAt: "2026-01-01T00:00:00.000Z",
299 - updatedAt: "2026-01-01T00:00:03.000Z",
300 - parentSession: "/tmp/parent.jsonl",
301 - log: ["checkpoint"],
302 - result: "DONE\nmore",
303 - },
304 - }),
305 - "utf8",
306 - );
307 - expect(command().getArgumentCompletions("open sp")).toContainEqual({
308 - value: "open sp-7",
309 - label: "sp-7",
310 - });
311 - expect(command().getArgumentCompletions("status sp")).toContainEqual({
312 - value: "status sp-7",
313 - label: "sp-7",
314 - });
315 - await command().handler("open sp-7", ctx());
316 - expect(t.events.uiCallsFor("editor")[0].args[0]).toBe("superpowers sp-7");
317 - expect(String(t.events.uiCallsFor("editor")[0].args[1])).toContain(
318 - "checkpoint",
319 - );
320 - await command().handler("status sp-7", ctx());
321 - expect(notices().at(-1)).toContain("✓ sp-7 done · demo · 3s — DONE");
322 - expect(notices().at(-1)).toContain("prompt:\ndemo prompt");
323 - });
325 - it("starts, announces, reannounces, reports, and stops visual session", async () => {
326 - t = await createTestSession({ extensions: [extPath()] });
327 - t.env.PI_SUPERPOWERS_NO_OPEN = "1";
328 - try {
329 - await command().handler("visual start", ctx());
330 - await waitFor(() =>
331 - t?.events.messages.some((m: any) => m.customType === "superpowers"),
332 - );
333 - const firstNotice = notices().at(-1);
334 - expect(firstNotice).toBeDefined();
335 - expect(firstNotice).toContain("visual live: http://127.0.0.1:");
336 - expect(firstNotice).toContain("content:");
337 - expect(firstNotice).toContain("events file:");
338 - expect(firstNotice).toContain("open manually: browser opener disabled");
339 - const firstMessage = t.events.messages.find(
340 - (m: any) => m.customType === "superpowers",
341 - ) as any;
342 - expect(firstMessage.content).toContain(
343 - "Superpowers visual brainstorming",
344 - );
345 - expect(firstMessage.content).toContain("visual live: http://127.0.0.1:");
346 - expect(firstMessage.content).toContain("content:");
347 - expect(firstMessage.content).toContain("events file:");
348 - expect(firstMessage.content).toContain("Agent rules:");
349 - expect(firstMessage.content).toContain(
350 - "Use visual only for active user decisions",
351 - );
352 - expect(firstMessage.content).toContain(
353 - "Do not use visual as progress reporting",
354 - );
355 - expect(firstMessage.content).toContain("data-choice");
356 - expect(firstMessage.content).toContain(
357 - "wait for terminal answer or browser event",
358 - );
359 - expect(firstMessage.content).toContain("Read the events file directly");
360 - expect(firstMessage.content).toContain("Continuing in terminal");
361 - expect(firstMessage.content).not.toContain("visual events");
362 - expect(firstMessage.content).not.toContain("hidden debug");
363 - const url = firstMessage.details.url;
364 - const contentDir = firstMessage.details.contentDir;
365 - const eventsFile = firstMessage.details.eventsFile;
367 - await command().handler("visual start", ctx());
368 - await waitFor(
369 - () =>
370 - t?.events.messages.filter((m: any) => m.customType === "superpowers")
371 - .length >= 2,
372 - );
373 - expect(notices().at(-1)).toContain(`visual already live: ${url}`);
374 - const secondMessage = t.events.messages
375 - .filter((m: any) => m.customType === "superpowers")
376 - .at(-1) as any;
377 - expect(secondMessage.details.url).toBe(url);
378 - expect(secondMessage.details.contentDir).toBe(contentDir);
379 - expect(secondMessage.details.eventsFile).toBe(eventsFile);
381 - await command().handler("visual status", ctx());
382 - expect(notices().at(-1)).toContain(`visual live: ${url}`);
383 - expect(notices().at(-1)).toContain(`content: ${contentDir}`);
384 - expect(notices().at(-1)).toContain(`events file: ${eventsFile}`);
386 - await command().handler("visual stop", ctx());
387 - expect(notices().at(-1)).toBe("visual stopped");
388 - } finally {
389 - delete t.env.PI_SUPERPOWERS_NO_OPEN;
390 - }
391 - });
393 - it("closes visual server on session shutdown", async () => {
394 - t = await createTestSession({ extensions: [extPath()] });
395 - t.env.PI_SUPERPOWERS_NO_OPEN = "1";
396 - try {
397 - await command().handler("visual start", ctx());
398 - await waitFor(() =>
399 - t?.events.messages.some((m: any) => m.customType === "superpowers"),
400 - );
401 - const message = t.events.messages.find(
402 - (m: any) => m.customType === "superpowers",
403 - ) as any;
404 - const url = message.details.url;
405 - expect(await fetch(url).then((r) => r.status)).toBe(200);
406 - await t.session.extensionRunner.emit({
407 - type: "session_shutdown",
408 - reason: "quit",
409 - });
410 - for (let i = 0; i < 40; i++) {
411 - try {
412 - await fetch(url);
413 - } catch {
414 - return;
415 - }
416 - await sleep(25);
417 - }
418 - expect.unreachable(
419 - "visual server still accepted requests after shutdown",
420 - );
421 - } finally {
422 - delete t.env.PI_SUPERPOWERS_NO_OPEN;
423 - }
424 - });
426 - it("branches into a child session and returns summary to parent", async () => {
427 - t = await createTestSession({ extensions: [extPath()] });
428 - const parentSession = path.join(t.cwd, "parent.jsonl");
429 - const childSession = path.join(t.cwd, "child.jsonl");
430 - mkdirSync(path.dirname(tasksPath()), { recursive: true });
431 - writeFileSync(
432 - tasksPath(),
433 - JSON.stringify({
434 - "sp-7": {
435 - id: "sp-7",
436 - agent: "demo",
437 - prompt: "demo prompt",
438 - status: "done",
439 - startedAt: "2026-01-01T00:00:00.000Z",
440 - updatedAt: "2026-01-01T00:00:03.000Z",
441 - parentSession,
442 - log: ["checkpoint"],
443 - result: "DONE",
444 - },
445 - }),
446 - "utf8",
447 - );
448 - const parent = fakeCtx(t.cwd, parentSession);
449 - const child = fakeCtx(t.cwd, childSession);
450 - parent.ctx.newSession = async (options: any) => {
451 - expect(options.parentSession).toBe(parentSession);
452 - await options.withSession(child.ctx);
453 - return { cancelled: false };
454 - };
455 - child.ctx.switchSession = async (sessionPath: string, options: any) => {
456 - expect(sessionPath).toBe(parentSession);
457 - await options.withSession(parent.ctx);
458 - return { cancelled: false };
459 - };
461 - await command().handler("branch sp-7", parent.ctx);
462 - expect(tasks()["sp-7"].status).toBe("branched");
463 - expect(tasks()["sp-7"].childSession).toBe(childSession);
464 - expect(child.entries.at(-1)?.data).toMatchObject({
465 - kind: "child",
466 - task: { id: "sp-7", childSession },
467 - });
468 - expect(child.messages.at(-1)?.content).toContain(
469 - "Superpowers takeover: sp-7",
470 - );
471 - expect(child.messages.at(-1)?.content).toContain(
472 - "/superpowers return <summary>",
473 - );
475 - await command().handler("return done", child.ctx);
476 - expect(parent.entries.at(-1)?.data).toMatchObject({
477 - kind: "return",
478 - taskId: "sp-7",
479 - summary: "done",
480 - childSession,
481 - });
482 - expect(parent.messages.at(-1)?.content).toContain(
483 - "Superpowers return sp-7",
484 - );
485 - expect(parent.messages.at(-1)?.content).toContain("done");
486 - expect(parent.messages.at(-1)?.content).toContain(childSession);
487 - });
489 - it("guards branch when harness has no persisted parent session", async () => {
490 - t = await createTestSession({ extensions: [extPath()] });
491 - mkdirSync(path.dirname(tasksPath()), { recursive: true });
492 - writeFileSync(
493 - tasksPath(),
494 - JSON.stringify({
495 - "sp-7": {
496 - id: "sp-7",
497 - agent: "demo",
498 - prompt: "demo",
499 - status: "done",
500 - startedAt: "a",
501 - updatedAt: "b",
502 - log: ["checkpoint"],
503 - },
504 - }),
505 - "utf8",
506 - );
507 - await command().handler("branch sp-7", ctx());
508 - expect(notices()).toContain(
509 - "/superpowers branch requires persisted parent session",
510 - );
511 - });
513 - it("detects no repo in plain directory", async () => {
514 - t = await createTestSession({ extensions: [extPath()] });
515 - expect(__test.detectRepo(t.cwd)).toBeNull();
516 - });
518 - it("detects jj repo", async () => {
519 - t = await createTestSession({ extensions: [extPath()] });
520 - mkdirSync(path.join(t.cwd, ".jj"), { recursive: true });
521 - expect(__test.detectRepo(t.cwd)).toBe("jj");
522 - });
524 - it("detects git standard checkout", async () => {
525 - t = await createTestSession({ extensions: [extPath()] });
526 - initGitRepo();
527 - const repo = __test.detectRepo(t.cwd);
528 - expect(repo).not.toBeNull();
529 - expect(repo).toHaveProperty("type", "git");
530 - expect(repo).toHaveProperty("layout", "standard");
531 - });
533 - it("creates and cleans up git worktree isolate", async () => {
534 - t = await createTestSession({ extensions: [extPath()] });
535 - const gitEnv = initGitRepo();
536 - const repo = __test.detectRepo(t.cwd);
537 - expect(repo).not.toBeNull();
538 - const piMock = {
539 - exec: async (_cmd: string, _args: string[]) => {
540 - execSync([_cmd, ..._args].join(" "), {
541 - cwd: t.cwd,
542 - env: gitEnv,
543 - stdio: "pipe",
544 - });
545 - },
546 - } as any;
547 - if (!repo) throw new Error("expected git repo");
548 - const isolate = await __test.createIsolate(t.cwd, "sp-test", repo, piMock);
549 - expect(isolate.type).toBe("git-standard");
550 - expect(existsSync(isolate.path)).toBe(true);
551 - const task = { isolate, log: [] as string[] } as any;
552 - await __test.cleanupIsolate(task, piMock);
553 - expect(existsSync(isolate.path)).toBe(false);
554 - });
556 - it("skips isolate when --share is passed", async () => {
557 - t = await createTestSession({ extensions: [extPath()] });
558 - initGitRepo();
559 - mkdirSync(path.join(t.cwd, ".pi/prompts"), { recursive: true });
560 - writeFileSync(
561 - path.join(t.cwd, ".pi/prompts/echo.md"),
562 - "Echo $ARGUMENTS",
563 - "utf8",
564 - );
565 - await command().handler("run echo smoke --share", ctx());
566 - await waitFor(
567 - () =>
568 - existsSync(tasksPath()) &&
569 - ["done", "error"].includes(tasks()["sp-1"]?.status),
570 - );
571 - expect(tasks()["sp-1"].isolate).toBeUndefined();
572 - await sleep(200);
573 - });
574 -});

extensions/superpowers/__tests__/helpers.test.ts

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

extensions/superpowers/docs-visual-brainstorming.md

Deleted
deleted file mode 100644
1 -# Visual Brainstorming Research
3 -Source inspected:
4 -upstream `obra/superpowers` brainstorming skill and visual companion docs.
6 -## How upstream works
8 -Visual brainstorming is not a separate mode.
9 -It is an optional browser companion offered during brainstorming when upcoming
10 -questions are easier to answer visually.
12 -Flow:
14 -1. Brainstorming starts with text/context exploration.
15 -2. If visual questions are likely, agent sends a standalone consent message.
16 -3. If user agrees, agent starts a local browser server.
17 -4. Agent writes HTML fragments into a watched content directory.
18 -5. Browser always shows newest HTML screen.
19 -6. User clicks options/cards/mockups in browser and also responds in terminal.
20 -7. Browser events are stored as JSONL in a state directory.
21 -8. Agent reads events next turn and merges them with terminal feedback.
22 -9. For non-visual questions, agent pushes a waiting screen and continues in
23 - terminal.
25 -## UX rules
27 -- Offer visual companion once, in its own message.
28 -- Decide per question whether visual helps.
29 -- Use browser for mockups, wireframes, diagrams, layout/color/design
30 - comparisons.
31 -- Use terminal for requirements, scope, text tradeoffs, technical decisions.
32 -- Visual companion is an active decision aid, not a reporting dashboard.
33 -- Every visual screen must ask a question, present selectable options, or show a
34 - mockup/diagram the user is meant to judge.
35 -- Do not use visual screens for progress updates, implementation summaries,
36 - final reports, or proof-of-work slides.
37 -- Use `data-choice` for clickable options; browser JS auto-records clicks.
38 -- After writing a decision screen, wait for terminal response or browser event
39 - before implementing.
40 -- User terminal response remains primary; click events are supporting evidence.
41 -- Each screen uses a new semantic filename.
42 -- Stale screens should be replaced with “Continuing in terminal…” when leaving
43 - visual mode.
44 -- End of visual phase:
45 - ask whether to leave browser open for inspection or stop it with `/superpowers
46 - visual stop`.
48 -## Technical shape
50 -Upstream server:
52 -- zero-dependency Node server using built-ins
53 -- serves newest `.html` from screen dir
54 -- wraps HTML fragments in a frame template
55 -- injects helper JS
56 -- records clicks/selections to JSONL events file
57 -- auto-records clicks on `[data-choice]` elements so agents do not need inline
58 - JS
59 -- uses polling reload to update browser
60 -- stores session under project `.superpowers/brainstorm/...`
62 -Important directories:
64 -```text
65 -.superpowers/brainstorm/<session>/content/ # HTML screens
66 -.superpowers/brainstorm/<session>/state/ # events + server-info
67 -```
69 -## Design implications for Pi
71 -For our Pi Superpowers:
73 -- Keep visual brainstorming explicitly activated by brainstorming workflow.
74 -- Do not make it a hidden hook.
75 -- It should be an explicit `/superpowers visual ...` tool, not automatic
76 - strict-mode behavior.
77 -- Store ephemeral files under platform state, not the repo:
78 - `${XDG_STATE_HOME:-~/.local/state}/pi/superpowers/<project-hash>/visual/...`
79 - on Linux, native equivalents on macOS/Windows.
80 -- Use Pi UI notification and a visible session message to show URL and paths.
81 -- Use `read`/`write` tool workflow for screens/events.
82 -- Create the events JSONL file at start so agent reads never fail before the
83 - first browser click.
84 -- Close server on `/superpowers visual stop` and session shutdown.
85 -- Keep zero dependency:
86 - Node built-ins or Bun server only.
88 -## Recommended Pi UX
90 -```text
91 -/brainstorming improve dashboard UX
92 -```
94 -Agent:
96 -```text
97 -Some choices are visual. I can open a local browser companion for mockups and layout comparisons. Use it? (local URL)
98 -```
100 -If yes:
102 -```text
103 -/superpowers visual start
104 -```
106 -Then:
108 -```text
109 -Showing 3 dashboard layout options at http://localhost:NNNN.
110 -Question: which layout would you actually want to use all day?
111 -Click one if useful, then tell me what you think here.
112 -```
114 -Future command candidates:
116 -```text
117 -/superpowers visual start
118 -/superpowers visual show <html-fragment-file>
119 -/superpowers visual stop
120 -```
122 -## What not to copy blindly
124 -- Do not vendor dependencies.
125 -- Do not force browser for conceptual questions.
126 -- Do not use visual companion as a status board or final report.
127 -- Do not let visual companion skip design approval/spec gates.
128 -- Do not store under non-Pi `.superpowers` unless intentionally matching
129 - upstream.
130 -- Do not make visual server start automatically on `/superpowers on`.

extensions/superpowers/index.ts

Deleted
deleted file mode 100644
1 -import { execSync } from "node:child_process";
2 -import { createHash } from "node:crypto";
3 -import {
4 - appendFileSync,
5 - existsSync,
6 - mkdirSync,
7 - readdirSync,
8 - readFileSync,
9 - rmdirSync,
10 - writeFileSync,
11 -} from "node:fs";
12 -import os from "node:os";
13 -import path from "node:path";
14 -import { fileURLToPath } from "node:url";
15 -import { getModel } from "@earendil-works/pi-ai";
16 -import {
17 - createAgentSession,
18 - DefaultResourceLoader,
19 - type ExtensionAPI,
20 - type ExtensionCommandContext,
21 - type ExtensionContext,
22 - getAgentDir,
23 - SessionManager,
24 - SettingsManager,
25 - type ThemeColor,
26 -} from "@earendil-works/pi-coding-agent";
27 -import { openBrowser, startVisualServer, type VisualSession } from "./visual";
29 -const ID = "superpowers";
30 -const STATUS_ID = "superpowers";
31 -const WIDGET = "superpowers";
32 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
33 -const FOOTER_SEGMENT = {
34 - id: STATUS_ID,
35 - icon: "⚡",
36 - zone: "workspace",
37 - order: 80,
38 -} as const;
39 -const EXT_DIR = path.dirname(fileURLToPath(import.meta.url));
40 -const FLAG_PROMPT = `
42 -Superpowers active. Strict mode.
44 -Before every non-trivial coding task:
45 -1. STATE YOUR WORKFLOW: print "Workflow: <skill-name>" on its own line before any other output. Pick from: brainstorming, writing-plans, executing-plans, test-driven-development, systematic-debugging, requesting-code-review, receiving-code-review, verification-before-completion, dispatching-parallel-agents, using-git-worktrees, writing-skills.
46 -2. Pick the earliest applicable lifecycle: brainstorming → writing-plans → executing-plans/TDD/debug → review → verification.
47 -3. Use brainstorming first for vague goals, UX/UI work, architecture choices, new features, or broad refactors. Do not use writing-plans unless an approved design/spec already exists.
48 -4. Load/follow that skill before acting. Do not skip to implementation.
49 -5. Prefer simplicity/minimalism/brutalism. No legacy/compat/edge-case bloat unless explicitly required.
50 -6. Before claiming done/fixed/shipped, run verification and cite evidence.
51 -7. For isolated or parallel worker tasks, use /superpowers run <prompt> <args>.
52 -`;
53 -const COMMANDS = [
54 - "run",
55 - "agent",
56 - "open",
57 - "branch",
58 - "return",
59 - "abort",
60 - "status",
61 - "on",
62 - "off",
63 - "design",
64 - "plan",
65 - "execute",
66 - "parallel",
67 - "review",
68 - "deslop",
69 - "compress",
70 - "debug",
71 - "git",
72 - "meta",
73 - "verify",
74 - "visual",
75 - "help",
76 -];
77 -const ALIASES: Record<string, string> = {
78 - design: "brainstorming",
79 - plan: "writing-plans",
80 - execute: "executing-plans",
81 - parallel: "dispatching-parallel-agents",
82 - review: "requesting-code-review",
83 - deslop: "requesting-code-review",
84 - compress: "requesting-code-review",
85 - debug: "systematic-debugging",
86 - git: "using-git-worktrees",
87 - meta: "writing-skills",
88 - verify: "verification-before-completion",
89 -};
90 -type Status = "running" | "done" | "error" | "aborted" | "branched";
91 -type Options = {
92 - tools?: string[];
93 - extensions?: string[];
94 - thinking?: string;
95 - model?: string;
96 - accent?: string;
97 -};
98 -type IsolateInfo = {
99 - type: "git-standard" | "git-bare" | "jj";
100 - path: string;
101 - branch?: string;
102 - workspaceName?: string;
103 - gitDir?: string;
104 - root?: string;
106 -type Task = {
107 - id: string;
108 - agent: string;
109 - prompt: string;
110 - status: Status;
111 - startedAt: string;
112 - updatedAt: string;
113 - parentSession?: string;
114 - childSession?: string;
115 - log: string[];
116 - result?: string;
117 - accent?: string;
118 - isolate?: IsolateInfo;
120 -type Runtime = {
121 - cwd: string;
122 - task: Task;
123 - abort?: () => void;
124 - dispose?: () => void;
126 -type Entry =
127 - | { kind: "task"; task: Task }
128 - | { kind: "child"; task: Task }
129 - | { kind: "return"; taskId: string; summary: string; childSession?: string };
131 -const live = new Map<string, Runtime>();
132 -let next = 1;
133 -let generation = 0;
134 -let currentCwd = process.cwd();
135 -let active = false;
136 -let visual: VisualSession | undefined;
137 -let api: ExtensionAPI | undefined;
139 -const now = () => new Date().toISOString();
140 -function platformStateDir(
141 - platform: NodeJS.Platform = process.platform,
142 - env: NodeJS.ProcessEnv = process.env,
143 - home = os.homedir(),
144 -) {
145 - const paths = platform === "win32" ? path.win32 : path.posix;
146 - if (platform === "win32")
147 - return paths.join(
148 - env.LOCALAPPDATA ?? paths.join(home, "AppData", "Local"),
149 - "pi",
150 - );
151 - if (env.XDG_STATE_HOME) return paths.join(env.XDG_STATE_HOME, "pi");
152 - if (platform === "darwin")
153 - return paths.join(home, "Library", "Application Support", "pi");
154 - return paths.join(home, ".local", "state", "pi");
156 -function hashProjectRoot(cwd: string) {
157 - return createHash("sha256").update(path.resolve(cwd)).digest("hex");
159 -const dir = (cwd: string) =>
160 - path.join(platformStateDir(), "superpowers", hashProjectRoot(cwd));
161 -const tasksFile = (cwd: string) => path.join(dir(cwd), "tasks.json");
162 -const sessionsDir = (cwd: string) => path.join(dir(cwd), "sessions");
163 -const ensure = (cwd: string) =>
164 - mkdirSync(sessionsDir(cwd), { recursive: true });
165 -const text = (x: unknown): string =>
166 - typeof x === "string"
167 - ? x
168 - : Array.isArray(x)
169 - ? x
170 - .map((p) => (p?.type === "text" ? p.text : ""))
171 - .filter(Boolean)
172 - .join("\n")
173 - : "";
175 -function readTasks(cwd: string): Record<string, Task> {
176 - try {
177 - return JSON.parse(readFileSync(tasksFile(cwd), "utf8"));
178 - } catch {
179 - return {};
182 -function writeTask(cwd: string, task: Task) {
183 - ensure(cwd);
184 - const all = readTasks(cwd);
185 - all[task.id] = task;
186 - writeFileSync(tasksFile(cwd), `${JSON.stringify(all, null, "\t")}\n`);
188 -function logRun(cwd: string, task: Task) {
189 - const entry = {
190 - id: task.id,
191 - agent: task.agent,
192 - status: task.status,
193 - startedAt: task.startedAt,
194 - updatedAt: task.updatedAt,
195 - tools: toolCount(task),
196 - result: firstLine(task.result ?? ""),
197 - };
198 - try {
199 - appendFileSync(
200 - path.join(dir(cwd), "runs.jsonl"),
201 - `${JSON.stringify(entry)}\n`,
202 - );
203 - } catch {
204 - /* best effort */
207 -function append(ctx: ExtensionContext, entry: Entry) {
208 - try {
210 - ctx.sessionManager as unknown as {
211 - appendCustomEntry(t: string, d: unknown): string;
213 - ).appendCustomEntry(ID, entry);
214 - } catch {
215 - /* session may have been disposed */
218 -function notify(
219 - ctx: ExtensionContext,
220 - msg: string,
221 - kind: "info" | "warning" | "error" = "info",
222 -) {
223 - if (ctx.hasUI) ctx.ui.notify(msg, kind);
225 -function hasFooter() {
226 - const footer = (globalThis as any)[FOOTER_KEY];
227 - return footer?.loaded === true && footer.version >= 1;
229 -function statusCounts(cwd: string) {
230 - const tasks = Object.values(readTasks(cwd));
231 - return {
232 - tasks,
233 - running: tasks.filter((t) => t.status === "running").length,
234 - errors: tasks.filter((t) => t.status === "error").length,
235 - };
237 -function uiStatusText(cwd: string) {
238 - const { running, errors } = statusCounts(cwd);
239 - if (!active && !running && !errors && !visual) return undefined;
240 - const parts: string[] = [];
241 - if (active) parts.push("on");
242 - if (running) parts.push(`${running}↑`);
243 - if (errors) parts.push(`${errors}✗`);
244 - if (visual) parts.push("eye");
245 - return parts.join(" ");
247 -function publishStatus(ctx: ExtensionContext) {
248 - if (!ctx.hasUI) return;
249 - const message = uiStatusText(ctx.cwd);
250 - if (hasFooter() && api) {
251 - (ctx.ui as any).setStatus?.(STATUS_ID, undefined);
252 - const runningTask = Object.values(readTasks(ctx.cwd)).find(
253 - (t) => t.status === "running",
254 - );
255 - const footerColor = runningTask
256 - ? taskAccent(runningTask.agent, runningTask.accent)
257 - : ((active ? "accent" : "muted") as ThemeColor);
258 - api.events.emit(
259 - "footer:segment",
260 - message
261 - ? {
262 - ...FOOTER_SEGMENT,
263 - text: message,
264 - variants: [message.replace(/^sp /, "")],
265 - color: footerColor,
267 - : { id: STATUS_ID, text: undefined },
268 - );
269 - return;
271 - api?.events.emit("footer:segment", { id: STATUS_ID, text: undefined });
272 - (ctx.ui as any).setStatus?.(STATUS_ID, message);
274 -const STATUS_ICONS: Record<Status, string> = {
275 - running: "▶",
276 - done: "✓",
277 - error: "✗",
278 - aborted: "⊘",
279 - branched: "⤴",
281 -const AGENT_SHORT: Record<string, string> = {
282 - "requesting-code-review": "review",
283 - "receiving-code-review": "fix",
284 - brainstorming: "design",
285 - "writing-plans": "plan",
286 - "executing-plans": "exec",
287 - "dispatching-parallel-agents": "parallel",
288 - "systematic-debugging": "debug",
289 - "verification-before-completion": "verify",
290 - "using-git-worktrees": "git",
291 - "writing-skills": "skill",
292 - "test-driven-development": "tdd",
293 - "finishing-a-development-branch": "finish",
294 - "using-superpowers": "sp",
295 - "subagent-driven-development": "sub",
297 -const ALIAS_ACCENT: Record<string, ThemeColor> = {
298 - design: "accent",
299 - plan: "dim",
300 - execute: "success",
301 - parallel: "syntaxVariable",
302 - review: "syntaxKeyword",
303 - deslop: "syntaxKeyword",
304 - compress: "syntaxKeyword",
305 - debug: "warning",
306 - verify: "toolTitle",
307 - git: "muted",
308 - meta: "syntaxFunction",
309 - tdd: "syntaxString",
310 - finish: "dim",
312 -function taskAccent(agent: string, explicit?: string): ThemeColor {
313 - if (explicit && THEMED_COLORS.has(explicit)) return explicit as ThemeColor;
314 - return ALIAS_ACCENT[AGENT_SHORT[agent] ?? agent] ?? "accent";
316 -const THEMED_COLORS: Set<string> = new Set([
317 - "accent",
318 - "border",
319 - "borderAccent",
320 - "borderMuted",
321 - "success",
322 - "error",
323 - "warning",
324 - "muted",
325 - "dim",
326 - "text",
327 - "thinkingText",
328 - "userMessageText",
329 - "customMessageText",
330 - "customMessageLabel",
331 - "toolTitle",
332 - "toolOutput",
333 - "mdHeading",
334 - "mdLink",
335 - "mdLinkUrl",
336 - "mdCode",
337 - "mdCodeBlock",
338 - "mdCodeBlockBorder",
339 - "mdQuote",
340 - "mdQuoteBorder",
341 - "mdHr",
342 - "mdListBullet",
343 - "toolDiffAdded",
344 - "toolDiffRemoved",
345 - "toolDiffContext",
346 - "syntaxComment",
347 - "syntaxKeyword",
348 - "syntaxFunction",
349 - "syntaxVariable",
350 - "syntaxString",
351 - "syntaxNumber",
352 - "syntaxType",
353 - "syntaxOperator",
354 - "syntaxPunctuation",
355 - "thinkingOff",
356 - "thinkingMinimal",
357 - "thinkingLow",
358 - "thinkingMedium",
359 - "thinkingHigh",
360 - "thinkingXhigh",
361 - "bashMode",
362 -]);
363 -function elapsedLive(start: string) {
364 - const a = Date.parse(start);
365 - if (!Number.isFinite(a)) return "?";
366 - const sec = Math.max(0, Math.round((Date.now() - a) / 1000));
367 - return sec < 60 ? `${sec}s` : `${Math.floor(sec / 60)}m${sec % 60}s`;
369 -function compactTaskLine(t: Task) {
370 - const icon = STATUS_ICONS[t.status] ?? "·";
371 - const name = AGENT_SHORT[t.agent] ?? t.agent;
372 - const time =
373 - t.status === "running"
374 - ? elapsedLive(t.startedAt)
375 - : elapsed(t.startedAt, t.updatedAt);
376 - const tools = toolCount(t);
377 - return `${icon} ${t.id} ${name} ${time}${tools ? ` · ${tools} tools` : ""}`;
379 -function firstLine(s: string | undefined) {
380 - return (s ?? "").split("\n")[0]?.trim() ?? "";
382 -function elapsed(start: string, end: string) {
383 - const a = Date.parse(start);
384 - const b = Date.parse(end);
385 - if (!Number.isFinite(a) || !Number.isFinite(b)) return "?";
386 - const sec = Math.max(0, Math.round((b - a) / 1000));
387 - return sec < 60 ? `${sec}s` : `${Math.floor(sec / 60)}m${sec % 60}s`;
389 -function toolCount(t: Task) {
390 - return t.log.filter((l) => / tool \S+/.test(l)).length;
392 -function summaryLine(t: Task) {
393 - const icon = STATUS_ICONS[t.status] ?? "·";
394 - const name = AGENT_SHORT[t.agent] ?? t.agent;
395 - const time =
396 - t.status === "running"
397 - ? elapsedLive(t.startedAt)
398 - : elapsed(t.startedAt, t.updatedAt);
399 - const tools = toolCount(t);
400 - const tail = firstLine(t.result ?? t.log.at(-1));
401 - const parts = [`${icon} ${t.id}`, name, time];
402 - if (tools) parts.push(`${tools} tools`);
403 - const header = parts.join(" · ");
404 - return tail ? `${header} — ${tail}` : header;
406 -function taskDetails(t: Task) {
407 - const icon = STATUS_ICONS[t.status] ?? "·";
408 - const time =
409 - t.status === "running"
410 - ? elapsedLive(t.startedAt)
411 - : elapsed(t.startedAt, t.updatedAt);
412 - const tools = toolCount(t);
413 - const name = AGENT_SHORT[t.agent] ?? t.agent;
414 - const tail = firstLine(t.result ?? t.log.at(-1));
415 - const header = [`${icon} ${t.id} ${t.status}`, name, time];
416 - if (tools) header.push(`${tools} tools`);
417 - return [
418 - header.join(" · ") + (tail ? ` — ${tail}` : ""),
419 - `agent: ${t.agent}`,
420 - `started: ${t.startedAt}`,
421 - `updated: ${t.updatedAt}`,
422 - `parent: ${t.parentSession ?? "none"}`,
423 - `child: ${t.childSession ?? "none"}`,
424 - "",
425 - "prompt:",
426 - t.prompt,
427 - "",
428 - "latest:",
429 - t.result ?? t.log.at(-1) ?? "",
430 - ].join("\n");
432 -function widget(ctx: ExtensionContext) {
433 - try {
434 - publishStatus(ctx);
435 - if (!ctx.hasUI) return;
436 - const running = Object.values(readTasks(ctx.cwd))
437 - .filter((t) => t.status === "running")
438 - .slice(-3);
439 - if (!running.length) {
440 - (ctx.ui as any).setWidget?.(WIDGET, undefined);
441 - return;
443 - const th = ctx.ui.theme;
444 - const lines = [
445 - th.fg(
446 - "dim",
447 - `${running.length} worker${running.length > 1 ? "s" : ""} running`,
448 - ),
449 - ...running.map((t) =>
450 - th.fg(taskAccent(t.agent, t.accent), compactTaskLine(t)),
451 - ),
452 - ];
453 - (ctx.ui as any).setWidget?.(WIDGET, lines);
454 - } catch {
455 - /* ctx may be stale after session disposal */
459 -function parseList(raw: string): string[] | undefined {
460 - const s = raw.trim().replace(/^\[/, "").replace(/\]$/, "");
461 - const xs = s
462 - .split(",")
463 - .map((x) => x.trim().replace(/^['"]|['"]$/g, ""))
464 - .filter(Boolean);
465 - return xs.length ? xs : undefined;
467 -function parseAgentFile(
468 - raw: string,
469 - args = "",
470 -): { prompt: string; options: Options } {
471 - let body = raw;
472 - const meta: Record<string, string> = {};
473 - if (raw.startsWith("---\n")) {
474 - const end = raw.indexOf("\n---\n", 4);
475 - if (end >= 0) {
476 - body = raw.slice(end + 5);
477 - for (const line of raw.slice(4, end).split("\n")) {
478 - const i = line.indexOf(":");
479 - if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim();
483 - return {
484 - prompt: body.replace(/\$ARGUMENTS|\$@/g, args).trim(),
485 - options: {
486 - tools: meta.tools && parseList(meta.tools),
487 - extensions: meta.extensions && parseList(meta.extensions),
488 - thinking: meta.thinking?.replace(/^['"]|['"]$/g, ""),
489 - model: meta.model?.replace(/^['"]|['"]$/g, ""),
490 - accent: meta.accent?.replace(/^['"]|['"]$/g, ""),
491 - },
492 - };
494 -function glob(pat: string, v: string) {
495 - return (
496 - pat === "*" ||
497 - (!pat.includes("*")
498 - ? pat === v
499 - : new RegExp(
500 - `^${pat.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*")}$`,
501 - ).test(v))
502 - );
504 -function resolveNames(
505 - patterns: string[] | undefined,
506 - names: string[],
507 -): string[] | undefined {
508 - if (!patterns) return undefined;
509 - const out = new Set<string>();
510 - for (const p of patterns.filter((x) => !x.startsWith("-")))
511 - for (const n of names) if (glob(p, n)) out.add(n);
512 - for (const p of patterns
513 - .filter((x) => x.startsWith("-"))
514 - .map((x) => x.slice(1)))
515 - for (const n of names) if (glob(p, n)) out.delete(n);
516 - return [...out];
518 -function promptDirs(cwd: string) {
519 - return [
520 - path.join(cwd, ".pi/prompts"),
521 - path.join(getAgentDir(), "prompts"),
522 - path.join(EXT_DIR, "prompts"),
523 - ];
525 -function agentNames(cwd: string) {
526 - return [
527 - ...new Set(
528 - promptDirs(cwd).flatMap((d) =>
529 - existsSync(d)
530 - ? readdirSync(d)
531 - .filter((f) => f.endsWith(".md"))
532 - .map((f) => f.slice(0, -3))
533 - : [],
534 - ),
535 - ),
536 - ].sort();
538 -function loadAgent(cwd: string, name: string, args: string) {
539 - if (!/^[\w-]+$/.test(name)) return;
540 - for (const d of promptDirs(cwd)) {
541 - const f = path.join(d, `${name}.md`);
542 - if (existsSync(f)) return parseAgentFile(readFileSync(f, "utf8"), args);
545 -function childPrompt(task: Pick<Task, "id" | "parentSession" | "log">) {
546 - 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.`;
548 -function latestChild(ctx: ExtensionContext): Task | undefined {
549 - let t: Task | undefined;
550 - for (const e of ctx.sessionManager.getBranch())
551 - if (
552 - e.type === "custom" &&
553 - e.customType === ID &&
554 - (e.data as Entry)?.kind === "child"
556 - t = (e.data as Extract<Entry, { kind: "child" }>).task;
557 - return t;
559 -function modelFrom(s: string | undefined, fallback: ExtensionContext["model"]) {
560 - const [provider, ...id] = s?.split("/") ?? [];
561 - if (provider && id.length) {
562 - const m = getModel(provider, id.join("/"));
563 - if (m?.provider && m.id) return m;
565 - return fallback ?? getModel("openai", "gpt-4o");
567 -function extName(p: string) {
568 - return path.basename(p) === "index.ts"
569 - ? path.basename(path.dirname(p))
570 - : path.basename(p).replace(/\.[^.]+$/, "");
572 -function stopRuntime(r: Runtime, status: Status) {
573 - r.abort?.();
574 - r.dispose?.();
575 - r.task.status = status;
576 - r.task.updatedAt = now();
577 - writeTask(r.cwd, r.task);
580 -function stopAll(status: Status = "aborted") {
581 - for (const [id, r] of live) {
582 - if (r.task.status === "running") stopRuntime(r, status);
583 - live.delete(id);
587 -function reapStale(cwd: string) {
588 - const tasks = readTasks(cwd);
589 - let reaped = 0;
590 - for (const t of Object.values(tasks)) {
591 - if (t.status === "running" && !live.has(t.id)) {
592 - t.status = "aborted";
593 - t.updatedAt = now();
594 - t.log.push(`${t.updatedAt} reaped (parent session gone)`);
595 - writeTask(cwd, t);
596 - reaped++;
599 - return reaped;
602 -function stopPeers(keepId: string) {
603 - for (const [id, r] of live) {
604 - if (id === keepId) continue;
605 - if (r.task.status === "running") stopRuntime(r, "aborted");
606 - live.delete(id);
610 -// ── Repo detection ──────────────────────────────────────────────────────────
612 -type GitLayout = {
613 - type: "git";
614 - layout: "standard" | "bare";
615 - gitDir: string;
616 - root: string;
619 -type RepoType = "jj" | GitLayout;
621 -function detectRepo(cwd: string): RepoType | null {
622 - // Prefer jj when colocated
623 - if (existsSync(path.join(cwd, ".jj"))) return "jj";
624 - try {
625 - const commonDir = execSync(
626 - "git rev-parse --path-format=absolute --git-common-dir",
628 - cwd,
629 - encoding: "utf8",
630 - stdio: ["pipe", "pipe", "ignore"],
631 - },
632 - ).trim();
633 - const isBare =
634 - execSync("git config --bool core.bare", {
635 - cwd: commonDir,
636 - encoding: "utf8",
637 - stdio: ["pipe", "pipe", "ignore"],
638 - })
639 - .trim()
640 - .toLowerCase() === "true";
641 - if (isBare) {
642 - return {
643 - type: "git",
644 - layout: "bare",
645 - gitDir: commonDir,
646 - root: path.dirname(commonDir),
647 - };
649 - return {
650 - type: "git",
651 - layout: "standard",
652 - gitDir: commonDir,
653 - root: path.dirname(commonDir),
654 - };
655 - } catch {
656 - return null;
660 -// ── Worktree / workspace creation ───────────────────────────────────────────
662 -async function createIsolate(
663 - cwd: string,
664 - id: string,
665 - repo: RepoType,
666 - pi: ExtensionAPI,
667 -): Promise<IsolateInfo> {
668 - if (repo === "jj") {
669 - const wsDir = path.join(cwd, ".jj", "workspaces", id);
670 - mkdirSync(path.dirname(wsDir), { recursive: true });
671 - await pi.exec("jj", ["workspace", "add", "--name", id, wsDir]);
672 - return { type: "jj", path: wsDir, workspaceName: id };
674 - // git
675 - const branch = `superpowers-${id}`;
676 - if (repo.layout === "bare") {
677 - const wtPath = path.join(repo.root, id);
678 - await pi.exec("git", [
679 - "-C",
680 - repo.gitDir,
681 - "worktree",
682 - "add",
683 - "-b",
684 - branch,
685 - wtPath,
686 - "HEAD",
687 - ]);
688 - return {
689 - type: "git-bare",
690 - path: wtPath,
691 - branch,
692 - gitDir: repo.gitDir,
693 - root: repo.root,
694 - };
696 - // standard checkout
697 - const wtPath = path.join(cwd, ".git", `wt-${id}`);
698 - await pi.exec("git", ["worktree", "add", "-b", branch, wtPath, "HEAD"]);
699 - return { type: "git-standard", path: wtPath, branch };
702 -async function cleanupIsolate(task: Task, pi: ExtensionAPI) {
703 - if (!task.isolate) return;
704 - const { isolate } = task;
705 - try {
706 - if (isolate.type === "jj") {
707 - if (isolate.workspaceName)
708 - await pi.exec("jj", ["workspace", "forget", isolate.workspaceName]);
709 - rmdirSync(isolate.path, { recursive: true });
710 - } else if (isolate.type === "git-bare") {
711 - if (!isolate.gitDir || !isolate.branch)
712 - throw new Error("git-bare isolate missing cleanup metadata");
713 - await pi.exec("git", [
714 - "-C",
715 - isolate.gitDir,
716 - "worktree",
717 - "remove",
718 - "--force",
719 - isolate.path,
720 - ]);
721 - await pi.exec("git", [
722 - "-C",
723 - isolate.gitDir,
724 - "branch",
725 - "-D",
726 - isolate.branch,
727 - ]);
728 - } else {
729 - if (!isolate.branch) throw new Error("git isolate missing branch");
730 - await pi.exec("git", ["worktree", "remove", "--force", isolate.path]);
731 - await pi.exec("git", ["branch", "-D", isolate.branch]);
733 - } catch {
734 - /* best effort cleanup */
738 -async function startAgent(
739 - name: string,
740 - loaded: { prompt: string; options: Options },
741 - ctx: ExtensionCommandContext,
742 - pi: ExtensionAPI,
743 - share = false,
744 -) {
745 - let cwd = ctx.cwd;
746 - const parentSession = ctx.sessionManager.getSessionFile();
747 - const model = ctx.model;
748 - const modelRegistry = ctx.modelRegistry;
749 - const availableTools = pi.getAllTools().map((t) => t.name);
750 - const thinking = pi.getThinkingLevel();
751 - ensure(cwd);
752 - const id = `sp-${next++}`;
753 - const task: Task = {
754 - id,
755 - agent: name,
756 - prompt: loaded.prompt,
757 - status: "running",
758 - startedAt: now(),
759 - updatedAt: now(),
760 - parentSession,
761 - log: [`${now()} start ${name}`],
762 - accent: loaded.options.accent,
763 - };
764 - // detect repo and optionally create isolated worktree
765 - const repo = share ? null : detectRepo(cwd);
766 - if (repo) {
767 - try {
768 - const isolate = await createIsolate(cwd, id, repo, pi);
769 - task.isolate = isolate;
770 - cwd = isolate.path;
771 - task.log.push(`${now()} isolate ${isolate.type} ${isolate.path}`);
772 - } catch (err) {
773 - task.log.push(`${now()} isolate-fallback ${(err as Error).message}`);
776 - live.set(id, { cwd, task });
777 - writeTask(cwd, task);
778 - append(ctx, { kind: "task", task });
779 - widget(ctx);
780 - pi.sendMessage(
782 - customType: ID,
783 - display: true,
784 - content: `Superpowers ${id} started: ${name}`,
785 - details: { taskId: id },
786 - },
787 - { triggerTurn: false },
788 - );
789 - notify(ctx, `${id} started`, "info");
790 - const gen = generation;
791 - void (async () => {
792 - let session:
793 - | Awaited<ReturnType<typeof createAgentSession>>["session"]
794 - | undefined;
795 - try {
796 - const agentDir = getAgentDir();
797 - const settingsManager = SettingsManager.create(cwd, agentDir);
798 - const ext = loaded.options.extensions;
799 - const loader = new DefaultResourceLoader({
800 - cwd,
801 - agentDir,
802 - settingsManager,
803 - additionalSkillPaths: [path.join(EXT_DIR, "skills")],
804 - additionalPromptTemplatePaths: [path.join(EXT_DIR, "prompts")],
805 - noExtensions: !ext,
806 - extensionsOverride: ext
807 - ? (base) => ({
808 - ...base,
809 - extensions: base.extensions.filter(
810 - (e) => (resolveNames(ext, [extName(e.path)])?.length ?? 0) > 0,
811 - ),
812 - })
813 - : undefined,
814 - });
815 - await loader.reload();
816 - const tools = resolveNames(loaded.options.tools, availableTools);
817 - const requested = loaded.options.model;
818 - const agentModel = modelFrom(requested, model);
819 - if (requested) {
820 - const [provider, ...id] = requested.split("/");
821 - const direct =
822 - provider && id.length ? getModel(provider, id.join("/")) : null;
823 - if (!direct?.provider) {
824 - notify(
825 - ctx,
826 - `warn: model "${requested}" not found, using fallback`,
827 - "warning",
828 - );
831 - const created = await createAgentSession({
832 - cwd,
833 - agentDir,
834 - model: agentModel,
835 - modelRegistry,
836 - thinkingLevel: (loaded.options.thinking ?? thinking) as never,
837 - settingsManager,
838 - resourceLoader: loader,
839 - sessionManager: SessionManager.create(cwd, sessionsDir(cwd), {
840 - parentSession: task.parentSession,
841 - }),
842 - ...(tools ? { tools } : { noTools: "all" as const }),
843 - });
844 - session = created.session;
845 - const rt = live.get(id);
846 - if (rt) {
847 - rt.abort = () => void session?.abort();
848 - rt.dispose = () => session?.dispose();
850 - let answer = "";
851 - const off = session.subscribe((e) => {
852 - if (gen !== generation || task.status !== "running") return;
853 - if (e.type === "tool_execution_start") {
854 - task.log.push(`${now()} tool ${e.toolName}`);
855 - task.updatedAt = now();
856 - writeTask(cwd, task);
857 - widget(ctx);
858 - } else if (e.type === "message_end" && e.message.role === "assistant")
859 - answer = text(e.message.content).trim();
860 - });
861 - try {
862 - await session.prompt(loaded.prompt, {
863 - source: "extension",
864 - expandPromptTemplates: false,
865 - });
866 - } finally {
867 - off();
869 - if (gen !== generation || task.status !== "running") return;
870 - task.result = answer;
871 - task.status = "done";
872 - task.updatedAt = now();
873 - task.log.push(`${task.updatedAt} done\n${task.result}`);
874 - } catch (err) {
875 - if (task.status === "running") {
876 - task.status = "error";
877 - task.updatedAt = now();
878 - task.log.push(`${task.updatedAt} error ${(err as Error).message}`);
880 - } finally {
881 - session?.dispose();
882 - live.delete(id);
883 - if (task.status !== "done") {
884 - await cleanupIsolate(task, pi);
886 - writeTask(cwd, task);
887 - logRun(cwd, task);
888 - if (gen === generation) {
889 - append(ctx, { kind: "task", task });
890 - widget(ctx);
893 - })();
896 -async function runAgent(
897 - name: string,
898 - args: string,
899 - ctx: ExtensionCommandContext,
900 - pi: ExtensionAPI,
901 -) {
902 - const share = args.includes("--share");
903 - const cleanArgs = args.replace(/--share/g, "").trim();
904 - const loaded = loadAgent(ctx.cwd, name, cleanArgs);
905 - if (!loaded) return notify(ctx, `agent not found: ${name}`, "error");
906 - return startAgent(name, loaded, ctx, pi, share);
909 -async function inlineAgent(
910 - prompt: string,
911 - ctx: ExtensionCommandContext,
912 - pi: ExtensionAPI,
913 -) {
914 - if (!prompt.trim())
915 - return notify(ctx, "usage: /superpowers agent <prompt>", "error");
916 - return startAgent(
917 - "inline",
918 - { prompt, options: { tools: ["*"], thinking: "off" } },
919 - ctx,
920 - pi,
921 - false,
922 - );
925 -async function openTask(id: string, ctx: ExtensionCommandContext) {
926 - const t = readTasks(ctx.cwd)[id.trim()];
927 - if (!t) return notify(ctx, `no such task: ${id.trim()}`, "error");
928 - if (ctx.hasUI)
929 - await ctx.ui.editor(
930 - `superpowers ${t.id}`,
932 - `# ${t.id} ${t.status}`,
933 - `agent: ${t.agent}`,
934 - `parent: ${t.parentSession ?? "none"}`,
935 - "",
936 - ...t.log,
937 - ].join("\n"),
938 - );
940 -async function branchTask(id: string, ctx: ExtensionCommandContext) {
941 - const task = readTasks(ctx.cwd)[id.trim()];
942 - if (!task) return notify(ctx, `no such task: ${id.trim()}`, "error");
943 - if (!task.parentSession)
944 - return notify(
945 - ctx,
946 - "/superpowers branch requires persisted parent session",
947 - "error",
948 - );
949 - const rt = live.get(task.id);
950 - if (rt) {
951 - stopRuntime(rt, "branched");
952 - live.delete(task.id);
954 - stopPeers(task.id);
955 - task.status = "branched";
956 - task.updatedAt = now();
957 - task.log.push(`${task.updatedAt} branched`);
958 - writeTask(ctx.cwd, task);
959 - append(ctx, { kind: "task", task });
960 - await ctx.waitForIdle();
961 - const r = await ctx.newSession({
962 - parentSession: task.parentSession,
963 - withSession: async (child) => {
964 - task.childSession = child.sessionManager.getSessionFile();
965 - writeTask(child.cwd, task);
966 - append(child, { kind: "child", task });
967 - if (child.hasUI)
968 - (child.ui as any).setWidget?.(WIDGET, [
969 - `superpowers child ${task.id}`,
970 - "return with: /superpowers return <summary>",
971 - ]);
972 - await child.sendMessage(
974 - customType: ID,
975 - display: true,
976 - content: childPrompt(task),
977 - details: { taskId: task.id },
978 - },
979 - { triggerTurn: false },
980 - );
981 - },
982 - });
983 - if (r.cancelled) notify(ctx, "branch cancelled", "warning");
985 -async function returnTask(summary: string, ctx: ExtensionCommandContext) {
986 - const task = latestChild(ctx);
987 - if (!task?.parentSession)
988 - return notify(ctx, "not in a superpowers child", "warning");
989 - const childSession = ctx.sessionManager.getSessionFile();
990 - await ctx.switchSession(task.parentSession, {
991 - withSession: async (parent) => {
992 - append(parent, {
993 - kind: "return",
994 - taskId: task.id,
995 - summary,
996 - childSession,
997 - });
998 - if (parent.hasUI) parent.ui.setWidget(WIDGET, undefined);
999 - await parent.sendMessage(
1001 - customType: ID,
1002 - display: true,
1003 - content: `Superpowers return ${task.id}\n\n${summary}\n\nChild session: ${childSession ?? "unknown"}`,
1004 - details: { taskId: task.id, childSession },
1005 - },
1006 - { triggerTurn: false },
1007 - );
1008 - },
1009 - });
1011 -function status(ctx: ExtensionCommandContext, id = "") {
1012 - const tasks = readTasks(ctx.cwd);
1013 - const key = id.trim();
1014 - if (key) {
1015 - const t = tasks[key];
1016 - notify(
1017 - ctx,
1018 - t ? taskDetails(t) : `no such task: ${key}`,
1019 - t ? "info" : "error",
1020 - );
1021 - widget(ctx);
1022 - return;
1024 - const xs = Object.values(tasks);
1025 - notify(
1026 - ctx,
1027 - [activeMessage(), ...(xs.length ? xs.map(summaryLine) : ["no tasks"])].join(
1028 - "\n",
1029 - ),
1030 - );
1031 - widget(ctx);
1033 -function activeMessage() {
1034 - return active ? "superpowers on" : "superpowers off";
1036 -function setActive(ctx: ExtensionCommandContext, value: boolean) {
1037 - active = value;
1038 - widget(ctx);
1039 - notify(ctx, activeMessage());
1041 -function toggle(ctx: ExtensionCommandContext) {
1042 - setActive(ctx, !active);
1044 -async function announceVisualSession(pi: ExtensionAPI, session: VisualSession) {
1045 - const agentMsg = [
1046 - "Superpowers visual brainstorming",
1047 - "",
1048 - `visual live: ${session.url}`,
1049 - `content: ${session.contentDir}`,
1050 - `events file: ${session.eventsFile}`,
1051 - "",
1052 - "Agent rules:",
1053 - "- Use visual only for active user decisions: options, mockups, diagrams, layouts.",
1054 - "- Do not use visual as progress reporting, implementation summary, final report, or proof slide.",
1055 - "- Every screen must ask a clear question or show something the user should judge.",
1056 - "- Use data-choice on clickable choices; the browser records clicks automatically.",
1057 - "- After writing a decision screen, wait for terminal answer or browser event before implementing.",
1058 - "- Read the events file directly when interpreting browser feedback.",
1059 - "- When done with visual decisions, write a waiting screen: Continuing in terminal…",
1060 - "- Ask whether to leave the browser open for inspection or stop it.",
1061 - ].join("\n");
1062 - await Promise.resolve(
1063 - pi.sendMessage(
1065 - customType: ID,
1066 - display: true,
1067 - content: agentMsg,
1068 - details: {
1069 - url: session.url,
1070 - contentDir: session.contentDir,
1071 - eventsFile: session.eventsFile,
1072 - },
1073 - },
1074 - { triggerTurn: false },
1075 - ),
1076 - );
1079 -async function visualCommand(
1080 - args: string,
1081 - ctx: ExtensionCommandContext,
1082 - pi: ExtensionAPI,
1083 -) {
1084 - const [sub = "status"] = args.trim().split(/\s+/);
1085 - if (sub === "start") {
1086 - if (visual) {
1087 - notify(
1088 - ctx,
1089 - `visual already live: ${visual.url}\ncontent: ${visual.contentDir}\nevents file: ${visual.eventsFile}`,
1090 - );
1091 - await announceVisualSession(pi, visual);
1092 - return;
1094 - visual = await startVisualServer({ root: dir(ctx.cwd) });
1095 - widget(ctx);
1096 - const opened = await openBrowser(visual.url);
1097 - const msg = [
1098 - `visual live: ${visual.url}`,
1099 - `content: ${visual.contentDir}`,
1100 - `events file: ${visual.eventsFile}`,
1101 - opened.ok
1102 - ? `opened: ${opened.command}`
1103 - : `open manually: ${opened.error}`,
1104 - ].join("\n");
1105 - notify(ctx, msg, opened.ok ? "info" : "warning");
1106 - await announceVisualSession(pi, visual);
1107 - return;
1109 - if (sub === "stop") {
1110 - if (!visual) return notify(ctx, "no visual session", "warning");
1111 - visual.close();
1112 - visual = undefined;
1113 - widget(ctx);
1114 - notify(ctx, "visual stopped");
1115 - return;
1117 - if (sub === "events") {
1118 - if (!visual) return notify(ctx, "no visual session", "warning");
1119 - const events = existsSync(visual.eventsFile)
1120 - ? readFileSync(visual.eventsFile, "utf8")
1121 - : "";
1122 - if (ctx.hasUI)
1123 - await ctx.ui.editor("superpowers visual events", events || "no events");
1124 - else notify(ctx, events || "no events");
1125 - return;
1127 - if (!visual)
1128 - return notify(
1129 - ctx,
1130 - "no visual session. use /superpowers visual start",
1131 - "warning",
1132 - );
1133 - notify(
1134 - ctx,
1135 - `visual live: ${visual.url}\ncontent: ${visual.contentDir}\nevents file: ${visual.eventsFile}`,
1136 - );
1139 -function help(ctx: ExtensionCommandContext) {
1140 - notify(
1141 - ctx,
1143 - "⚡ superpowers",
1144 - "toggle: /superpowers | on | off",
1145 - "status: /superpowers status [id]",
1146 - "workers: run <agent> [--share] | agent <prompt> | abort <id> | open <id>",
1147 - "session: branch <id> | return <summary>",
1148 - "workflows: design | plan | execute | debug | review | deslop | compress | verify | parallel | git | meta",
1149 - "visual: start | status | events | stop",
1150 - ].join("\n"),
1151 - );
1154 -export default function (pi: ExtensionAPI) {
1155 - api = pi;
1156 - pi.registerFlag("superpowers", {
1157 - description: "Activate Superpowers workflow discipline for this Pi run",
1158 - type: "boolean",
1159 - default: false,
1160 - });
1161 - pi.on("before_agent_start", (event) => {
1162 - if (!active && !pi.getFlag("superpowers")) return;
1163 - if (event.systemPrompt.includes("Superpowers active. Strict mode.")) return;
1164 - return { systemPrompt: event.systemPrompt + FLAG_PROMPT };
1165 - });
1166 - pi.on("session_start", async (_e, ctx) => {
1167 - generation++;
1168 - active = Boolean(pi.getFlag("superpowers"));
1169 - currentCwd = ctx.cwd;
1170 - const ids = Object.keys(readTasks(ctx.cwd))
1171 - .map((id) => Number(id.slice(3)))
1172 - .filter(Number.isFinite);
1173 - next = Math.max(next, 1 + Math.max(0, ...ids));
1174 - reapStale(ctx.cwd);
1175 - widget(ctx);
1176 - });
1177 - pi.on("session_shutdown", async () => {
1178 - generation++;
1179 - visual?.close();
1180 - visual = undefined;
1181 - stopAll();
1182 - pi.events.emit("footer:segment", { id: STATUS_ID, text: undefined });
1183 - });
1184 - pi.registerCommand("superpowers", {
1185 - description: "Run background agents and branch into them",
1186 - getArgumentCompletions(input: string) {
1187 - const parts = input.trimStart().split(/\s+/);
1188 - const [cmd = "", q = ""] = parts;
1189 - if (parts.length === 1 && !input.endsWith(" "))
1190 - return COMMANDS.filter((s) => s.startsWith(cmd)).map((s) => ({
1191 - value: s,
1192 - label: s,
1193 - }));
1194 - if (parts.length !== 2) return [];
1195 - if (cmd === "run")
1196 - return agentNames(currentCwd)
1197 - .filter((n) => n.startsWith(q))
1198 - .map((n) => ({ value: `run ${n}`, label: n }));
1199 - if (["open", "branch", "abort", "status"].includes(cmd))
1200 - return Object.keys(readTasks(currentCwd))
1201 - .filter((id) => id.startsWith(q))
1202 - .map((id) => ({ value: `${cmd} ${id}`, label: id }));
1203 - return [];
1204 - },
1205 - async handler(args, ctx) {
1206 - currentCwd = ctx.cwd;
1207 - const raw = args.trim();
1208 - if (!raw) return toggle(ctx);
1209 - const [cmd = "", ...rest] = raw.split(/\s+/);
1210 - const tail = rest.join(" ");
1211 - if (cmd === "run") {
1212 - const [name = "", ...xs] = rest;
1213 - return runAgent(name, xs.join(" "), ctx, pi);
1215 - if (cmd === "agent") return inlineAgent(tail, ctx, pi);
1216 - if (cmd === "open") return openTask(tail, ctx);
1217 - if (cmd === "branch") return branchTask(tail, ctx);
1218 - if (cmd === "return") return returnTask(tail, ctx);
1219 - if (cmd === "abort") {
1220 - const t = live.get(tail.trim());
1221 - if (!t)
1222 - return notify(ctx, `no running task: ${tail.trim()}`, "warning");
1223 - t.abort?.();
1224 - t.dispose?.();
1225 - t.task.status = "aborted";
1226 - t.task.updatedAt = now();
1227 - t.task.log.push(`${t.task.updatedAt} aborted by user`);
1228 - writeTask(ctx.cwd, t.task);
1229 - live.delete(t.task.id);
1230 - widget(ctx);
1231 - return notify(ctx, `aborted ${t.task.id}`);
1233 - if (cmd === "on") return setActive(ctx, true);
1234 - if (cmd === "off") return setActive(ctx, false);
1235 - if (cmd === "visual") return visualCommand(tail, ctx, pi);
1236 - if (cmd in ALIASES) return runAgent(ALIASES[cmd], tail, ctx, pi);
1237 - if (cmd === "help") return help(ctx);
1238 - return status(ctx, tail);
1239 - },
1240 - });
1243 -export const __test = {
1244 - parseAgentFile,
1245 - resolveNames,
1246 - childPrompt,
1247 - summaryLine,
1248 - taskDetails,
1249 - platformStateDir,
1250 - hashProjectRoot,
1251 - tasksFile,
1252 - dir,
1253 - detectRepo,
1254 - createIsolate,
1255 - cleanupIsolate,

extensions/superpowers/package.json

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

extensions/superpowers/prompts/brainstorming.md

Deleted
deleted 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 -accent: accent
7 ----
9 -# Brainstorming
11 -Design before code.
12 -No exceptions for “simple” work.
14 -## Hard gate
16 -Do not implement, scaffold, edit production code, or invoke implementation
17 -workflows until:
19 -1. design was presented,
20 -2. user approved it,
21 -3. spec was written,
22 -4. spec self-review passed,
23 -5. user approved the written spec.
25 -Tiny tasks may have tiny designs.
26 -They still need approval.
28 -## Flow
30 -1. Explore project context.
31 - - read relevant docs/files
32 - - inspect current structure
33 - - note constraints and existing patterns
34 - - inspect recent commits if useful
35 -2. If visual questions are likely, offer visual companion in its own message.
36 -3. Ask clarifying questions one at a time.
37 -4. Propose 2-3 approaches with tradeoffs.
38 -5. Recommend one.
39 -6. Present design in small sections.
40 -7. Ask approval after each section.
41 -8. Write spec to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` unless
42 - project rules say otherwise.
43 -9. Self-review spec; fix placeholders, contradictions, ambiguity, overscope.
44 -10. Commit the spec when project workflow uses git and project rules allow it.
45 -11. Ask user to review spec file.
46 -12. After approval, hand off only to `writing-plans`.
48 -## Question rules
50 -- One question per message.
51 -- Multiple choice preferred.
52 -- Ask only blocking questions.
53 -- If request is too large, decompose first; brainstorm one subproject.
55 -## Design sections
57 -Scale section length to complexity.
58 -Cover only relevant sections:
60 -- goal and non-goals
61 -- UX/API behavior
62 -- architecture/components
63 -- data flow/state
64 -- component boundaries:
65 - single responsibility, clear interfaces, independent tests
66 -- errors/failure modes
67 -- testing/proof
68 -- migration/rollout, only if truly needed
70 -## Spec self-review
72 -Before user review, check:
74 -- `TODO`, `TBD`, placeholders
75 -- contradictions
76 -- unclear ownership or boundaries
77 -- requirements that can be interpreted two ways
78 -- scope too large for one implementation plan
79 -- missing verification strategy
81 -Fix inline before asking user.
83 -## Output checkpoints
85 -```text
86 -BRAINSTORM_CONTEXT
87 -- existing patterns: ...
88 -- constraints: ...
89 -- visual companion: useful | not useful
90 -```
92 -```text
93 -BRAINSTORM_OPTIONS
94 -- recommendation: ...
95 -- options:
96 - 1. ... tradeoff ...
97 - 2. ... tradeoff ...
98 -```
100 -```text
101 -DESIGN_SECTION n/N — <name>
102 -...
103 -Approve / edit?
104 -```
106 -```text
107 -SPEC_READY
108 -- path: docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md
109 -- self-review: passed
110 -- next after approval: /writing-plans <path>
111 -```
113 -## Anti-patterns
115 -- Coding during brainstorming.
116 -- Dumping a giant spec without section approval.
117 -- Asking five questions at once.
118 -- “This is too simple for design.”
119 -- Generic scalable/flexible fluff.
120 -- Unrelated refactors while touching existing code.
121 -- Writing a spec full of hedges instead of decisions.
123 -## Visual companion
125 -Use only when seeing beats reading:
126 -mockups, layouts, palettes, diagrams, side-by-side UX choices.
128 -This is an active decision aid, not a reporting dashboard.
129 -Every visual screen must either ask a question, present selectable options, or
130 -show a mockup/diagram the user is meant to judge.
131 -Do not use it for progress updates, implementation summaries, final reports, or
132 -proof-of-work slides.
134 -Offer in its own message:
136 -```text
137 -Some of this may be easier to judge visually. I can open a local browser companion for mockups/diagrams/options. Use it?
138 -```
140 -If user accepts:
142 -1. Ask user to run `/superpowers visual start` if not already live.
143 -2. Use returned `content` dir.
144 -3. Write one fresh `.html` fragment per decision screen.
145 -4. Each screen must include a clear prompt/question and obvious clickable
146 - choices when choice is useful.
147 -5. Use `data-choice="..."` on clickable options; the browser records those
148 - clicks automatically.
149 -6. Tell user the URL and the exact decision you need from the screen.
150 -7. Ask user to click/select if useful and answer in terminal.
151 -8. Wait for a terminal answer or browser event before implementing from a visual
152 - decision screen.
153 -9. Read the events file path announced by `/superpowers visual start` directly
154 - when interpreting browser feedback.
155 -10. After the visual decision is resolved, push a waiting screen saying
156 - `Continuing in terminal…` before returning to text-only discussion.
157 -11. At the end of the visual phase, ask whether to leave the browser companion
158 - open for inspection or stop it with `/superpowers visual stop`.
160 -Visual state is ephemeral platform state, not project files.
161 -Specs/design docs remain project files when approved.
163 -Target:
165 -$ARGUMENTS

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

Deleted
deleted 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 -accent: syntaxVariable
7 ----
9 -# Dispatching Parallel Agents
11 -Parallel only when independent.
12 -One worker per independent problem domain.
14 -## Independence test
16 -Tasks are parallelizable if:
18 -- no task needs another task's output
19 -- no two tasks edit same file/region
20 -- failures can be understood separately
22 -If not, run sequentially.
24 -## Worker prompt must include
26 -- shared context
27 -- exact scope
28 -- allowed files
29 -- forbidden files/actions
30 -- verification command
31 -- required return format
32 -- enough context so worker does not need session history
34 -## Output
36 -```text
37 -DISPATCH_PLAN
38 -- shared context: ...
39 -- workers:
40 - - /superpowers run <prompt> ...
41 -- merge order: ...
42 -- conflicts: ...
43 -- final verify: ...
44 -```
46 -After workers return:
47 -read summaries, inspect changed files, check conflicts, run final verification.
49 -## Law
51 -Benchmark prompts must stay fair/profile-neutral.
52 -Do not steer toward a tool just to make an extension look good.
54 -Target:
56 -$ARGUMENTS

extensions/superpowers/prompts/executing-plans.md

Deleted
deleted 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 -accent: success
7 ----
9 -# Executing Plans
11 -Implement plan.
12 -Do not improvise silently.
14 -## Loop
16 -1. Read the whole plan.
17 -2. Review it critically for gaps, contradictions, missing files/commands.
18 -3. Inspect current state.
19 -4. Run baseline check if cheap.
20 -5. Execute 1-3 plan steps exactly.
21 -6. Run listed verification.
22 -7. Record changed files and evidence.
23 -8. Stop if verification fails.
24 -9. If plan is wrong, report exact mismatch and minimal correction.
26 -## Output per batch
28 -```text
29 -BATCH_DONE
30 -- tasks: ...
31 -- changed: ...
32 -- verify: command → result
33 -- next: ...
34 -```
36 -## Forbidden
38 -- Big-bang edits.
39 -- Claiming “done” without `verification-before-completion`.
40 -- Changing scope because it “seemed useful”.
41 -- Starting implementation on `main`/`master` without explicit user consent.
42 -- Guessing through blockers instead of asking.
44 -Target:
46 -$ARGUMENTS

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

Deleted
deleted 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 -accent: dim
7 ----
9 -# Finishing a Development Branch
11 -Finish cleanly.
13 -## Steps
15 -1. Inspect `git status`, diff, recent commits, branch, and worktree state.
16 -2. Run full verification before offering completion choices.
17 -3. If tests fail, stop and report failures.
18 -4. Summarize changes and evidence.
19 -5. Present options exactly:
20 - - merge locally
21 - - push/open PR
22 - - keep branch/worktree
23 - - discard
24 -6. Cleanup only after explicit choice.
25 -7. For discard, require typed confirmation.
26 -8. Remove only worktrees this workflow owns; never delete harness-owned
27 - workspace.
29 -## Output
31 -```text
32 -BRANCH_FINISH
33 -- branch: ...
34 -- status: clean | dirty
35 -- changes: ...
36 -- verify: ...
37 -- risks: ...
38 -- options: merge | PR | keep | discard
39 -```
41 -Target:
43 -$ARGUMENTS

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

Deleted
deleted 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 -accent: syntaxFunction
7 ----
9 -# Receiving Code Review
11 -Address review without churn.
13 -## Process
15 -1. Read all feedback before reacting.
16 -2. Restate or clarify unclear findings before implementing anything.
17 -3. Verify each finding against the codebase.
18 -4. List findings by severity.
19 -5. Fix BLOCKER and MAJOR first, one item at a time.
20 -6. Reject invalid findings only with evidence.
21 -7. Do not touch unrelated code.
22 -8. Add tests when behavior changes.
23 -9. Rerun verification.
25 -## Output
27 -```text
28 -REVIEW_RESPONSE
29 -- fixed: ...
30 -- rejected: finding → evidence
31 -- changed: ...
32 -- tests: ...
33 -- remaining: none | ...
34 -```
36 -## Anti-patterns
38 -- Performative agreement before checking:
39 - “absolutely right”, “great point”.
40 -- Blindly implementing external review without codebase verification.
41 -- Rewriting whole module to fix one finding.
42 -- “Addressed” without commit/file/test evidence.
43 -- Adding unused “professional” features instead of applying YAGNI.
45 -Target:
47 -$ARGUMENTS

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

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

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

Deleted
deleted 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 -accent: syntaxVariable
7 ----
9 -# Subagent-Driven Development
11 -Workers implement.
12 -Parent owns quality.
13 -Continue task-by-task without “should I continue?” check-ins unless blocked.
15 -## Process
17 -1. Require approved spec/plan.
18 - If absent, use `brainstorming` or `writing-plans`.
19 -2. Extract each task with full text and needed context.
20 -3. Create one worker prompt per bounded task.
21 - Do not make worker read the whole plan if the task text can be provided.
22 -4. Run worker with `/superpowers run <prompt> ...`.
23 -5. Inspect result with `/superpowers status <id>` or `/superpowers open <id>`.
24 -6. Handle worker state:
25 - done → review; needs-context → provide context; blocked → change
26 - prompt/model/scope or escalate.
27 -7. Review twice, in order:
28 - - spec compliance
29 - - code quality/simplicity
30 -8. Fix concrete issues and re-review before next task.
31 -9. Run final verification.
33 -## Review gates
35 -- Spec miss → send back/fix before next task.
36 -- Overbuilt code → simplify.
37 -- No tests/evidence → incomplete.
38 -- Multiple implementation workers editing overlapping files → forbidden.
40 -## Return format
42 -```text
43 -SDD_DONE
44 -- workers: ...
45 -- accepted: ...
46 -- rejected/fixed: ...
47 -- tests: ...
48 -- evidence: ...
49 -```
51 -Target:
53 -$ARGUMENTS

extensions/superpowers/prompts/systematic-debugging.md

Deleted
deleted 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 -accent: warning
7 ----
9 -# Systematic Debugging
11 -No fix before root-cause evidence.
13 -## Phases
15 -1. Reproduce:
16 - exact command/input and observed failure.
17 - If not reproducible, gather more data; do not guess.
18 -2. Read errors fully; check recent changes and relevant config/env.
19 -3. Pattern analysis:
20 - find working examples and compare exact differences.
21 -4. Trace:
22 - follow data/control flow to root cause.
23 -5. Hypothesis:
24 - one cause, one prediction, one test.
25 -6. Fix:
26 - smallest root-cause change, preferably after a failing regression test.
27 -7. Verify:
28 - original failure + nearby regression.
30 -## Three-strike rule
32 -After 3 failed fixes, stop.
33 -Request architecture/design review.
35 -## Output
37 -```text
38 -DEBUG_DONE
39 -- repro: ...
40 -- evidence: ...
41 -- root cause: ...
42 -- fix: ...
43 -- verify: ...
44 -- failed attempts: N
45 -```
47 -## Forbidden
49 -- Guess-and-patch.
50 -- “Maybe race condition” without trace.
51 -- Multiple changes at once while testing a hypothesis.
52 -- Broad rewrites before root cause.
54 -Target:
56 -$ARGUMENTS

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

Deleted
deleted 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 -accent: syntaxString
7 ----
9 -# Test-Driven Development
11 -RED first.
12 -No production code without a failing test first.
14 -If production code was written first, delete it and restart from RED.
15 -Do not keep it as reference.
17 -## Loop
19 -1. Write smallest failing test.
20 -2. Run it.
21 - Confirm failure is expected.
22 -3. Implement smallest passing code.
23 -4. Run focused test.
24 - Green.
25 -5. Refactor only to simplify.
26 -6. Run focused test again.
27 -7. Run relevant full suite.
29 -## Stop if
31 -- Test passes before implementation → bad test.
32 -- Failure is unrelated → fix test/setup first.
33 -- Implementation grows abstractions → cut it down.
34 -- User explicitly forbids tests → state risk and use manual proof.
35 -- Test needs heavy mocks → simplify API/design first.
37 -## Output
39 -```text
40 -TDD_DONE
41 -- red: command + expected failure
42 -- green: command + pass
43 -- refactor: yes/no
44 -- full verify: ...
45 -- files: ...
46 -```
48 -Target:
50 -$ARGUMENTS

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

Deleted
deleted 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 -accent: muted
7 ----
9 -# Using Git Worktrees
11 -Protect trunk.
12 -Isolate risk.
14 -## Before creating
16 -First detect existing isolation:
18 -```bash
19 -git rev-parse --git-dir
20 -git rev-parse --git-common-dir
21 -git rev-parse --show-superproject-working-tree 2>/dev/null
22 -```
24 -If already in a linked worktree and not a submodule, do not create another.
26 -Record:
28 -- current branch
29 -- HEAD
30 -- remote/upstream
31 -- dirty status
32 -- likely trunk (`main`, `master`, `trunk`, `develop`)
34 -If current worktree is dirty, do not hide it.
35 -Ask or choose a safe path.
37 -## Process
39 -1. Prefer host/native worktree tools if available.
40 -2. Pick branch name from task.
41 -3. Create worktree outside current directory.
42 -4. If using project-local `.worktrees/` or `worktrees/`, verify path is
43 - gitignored first.
44 -5. Run setup/baseline tests there.
45 -6. Do implementation only in worktree.
46 -7. Finish with `finishing-a-development-branch`.
48 -## Output
50 -```text
51 -WORKTREE_READY
52 -- trunk: ...
53 -- branch: ...
54 -- path: ...
55 -- baseline: command → result
56 -```
58 -Target:
60 -$ARGUMENTS

extensions/superpowers/prompts/using-superpowers.md

Deleted
deleted 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 -accent: accent
7 ----
9 -# Using Superpowers
11 -Superpowers = process discipline.
12 -Not vibes.
14 -## Rule
16 -Before non-trivial work, choose and follow one workflow skill:
18 -| Situation | Skill |
19 -| ---------------------------------- | -------------------------------- |
20 -| fuzzy feature/design | `brainstorming` |
21 -| approved design → tasks | `writing-plans` |
22 -| plan exists → implement | `executing-plans` |
23 -| independent subtasks | `dispatching-parallel-agents` |
24 -| worker + review loop | `subagent-driven-development` |
25 -| code change with testable behavior | `test-driven-development` |
26 -| bug/regression/flake | `systematic-debugging` |
27 -| before saying done | `verification-before-completion` |
28 -| isolated branch needed | `using-git-worktrees` |
29 -| branch is complete | `finishing-a-development-branch` |
30 -| creating/revising skills | `writing-skills` |
32 -Load the selected skill before acting.
33 -If multiple skills apply, use the earliest lifecycle gate:
34 -brainstorming → writing-plans → execution/TDD/debug → review → verification →
35 -finishing.
37 -## Local style
39 -- Simplicity/minimalism/brutalism.
40 -- Evidence > claims.
41 -- Exact files/commands > summaries.
42 -- No legacy/compat/edge-case bloat unless required.
43 -- User instructions override skills unless unsafe/impossible.
45 -## Red flags
47 -Stop and load a workflow if you are about to:
49 -- implement a fuzzy request without design approval
50 -- fix a bug without root-cause evidence
51 -- claim done without fresh verification
52 -- accept worker/reviewer output without checking evidence
54 -## Superpowers workers
56 -Use normal prompt templates:
58 -```text
59 -/<prompt> ...
60 -/superpowers run <prompt> ...
61 -```
63 -Use workers for isolated investigation/implementation.
64 -Parent integrates.
66 -Target:
68 -$ARGUMENTS

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

Deleted
deleted 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 -accent: toolTitle
7 ----
9 -# Verification Before Completion
11 -No fresh proof → not done.
12 -Evidence before claims.
14 -## Checklist
16 -- Changed files match scope.
17 -- Relevant tests/build/lint were run fresh.
18 -- Full output/exit code was read, not assumed.
19 -- Manual/UI requirements were actually exercised.
20 -- Artifacts exist and are executable/readable when required.
21 -- Docs match behavior.
22 -- No stray debug processes/files unless intentional.
24 -## Output
26 -```text
27 -VERIFIED
28 -- verdict: complete | incomplete
29 -- commands: ...
30 -- evidence: ...
31 -- changed: ...
32 -- remaining: none | ...
33 -```
35 -## Forbidden
37 -- “Should work.”
38 -- “Looks good.”
39 -- Passing unit tests when manual criterion was required.
40 -- Redefining success smaller.
41 -- Trusting worker/agent success without checking diff and evidence.
42 -- Regression test claimed without red-green proof when applicable.
44 -Target:
46 -$ARGUMENTS

extensions/superpowers/prompts/writing-plans.md

Deleted
deleted 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 -accent: dim
7 ----
9 -# Writing Plans
11 -Plan for a fast careless implementer with zero project context.
13 -Save plans to `docs/superpowers/plans/YYYY-MM-DD-<feature>.md` unless project
14 -rules say otherwise.
16 -## Task requirements
18 -Each task must include:
20 -- exact files
21 -- concrete edit/action
22 -- complete code or command for the step
23 -- expected result/output
24 -- verification command
25 -- commit step when project workflow uses git
26 -- rollback/failure note if risky
28 -## Shape
30 -```text
31 -PLAN
32 -- scope: ...
33 -- invariants: ...
34 -- tasks:
35 - 1. files: ...
36 - action: ...
37 - verify: ...
38 -- checkpoints: ...
39 -- acceptance: ...
40 -```
42 -## Rules
44 -- 2-10 minute tasks.
45 -- Tests before behavior when possible.
46 -- Every batch leaves repo working.
47 -- Mark unknown decisions `[?]`; stop before passing them.
48 -- No `TODO`/`TBD`/`similar to task N`/`write tests for above` placeholders.
49 -- No “refactor architecture” without file-level detail.
50 -- Self-review plan against spec:
51 - coverage, placeholders, type/name consistency.
52 -- End by offering `subagent-driven-development` or `executing-plans`.
54 -Target:
56 -$ARGUMENTS

extensions/superpowers/prompts/writing-skills.md

Deleted
deleted 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 -accent: syntaxFunction
7 ----
9 -# Writing Skills
11 -Skills are operational memory.
12 -Keep them sharp.
14 -## Required shape
16 -```text
17 -skills/<name>/SKILL.md
18 -```
20 -Frontmatter:
22 -```yaml
23 -name: lowercase-hyphen-name
24 -description: Use when <specific trigger>. Does <specific outcome>.
25 -```
27 -## Body rules
29 -- Short enough to load.
30 -- Concrete steps.
31 -- Anti-patterns included.
32 -- Examples only when useful.
33 -- Link deeper refs instead of dumping.
34 -- Local style, not upstream prose.
36 -## Test
38 -Use TDD for skills:
39 -first write a case where current behavior would not load/follow the skill, then
40 -update the skill until it passes.
42 -Create trigger cases:
44 -- should use skill
45 -- should not use skill
46 -- ambiguous case
48 -## Description rules
50 -- Include concrete trigger keywords.
51 -- Do not put the whole workflow in the description.
52 -- Avoid vague descriptions like “useful for development”.
53 -- If reference material is long, put it in separate files and link it.
55 -## Output
57 -```text
58 -SKILL_DONE
59 -- path: ...
60 -- trigger: ...
61 -- body: ...
62 -- tests: ...
63 -```
65 -Target:
67 -$ARGUMENTS

extensions/superpowers/skills/brainstorming/SKILL.md

Deleted
deleted 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.
9 -No exceptions for “simple” work.
11 -## Hard gate
13 -Do not implement, scaffold, edit production code, or invoke implementation
14 -workflows until:
16 -1. design was presented,
17 -2. user approved it,
18 -3. spec was written,
19 -4. spec self-review passed,
20 -5. user approved the written spec.
22 -Tiny tasks may have tiny designs.
23 -They still need approval.
25 -## Flow
27 -1. Explore project context.
28 - - read relevant docs/files
29 - - inspect current structure
30 - - note constraints and existing patterns
31 - - inspect recent commits if useful
32 -2. If visual questions are likely, offer visual companion in its own message.
33 -3. Ask clarifying questions one at a time.
34 -4. Propose 2-3 approaches with tradeoffs.
35 -5. Recommend one.
36 -6. Present design in small sections.
37 -7. Ask approval after each section.
38 -8. Write spec to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` unless
39 - project rules say otherwise.
40 -9. Self-review spec; fix placeholders, contradictions, ambiguity, overscope.
41 -10. Commit the spec when project workflow uses git and project rules allow it.
42 -11. Ask user to review spec file.
43 -12. After approval, hand off only to `writing-plans`.
45 -## Question rules
47 -- One question per message.
48 -- Multiple choice preferred.
49 -- Ask only blocking questions.
50 -- If request is too large, decompose first; brainstorm one subproject.
52 -## Design sections
54 -Scale section length to complexity.
55 -Cover only relevant sections:
57 -- goal and non-goals
58 -- UX/API behavior
59 -- architecture/components
60 -- data flow/state
61 -- component boundaries:
62 - single responsibility, clear interfaces, independent tests
63 -- errors/failure modes
64 -- testing/proof
65 -- migration/rollout, only if truly needed
67 -## Spec self-review
69 -Before user review, check:
71 -- `TODO`, `TBD`, placeholders
72 -- contradictions
73 -- unclear ownership or boundaries
74 -- requirements that can be interpreted two ways
75 -- scope too large for one implementation plan
76 -- missing verification strategy
78 -Fix inline before asking user.
80 -## Output checkpoints
82 -```text
83 -BRAINSTORM_CONTEXT
84 -- existing patterns: ...
85 -- constraints: ...
86 -- visual companion: useful | not useful
87 -```
89 -```text
90 -BRAINSTORM_OPTIONS
91 -- recommendation: ...
92 -- options:
93 - 1. ... tradeoff ...
94 - 2. ... tradeoff ...
95 -```
97 -```text
98 -DESIGN_SECTION n/N — <name>
99 -...
100 -Approve / edit?
101 -```
103 -```text
104 -SPEC_READY
105 -- path: docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md
106 -- self-review: passed
107 -- next after approval: /writing-plans <path>
108 -```
110 -## Anti-patterns
112 -- Coding during brainstorming.
113 -- Dumping a giant spec without section approval.
114 -- Asking five questions at once.
115 -- “This is too simple for design.”
116 -- Generic scalable/flexible fluff.
117 -- Unrelated refactors while touching existing code.
118 -- Writing a spec full of hedges instead of decisions.
120 -## Visual companion
122 -Use only when seeing beats reading:
123 -mockups, layouts, palettes, diagrams, side-by-side UX choices.
125 -This is an active decision aid, not a reporting dashboard.
126 -Every visual screen must either ask a question, present selectable options, or
127 -show a mockup/diagram the user is meant to judge.
128 -Do not use it for progress updates, implementation summaries, final reports, or
129 -proof-of-work slides.
131 -Offer in its own message:
133 -```text
134 -Some of this may be easier to judge visually. I can open a local browser companion for mockups/diagrams/options. Use it?
135 -```
137 -If user accepts:
139 -1. Ask user to run `/superpowers visual start` if not already live.
140 -2. Use returned `content` dir.
141 -3. Write one fresh `.html` fragment per decision screen.
142 -4. Each screen must include a clear prompt/question and obvious clickable
143 - choices when choice is useful.
144 -5. Use `data-choice="..."` on clickable options; the browser records those
145 - clicks automatically.
146 -6. Tell user the URL and the exact decision you need from the screen.
147 -7. Ask user to click/select if useful and answer in terminal.
148 -8. Wait for a terminal answer or browser event before implementing from a visual
149 - decision screen.
150 -9. Read the events file path announced by `/superpowers visual start` directly
151 - when interpreting browser feedback.
152 -10. After the visual decision is resolved, push a waiting screen saying
153 - `Continuing in terminal…` before returning to text-only discussion.
154 -11. At the end of the visual phase, ask whether to leave the browser companion
155 - open for inspection or stop it with `/superpowers visual stop`.
157 -Visual state is ephemeral platform state, not project files.
158 -Specs/design docs remain project files when approved.

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

Deleted
deleted 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.
9 -One worker per independent problem domain.
11 -## Independence test
13 -Tasks are parallelizable if:
15 -- no task needs another task's output
16 -- no two tasks edit same file/region
17 -- failures can be understood separately
19 -If not, run sequentially.
21 -## Worker prompt must include
23 -- shared context
24 -- exact scope
25 -- allowed files
26 -- forbidden files/actions
27 -- verification command
28 -- required return format
29 -- enough context so worker does not need session history
31 -## Output
33 -```text
34 -DISPATCH_PLAN
35 -- shared context: ...
36 -- workers:
37 - - /superpowers run <prompt> ...
38 -- merge order: ...
39 -- conflicts: ...
40 -- final verify: ...
41 -```
43 -After workers return:
44 -read summaries, inspect changed files, check conflicts, run final verification.
46 -## Law
48 -Benchmark prompts must stay fair/profile-neutral.
49 -Do not steer toward a tool just to make an extension look good.

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

Deleted
deleted 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.
9 -Do not improvise silently.
11 -## Loop
13 -1. Read the whole plan.
14 -2. Review it critically for gaps, contradictions, missing files/commands.
15 -3. Inspect current state.
16 -4. Run baseline check if cheap.
17 -5. Execute 1-3 plan steps exactly.
18 -6. Run listed verification.
19 -7. Record changed files and evidence.
20 -8. Stop if verification fails.
21 -9. If plan is wrong, report exact mismatch and minimal correction.
23 -## Output per batch
25 -```text
26 -BATCH_DONE
27 -- tasks: ...
28 -- changed: ...
29 -- verify: command → result
30 -- next: ...
31 -```
33 -## Forbidden
35 -- Big-bang edits.
36 -- Claiming “done” without `verification-before-completion`.
37 -- Changing scope because it “seemed useful”.
38 -- Starting implementation on `main`/`master` without explicit user consent.
39 -- Guessing through blockers instead of asking.

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

Deleted
deleted 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
24 - workspace.
26 -## Output
28 -```text
29 -BRANCH_FINISH
30 -- branch: ...
31 -- status: clean | dirty
32 -- changes: ...
33 -- verify: ...
34 -- risks: ...
35 -- options: merge | PR | keep | discard
36 -```

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

Deleted
deleted 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:
36 - “absolutely right”, “great point”.
37 -- Blindly implementing external review without codebase verification.
38 -- Rewriting whole module to fix one finding.
39 -- “Addressed” without commit/file/test evidence.
40 -- Adding unused “professional” features instead of applying YAGNI.

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

Deleted
deleted 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.
9 -Do not edit.
11 -No politeness tax.
12 -No generic praise.
13 -Findings need evidence.
15 -## Inputs
17 -Establish:
19 -- target files/diff/plan
20 -- base/head commit range when available
21 -- user objective
22 -- relevant project rules
23 -- tests or proof expected
25 -If target is ambiguous, inspect likely changed files and state scope.
27 -## Pass 1 — Correctness Gate
29 -Check:
31 -- requested behavior implemented
32 -- logic errors, race/order bugs, off-by-one, bad state transitions
33 -- error paths and failure modes
34 -- API/CLI/UI contract drift
35 -- docs match behavior
37 -## Pass 2 — Test/Proof Gate
39 -Check:
41 -- tests prove behavior, not implementation trivia
42 -- failing paths covered when important
43 -- manual/UI proof exists when requested
44 -- benchmark/profiling exists for perf claims
45 -- no completion claim without evidence
47 -## Pass 3 — Deslop Gate
49 -Find LLM slop:
51 -- plausible but unverified APIs or assumptions
52 -- needless traits/classes/wrappers/pass-through layers
53 -- generic soup, global state, vague config
54 -- duplicated near-identical code with renamed variables
55 -- stringly typed domains where enum/newtype/validated shape fits
56 -- `unwrap`/`expect`/panic/swallowed errors/vague catch-all errors
57 -- missing docs/tests for public behavior or risky failure paths
58 -- insecure input/path/shell/env handling
60 -## Pass 4 — Compression Gate
62 -Find design compression opportunities:
64 -- repeated command handlers, parsers, errors, tests, data shapes
65 -- boilerplate that should become a helper/table/enum/data-driven path
66 -- overbroad abstractions hiding simple control flow
67 -- under-abstracted repeated logic likely to drift
68 -- dead layers, needless adapters, repeated conversions
70 -Compression is not code golf.
71 -Prefer one good abstraction over many clever ones.
73 -## Pass 5 — Handmade UX/Style Gate
75 -Check:
77 -- direct code, small functions, explicit state
78 -- no legacy/compat sludge unless required
79 -- no edge-case theater
80 -- readable names and boring control flow
81 -- UI is usable, high-contrast, keyboard-friendly, not ugly
82 -- performance avoids obvious allocations/O(n²)/N+1/process churn
84 -## Severity
86 -- BLOCKER:
87 - incorrect, unsafe, untested critical path, violates spec, or fake completion.
88 -- MAJOR:
89 - likely bug, bad API, serious slop, duplicated design risk, missing important
90 - proof.
91 -- MINOR:
92 - cleanup, naming, small simplification.
93 -- NOTE:
94 - observation, no action required.
96 -## Output
98 -```text
99 -REVIEW
100 -- verdict: pass | fail
101 -- scope: ...
102 -- blockers:
103 - - file:line — issue — required fix
104 -- major:
105 - - ...
106 -- minor:
107 - - ...
108 -- slop:
109 - - pattern — evidence — severity
110 -- compression:
111 - - repeated shape — proposed simpler shape — risk
112 -- tests/proof:
113 - - present: ...
114 - - missing: ...
115 -- required fixes: ...
116 -- verify: ...
117 -```
119 -## Follow-up
121 -- Critical/BLOCKER and MAJOR findings must be fixed or explicitly rejected with
122 - evidence before proceeding.
123 -- If findings exist:
124 - use `receiving-code-review`.
125 -- If fixes are large:
126 - write a plan first.
127 -- If review passes:
128 - run `verification-before-completion` before claiming shipped.

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

Deleted
deleted 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.
9 -Parent owns quality.
10 -Continue task-by-task without “should I continue?” check-ins unless blocked.
12 -## Process
14 -1. Require approved spec/plan.
15 - If absent, use `brainstorming` or `writing-plans`.
16 -2. Extract each task with full text and needed context.
17 -3. Create one worker prompt per bounded task.
18 - Do not make worker read the whole plan if the task text can be provided.
19 -4. Run worker with `/superpowers run <prompt> ...`.
20 -5. Inspect result with `/superpowers status <id>` or `/superpowers open <id>`.
21 -6. Handle worker state:
22 - done → review; needs-context → provide context; blocked → change
23 - prompt/model/scope or escalate.
24 -7. Review twice, in order:
25 - - spec compliance
26 - - code quality/simplicity
27 -8. Fix concrete issues and re-review before next task.
28 -9. Run final verification.
30 -## Review gates
32 -- Spec miss → send back/fix before next task.
33 -- Overbuilt code → simplify.
34 -- No tests/evidence → incomplete.
35 -- Multiple implementation workers editing overlapping files → forbidden.
37 -## Return format
39 -```text
40 -SDD_DONE
41 -- workers: ...
42 -- accepted: ...
43 -- rejected/fixed: ...
44 -- tests: ...
45 -- evidence: ...
46 -```

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

Deleted
deleted 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:
13 - exact command/input and observed failure.
14 - If not reproducible, gather more data; do not guess.
15 -2. Read errors fully; check recent changes and relevant config/env.
16 -3. Pattern analysis:
17 - find working examples and compare exact differences.
18 -4. Trace:
19 - follow data/control flow to root cause.
20 -5. Hypothesis:
21 - one cause, one prediction, one test.
22 -6. Fix:
23 - smallest root-cause change, preferably after a failing regression test.
24 -7. Verify:
25 - original failure + nearby regression.
27 -## Three-strike rule
29 -After 3 failed fixes, stop.
30 -Request architecture/design review.
32 -## Output
34 -```text
35 -DEBUG_DONE
36 -- repro: ...
37 -- evidence: ...
38 -- root cause: ...
39 -- fix: ...
40 -- verify: ...
41 -- failed attempts: N
42 -```
44 -## Forbidden
46 -- Guess-and-patch.
47 -- “Maybe race condition” without trace.
48 -- Multiple changes at once while testing a hypothesis.
49 -- Broad rewrites before root cause.

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

Deleted
deleted 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.
9 -No production code without a failing test first.
11 -If production code was written first, delete it and restart from RED.
12 -Do not keep it as reference.
14 -## Loop
16 -1. Write smallest failing test.
17 -2. Run it.
18 - Confirm failure is expected.
19 -3. Implement smallest passing code.
20 -4. Run focused test.
21 - Green.
22 -5. Refactor only to simplify.
23 -6. Run focused test again.
24 -7. Run relevant full suite.
26 -## Stop if
28 -- Test passes before implementation → bad test.
29 -- Failure is unrelated → fix test/setup first.
30 -- Implementation grows abstractions → cut it down.
31 -- User explicitly forbids tests → state risk and use manual proof.
32 -- Test needs heavy mocks → simplify API/design first.
34 -## Output
36 -```text
37 -TDD_DONE
38 -- red: command + expected failure
39 -- green: command + pass
40 -- refactor: yes/no
41 -- full verify: ...
42 -- files: ...
43 -```

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

Deleted
deleted 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.
9 -Isolate risk.
11 -## Before creating
13 -First detect existing isolation:
15 -```bash
16 -git rev-parse --git-dir
17 -git rev-parse --git-common-dir
18 -git rev-parse --show-superproject-working-tree 2>/dev/null
19 -```
21 -If already in a linked worktree and not a submodule, do not create another.
23 -Record:
25 -- current branch
26 -- HEAD
27 -- remote/upstream
28 -- dirty status
29 -- likely trunk (`main`, `master`, `trunk`, `develop`)
31 -If current worktree is dirty, do not hide it.
32 -Ask or choose a safe path.
34 -## Process
36 -1. Prefer host/native worktree tools if available.
37 -2. Pick branch name from task.
38 -3. Create worktree outside current directory.
39 -4. If using project-local `.worktrees/` or `worktrees/`, verify path is
40 - gitignored first.
41 -5. Run setup/baseline tests there.
42 -6. Do implementation only in worktree.
43 -7. Finish with `finishing-a-development-branch`.
45 -## Output
47 -```text
48 -WORKTREE_READY
49 -- trunk: ...
50 -- branch: ...
51 -- path: ...
52 -- baseline: command → result
53 -```

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

Deleted
deleted 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.
9 -Not vibes.
11 -## Rule
13 -Before non-trivial work, choose and follow one workflow skill:
15 -| Situation | Skill |
16 -| ---------------------------------- | -------------------------------- |
17 -| fuzzy feature/design | `brainstorming` |
18 -| approved design → tasks | `writing-plans` |
19 -| plan exists → implement | `executing-plans` |
20 -| independent subtasks | `dispatching-parallel-agents` |
21 -| worker + review loop | `subagent-driven-development` |
22 -| code change with testable behavior | `test-driven-development` |
23 -| bug/regression/flake | `systematic-debugging` |
24 -| before saying done | `verification-before-completion` |
25 -| isolated branch needed | `using-git-worktrees` |
26 -| branch is complete | `finishing-a-development-branch` |
27 -| creating/revising skills | `writing-skills` |
29 -Load the selected skill before acting.
30 -If multiple skills apply, use the earliest lifecycle gate:
31 -brainstorming → writing-plans → execution/TDD/debug → review → verification →
32 -finishing.
34 -## Local style
36 -- Simplicity/minimalism/brutalism.
37 -- Evidence > claims.
38 -- Exact files/commands > summaries.
39 -- No legacy/compat/edge-case bloat unless required.
40 -- User instructions override skills unless unsafe/impossible.
42 -## Red flags
44 -Stop and load a workflow if you are about to:
46 -- implement a fuzzy request without design approval
47 -- fix a bug without root-cause evidence
48 -- claim done without fresh verification
49 -- accept worker/reviewer output without checking evidence
51 -## Superpowers workers
53 -Use normal prompt templates:
55 -```text
56 -/<prompt> ...
57 -/superpowers run <prompt> ...
58 -```
60 -Use workers for isolated investigation/implementation.
61 -Parent integrates.

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

Deleted
deleted 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.
9 -Evidence before claims.
11 -## Checklist
13 -- Changed files match scope.
14 -- Relevant tests/build/lint were run fresh.
15 -- Full output/exit code was read, not assumed.
16 -- Manual/UI requirements were actually exercised.
17 -- Artifacts exist and are executable/readable when required.
18 -- Docs match behavior.
19 -- No stray debug processes/files unless intentional.
21 -## Output
23 -```text
24 -VERIFIED
25 -- verdict: complete | incomplete
26 -- commands: ...
27 -- evidence: ...
28 -- changed: ...
29 -- remaining: none | ...
30 -```
32 -## Forbidden
34 -- “Should work.”
35 -- “Looks good.”
36 -- Passing unit tests when manual criterion was required.
37 -- Redefining success smaller.
38 -- Trusting worker/agent success without checking diff and evidence.
39 -- Regression test claimed without red-green proof when applicable.

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

Deleted
deleted 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
11 -rules say otherwise.
13 -## Task requirements
15 -Each task must include:
17 -- exact files
18 -- concrete edit/action
19 -- complete code or command for the step
20 -- expected result/output
21 -- verification command
22 -- commit step when project workflow uses git
23 -- rollback/failure note if risky
25 -## Shape
27 -```text
28 -PLAN
29 -- scope: ...
30 -- invariants: ...
31 -- tasks:
32 - 1. files: ...
33 - action: ...
34 - verify: ...
35 -- checkpoints: ...
36 -- acceptance: ...
37 -```
39 -## Rules
41 -- 2-10 minute tasks.
42 -- Tests before behavior when possible.
43 -- Every batch leaves repo working.
44 -- Mark unknown decisions `[?]`; stop before passing them.
45 -- No `TODO`/`TBD`/`similar to task N`/`write tests for above` placeholders.
46 -- No “refactor architecture” without file-level detail.
47 -- Self-review plan against spec:
48 - coverage, placeholders, type/name consistency.
49 -- End by offering `subagent-driven-development` or `executing-plans`.

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

Deleted
deleted 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.
9 -Keep them sharp.
11 -## Required shape
13 -```text
14 -skills/<name>/SKILL.md
15 -```
17 -Frontmatter:
19 -```yaml
20 ----
21 -name: lowercase-hyphen-name
22 -description: Use when <specific trigger>. Does <specific outcome>.
23 ----
24 -```
26 -## Body rules
28 -- Short enough to load.
29 -- Concrete steps.
30 -- Anti-patterns included.
31 -- Examples only when useful.
32 -- Link deeper refs instead of dumping.
33 -- Local style, not upstream prose.
35 -## Test
37 -Use TDD for skills:
38 -first write a case where current behavior would not load/follow the skill, then
39 -update the skill until it passes.
41 -Create trigger cases:
43 -- should use skill
44 -- should not use skill
45 -- ambiguous case
47 -## Description rules
49 -- Include concrete trigger keywords.
50 -- Do not put the whole workflow in the description.
51 -- Avoid vague descriptions like “useful for development”.
52 -- If reference material is long, put it in separate files and link it.
54 -## Output
56 -```text
57 -SKILL_DONE
58 -- path: ...
59 -- trigger: ...
60 -- body: ...
61 -- tests: ...
62 -```

extensions/superpowers/visual.ts

Deleted
deleted file mode 100644
1 -import { spawn } from "node:child_process";
2 -import { randomBytes, randomUUID } from "node:crypto";
3 -import {
4 - appendFileSync,
5 - existsSync,
6 - mkdirSync,
7 - readdirSync,
8 - readFileSync,
9 - statSync,
10 - writeFileSync,
11 -} from "node:fs";
12 -import {
13 - createServer,
14 - type IncomingMessage,
15 - type Server,
16 - type ServerResponse,
17 -} from "node:http";
18 -import path from "node:path";
20 -export type VisualSession = {
21 - id: string;
22 - url: string;
23 - contentDir: string;
24 - stateDir: string;
25 - eventsFile: string;
26 - serverInfoFile: string;
27 - close(): void;
28 -};
30 -type StartVisualOptions = {
31 - root: string;
32 - preferredPort?: number;
33 -};
35 -const COOKIE = "pi_superpowers_visual";
36 -const BODY_LIMIT = 64 * 1024;
38 -export async function startVisualServer({
39 - root,
40 - preferredPort = 47718,
41 -}: StartVisualOptions): Promise<VisualSession> {
42 - const id = randomUUID();
43 - const token = randomBytes(32).toString("base64url");
44 - const sessionRoot = path.join(root, "visual", id);
45 - const contentDir = path.join(sessionRoot, "content");
46 - const stateDir = path.join(sessionRoot, "state");
47 - const eventsFile = path.join(stateDir, "events.jsonl");
48 - const serverInfoFile = path.join(stateDir, "server-info.json");
49 - mkdirSync(contentDir, { recursive: true });
50 - mkdirSync(stateDir, { recursive: true });
51 - writeFileSync(path.join(contentDir, "000-waiting.html"), waitingFragment());
52 - writeFileSync(eventsFile, "");
54 - let server!: Server;
55 - const authorized = (req: IncomingMessage, url: URL) =>
56 - url.searchParams.get("token") === token ||
57 - req.headers.authorization === `Bearer ${token}` ||
58 - (req.headers.cookie ?? "").split(/;\s*/).includes(`${COOKIE}=${token}`);
60 - server = createServer((req, res) => {
61 - void (async () => {
62 - try {
63 - const url = new URL(req.url ?? "/", "http://127.0.0.1");
64 - if (!authorized(req, url))
65 - return json(res, 401, { error: "unauthorized" });
66 - if (url.pathname === "/" && req.method === "GET") {
67 - res.setHeader(
68 - "Set-Cookie",
69 - `${COOKIE}=${token}; SameSite=Strict; Path=/`,
70 - );
71 - return html(
72 - res,
73 - frame(latestFragment(contentDir), latestStamp(contentDir)),
74 - );
75 - }
76 - if (url.pathname === "/api/latest" && req.method === "GET")
77 - return json(res, 200, latestStamp(contentDir));
78 - if (url.pathname === "/api/events" && req.method === "GET")
79 - return text(
80 - res,
81 - existsSync(eventsFile) ? readFileSync(eventsFile, "utf8") : "",
82 - );
83 - if (url.pathname === "/api/event" && req.method === "POST") {
84 - const body = await readBody(req);
85 - const event = JSON.parse(body || "{}");
86 - appendFileSync(
87 - eventsFile,
88 - `${JSON.stringify({ ...event, timestamp: Date.now() })}\n`,
89 - );
90 - return json(res, 200, { ok: true });
91 - }
92 - return json(res, 404, { error: "not found" });
93 - } catch (err) {
94 - return json(res, 500, {
95 - error: err instanceof Error ? err.message : String(err),
96 - });
97 - }
98 - })();
99 - });
100 - await listen(server, preferredPort);
101 - const address = server.address();
102 - if (!address || typeof address === "string")
103 - throw new Error("visual server failed to bind");
104 - const url = `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`;
105 - const info = { id, url, contentDir, stateDir, eventsFile };
106 - writeFileSync(serverInfoFile, `${JSON.stringify(info, null, "\t")}\n`);
107 - return { ...info, serverInfoFile, close: () => server.close() };
110 -export async function openBrowser(
111 - url: string,
112 -): Promise<{ ok: boolean; command?: string; error?: string }> {
113 - if (process.env.NODE_ENV === "test" || process.env.PI_SUPERPOWERS_NO_OPEN)
114 - return { ok: false, error: "browser opener disabled" };
115 - for (const candidate of openerCandidates(url)) {
116 - const result = await trySpawn(candidate.command, candidate.args);
117 - if (result.ok) return { ok: true, command: candidate.command };
118 - }
119 - return { ok: false, error: "no browser opener found" };
122 -function openerCandidates(
123 - url: string,
124 -): Array<{ command: string; args: string[] }> {
125 - if (process.env.TERMUX_VERSION)
126 - return [{ command: "termux-open-url", args: [url] }];
127 - if (process.platform === "darwin") return [{ command: "open", args: [url] }];
128 - if (process.platform === "win32")
129 - return [{ command: "cmd.exe", args: ["/c", "start", "", url] }];
130 - return [
131 - { command: "xdg-open", args: [url] },
132 - { command: "wslview", args: [url] },
133 - { command: "gio", args: ["open", url] },
134 - ];
137 -function trySpawn(
138 - command: string,
139 - args: string[],
140 -): Promise<{ ok: boolean; error?: string }> {
141 - return new Promise((resolve) => {
142 - const child = spawn(command, args, { detached: true, stdio: "ignore" });
143 - let settled = false;
144 - const done = (ok: boolean, error?: string) => {
145 - if (settled) return;
146 - settled = true;
147 - resolve({ ok, error });
148 - };
149 - child.once("error", (err) => done(false, err.message));
150 - child.once("spawn", () => {
151 - child.unref();
152 - done(true);
153 - });
154 - setTimeout(() => done(false, "timeout"), 1500).unref();
155 - });
158 -function listen(server: Server, preferredPort: number) {
159 - return new Promise<void>((resolve, reject) => {
160 - const onError = (err: NodeJS.ErrnoException) => {
161 - server.off("error", onError);
162 - if (err.code !== "EADDRINUSE") return reject(err);
163 - server.listen(0, "127.0.0.1", () => resolve());
164 - };
165 - server.once("error", onError);
166 - server.listen(preferredPort, "127.0.0.1", () => {
167 - server.off("error", onError);
168 - resolve();
169 - });
170 - });
173 -function latestFiles(contentDir: string) {
174 - return readdirSync(contentDir)
175 - .filter((f) => f.endsWith(".html"))
176 - .map((name) => ({
177 - name,
178 - path: path.join(contentDir, name),
179 - mtime: statSync(path.join(contentDir, name)).mtimeMs,
180 - }))
181 - .sort((a, b) => b.mtime - a.mtime || b.name.localeCompare(a.name));
184 -function latestFragment(contentDir: string) {
185 - const file = latestFiles(contentDir)[0];
186 - return file ? readFileSync(file.path, "utf8") : waitingFragment();
189 -function latestStamp(contentDir: string) {
190 - const file = latestFiles(contentDir)[0];
191 - return file ? { name: file.name, mtime: file.mtime } : { name: "", mtime: 0 };
194 -function waitingFragment() {
195 - return `<div class="center"><p class="subtitle">Waiting for Pi to write a visual screen…</p></div>`;
198 -function frame(fragment: string, stamp: { name: string; mtime: number }) {
199 - const body =
200 - /<html[\s>]/i.test(fragment) || /<!doctype/i.test(fragment)
201 - ? fragment
202 - : `<main id="main">${fragment}</main>`;
203 - return `<!doctype html>
204 -<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
205 -<title>Pi Superpowers Visual Brainstorming</title><link rel="icon" href="data:,"><style>${css()}</style></head><body data-stamp="${escapeAttr(JSON.stringify(stamp))}">
206 -<div id="app"><header id="topbar"><div class="brand"><h1>Visual Brainstorming</h1><div class="subtitle">${escapeHtml(stamp.name || "waiting")}</div></div><div class="topbar-actions"><label class="theme-label" aria-label="Theme mode"><span class="theme-icon">◐</span><select id="theme-mode" aria-label="Theme mode"><option value="system">system</option><option value="dark">dark</option><option value="light">light</option></select></label><div id="status" class="status-pill">ready</div></div></header>${body}</div>
207 -<script>${js()}</script></body></html>`;
210 -function css() {
211 - return `:root{color-scheme:dark light;--nugu-info:#3ec5dd;--nugu-content-normal:#ededed;--nugu-content-backdrop:#121212;--nugu-ui-backdrop:#242424;--nugu-ui-accent:#d86dd8;--nugu-ui-minor:#9d9d9d;--nugu-ui-focus:#9aabae;--nugu-ui-unfocus:#6f6f6f;--bg:var(--nugu-content-backdrop);--panel:color-mix(in srgb,var(--nugu-ui-backdrop) 86%,var(--bg));--panel-2:var(--nugu-ui-backdrop);--fg:var(--nugu-content-normal);--muted:var(--nugu-ui-minor);--faint:var(--nugu-ui-unfocus);--accent:var(--nugu-ui-accent);--accent-2:var(--nugu-info);--focus:var(--nugu-ui-focus);--border:color-mix(in srgb,var(--fg) 14%,transparent);--radius:10px;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:var(--bg);color:var(--fg)}:root[data-theme="light"]{color-scheme:light;--nugu-info:#13616e;--nugu-content-normal:#121212;--nugu-content-backdrop:#ededed;--nugu-ui-backdrop:#dbdbdb;--nugu-ui-accent:#922792;--nugu-ui-minor:#292929;--nugu-ui-focus:#15333b;--nugu-ui-unfocus:#5d5d5d;--panel:color-mix(in srgb,var(--nugu-ui-backdrop) 72%,white);--border:color-mix(in srgb,var(--fg) 16%,transparent)}*{box-sizing:border-box}html,body,#app{height:100%}body{margin:0;background:var(--bg)}button,select,input,textarea{font:inherit}code,pre{font-family:"JetBrains Mono","Fira Code",ui-monospace,Menlo,Consolas,monospace}button{cursor:pointer}#app{display:grid;grid-template-rows:auto minmax(0,1fr);overflow:hidden}#topbar{display:flex;align-items:center;gap:12px;padding:8px 12px;border-bottom:1px solid var(--border);background:color-mix(in srgb,var(--panel) 95%,transparent)}#main{overflow:auto;padding:18px;width:100%;height:100%}.brand{min-width:0;margin-right:auto}.brand h1{font-size:14px;line-height:1.1;margin:0}.subtitle{color:var(--muted);margin:.1rem 0 0;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.topbar-actions{display:flex;align-items:center;gap:8px}.theme-label{position:relative;display:inline-grid;place-items:center;width:28px;height:28px;min-width:28px;margin:0;padding:0;border:1px solid color-mix(in srgb,var(--border) 78%,transparent);border-radius:999px;background:color-mix(in srgb,var(--panel-2) 56%,transparent);opacity:.72}.theme-label:hover,.theme-label:focus-within{opacity:1}.theme-icon{display:grid;place-items:center;width:100%;height:100%;color:color-mix(in srgb,var(--fg) 70%,var(--muted));font-size:13px;font-weight:800;line-height:1;pointer-events:none}.theme-label select{position:absolute;inset:0;width:100%;height:100%;min-width:0;padding:0;border:0;border-radius:999px;background:transparent;color:transparent;opacity:0;cursor:pointer}.theme-label:focus-within{border-color:color-mix(in srgb,var(--focus) 52%,var(--border));box-shadow:0 0 0 3px color-mix(in srgb,var(--focus) 18%,transparent)}.theme-label select:focus{box-shadow:none}.card-title{font-weight:700;color:var(--accent-2)}select,.mock-input,textarea,input{background:var(--panel-2);color:var(--fg);border:1px solid var(--border);border-radius:8px;padding:6px 8px}.card,.option,.mockup{border:1px solid var(--border);background:var(--panel);border-radius:var(--radius);padding:14px}.card{margin-bottom:10px}.options,.cards{display:grid;gap:10px;margin:12px 0 18px}.option,.card[data-choice]{cursor:pointer}.option:hover,.card[data-choice]:hover{border-color:var(--focus);background:color-mix(in srgb,var(--focus) 10%,var(--panel))}.selected{outline:2px solid var(--accent);border-color:var(--accent)!important}.letter{display:inline-grid;place-items:center;width:24px;height:24px;margin-right:8px;border-radius:999px;background:var(--accent);color:var(--bg);font-weight:800}.split{display:grid;grid-template-columns:1fr 1fr;gap:12px}.mockup-header{color:var(--accent-2);font-weight:800;margin-bottom:10px}.mock-nav{background:var(--panel-2);border-radius:8px;padding:8px;margin-bottom:8px}.pros-cons{display:grid;grid-template-columns:1fr 1fr;gap:12px}.pros,.cons{padding:12px;border-radius:10px;background:color-mix(in srgb,var(--panel-2) 92%,var(--bg))}.mock-button{background:var(--panel-2);color:var(--fg);border:1px solid color-mix(in srgb,var(--accent) 58%,var(--border));border-radius:8px;padding:7px 10px}.placeholder{border:1px dashed var(--border);border-radius:10px;padding:18px;text-align:center;color:var(--muted)}.center{min-height:55vh;display:grid;place-items:center}.status-pill{display:inline-flex;align-items:center;min-height:28px;border:1px solid var(--border);border-radius:999px;padding:3px 9px;color:var(--muted);background:color-mix(in srgb,var(--panel-2) 56%,transparent);font-size:12px}dialog{border:1px solid var(--border);border-radius:12px;background:var(--panel);color:var(--fg);padding:16px;max-width:420px}dialog::backdrop{background:rgba(0,0,0,.55)}@media(max-width:840px){#topbar{flex-wrap:wrap}.split,.pros-cons{grid-template-columns:1fr}#main{padding:12px}}`;
214 -function js() {
215 - return `const select=document.getElementById('theme-mode');const saved=localStorage.getItem('superpowers-visual-theme')||'system';function applyTheme(mode){const light=matchMedia('(prefers-color-scheme: light)').matches;document.documentElement.dataset.theme=mode==='system'?(light?'light':'dark'):mode;if(select)select.value=mode}applyTheme(saved);select?.addEventListener('change',()=>{localStorage.setItem('superpowers-visual-theme',select.value);applyTheme(select.value)});let stamp=JSON.parse(document.body.dataset.stamp||'{"mtime":0}');async function post(e){const status=document.getElementById('status');if(status)status.textContent='saved';await fetch('/api/event',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(e)}).catch(()=>{})}window.toggleSelect=(el)=>{const multi=el.closest('[data-multiselect]');if(!multi)document.querySelectorAll('.selected').forEach(x=>x.classList.remove('selected'));el.classList.toggle('selected');post({type:'click',choice:el.dataset.choice||'',text:el.innerText.trim()})};document.addEventListener('click',e=>{const el=e.target.closest?.('[data-choice]');if(!el||el.hasAttribute('onclick'))return;window.toggleSelect(el)});setInterval(async()=>{try{const n=await fetch('/api/latest').then(r=>r.json());if(n.mtime&&n.mtime!==stamp.mtime)location.reload()}catch{}},1000);`;
218 -async function readBody(req: IncomingMessage) {
219 - let body = "";
220 - for await (const chunk of req) {
221 - body += String(chunk);
222 - if (Buffer.byteLength(body, "utf8") > BODY_LIMIT)
223 - throw new Error("request body too large");
224 - }
225 - return body;
228 -function html(res: ServerResponse, body: string) {
229 - res.statusCode = 200;
230 - res.setHeader("content-type", "text/html; charset=utf-8");
231 - res.setHeader("cache-control", "no-store");
232 - res.end(body);
234 -function json(res: ServerResponse, status: number, data: unknown) {
235 - res.statusCode = status;
236 - res.setHeader("content-type", "application/json; charset=utf-8");
237 - res.end(JSON.stringify(data));
239 -function text(res: ServerResponse, body: string) {
240 - res.statusCode = 200;
241 - res.setHeader("content-type", "text/plain; charset=utf-8");
242 - res.end(body);
244 -function escapeHtml(s: string) {
245 - return s
246 - .replaceAll("&", "&amp;")
247 - .replaceAll("<", "&lt;")
248 - .replaceAll(">", "&gt;");
250 -function escapeAttr(s: string) {
251 - return escapeHtml(s).replaceAll('"', "&quot;");

package.json

Modified
2 + "scripts": {
3 + "typecheck": "bash scripts/typecheck.sh"
4 + },
2 5 "name": "pi-ext",
3 6 "version": "0.0.3",
4 7 "private": true,

research/pi-superagents

Added
new file mode 160000
1 +Subproject commit e3500982d09516848c1a5ac4d4080274d119d403

research/pi-supergsd

Added
new file mode 160000
1 +Subproject commit e88bd028dded2a9e153ef3b24b882abfdbf9ae93

research/pi-superpower

Added
new file mode 160000
1 +Subproject commit 5819dffc318e0b09866fb2498efa4507ed3ee037

scripts/typecheck.sh

Added
new file mode 100755
1 +#!/usr/bin/env bash
2 +# Typecheck gate: fails if new errors appear beyond baseline
3 +# Usage: bun run typecheck (or npm run typecheck)
4 +set -eo pipefail
6 +BASELINE_FILE=".tsc-baseline.txt"
7 +BASELINE_COUNT=$(grep -c 'error TS' "$BASELINE_FILE" 2>/dev/null || echo 0)
9 +CURRENT_OUTPUT=$(tsc --noEmit 2>&1 || true)
10 +CURRENT_COUNT=$(echo "$CURRENT_OUTPUT" | grep -c 'error TS' || true)
12 +if [ "$CURRENT_COUNT" -eq 0 ]; then
13 + echo "✅ tsc --noEmit: 0 errors (clean!)"
14 + exit 0
15 +fi
17 +echo "⚠️ tsc --noEmit: $CURRENT_COUNT errors (baseline: $BASELINE_COUNT)"
19 +if [ "$CURRENT_COUNT" -gt "$BASELINE_COUNT" ]; then
20 + echo ""
21 + echo "❌ Error count increased ($CURRENT_COUNT > $BASELINE_COUNT). New errors:"
22 + echo "$CURRENT_OUTPUT" | grep 'error TS' > /tmp/tsc-current.txt
23 + diff --old-line-format='' --new-line-format='%L' --unchanged-line-format='' "$BASELINE_FILE" /tmp/tsc-current.txt || true
24 + exit 1
25 +fi
27 +echo "No new errors (baseline maintained)."
28 +exit 0

skills/acli/md2confluence.py

Modified
6 6 def convert(md_path):
7 7 result = subprocess.run(
8 - ['pandoc', '-f', 'markdown', '-t', 'html', '--no-highlight', md_path],
8 + ['pandoc', '-f', 'markdown', '-t', 'html', '--no-highlight', '--wrap=none', md_path],
9 9 capture_output=True, text=True
11 11 h = result.stdout
13 + # Remove leading h1 — Confluence already has the page title
14 + h = re.sub(r'^<h1[^>]*>.*?</h1>\s*', '', h, count=1, flags=re.DOTALL)
13 16 # Replace <pre class="LANG"><code>...</code></pre>
14 17 def code_to_macro(m):
15 18 lang = m.group(1) or ''

skills/pandoc/SKILL.md

Added
new file mode 100644
1 +---
2 +name: pandoc
3 +description: >
4 + Universal document converter — format conversion (Markdown, HTML, LaTeX, docx,
5 + PDF, EPUB, presentations), Lua filters, templates, citations, YAML metadata,
6 + and document pipelines. Use when converting between document formats, generating
7 + PDFs, extracting content, or programmatically transforming documents.
8 +---
10 +# Pandoc Skill
12 +Pandoc is a universal document converter. It reads many input formats, transforms them
13 +through an AST, and writes to many output formats. Agents use it primarily for:
14 +format conversion, PDF generation, content extraction, and document pipelines with Lua filters.
16 +**Version**: targets pandoc 3.x (tested on 3.6). Features like `--sandbox`, `--syntax-highlighting`,
17 +`--variable-json`, and the modern Table AST require pandoc ≥ 3.0.
19 +**Official docs**: <https://pandoc.org/MANUAL.html>
21 +---
23 +## Quick Reference: Essential Commands
25 +```bash
26 +# Markdown → HTML (standalone page)
27 +pandoc input.md -s -o output.html
29 +# Markdown → PDF (requires LaTeX engine)
30 +pandoc input.md -o output.pdf
32 +# Markdown → Word docx
33 +pandoc input.md -o output.docx
35 +# Markdown → LaTeX
36 +pandoc input.md -o output.tex
38 +# HTML → Markdown
39 +pandoc -f html -t markdown input.html -o output.md
41 +# URL → Markdown (fetch and convert)
42 +pandoc -f html -t markdown https://example.com -o page.md
44 +# With table of contents and numbered sections
45 +pandoc input.md -s --toc -N -o output.html
47 +# Multiple input files → single output
48 +pandoc ch1.md ch2.md ch3.md -s -o book.html
50 +# Pipe: stdout to pandoc
51 +echo "# Hello" | pandoc -f markdown -t html
53 +# Check supported formats
54 +pandoc --list-input-formats
55 +pandoc --list-output-formats
56 +```
58 +---
60 +## 1. Format Conversion Matrix
62 +### Input Formats (most useful for agents)
64 +| Format | Flag | Notes |
65 +|--------|------|-------|
66 +| Markdown (pandoc) | `markdown` | Default input; richest extensions |
67 +| GFM | `gfm` | GitHub-Flavored Markdown |
68 +| CommonMark | `commonmark` | Strict spec |
69 +| HTML | `html` | Parses web pages |
70 +| LaTeX | `latex` | Requires valid LaTeX |
71 +| Docx | `docx` | MS Word |
72 +| ODT | `odt` | LibreOffice |
73 +| EPUB | `epub` | E-books |
74 +| Org | `org` | Emacs Org mode |
75 +| RST | `rst` | reStructuredText |
76 +| Jupyter | `ipynb` | Notebooks |
77 +| CSV/TSV | `csv` / `tsv` | Tabular data |
78 +| Typst | `typst` | Modern typesetting |
79 +| Djot | `djot` | Lightweight markup |
81 +### Output Formats (most useful for agents)
83 +| Format | Flag | Notes |
84 +|--------|------|-------|
85 +| HTML5 | `html` | Default output |
86 +| PDF | `pdf` | Via LaTeX/Typst/HTML engine |
87 +| LaTeX | `latex` | Intermediate for PDF |
88 +| Docx | `docx` | MS Word |
89 +| PPTX | `pptx` | PowerPoint presentations |
90 +| EPUB3 | `epub` | E-books |
91 +| Markdown | `markdown` | Pandoc's extended MD |
92 +| GFM | `gfm` | For GitHub |
93 +| Beamer | `beamer` | LaTeX slide shows |
94 +| reveal.js | `revealjs` | HTML slide shows |
95 +| Typst | `typst` | Modern typesetting |
96 +| Plain text | `plain` | Stripped formatting |
97 +| ANSI | `ansi` | Terminal output with colors |
98 +| Man page | `man` | Unix manual pages |
100 +### Extension Syntax
102 +Enable/disable per-format extensions with `+EXTENSION` / `-EXTENSION`:
104 +```bash
105 +# Markdown with emoji support, without footnotes
106 +pandoc -f markdown+emoji-footnotes input.md
108 +# GFM with raw HTML
109 +pandoc -f gfm+raw_html input.md
110 +```
112 +---
114 +## 2. PDF Generation
116 +### Engines
118 +| Engine | Flag | When to Use |
119 +|--------|------|-------------|
120 +| pdflatex | `--pdf-engine=pdflatex` | Default; fastest, Latin scripts |
121 +| xelatex | `--pdf-engine=xelatex` | CJK, Unicode fonts, system fonts |
122 +| lualatex | `--pdf-engine=lualatex` | Lua scripting, font fallbacks |
123 +| typst | `--pdf-engine=typst` | Fast, modern, no TeX needed |
124 +| weasyprint | `--pdf-engine=weasyprint` | HTML/CSS → PDF, no TeX |
125 +| context | `--pdf-engine=context` | ConTeXt engine |
127 +### Common PDF Recipes
129 +```bash
130 +# Basic PDF
131 +pandoc doc.md -o doc.pdf
133 +# CJK / Unicode (use xelatex or lualatex)
134 +pandoc doc.md --pdf-engine=xelatex -V mainfont="Noto Sans CJK SC" -o doc.pdf
136 +# Custom margins
137 +pandoc doc.md -V geometry:margin=1in -o doc.pdf
139 +# Landscape, two-column
140 +pandoc doc.md -V geometry:margin=1in -V classoption=twocolumn -V classoption=landscape -o doc.pdf
142 +# Numbered sections + TOC
143 +pandoc doc.md -N --toc --toc-depth=3 -o doc.pdf
145 +# Via Typst (no LaTeX needed)
146 +pandoc doc.md --pdf-engine=typst -o doc.pdf
148 +# Via HTML (good for web content)
149 +pandoc doc.md -t html --css=style.css --pdf-engine=weasyprint -o doc.pdf
151 +# Debug: output intermediate LaTeX
152 +pandoc doc.md -s -o debug.tex
153 +```
155 +### Key LaTeX Variables
157 +| Variable | Example | Effect |
158 +|----------|---------|--------|
159 +| `geometry` | `margin=1in` | Page margins |
160 +| `papersize` | `a4`, `letter` | Paper size |
161 +| `fontsize` | `12pt` | Body font size |
162 +| `documentclass` | `article`, `book`, `report` | LaTeX class |
163 +| `mainfont` | `"Noto Sans"` | Body font (xelatex/lualatex) |
164 +| `monofont` | `"JetBrains Mono"` | Code font |
165 +| `linestretch` | `1.5` | Line spacing |
166 +| `colorlinks` | `true` | Colored links instead of boxes |
167 +| `linkcolor` | `blue` | Link color |
168 +| `toc` | (flag) | Include TOC |
169 +| `toc-depth` | `3` | TOC heading depth |
170 +| `numbersections` | (flag) | Number sections |
172 +---
174 +## 3. HTML Output
176 +```bash
177 +# Standalone HTML with default styling
178 +pandoc doc.md -s -o doc.html
180 +# Self-contained HTML (inline CSS/JS/images)
181 +pandoc doc.md -s --embed-resources -o doc.html
183 +# With custom CSS
184 +pandoc doc.md -s --css=style.css -o doc.html
186 +# With syntax highlighting style
187 +pandoc doc.md -s --syntax-highlighting=kate -o doc.html
189 +# Section divs (wrap in <section> tags)
190 +pandoc doc.md -s --section-divs -o doc.html
192 +# Math with KaTeX
193 +pandoc doc.md -s --katex -o doc.html
195 +# Math with MathJax
196 +pandoc doc.md -s --mathjax -o doc.html
198 +# Number sections
199 +pandoc doc.md -s -N -o doc.html
201 +# TOC with custom depth
202 +pandoc doc.md -s --toc --toc-depth=2 -o doc.html
203 +```
205 +### HTML Variables
207 +| Variable | Effect |
208 +|----------|--------|
209 +| `mainfont` | CSS font-family on html |
210 +| `fontsize` | Base font-size |
211 +| `monofont` | Code font-family |
212 +| `monobackgroundcolor` | Code background |
213 +| `linkcolor` | Link color |
214 +| `maxwidth` | Max content width (default 36em) |
215 +| `margin-left/right/top/bottom` | Body padding |
217 +---
219 +## 4. Docx (Word) Output
221 +```bash
222 +# Basic conversion
223 +pandoc doc.md -o doc.docx
225 +# With reference doc (styles, margins, fonts)
226 +pandoc doc.md --reference-doc=template.docx -o doc.docx
228 +# Generate default reference doc for customization
229 +pandoc -o custom-reference.docx --print-default-data-file reference.docx
231 +# Extract media (images) from docx input
232 +pandoc input.docx --extract-media=./images -t markdown -o output.md
234 +# Track changes: accept, reject, or keep all
235 +pandoc input.docx --track-changes=accept -o output.md
236 +```
238 +### Reference Doc Styles
240 +When customizing `reference.docx`, modify these styles:
241 +Normal, Body Text, Title, Subtitle, Author, Date, Heading 1–9,
242 +Block Text, Source Code, Footnote Text, Caption, Table, Hyperlink.
244 +---
246 +## 5. Presentations
248 +### reveal.js (HTML Slides)
250 +```bash
251 +pandoc slides.md -t revealjs -s -o slides.html
253 +# With theme and custom options
254 +pandoc slides.md -t revealjs -s -V revealjs-url=https://unpkg.com/reveal.js@^5 \
255 + -V theme=moon -o slides.html
257 +# Self-contained (offline use)
258 +pandoc slides.md -t revealjs -s --embed-resources -o slides.html
260 +# Incremental lists
261 +pandoc slides.md -t revealjs -s -i -o slides.html
262 +```
264 +### Beamer (PDF Slides)
266 +```bash
267 +pandoc slides.md -t beamer -o slides.pdf
269 +# With theme
270 +pandoc slides.md -t beamer -V theme=metropolis -o slides.pdf
272 +# Aspect ratio (default 4:3)
273 +pandoc slides.md -t beamer -V aspectratio=169 -o slides.pdf
274 +```
276 +### Slide Syntax
278 +Slides are separated by headings. The `--slide-level` option controls which heading level creates slides:
280 +```markdown
281 +# Section Title <!-- creates a section divider -->
283 +## Slide Title <!-- creates a slide (if slide-level=2) -->
285 +Content here.
287 +## Next Slide
289 +More content.
290 +```
292 +Use horizontal rules `---` to force slide breaks when needed.
294 +### PowerPoint (PPTX)
296 +```bash
297 +pandoc slides.md -o slides.pptx
299 +# With reference template
300 +pandoc slides.md --reference-doc=template.pptx -o slides.pptx
301 +```
303 +---
305 +## 6. Lua Filters
307 +Lua filters modify the pandoc AST between parsing and writing. No external deps — Lua 5.4 is built into pandoc.
309 +### Basic Filter Structure
311 +```lua
312 +-- Save as myfilter.lua, use with: pandoc --lua-filter=myfilter.lua
313 +return {
314 + Str = function(elem)
315 + -- Transform inline text elements
316 + return elem
317 + end,
318 + Para = function(elem)
319 + -- Transform paragraph blocks
320 + return elem
321 + end,
323 +```
325 +### Return Values
327 +- `nil` → element unchanged
328 +- New element → replaces original (must be same type)
329 +- List of elements → spliced in place (empty list = delete)
331 +### Global Variables Available
333 +| Variable | Description |
334 +|----------|-------------|
335 +| `FORMAT` | Output format name (`html`, `latex`, etc.) |
336 +| `PANDOC_VERSION` | Pandoc version as table `{major, minor, patch}` |
337 +| `PANDOC_READER_OPTIONS` | Reader options |
338 +| `PANDOC_WRITER_OPTIONS` | Writer options |
339 +| `PANDOC_SCRIPT_FILE` | Path to current filter file |
341 +### Common Filter Patterns
343 +```lua
344 +-- 1. Format-conditional logic
345 +if FORMAT:match 'html' then
346 + function Image(elem)
347 + elem.attributes.style = 'max-width:100%;'
348 + return elem
349 + end
350 +end
352 +-- 2. Replace text with inline elements
353 +return {
354 + Str = function(elem)
355 + if elem.text == "{{date}}" then
356 + return pandoc.Str(os.date("%Y-%m-%d"))
357 + end
358 + end,
361 +-- 3. Remove all links, keep text
362 +return {
363 + Link = function(el)
364 + return el.content -- unwrap link, keep inline content
365 + end,
368 +-- 4. Add class to all code blocks
369 +return {
370 + CodeBlock = function(el)
371 + table.insert(el.classes, "highlight")
372 + return el
373 + end,
376 +-- 5. Extract all headings (metadata → document)
377 +function Pandoc(doc)
378 + local headings = {}
379 + for _, el in ipairs(doc.blocks) do
380 + if el.t == "Header" then
381 + table.insert(headings, pandoc.Para(el.content))
382 + end
383 + end
384 + return pandoc.Pandoc(headings, doc.meta)
385 +end
387 +-- 6. Word count
388 +local words = 0
389 +return {
390 + Str = function(el)
391 + if el.text:match("%P") then words = words + 1 end
392 + end,
393 + Pandoc = function(doc)
394 + doc.blocks:walk({
395 + Str = function(el)
396 + if el.text:match("%P") then words = words + 1 end
397 + end
398 + })
399 + print(words .. " words in body")
400 + os.exit(0)
401 + end,
404 +-- 7. Top-down traversal (process parents before children)
405 +local filter = {
406 + traverse = 'topdown',
407 + Div = function(el)
408 + if el.classes[1] == 'skip' then
409 + return el, false -- skip children
410 + end
411 + end,
413 +return filter
414 +```
416 +### Traversal Order
418 +Default is `typewise`: all Inlines → all Blocks → Meta → Pandoc.
419 +Set `traverse = 'topdown'` for depth-first parent-before-children.
421 +### Useful Lua Modules (built-in)
423 +| Module | Use |
424 +|--------|-----|
425 +| `pandoc.utils` | `stringify`, `type`, `sha1`, `to_simple_table` |
426 +| `pandoc.text` | Unicode-aware `upper`, `lower`, `len` |
427 +| `pandoc.mediabag` | `insert`, `fetch`, `list` — manage binary assets |
428 +| `pandoc.system` | `with_temporary_directory`, `with_working_directory` |
429 +| `pandoc.layout` | Pretty-printing, text wrapping |
430 +| `pandoc.path` | Path manipulation (`directory`, `filename`, `join`) |
431 +| `lpeg` | Parsing Expression Grammars |
432 +| `re` | Regex-like pattern matching via lpeg |
434 +### Running External Commands in Lua
436 +```lua
437 +local output = pandoc.pipe("sed", {"-e", "s/foo/bar/"}, input_string)
438 +```
440 +### Multiple Filters
442 +Filters run in command-line order. Lua filters (`--lua-filter`) are faster than JSON filters (`--filter`):
444 +```bash
445 +pandoc doc.md --lua-filter=filter1.lua --lua-filter=filter2.lua -o out.html
446 +```
448 +---
450 +## 7. YAML Metadata
452 +```yaml
453 +---
454 +title: "Document Title"
455 +author: "Author Name"
456 +date: "2024-01-15"
457 +abstract: |
458 + This is the abstract.
459 + It can span multiple lines.
460 +keywords: [pandoc, markdown, conversion]
461 +subtitle: "A Subtitle"
462 +lang: en
463 +geometry: margin=1in
464 +fontsize: 12pt
465 +toc: true
466 +toc-depth: 3
467 +numbersections: true
468 +colorlinks: true
469 +linkcolor: blue
470 +header-includes: |
471 + \usepackage{cleveref}
472 +---
474 +# Introduction
476 +Content starts here.
477 +```
479 +### Setting Metadata from CLI
481 +```bash
482 +# String value
483 +pandoc doc.md -M title="My Title" -o out.html
485 +# Boolean
486 +pandoc doc.md -M toc=true -o out.html
488 +# From file
489 +pandoc doc.md --metadata-file=meta.yaml -o out.html
490 +```
492 +### Template Variables vs Metadata
494 +- `-V` / `--variable` → template variables only (strings, not parsed as Markdown)
495 +- `-M` / `--metadata` → metadata (affects document, accessible in filters, parsed as Markdown)
497 +---
499 +## 8. Templates
501 +Templates control standalone output structure. Variables are interpolated with `$var$` syntax.
503 +```bash
504 +# View default template for a format
505 +pandoc -D html
506 +pandoc -D latex
507 +pandoc -D revealjs
509 +# Use custom template
510 +pandoc doc.md --template=mytemplate.html -o out.html
511 +```
513 +### Template Syntax
515 +```
516 +$if(title)$
517 +<h1>$title$</h1>
518 +$endif$
520 +$for(author)$
521 +<p>$author$</p>
522 +$sep$,
523 +$endfor$
525 +${body} <!-- variable interpolation -->
526 +$if(foo)$ <!-- conditional -->
527 +$else$
528 +$endif$
529 +$for(items)$ <!-- loop -->
530 +$sep$, $endfor$ <!-- separator -->
531 +```
533 +### Custom Templates Location
535 +Place in `$HOME/.local/share/pandoc/templates/default.FORMAT` to override defaults.
537 +---
539 +## 9. Citations & Bibliography
541 +```bash
542 +# Process citations with citeproc
543 +pandoc doc.md --citeproc -o out.html
545 +# Specify bibliography file
546 +pandoc doc.md --citeproc --bibliography=refs.bib -o out.html
548 +# Specify CSL style
549 +pandoc doc.md --citeproc --csl=ieee.csl -o out.html
550 +```
552 +### Citation Syntax (in Markdown)
554 +```markdown
555 +See @smith2020 for details.
556 +Multiple: [@smith2020; @jones2019].
557 +Suppress author: [-@smith2020].
558 +```
560 +### YAML for Bibliography
562 +```yaml
563 +---
564 +bibliography: refs.bib
565 +csl: https://www.zotero.org/styles/ieee
566 +nocite: "@*" # include all entries in bibliography
567 +---
568 +```
570 +---
572 +## 10. Content Extraction & Processing
574 +```bash
575 +# Extract images/media from binary formats
576 +pandoc input.docx --extract-media=./media -t markdown -o output.md
578 +# Convert only specific parts via Lua filter
579 +pandoc doc.md --lua-filter=extract-headings.lua -t markdown
581 +# Read URL, convert to Markdown
582 +pandoc -f html -t markdown https://example.com -o page.md
584 +# JSON AST (for piping to external filters)
585 +pandoc doc.md -t json | ./my-filter.py | pandoc -f json -t html
587 +# Get word count via Lua filter
588 +pandoc doc.md --lua-filter=wordcount.lua
589 +```
591 +---
593 +## 11. Defaults Files
595 +Reusable YAML config files instead of long CLI commands:
597 +```yaml
598 +# defaults/pdf.yaml
599 +input-files:
600 + - chapters/*.md
601 +from: markdown
602 +to: pdf
603 +standalone: true
604 +toc: true
605 +toc-depth: 3
606 +number-sections: true
607 +variables:
608 + geometry: margin=1in
609 + fontsize: 12pt
610 + documentclass: book
611 +pdf-engine: xelatex
612 +```
614 +```bash
615 +pandoc -d pdf
616 +# or
617 +pandoc --defaults=pdf.yaml
618 +```
620 +Place in `$HOME/.local/share/pandoc/defaults/` for global access by name.
622 +---
624 +## 12. Common Agent Pipelines
626 +### Web Page → Clean Markdown
628 +```bash
629 +pandoc -f html -t markdown --wrap=none \
630 + https://example.com -o page.md
631 +```
633 +### Markdown → Professional PDF Report
635 +```bash
636 +pandoc report.md -o report.pdf \
637 + --pdf-engine=xelatex \
638 + -V geometry:margin=1in \
639 + -V fontsize=11pt \
640 + -V mainfont="TeX Gyre Pagella" \
641 + -V monofont="JetBrains Mono" \
642 + -V colorlinks=true \
643 + -V linkcolor=blue \
644 + --toc --toc-depth=3 \
645 + -N \
646 + --syntax-highlighting=kate
647 +```
649 +### Docx → Markdown (with images)
651 +```bash
652 +pandoc input.docx \
653 + --extract-media=./images \
654 + -t markdown \
655 + -o output.md
656 +```
658 +### Notebook → HTML Report
660 +```bash
661 +pandoc analysis.ipynb \
662 + -s --embed-resources \
663 + --css=report.css \
664 + --syntax-highlighting=tango \
665 + -o report.html
666 +```
668 +### Batch Convert Directory
670 +```bash
671 +# Markdown → HTML
672 +for f in *.md; do
673 + pandoc "$f" -s -o "${f%.md}.html"
674 +done
676 +# Markdown → PDF
677 +for f in *.md; do
678 + pandoc "$f" --pdf-engine=xelatex -o "${f%.md}.pdf"
679 +done
680 +```
682 +### Combine Chapters into Book
684 +```bash
685 +pandoc ch1.md ch2.md ch3.md metadata.yaml \
686 + -s --toc -N \
687 + --pdf-engine=xelatex \
688 + -o book.pdf
689 +```
691 +### AST Inspection
693 +```bash
694 +# JSON AST for debugging
695 +pandoc doc.md -t json | jq '.blocks[0]'
697 +# Native Haskell AST (human-readable)
698 +pandoc doc.md -t native
699 +```
701 +---
703 +## 13. Key CLI Options Reference
705 +| Option | Effect |
706 +|--------|--------|
707 +| `-f` / `--from` | Input format |
708 +| `-t` / `--to` | Output format |
709 +| `-o` / `--output` | Output file |
710 +| `-s` / `--standalone` | Full document (header + footer) |
711 +| `--toc` | Table of contents |
712 +| `--toc-depth=N` | TOC depth (default 3) |
713 +| `-N` / `--number-sections` | Number sections |
714 +| `--lua-filter=FILE` | Apply Lua filter |
715 +| `--filter=PROG` | Apply JSON filter (external) |
716 +| `-M KEY=VAL` | Set metadata |
717 +| `-V KEY=VAL` | Set template variable |
718 +| `--metadata-file=FILE` | Load metadata from YAML |
719 +| `--template=FILE` | Custom template |
720 +| `--css=URL` | Link CSS (HTML/EPUB) |
721 +| `--embed-resources` | Inline all resources (HTML) |
722 +| `--extract-media=DIR` | Extract media to directory |
723 +| `--wrap=auto\|none\|preserve` | Text wrapping |
724 +| `--columns=N` | Line width (default 72) |
725 +| `--shift-heading-level-by=N` | Adjust heading levels |
726 +| `--reference-doc=FILE` | Style reference (docx/odt/pptx) |
727 +| `--pdf-engine=PROG` | PDF engine |
728 +| `--citeproc` | Process citations |
729 +| `--bibliography=FILE` | Bibliography file |
730 +| `-d` / `--defaults=FILE` | Defaults file |
731 +| `--sandbox` | Restrict file access |
732 +| `--syntax-highlighting=STYLE` | Highlighting style or `none` |
733 +| `-H` / `--include-in-header` | Include raw in header |
734 +| `-B` / `--include-before-body` | Include before body |
735 +| `-A` / `--include-after-body` | Include after body |
736 +| `--resource-path=PATH` | Search path for resources |
737 +| `--file-scope` | Parse files individually |
738 +| `--fail-if-warnings` | Exit on warnings |
740 +---
742 +## 14. Exit Codes
744 +| Code | Meaning |
745 +|------|---------|
746 +| 0 | Success |
747 +| 1 | IO error |
748 +| 3 | Fail on warnings |
749 +| 5 | Template error |
750 +| 6 | Option error |
751 +| 21 | Unknown reader |
752 +| 22 | Unknown writer |
753 +| 43 | PDF error |
754 +| 47 | PDF engine not found |
755 +| 83 | Filter error |
756 +| 84 | Lua error |
758 +---
760 +## 15. Helper Scripts
762 +See `scripts/` directory:
764 +- `pandoc-batch-convert.sh` — Batch convert files between formats
765 +- `pandoc-md-to-pdf.sh` — Markdown to polished PDF with sensible defaults
766 +- `pandoc-web-to-md.sh` — Fetch URL and convert to clean Markdown
767 +- `pandoc-wordcount.lua` — Count words in document body
769 +### Lua Filter Library
771 +See `references/` directory:
773 +- `filters/strong-to-smallcaps.lua` — Convert **bold** to SMALL CAPS
774 +- `filters/center-images.lua` — Center images in HTML/LaTeX
775 +- `filters/meta-vars.lua` — Replace `%var%` placeholders with metadata values
776 +- `filters/extract-headings.lua` — Extract document outline
777 +- `filters/add-meta-date.lua` — Auto-set date metadata
778 +- `filters/remove-empty-paras.lua` — Strip empty paragraphs
780 +---
782 +## Related Skills
784 +- **mdbook**: Building documentation books from Markdown
785 +- **presenterm**: Terminal-based presentations
786 +- **d2**: Diagram syntax used with pandoc preprocessing
787 +- **jq**: Processing pandoc JSON AST output

skills/pandoc/references/filters/add-meta-date.lua

Added
new file mode 100644
1 +-- add-meta-date.lua — Auto-set date metadata if not already present
2 +-- Usage: pandoc --lua-filter=add-meta-date.lua doc.md -o out.html
4 +function Meta(m)
5 + if m.date == nil then
6 + m.date = os.date("%Y-%m-%d")
7 + return m
8 + end
9 +end

skills/pandoc/references/filters/center-images.lua

Added
new file mode 100644
1 +-- center-images.lua — Center images in HTML and LaTeX output
2 +-- Usage: pandoc --lua-filter=center-images.lua doc.md -o out.html
4 +if FORMAT:match 'html' then
5 + function Image(elem)
6 + elem.attributes.style = (elem.attributes.style or '')
7 + .. 'display:block; margin-left:auto; margin-right:auto;'
8 + return elem
9 + end
10 +elseif FORMAT:match 'latex' then
11 + function Image(elem)
12 + return {
13 + pandoc.RawInline('latex', '\\begin{center}'),
14 + elem,
15 + pandoc.RawInline('latex', '\\end{center}'),
16 + }
17 + end
18 +end

skills/pandoc/references/filters/extract-headings.lua

Added
new file mode 100644
1 +-- extract-headings.lua — Extract document outline (headings only)
2 +-- Usage: pandoc --lua-filter=extract-headings.lua doc.md -t markdown
4 +function Pandoc(doc)
5 + local headings = {}
6 + for _, el in ipairs(doc.blocks) do
7 + if el.t == "Header" then
8 + local indent = string.rep(" ", el.level - 1)
9 + local text = pandoc.utils.stringify(el.content)
10 + local link = "[" .. text .. "](#" .. el.identifier .. ")"
11 + table.insert(headings, pandoc.Para(indent .. "- " .. link))
12 + end
13 + end
14 + return pandoc.Pandoc(headings, doc.meta)
15 +end

skills/pandoc/references/filters/meta-vars.lua

Added
new file mode 100644
1 +-- meta-vars.lua — Replace %key% placeholders with metadata values
2 +-- Usage: pandoc --lua-filter=meta-vars.lua doc.md -o out.html
3 +--
4 +-- In your Markdown:
5 +-- ---
6 +-- name: Samuel Q. Smith
7 +-- role: Professor
8 +-- ---
9 +-- Name: %name%, Role: %role%
11 +local vars = {}
13 +local function get_vars(meta)
14 + for k, v in pairs(meta) do
15 + if pandoc.utils.type(v) == 'Inlines' then
16 + vars["%" .. k .. "%"] = {table.unpack(v)}
17 + end
18 + end
19 +end
21 +local function replace(el)
22 + if vars[el.text] then
23 + return pandoc.Span(vars[el.text])
24 + end
25 + return el
26 +end
28 +function Pandoc(doc)
29 + return doc:walk { Meta = get_vars }:walk { Str = replace }
30 +end

skills/pandoc/references/filters/remove-empty-paras.lua

Added
new file mode 100644
1 +-- remove-empty-paras.lua — Strip empty paragraphs from document
2 +-- Usage: pandoc --lua-filter=remove-empty-paras.lua doc.md -o out.html
4 +function Para(el)
5 + local content = el.content
6 + -- Check if all content is whitespace/empty
7 + local text = pandoc.utils.stringify(content)
8 + if text:match("^%s*$") then
9 + return {} -- delete
10 + end
11 + return el
12 +end

skills/pandoc/references/filters/strong-to-smallcaps.lua

Added
new file mode 100644
1 +-- strong-to-smallcaps.lua — Convert **bold** text to SMALL CAPS
2 +-- Usage: pandoc --lua-filter=strong-to-smallcaps.lua doc.md -o out.html
4 +return {
5 + Strong = function(elem)
6 + return pandoc.SmallCaps(elem.content)
7 + end,
8 +}

skills/pandoc/scripts/pandoc-batch-convert.sh

Added
new file mode 100755
1 +#!/usr/bin/env bash
2 +# pandoc-batch-convert.sh — Batch convert files between formats
3 +# Usage: pandoc-batch-convert.sh <input-ext> <output-ext> [pandoc-args...]
4 +# Example: pandoc-batch-convert.sh md html -s --toc
5 +# pandoc-batch-convert.sh md pdf --pdf-engine=xelatex
7 +set -euo pipefail
9 +if [[ $# -lt 2 ]]; then
10 + echo "Usage: $0 <input-ext> <output-ext> [pandoc-args...]" >&2
11 + echo "Example: $0 md html -s --toc" >&2
12 + exit 1
13 +fi
15 +IN_EXT="$1"
16 +OUT_EXT="$2"
17 +shift 2
19 +shopt -s nullglob
20 +files=(*."${IN_EXT}")
22 +if [[ ${#files[@]} -eq 0 ]]; then
23 + echo "No *.${IN_EXT} files found in $(pwd)" >&2
24 + exit 1
25 +fi
27 +count=0
28 +failed=0
29 +for f in "${files[@]}"; do
30 + base="${f%.${IN_EXT}}"
31 + out="${base}.${OUT_EXT}"
32 + echo "Converting: $f → $out"
33 + if pandoc "$f" -o "$out" "$@" 2>/dev/null; then
34 + ((count++))
35 + else
36 + echo " FAILED: $f" >&2
37 + ((failed++))
38 + fi
39 +done
41 +echo "Done: ${count} converted, ${failed} failed."

skills/pandoc/scripts/pandoc-md-to-pdf.sh

Added
new file mode 100755
1 +#!/usr/bin/env bash
2 +# pandoc-md-to-pdf.sh — Markdown to polished PDF with sensible defaults
3 +# Usage: pandoc-md-to-pdf.sh <input.md> [output.pdf] [--draft|--final]
4 +# Requires: xelatex (or set PANDOC_PDF_ENGINE)
6 +set -euo pipefail
8 +if [[ $# -lt 1 ]]; then
9 + echo "Usage: $0 <input.md> [output.pdf] [--draft|--final]" >&2
10 + exit 1
11 +fi
13 +INPUT="$1"
14 +shift
16 +OUTPUT=""
17 +MODE="final"
18 +ENGINE="${PANDOC_PDF_ENGINE:-xelatex}"
20 +while [[ $# -gt 0 ]]; do
21 + case "$1" in
22 + --draft) MODE="draft"; shift ;;
23 + --final) MODE="final"; shift ;;
24 + *) OUTPUT="$1"; shift ;;
25 + esac
26 +done
28 +[[ -z "$OUTPUT" ]] && OUTPUT="${INPUT%.md}.pdf"
30 +COMMON_ARGS=(
31 + --pdf-engine="$ENGINE"
32 + -V geometry:margin=1in
33 + -V colorlinks=true
34 + -V linkcolor=blue
35 + -V urlcolor=blue
36 + --toc
37 + --toc-depth=3
38 + -N
39 + --syntax-highlighting=kate
42 +if [[ "$MODE" == "draft" ]]; then
43 + COMMON_ARGS+=(
44 + -V fontsize=12pt
45 + -V linestretch=1.5
46 + )
47 +else
48 + COMMON_ARGS+=(
49 + -V fontsize=11pt
50 + )
51 +fi
53 +echo "Converting: $INPUT → $OUTPUT (engine=$ENGINE, mode=$MODE)"
54 +pandoc "$INPUT" -o "$OUTPUT" "${COMMON_ARGS[@]}"
55 +echo "Done: $OUTPUT"

skills/pandoc/scripts/pandoc-web-to-md.sh

Added
new file mode 100755
1 +#!/usr/bin/env bash
2 +# pandoc-web-to-md.sh — Fetch URL and convert to clean Markdown
3 +# Usage: pandoc-web-to-md.sh <url> [output.md]
4 +# Example: pandoc-web-to-md.sh https://example.com page.md
6 +set -euo pipefail
8 +if [[ $# -lt 1 ]]; then
9 + echo "Usage: $0 <url> [output.md]" >&2
10 + exit 1
11 +fi
13 +URL="$1"
14 +OUTPUT="${2:--}" # default to stdout
16 +pandoc -f html -t markdown \
17 + --wrap=none \
18 + --shift-heading-level-by=-1 \
19 + "$URL" -o "$OUTPUT"

skills/pandoc/scripts/pandoc-wordcount.lua

Added
new file mode 100644
1 +-- wordcount.lua — Count words in document body
2 +-- Usage: pandoc --lua-filter=wordcount.lua doc.md
3 +-- Prints word count to stderr and exits.
5 +local words = 0
7 +local function count_str(el)
8 + if el.text:match("%P") then
9 + words = words + 1
10 + end
11 +end
13 +local function count_code(el)
14 + local _, n = el.text:gsub("%S+", "")
15 + words = words + n
16 +end
18 +function Pandoc(doc)
19 + doc.blocks:walk({
20 + Str = count_str,
21 + Code = count_code,
22 + CodeBlock = count_code,
23 + })
24 + io.stderr:write(words .. " words in body\n")
25 + os.exit(0)
26 +end

tsconfig.json

Modified
5 5 "compilerOptions": {
6 6 "target": "ESNext",
7 7 "module": "ESNext",
8 8 "moduleResolution": "bundler",
9 9 "strict": true,
10 - "esModuleInterop": true,
11 - "skipLibCheck": true,
12 10 "noEmit": true,
11 + "skipLibCheck": true,
12 + "esModuleInterop": true,
13 + "forceConsistentCasingInFileNames": true,
13 14 "resolveJsonModule": true,
14 15 "allowImportingTsExtensions": true
16 17 "prompts/**/*.ts",
17 18 "themes/**/*.ts"
19 - "exclude": ["node_modules", "**/*.test.ts"]
20 + "exclude": [
21 + "node_modules",
22 + "extensions/*/node_modules",
23 + "extensions/**/__tests__/**",
24 + "extensions/**/*.test.ts",
25 + "extensions/**/*.bench.ts",
26 + "extensions/**/scripts/**"
27 + ]