RSS Reader using AT Protocol rssbase.io
feed atom rss reader atproto social
2

Configure Feed

Select the types of activity you want to include in your feed.

add more skills

Romain Gautier (Jul 3, 2026, 12:51 PM +0200) a8a0de86 410924fe

+2436
+159
.agents/skills/brainstorming/SKILL.md
··· 1 + --- 2 + name: brainstorming 3 + description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation." 4 + --- 5 + 6 + # Brainstorming Ideas Into Designs 7 + 8 + Help turn ideas into fully formed designs and specs through natural collaborative dialogue. 9 + 10 + Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design and get user approval. 11 + 12 + <HARD-GATE> 13 + Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity. 14 + </HARD-GATE> 15 + 16 + ## Anti-Pattern: "This Is Too Simple To Need A Design" 17 + 18 + Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval. 19 + 20 + ## Checklist 21 + 22 + You MUST create a task for each of these items and complete them in order: 23 + 24 + 1. **Explore project context** — check files, docs, recent commits 25 + 2. **Offer the visual companion just-in-time** — NOT upfront. The first time a question would genuinely be clearer shown than described, offer it then (its own message); on approval its browser tab opens for you. If no visual question ever arises, never offer it. See the Visual Companion section below. 26 + 3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria 27 + 4. **Propose 2-3 approaches** — with trade-offs and your recommendation 28 + 5. **Present design** — in sections scaled to their complexity, get user approval after each section 29 + 6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit 30 + 7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below) 31 + 8. **User reviews written spec** — ask user to review the spec file before proceeding 32 + 9. **Transition to implementation** — invoke writing-plans skill to create implementation plan 33 + 34 + ## Process Flow 35 + 36 + ```dot 37 + digraph brainstorming { 38 + "Explore project context" [shape=box]; 39 + "Ask clarifying questions" [shape=box]; 40 + "Propose 2-3 approaches" [shape=box]; 41 + "Present design sections" [shape=box]; 42 + "User approves design?" [shape=diamond]; 43 + "Write design doc" [shape=box]; 44 + "Spec self-review\n(fix inline)" [shape=box]; 45 + "User reviews spec?" [shape=diamond]; 46 + "Invoke writing-plans skill" [shape=doublecircle]; 47 + 48 + "Explore project context" -> "Ask clarifying questions"; 49 + "Ask clarifying questions" -> "Propose 2-3 approaches"; 50 + "Propose 2-3 approaches" -> "Present design sections"; 51 + "Present design sections" -> "User approves design?"; 52 + "User approves design?" -> "Present design sections" [label="no, revise"]; 53 + "User approves design?" -> "Write design doc" [label="yes"]; 54 + "Write design doc" -> "Spec self-review\n(fix inline)"; 55 + "Spec self-review\n(fix inline)" -> "User reviews spec?"; 56 + "User reviews spec?" -> "Write design doc" [label="changes requested"]; 57 + "User reviews spec?" -> "Invoke writing-plans skill" [label="approved"]; 58 + } 59 + ``` 60 + 61 + **The terminal state is invoking writing-plans.** Do NOT invoke frontend-design, mcp-builder, or any other implementation skill. The ONLY skill you invoke after brainstorming is writing-plans. 62 + 63 + ## The Process 64 + 65 + **Understanding the idea:** 66 + 67 + - Check out the current project state first (files, docs, recent commits) 68 + - Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., "build a platform with chat, file storage, billing, and analytics"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first. 69 + - If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → plan → implementation cycle. 70 + - For appropriately-scoped projects, ask questions one at a time to refine the idea 71 + - Prefer multiple choice questions when possible, but open-ended is fine too 72 + - Only one question per message - if a topic needs more exploration, break it into multiple questions 73 + - Focus on understanding: purpose, constraints, success criteria 74 + 75 + **Exploring approaches:** 76 + 77 + - Propose 2-3 different approaches with trade-offs 78 + - Present options conversationally with your recommendation and reasoning 79 + - Lead with your recommended option and explain why 80 + 81 + **Presenting the design:** 82 + 83 + - Once you believe you understand what you're building, present the design 84 + - Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced 85 + - Ask after each section whether it looks right so far 86 + - Cover: architecture, components, data flow, error handling, testing 87 + - Be ready to go back and clarify if something doesn't make sense 88 + 89 + **Design for isolation and clarity:** 90 + 91 + - Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently 92 + - For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on? 93 + - Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work. 94 + - Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much. 95 + 96 + **Working in existing codebases:** 97 + 98 + - Explore the current structure before proposing changes. Follow existing patterns. 99 + - Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in. 100 + - Don't propose unrelated refactoring. Stay focused on what serves the current goal. 101 + 102 + ## After the Design 103 + 104 + **Documentation:** 105 + 106 + - Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` 107 + - (User preferences for spec location override this default) 108 + - Use elements-of-style:writing-clearly-and-concisely skill if available 109 + - Commit the design document to git 110 + 111 + **Spec Self-Review:** 112 + After writing the spec document, look at it with fresh eyes: 113 + 114 + 1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them. 115 + 2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions? 116 + 3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition? 117 + 4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit. 118 + 119 + Fix any issues inline. No need to re-review — just fix and move on. 120 + 121 + **User Review Gate:** 122 + After the spec review loop passes, ask the user to review the written spec before proceeding: 123 + 124 + > "Spec written and committed to `<path>`. Please review it and let me know if you want to make any changes before we start writing out the implementation plan." 125 + 126 + Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves. 127 + 128 + **Implementation:** 129 + 130 + - Invoke the writing-plans skill to create a detailed implementation plan 131 + - Do NOT invoke any other skill. writing-plans is the next step. 132 + 133 + ## Key Principles 134 + 135 + - **One question at a time** - Don't overwhelm with multiple questions 136 + - **Multiple choice preferred** - Easier to answer than open-ended when possible 137 + - **YAGNI ruthlessly** - Remove unnecessary features from all designs 138 + - **Explore alternatives** - Always propose 2-3 approaches before settling 139 + - **Incremental validation** - Present design, get approval before moving on 140 + - **Be flexible** - Go back and clarify when something doesn't make sense 141 + 142 + ## Visual Companion 143 + 144 + A browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser. 145 + 146 + **Offering the companion (just-in-time):** Do NOT offer it upfront. Wait until a question would genuinely be clearer shown than told — a real mockup / layout / diagram question, not merely a UI *topic*. The first time that happens, offer it then, as its own message: 147 + > "This next part might be easier if I show you — I can put together mockups, diagrams, and comparisons in a browser tab as we go. It's still new and can be token-intensive. Want me to? I'll open it for you." 148 + 149 + **This offer MUST be its own message.** Only the offer — no clarifying question, summary, or other content. Wait for the user's response. If they accept, start the server with `--open` so their browser opens to the first screen automatically. If they decline, continue text-only and don't offer again unless they raise it. 150 + 151 + **Per-question decision:** Even after the user accepts, decide FOR EACH QUESTION whether to use the browser or the terminal. The test: **would the user understand this better by seeing it than reading it?** 152 + 153 + - **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs 154 + - **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions 155 + 156 + A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is a conceptual question — use the terminal. "Which wizard layout works better?" is a visual question — use the browser. 157 + 158 + If they agree to the companion, read the detailed guide before proceeding: 159 + `skills/brainstorming/visual-companion.md`
+213
.agents/skills/brainstorming/scripts/frame-template.html
··· 1 + <!DOCTYPE html> 2 + <html> 3 + <head> 4 + <meta charset="utf-8"> 5 + <title>Superpowers Brainstorming</title> 6 + <style> 7 + /* 8 + * BRAINSTORM COMPANION FRAME TEMPLATE 9 + * 10 + * This template provides a consistent frame with: 11 + * - OS-aware light/dark theming 12 + * - Header branding and connection status 13 + * - Scrollable main content area 14 + * - CSS helpers for common UI patterns 15 + * 16 + * Content is injected via placeholder comment in #frame-content. 17 + */ 18 + 19 + * { box-sizing: border-box; margin: 0; padding: 0; } 20 + html, body { height: 100%; overflow: hidden; } 21 + 22 + /* ===== THEME VARIABLES ===== */ 23 + :root { 24 + --bg-primary: #f5f5f7; 25 + --bg-secondary: #ffffff; 26 + --bg-tertiary: #e5e5e7; 27 + --border: #d1d1d6; 28 + --text-primary: #1d1d1f; 29 + --text-secondary: #86868b; 30 + --text-tertiary: #aeaeb2; 31 + --accent: #0071e3; 32 + --accent-hover: #0077ed; 33 + --success: #34c759; 34 + --warning: #ff9f0a; 35 + --error: #ff3b30; 36 + --selected-bg: #e8f4fd; 37 + --selected-border: #0071e3; 38 + } 39 + 40 + @media (prefers-color-scheme: dark) { 41 + :root { 42 + --bg-primary: #1d1d1f; 43 + --bg-secondary: #2d2d2f; 44 + --bg-tertiary: #3d3d3f; 45 + --border: #424245; 46 + --text-primary: #f5f5f7; 47 + --text-secondary: #86868b; 48 + --text-tertiary: #636366; 49 + --accent: #0a84ff; 50 + --accent-hover: #409cff; 51 + --selected-bg: rgba(10, 132, 255, 0.15); 52 + --selected-border: #0a84ff; 53 + } 54 + } 55 + 56 + body { 57 + font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif; 58 + background: var(--bg-primary); 59 + color: var(--text-primary); 60 + display: flex; 61 + flex-direction: column; 62 + line-height: 1.5; 63 + } 64 + 65 + /* ===== FRAME STRUCTURE ===== */ 66 + .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; color: var(--text-secondary); line-height: 1; } 67 + .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; } 68 + .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); } 69 + .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; flex-shrink: 0; filter: invert(1); } 70 + @media (prefers-color-scheme: dark) { 71 + .brand-logo { filter: none; } 72 + } 73 + .status { font-size: 0.7rem; color: var(--status-color, var(--success)); display: flex; align-items: center; gap: 0.4rem; justify-self: end; white-space: nowrap; line-height: 1; } 74 + .status::before { content: ''; width: 6px; height: 6px; background: var(--status-color, var(--success)); border-radius: 50%; } 75 + 76 + .main { flex: 1; overflow-y: auto; } 77 + #frame-content { padding: 2rem; min-height: 100%; } 78 + 79 + .header { 80 + background: var(--bg-secondary); 81 + border-bottom: 1px solid var(--border); 82 + padding: 0.5rem 1.5rem; 83 + flex-shrink: 0; 84 + display: grid; 85 + grid-template-columns: minmax(0, 1fr) auto; 86 + align-items: center; 87 + gap: 1rem; 88 + min-height: 42px; 89 + } 90 + .header .brand { justify-self: start; width: 100%; font-size: 0.75rem; line-height: 1; } 91 + .header .status { grid-column: 2; line-height: 1; } 92 + .header span { 93 + font-size: 0.75rem; 94 + color: var(--text-secondary); 95 + } 96 + .header .selected-text { 97 + color: var(--accent); 98 + font-weight: 500; 99 + } 100 + 101 + /* ===== TYPOGRAPHY ===== */ 102 + h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; } 103 + h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; } 104 + .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; } 105 + .section { margin-bottom: 2rem; } 106 + .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; } 107 + 108 + /* ===== OPTIONS (for A/B/C choices) ===== */ 109 + .options { display: flex; flex-direction: column; gap: 0.75rem; } 110 + .option { 111 + background: var(--bg-secondary); 112 + border: 2px solid var(--border); 113 + border-radius: 12px; 114 + padding: 1rem 1.25rem; 115 + cursor: pointer; 116 + transition: all 0.15s ease; 117 + display: flex; 118 + align-items: flex-start; 119 + gap: 1rem; 120 + } 121 + .option:hover { border-color: var(--accent); } 122 + .option.selected { background: var(--selected-bg); border-color: var(--selected-border); } 123 + .option .letter { 124 + background: var(--bg-tertiary); 125 + color: var(--text-secondary); 126 + width: 1.75rem; height: 1.75rem; 127 + border-radius: 6px; 128 + display: flex; align-items: center; justify-content: center; 129 + font-weight: 600; font-size: 0.85rem; flex-shrink: 0; 130 + } 131 + .option.selected .letter { background: var(--accent); color: white; } 132 + .option .content { flex: 1; } 133 + .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; } 134 + .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; } 135 + 136 + /* ===== CARDS (for showing designs/mockups) ===== */ 137 + .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; } 138 + .card { 139 + background: var(--bg-secondary); 140 + border: 1px solid var(--border); 141 + border-radius: 12px; 142 + overflow: hidden; 143 + cursor: pointer; 144 + transition: all 0.15s ease; 145 + } 146 + .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); } 147 + .card.selected { border-color: var(--selected-border); border-width: 2px; } 148 + .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; } 149 + .card-body { padding: 1rem; } 150 + .card-body h3 { margin-bottom: 0.25rem; } 151 + .card-body p { color: var(--text-secondary); font-size: 0.85rem; } 152 + 153 + /* ===== MOCKUP CONTAINER ===== */ 154 + .mockup { 155 + background: var(--bg-secondary); 156 + border: 1px solid var(--border); 157 + border-radius: 12px; 158 + overflow: hidden; 159 + margin-bottom: 1.5rem; 160 + } 161 + .mockup-header { 162 + background: var(--bg-tertiary); 163 + padding: 0.5rem 1rem; 164 + font-size: 0.75rem; 165 + color: var(--text-secondary); 166 + border-bottom: 1px solid var(--border); 167 + } 168 + .mockup-body { padding: 1.5rem; } 169 + 170 + /* ===== SPLIT VIEW (side-by-side comparison) ===== */ 171 + .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; } 172 + @media (max-width: 700px) { .split { grid-template-columns: 1fr; } } 173 + 174 + /* ===== PROS/CONS ===== */ 175 + .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; } 176 + .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; } 177 + .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; } 178 + .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; } 179 + .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); } 180 + .pros li, .cons li { margin-bottom: 0.25rem; } 181 + 182 + /* ===== PLACEHOLDER (for mockup areas) ===== */ 183 + .placeholder { 184 + background: var(--bg-tertiary); 185 + border: 2px dashed var(--border); 186 + border-radius: 8px; 187 + padding: 2rem; 188 + text-align: center; 189 + color: var(--text-tertiary); 190 + } 191 + 192 + /* ===== INLINE MOCKUP ELEMENTS ===== */ 193 + .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; } 194 + .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; } 195 + .mock-content { padding: 1.5rem; flex: 1; } 196 + .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; } 197 + .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; } 198 + </style> 199 + </head> 200 + <body> 201 + <div class="header"> 202 + <!-- BRANDING --> 203 + <div class="status">Connecting…</div> 204 + </div> 205 + 206 + <div class="main"> 207 + <div id="frame-content"> 208 + <!-- CONTENT --> 209 + </div> 210 + </div> 211 + 212 + </body> 213 + </html>
+167
.agents/skills/brainstorming/scripts/helper.js
··· 1 + (function() { 2 + const MIN_RECONNECT_MS = 500; 3 + const MAX_RECONNECT_MS = 30000; 4 + const TOMBSTONE_AFTER_MS = 15000; // show the "paused" overlay after this long disconnected 5 + 6 + // Pure: next backoff delay (doubles, capped). Exported for unit tests. 7 + function nextReconnectDelay(current, max) { 8 + return Math.min(current * 2, max); 9 + } 10 + if (typeof module !== 'undefined' && module.exports) { 11 + module.exports = { nextReconnectDelay, MIN_RECONNECT_MS, MAX_RECONNECT_MS, TOMBSTONE_AFTER_MS }; 12 + } 13 + 14 + // Everything below is browser-only; bail out when loaded in Node (tests). 15 + if (typeof window === 'undefined') return; 16 + 17 + let ws = null; 18 + let eventQueue = []; 19 + let reconnectDelay = MIN_RECONNECT_MS; 20 + let reconnectTimer = null; 21 + let disconnectedSince = null; 22 + let everConnected = false; 23 + let tombstoneShown = false; 24 + 25 + function sessionKey() { 26 + try { 27 + return window.sessionStorage && window.sessionStorage.getItem('brainstorm-session-key'); 28 + } catch (e) {} 29 + return null; 30 + } 31 + 32 + function websocketUrl() { 33 + const key = sessionKey(); 34 + return 'ws://' + window.location.host + (key ? '/?key=' + encodeURIComponent(key) : ''); 35 + } 36 + 37 + function reloadAfterRecovery() { 38 + const key = sessionKey(); 39 + if (key) { 40 + window.location.replace('/?key=' + encodeURIComponent(key)); 41 + } else { 42 + window.location.reload(); 43 + } 44 + } 45 + 46 + // Reflect connection state in the frame's status pill (absent on full-doc screens). 47 + function setStatus(state) { 48 + const el = document.querySelector('.status'); 49 + if (!el) return; 50 + const map = { 51 + connecting: ['Connecting…', 'var(--text-tertiary)'], 52 + connected: ['Connected', 'var(--success)'], 53 + reconnecting: ['Reconnecting…', 'var(--warning)'], 54 + disconnected: ['Disconnected', 'var(--error)'] 55 + }; 56 + const [text, color] = map[state] || map.disconnected; 57 + el.textContent = text; 58 + el.style.setProperty('--status-color', color); 59 + } 60 + 61 + // Self-styled so it works on framed and full-document screens alike. 62 + function showTombstone() { 63 + if (tombstoneShown) return; 64 + tombstoneShown = true; 65 + const el = document.createElement('div'); 66 + el.id = 'bs-tombstone'; 67 + el.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;' + 68 + 'align-items:center;justify-content:center;padding:2rem;text-align:center;' + 69 + 'background:rgba(20,20,22,0.92);color:#f5f5f7;font-family:system-ui,sans-serif'; 70 + el.innerHTML = '<div style="max-width:480px">' + 71 + '<h2 style="margin:0 0 .5rem;font-weight:600">Companion paused</h2>' + 72 + '<p style="margin:0;opacity:.85">This brainstorm companion has stopped. ' + 73 + 'Ask your coding agent to bring it back — this page reconnects automatically.</p></div>'; 74 + if (document.body) document.body.appendChild(el); 75 + } 76 + 77 + function connect() { 78 + if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } 79 + setStatus(everConnected ? 'reconnecting' : 'connecting'); 80 + ws = new WebSocket(websocketUrl()); 81 + 82 + ws.onopen = () => { 83 + const recovered = tombstoneShown; 84 + everConnected = true; 85 + disconnectedSince = null; 86 + reconnectDelay = MIN_RECONNECT_MS; 87 + tombstoneShown = false; 88 + setStatus('connected'); 89 + eventQueue.forEach(e => ws.send(JSON.stringify(e))); 90 + eventQueue = []; 91 + // Recovered from a tombstoned outage (e.g. the server restarted on the same 92 + // port) — reload through the keyed bootstrap when possible so the cookie is 93 + // refreshed before the visible URL returns to bare /. 94 + if (recovered) reloadAfterRecovery(); 95 + }; 96 + 97 + ws.onmessage = (msg) => { 98 + let data; 99 + try { data = JSON.parse(msg.data); } catch (e) { return; } 100 + if (data.type === 'reload') window.location.reload(); 101 + }; 102 + 103 + ws.onclose = () => { 104 + ws = null; 105 + if (disconnectedSince === null) disconnectedSince = Date.now(); 106 + if (Date.now() - disconnectedSince >= TOMBSTONE_AFTER_MS) { 107 + setStatus('disconnected'); 108 + showTombstone(); 109 + } else { 110 + setStatus('reconnecting'); 111 + } 112 + reconnectTimer = setTimeout(connect, reconnectDelay); 113 + reconnectDelay = nextReconnectDelay(reconnectDelay, MAX_RECONNECT_MS); 114 + }; 115 + 116 + // Let onclose own reconnection so we don't schedule it twice. 117 + ws.onerror = () => { try { ws.close(); } catch (e) {} }; 118 + } 119 + 120 + function sendEvent(event) { 121 + event.timestamp = Date.now(); 122 + if (ws && ws.readyState === WebSocket.OPEN) { 123 + ws.send(JSON.stringify(event)); 124 + } else { 125 + eventQueue.push(event); 126 + } 127 + } 128 + 129 + // Capture clicks on choice elements 130 + document.addEventListener('click', (e) => { 131 + const target = e.target.closest('[data-choice]'); 132 + if (!target) return; 133 + 134 + sendEvent({ 135 + type: 'click', 136 + text: target.textContent.trim(), 137 + choice: target.dataset.choice, 138 + id: target.id || null 139 + }); 140 + 141 + }); 142 + 143 + // Frame UI: selection tracking 144 + window.selectedChoice = null; 145 + 146 + window.toggleSelect = function(el) { 147 + const container = el.closest('.options') || el.closest('.cards'); 148 + const multi = container && container.dataset.multiselect !== undefined; 149 + if (container && !multi) { 150 + container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected')); 151 + } 152 + if (multi) { 153 + el.classList.toggle('selected'); 154 + } else { 155 + el.classList.add('selected'); 156 + } 157 + window.selectedChoice = el.dataset.choice; 158 + }; 159 + 160 + // Expose API for explicit use 161 + window.brainstorm = { 162 + send: sendEvent, 163 + choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata }) 164 + }; 165 + 166 + connect(); 167 + })();
+723
.agents/skills/brainstorming/scripts/server.cjs
··· 1 + const crypto = require('crypto'); 2 + const http = require('http'); 3 + const fs = require('fs'); 4 + const path = require('path'); 5 + 6 + // ========== WebSocket Protocol (RFC 6455) ========== 7 + 8 + const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A }; 9 + const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; 10 + const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024; 11 + 12 + function computeAcceptKey(clientKey) { 13 + return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64'); 14 + } 15 + 16 + function encodeFrame(opcode, payload) { 17 + const fin = 0x80; 18 + const len = payload.length; 19 + let header; 20 + 21 + if (len < 126) { 22 + header = Buffer.alloc(2); 23 + header[0] = fin | opcode; 24 + header[1] = len; 25 + } else if (len < 65536) { 26 + header = Buffer.alloc(4); 27 + header[0] = fin | opcode; 28 + header[1] = 126; 29 + header.writeUInt16BE(len, 2); 30 + } else { 31 + header = Buffer.alloc(10); 32 + header[0] = fin | opcode; 33 + header[1] = 127; 34 + header.writeBigUInt64BE(BigInt(len), 2); 35 + } 36 + 37 + return Buffer.concat([header, payload]); 38 + } 39 + 40 + function decodeFrame(buffer) { 41 + if (buffer.length < 2) return null; 42 + 43 + const secondByte = buffer[1]; 44 + const opcode = buffer[0] & 0x0F; 45 + const masked = (secondByte & 0x80) !== 0; 46 + let payloadLen = secondByte & 0x7F; 47 + let offset = 2; 48 + 49 + if (!masked) throw new Error('Client frames must be masked'); 50 + 51 + if (payloadLen === 126) { 52 + if (buffer.length < 4) return null; 53 + payloadLen = buffer.readUInt16BE(2); 54 + offset = 4; 55 + } else if (payloadLen === 127) { 56 + if (buffer.length < 10) return null; 57 + const extendedLen = buffer.readBigUInt64BE(2); 58 + if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) { 59 + throw new Error('WebSocket frame payload exceeds maximum allowed size'); 60 + } 61 + payloadLen = Number(extendedLen); 62 + offset = 10; 63 + } 64 + 65 + if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) { 66 + throw new Error('WebSocket frame payload exceeds maximum allowed size'); 67 + } 68 + 69 + const maskOffset = offset; 70 + const dataOffset = offset + 4; 71 + const totalLen = dataOffset + payloadLen; 72 + if (buffer.length < totalLen) return null; 73 + 74 + const mask = buffer.slice(maskOffset, dataOffset); 75 + const data = Buffer.alloc(payloadLen); 76 + for (let i = 0; i < payloadLen; i++) { 77 + data[i] = buffer[dataOffset + i] ^ mask[i % 4]; 78 + } 79 + 80 + return { opcode, payload: data, bytesConsumed: totalLen }; 81 + } 82 + 83 + // ========== Configuration ========== 84 + 85 + const PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null; 86 + const randomPort = () => 49152 + Math.floor(Math.random() * 16383); 87 + // Prefer an explicit port, else the port this session last bound (so a restart 88 + // reuses it and an already-open browser tab reconnects), else a random high port. 89 + function preferredPort() { 90 + if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT); 91 + if (PORT_FILE) { 92 + try { 93 + const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim()); 94 + if (Number.isInteger(p) && p > 1023 && p < 65536) return p; 95 + } catch (e) { /* no prior port recorded */ } 96 + } 97 + return randomPort(); 98 + } 99 + let PORT = preferredPort(); 100 + const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1'; 101 + const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST); 102 + const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm'; 103 + const CONTENT_DIR = path.join(SESSION_DIR, 'content'); 104 + const STATE_DIR = path.join(SESSION_DIR, 'state'); 105 + const SUPERPOWERS_VERSION = readSuperpowersVersion(); 106 + const SUPERPOWERS_BRAND_IMAGE_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png'; 107 + const TELEMETRY_DISABLE_ENV_VARS = [ 108 + 'SUPERPOWERS_DISABLE_TELEMETRY', 109 + 'DISABLE_TELEMETRY', 110 + 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' 111 + ]; 112 + const SUPERPOWERS_TELEMETRY_DISABLED = TELEMETRY_DISABLE_ENV_VARS.some(name => isTruthyEnv(process.env[name])); 113 + let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null; 114 + 115 + // Per-session secret key. The companion is reachable by any local browser tab 116 + // and, when bound to a non-loopback host, by any host that can route to it. 117 + // The key authenticates the real client uniformly across loopback, tunnel, and 118 + // remote binds — and defeats DNS rebinding — where a Host/Origin allowlist 119 + // cannot. It rides the served URL as ?key= and is mirrored into a cookie on 120 + // first load so same-origin subresources and the WebSocket carry it for free. 121 + // Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the 122 + // same key and an already-open tab's cookie still validates. 123 + const TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null; 124 + function generateToken() { 125 + return crypto.randomBytes(32).toString('hex'); 126 + } 127 + 128 + function chmodOwnerOnly(file) { 129 + try { fs.chmodSync(file, 0o600); } catch (e) { /* best effort */ } 130 + } 131 + 132 + function initialToken() { 133 + if (process.env.BRAINSTORM_TOKEN) { 134 + return { value: process.env.BRAINSTORM_TOKEN, source: 'env' }; 135 + } 136 + if (TOKEN_FILE) { 137 + try { 138 + const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim(); 139 + if (/^[0-9a-f]{32,}$/i.test(t)) { 140 + chmodOwnerOnly(TOKEN_FILE); 141 + return { value: t, source: 'file' }; 142 + } 143 + } catch (e) { /* no prior token recorded */ } 144 + } 145 + return { value: generateToken(), source: 'generated' }; 146 + } 147 + 148 + const tokenInfo = initialToken(); 149 + let TOKEN = tokenInfo.value; 150 + let tokenSource = tokenInfo.source; 151 + let COOKIE_NAME = 'brainstorm-key-' + PORT; // refined to the actual bound port in onListen 152 + 153 + const MIME_TYPES = { 154 + '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', 155 + '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', 156 + '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml' 157 + }; 158 + 159 + // ========== Templates and Constants ========== 160 + 161 + function waitingPage() { 162 + return renderBranding(`<!DOCTYPE html> 163 + <html> 164 + <head><meta charset="utf-8"><title>Brainstorm Companion</title> 165 + <style> 166 + body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; } 167 + h1 { color: #333; } p { color: #666; } 168 + .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; } 169 + .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; } 170 + .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); } 171 + .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); } 172 + </style> 173 + </head> 174 + <body><!-- BRANDING --><h1>Brainstorm Companion</h1> 175 + <p>Waiting for the agent to push a screen...</p></body></html>`); 176 + } 177 + 178 + const FORBIDDEN_PAGE = `<!DOCTYPE html> 179 + <html> 180 + <head><meta charset="utf-8"><title>Session key required</title> 181 + <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; } 182 + h1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style> 183 + </head> 184 + <body><h1>Session key required</h1> 185 + <p>This page needs the full URL your coding agent gave you, including the 186 + <code>?key=&hellip;</code> part. Copy the complete URL and open it again.</p></body></html>`; 187 + 188 + function bootstrapPage(key) { 189 + const jsonKey = JSON.stringify(String(key)); 190 + return `<!DOCTYPE html> 191 + <html> 192 + <head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head> 193 + <body> 194 + <script> 195 + try { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {} 196 + location.replace('/'); 197 + </script> 198 + </body> 199 + </html>`; 200 + } 201 + 202 + const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8'); 203 + const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8'); 204 + const helperInjection = '<script>\n' + helperScript + '\n</script>'; 205 + 206 + // ========== Helper Functions ========== 207 + 208 + function readSuperpowersVersion() { 209 + const root = path.join(__dirname, '../../..'); 210 + const manifests = [ 211 + path.join(root, 'package.json'), 212 + path.join(root, '.codex-plugin/plugin.json') 213 + ]; 214 + 215 + for (const manifest of manifests) { 216 + try { 217 + const data = JSON.parse(fs.readFileSync(manifest, 'utf-8')); 218 + if (data.version) return String(data.version); 219 + } catch (e) { 220 + // Packaged Codex plugins omit package.json; try the next manifest. 221 + } 222 + } 223 + 224 + return 'unknown'; 225 + } 226 + 227 + function isTruthyEnv(value) { 228 + if (!value) return false; 229 + const normalized = String(value).trim().toLowerCase(); 230 + if (!normalized) return false; 231 + return !['0', 'false', 'no', 'off'].includes(normalized); 232 + } 233 + 234 + function escapeHtmlText(value) { 235 + return String(value) 236 + .replace(/&/g, '&amp;') 237 + .replace(/</g, '&lt;') 238 + .replace(/>/g, '&gt;') 239 + .replace(/"/g, '&quot;'); 240 + } 241 + 242 + function brandMarkup() { 243 + const version = escapeHtmlText(SUPERPOWERS_VERSION); 244 + const text = SUPERPOWERS_TELEMETRY_DISABLED 245 + ? 'Prime Radiant Superpowers v' + version 246 + : 'Superpowers v' + version; 247 + const logo = SUPERPOWERS_TELEMETRY_DISABLED 248 + ? '' 249 + : '<img class="brand-logo" src="' + SUPERPOWERS_BRAND_IMAGE_URL + '?v=' + encodeURIComponent(SUPERPOWERS_VERSION) + '" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">'; 250 + 251 + return '<div class="brand"><a href="https://github.com/obra/superpowers">' + logo + '<span class="brand-copy">' + text + '</span></a></div>'; 252 + } 253 + 254 + function renderBranding(html) { 255 + return html.split('<!-- BRANDING -->').join(brandMarkup()); 256 + } 257 + 258 + function isFullDocument(html) { 259 + const trimmed = html.trimStart().toLowerCase(); 260 + return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html'); 261 + } 262 + 263 + function wrapInFrame(content) { 264 + return renderBranding(frameTemplate).replace('<!-- CONTENT -->', content); 265 + } 266 + 267 + function getNewestScreen() { 268 + const files = fs.readdirSync(CONTENT_DIR) 269 + .filter(f => !f.startsWith('.') && f.endsWith('.html')) 270 + .map(f => { 271 + const fp = path.join(CONTENT_DIR, f); 272 + if (!isRegularFileInsideContentDir(fp)) return null; 273 + return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }; 274 + }) 275 + .filter(Boolean) 276 + .sort((a, b) => b.mtime - a.mtime); 277 + return files.length > 0 ? files[0].path : null; 278 + } 279 + 280 + function urlHostForHttp(host) { 281 + const h = String(host); 282 + if (h.startsWith('[') && h.endsWith(']')) return h; 283 + return h.includes(':') ? '[' + h + ']' : h; 284 + } 285 + 286 + function companionUrl() { 287 + return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN; 288 + } 289 + 290 + function browserLauncherForPlatform(url, { 291 + platform = process.platform, 292 + osRelease = require('os').release(), 293 + env = process.env 294 + } = {}) { 295 + const isWSL = platform === 'linux' && /microsoft/i.test(osRelease); 296 + if (platform === 'darwin') return { bin: 'open', args: [url] }; 297 + if (platform === 'win32' || isWSL) { 298 + return { bin: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] }; 299 + } 300 + if (env.DISPLAY || env.WAYLAND_DISPLAY) return { bin: 'xdg-open', args: [url] }; 301 + return null; 302 + } 303 + 304 + function isRegularFileInsideContentDir(filePath) { 305 + let stat, realContentDir, realFilePath; 306 + try { 307 + stat = fs.lstatSync(filePath); 308 + if (stat.isSymbolicLink()) return false; 309 + if (!stat.isFile()) return false; 310 + if (stat.nlink !== 1) return false; 311 + realContentDir = fs.realpathSync(CONTENT_DIR); 312 + realFilePath = fs.realpathSync(filePath); 313 + } catch (e) { 314 + return false; 315 + } 316 + return realFilePath.startsWith(realContentDir + path.sep); 317 + } 318 + 319 + // ========== Authentication ========== 320 + 321 + function timingSafeEqualStr(a, b) { 322 + const ab = Buffer.from(String(a)); 323 + const bb = Buffer.from(String(b)); 324 + if (ab.length !== bb.length) return false; 325 + return crypto.timingSafeEqual(ab, bb); 326 + } 327 + 328 + function parseCookies(header) { 329 + const out = {}; 330 + if (!header) return out; 331 + for (const part of header.split(';')) { 332 + const eq = part.indexOf('='); 333 + if (eq < 0) continue; 334 + out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim(); 335 + } 336 + return out; 337 + } 338 + 339 + // A request is authorized if it carries the session key as ?key= or as the 340 + // session cookie. Both are compared in constant time. 341 + function isAuthorized(req) { 342 + const q = req.url.indexOf('?'); 343 + if (q >= 0) { 344 + const params = new URLSearchParams(req.url.slice(q + 1)); 345 + if (params.has('key')) { 346 + const key = params.get('key'); 347 + return Boolean(key && timingSafeEqualStr(key, TOKEN)); 348 + } 349 + } 350 + const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME]; 351 + if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true; 352 + return false; 353 + } 354 + 355 + function pathnameOf(url) { 356 + const q = url.indexOf('?'); 357 + return q >= 0 ? url.slice(0, q) : url; 358 + } 359 + 360 + function queryKey(url) { 361 + const q = url.indexOf('?'); 362 + if (q < 0) return null; 363 + return new URLSearchParams(url.slice(q + 1)).get('key'); 364 + } 365 + 366 + function securityHeaders(headers = {}) { 367 + return { 368 + 'Referrer-Policy': 'no-referrer', 369 + 'Cache-Control': 'no-store', 370 + 'X-Frame-Options': 'DENY', 371 + 'Content-Security-Policy': "frame-ancestors 'none'", 372 + 'Cross-Origin-Resource-Policy': 'same-origin', 373 + ...headers 374 + }; 375 + } 376 + 377 + function isAllowedWebSocketOrigin(req) { 378 + const origin = req.headers.origin; 379 + if (!origin) return true; 380 + const host = req.headers.host; 381 + if (!host) return false; 382 + return origin === 'http://' + host; 383 + } 384 + 385 + // ========== HTTP Request Handler ========== 386 + 387 + function handleRequest(req, res) { 388 + if (!isAuthorized(req)) { 389 + res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); 390 + res.end(FORBIDDEN_PAGE); 391 + return; 392 + } 393 + touchActivity(); // only authorized requests count as activity 394 + 395 + // Mirror the key into a cookie so same-origin subresources (/files/*) can 396 + // authenticate after bootstrap. HttpOnly keeps it away from page scripts; the 397 + // WebSocket Origin check below is what blocks cross-origin localhost injection. 398 + res.setHeader('Set-Cookie', 399 + COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/'); 400 + 401 + const pathname = pathnameOf(req.url); 402 + const keyFromQuery = queryKey(req.url); 403 + if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) { 404 + res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); 405 + res.end(bootstrapPage(keyFromQuery)); 406 + } else if (req.method === 'GET' && pathname === '/') { 407 + const screenFile = getNewestScreen(); 408 + let html = screenFile 409 + ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8')) 410 + : waitingPage(); 411 + 412 + if (html.includes('</body>')) { 413 + html = html.replace('</body>', helperInjection + '\n</body>'); 414 + } else { 415 + html += helperInjection; 416 + } 417 + 418 + res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); 419 + res.end(html); 420 + } else if (req.method === 'GET' && pathname.startsWith('/files/')) { 421 + const fileName = path.basename(pathname.slice(7)); 422 + const filePath = path.join(CONTENT_DIR, fileName); 423 + // Reject empty/dotfile names and anything that isn't a regular file — 424 + // `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR). 425 + if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) { 426 + res.writeHead(404, securityHeaders()); 427 + res.end('Not found'); 428 + return; 429 + } 430 + const ext = path.extname(filePath).toLowerCase(); 431 + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; 432 + res.writeHead(200, securityHeaders({ 'Content-Type': contentType })); 433 + res.end(fs.readFileSync(filePath)); 434 + } else { 435 + res.writeHead(404, securityHeaders()); 436 + res.end('Not found'); 437 + } 438 + } 439 + 440 + // ========== WebSocket Connection Handling ========== 441 + 442 + const clients = new Set(); 443 + 444 + function handleUpgrade(req, socket) { 445 + if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; } 446 + 447 + const key = req.headers['sec-websocket-key']; 448 + if (!key) { socket.destroy(); return; } 449 + 450 + const accept = computeAcceptKey(key); 451 + socket.write( 452 + 'HTTP/1.1 101 Switching Protocols\r\n' + 453 + 'Upgrade: websocket\r\n' + 454 + 'Connection: Upgrade\r\n' + 455 + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n' 456 + ); 457 + 458 + let buffer = Buffer.alloc(0); 459 + clients.add(socket); 460 + 461 + socket.on('data', (chunk) => { 462 + buffer = Buffer.concat([buffer, chunk]); 463 + while (buffer.length > 0) { 464 + let result; 465 + try { 466 + result = decodeFrame(buffer); 467 + } catch (e) { 468 + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); 469 + clients.delete(socket); 470 + return; 471 + } 472 + if (!result) break; 473 + buffer = buffer.slice(result.bytesConsumed); 474 + 475 + switch (result.opcode) { 476 + case OPCODES.TEXT: 477 + handleMessage(result.payload.toString()); 478 + break; 479 + case OPCODES.CLOSE: 480 + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); 481 + clients.delete(socket); 482 + return; 483 + case OPCODES.PING: 484 + socket.write(encodeFrame(OPCODES.PONG, result.payload)); 485 + break; 486 + case OPCODES.PONG: 487 + break; 488 + default: { 489 + const closeBuf = Buffer.alloc(2); 490 + closeBuf.writeUInt16BE(1003); 491 + socket.end(encodeFrame(OPCODES.CLOSE, closeBuf)); 492 + clients.delete(socket); 493 + return; 494 + } 495 + } 496 + } 497 + }); 498 + 499 + socket.on('close', () => clients.delete(socket)); 500 + socket.on('error', () => clients.delete(socket)); 501 + } 502 + 503 + function handleMessage(text) { 504 + let event; 505 + try { 506 + event = JSON.parse(text); 507 + } catch (e) { 508 + console.error('Failed to parse WebSocket message:', e.message); 509 + return; 510 + } 511 + touchActivity(); 512 + console.log(JSON.stringify({ source: 'user-event', ...event })); 513 + if (event && event.choice) { 514 + const eventsFile = path.join(STATE_DIR, 'events'); 515 + fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n'); 516 + } 517 + } 518 + 519 + function broadcast(msg) { 520 + const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg))); 521 + for (const socket of clients) { 522 + try { socket.write(frame); } catch (e) { clients.delete(socket); } 523 + } 524 + } 525 + 526 + // Best-effort: open the user's browser the first time a screen is actually ready 527 + // to show. Skips when disabled, on a non-loopback (remote) bind, or when a 528 + // browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD. 529 + let browserOpened = false; 530 + function maybeOpenBrowser() { 531 + if (browserOpened) return; 532 + browserOpened = true; 533 + if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion 534 + if (HOST !== '127.0.0.1' && HOST !== 'localhost') return; 535 + if (clients.size > 0) return; // the user already opened it 536 + const url = companionUrl(); // must carry the key or the gate 403s it 537 + const cp = require('child_process'); 538 + // Operator-provided launcher: run as given (this env var is trusted operator input). 539 + if (process.env.BRAINSTORM_OPEN_CMD) { 540 + try { cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ } 541 + return; 542 + } 543 + // Platform launchers: pass the URL as an argv element via execFile (no shell), 544 + // so a url-host containing shell metacharacters can't inject a command. 545 + const launcher = browserLauncherForPlatform(url); 546 + if (!launcher) return; // headless: nothing to open 547 + try { cp.execFile(launcher.bin, launcher.args, () => {}); } catch (e) { /* best effort */ } 548 + } 549 + 550 + // ========== Activity Tracking ========== 551 + 552 + // Idle timeout: shut down after this long with no activity. Default 4 hours; 553 + // override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes). 554 + const IDLE_TIMEOUT_MS = (() => { 555 + const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS); 556 + return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000; 557 + })(); 558 + // How often the watchdog checks for owner-death / idleness. Configurable mainly 559 + // so tests can run fast; production default is 60s. 560 + const LIFECYCLE_CHECK_MS = (() => { 561 + const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS); 562 + return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000; 563 + })(); 564 + let lastActivity = Date.now(); 565 + 566 + function touchActivity() { 567 + lastActivity = Date.now(); 568 + } 569 + 570 + // ========== File Watching ========== 571 + 572 + const debounceTimers = new Map(); 573 + 574 + // ========== Server Startup ========== 575 + 576 + function startServer() { 577 + if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true }); 578 + if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true }); 579 + 580 + // Track known files to distinguish new screens from updates. 581 + // macOS fs.watch reports 'rename' for both new files and overwrites, 582 + // so we can't rely on eventType alone. 583 + const knownFiles = new Set( 584 + fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html')) 585 + ); 586 + 587 + const server = http.createServer(handleRequest); 588 + server.on('upgrade', handleUpgrade); 589 + 590 + const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => { 591 + if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return; 592 + 593 + if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename)); 594 + debounceTimers.set(filename, setTimeout(() => { 595 + debounceTimers.delete(filename); 596 + const filePath = path.join(CONTENT_DIR, filename); 597 + 598 + if (!fs.existsSync(filePath)) return; // file was deleted 599 + touchActivity(); 600 + 601 + if (!knownFiles.has(filename)) { 602 + knownFiles.add(filename); 603 + const eventsFile = path.join(STATE_DIR, 'events'); 604 + if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile); 605 + console.log(JSON.stringify({ type: 'screen-added', file: filePath })); 606 + maybeOpenBrowser(); 607 + } else { 608 + console.log(JSON.stringify({ type: 'screen-updated', file: filePath })); 609 + } 610 + 611 + broadcast({ type: 'reload' }); 612 + }, 100)); 613 + }); 614 + watcher.on('error', (err) => console.error('fs.watch error:', err.message)); 615 + 616 + function shutdown(reason) { 617 + console.log(JSON.stringify({ type: 'server-stopped', reason })); 618 + const infoFile = path.join(STATE_DIR, 'server-info'); 619 + if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile); 620 + fs.writeFileSync( 621 + path.join(STATE_DIR, 'server-stopped'), 622 + JSON.stringify({ reason, timestamp: Date.now() }) + '\n' 623 + ); 624 + watcher.close(); 625 + clearInterval(lifecycleCheck); 626 + // Close any upgraded WebSocket sockets so server.close() can complete and 627 + // the process actually exits instead of lingering on an open connection. 628 + for (const socket of clients) { 629 + try { socket.destroy(); } catch (e) { /* already gone */ } 630 + } 631 + server.close(() => process.exit(0)); 632 + } 633 + 634 + function ownerAlive() { 635 + if (!ownerPid) return true; 636 + try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; } 637 + } 638 + 639 + // Periodically exit if the owner process died or we've been idle too long. 640 + const lifecycleCheck = setInterval(() => { 641 + if (!ownerAlive()) shutdown('owner process exited'); 642 + else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout'); 643 + }, LIFECYCLE_CHECK_MS); 644 + lifecycleCheck.unref(); 645 + 646 + // Validate owner PID at startup. If it's already dead, the PID resolution 647 + // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios). 648 + // Disable monitoring and rely on the idle timeout instead. 649 + if (ownerPid) { 650 + try { process.kill(ownerPid, 0); } 651 + catch (e) { 652 + if (e.code !== 'EPERM') { 653 + console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' })); 654 + ownerPid = null; 655 + } 656 + } 657 + } 658 + 659 + // If the preferred port is already taken (e.g. a previous server is still 660 + // alive), fall back to a random port once instead of failing. 661 + let triedFallback = false; 662 + 663 + function onListen() { 664 + // Cookie name keys on the ACTUAL bound port (may differ from the preferred 665 + // one after an EADDRINUSE fallback) so it can't collide with another server's 666 + // cookie in the shared localhost jar. 667 + COOKIE_NAME = 'brainstorm-key-' + PORT; 668 + // Record the bound port AND token so the next restart of this session reuses 669 + // them — but ONLY when we got our preferred port. On a fallback we bound a 670 + // *different* port because someone else holds the preferred one; persisting 671 + // would overwrite the shared files and strand that other session's open tab. 672 + if (PORT_FILE && !triedFallback) { 673 + try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ } 674 + if (TOKEN_FILE) { 675 + try { 676 + fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 }); 677 + chmodOwnerOnly(TOKEN_FILE); 678 + } catch (e) { /* best effort */ } 679 + } 680 + } 681 + const info = JSON.stringify({ 682 + type: 'server-started', port: Number(PORT), host: HOST, 683 + url_host: URL_HOST, url: companionUrl(), 684 + screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS 685 + }); 686 + console.log(info); 687 + // server-info embeds the key — keep it owner-only. 688 + fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 }); 689 + } 690 + 691 + server.on('error', (err) => { 692 + if (err.code === 'EADDRINUSE' && !triedFallback) { 693 + if (tokenSource === 'env') { 694 + console.error('Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token'); 695 + process.exit(1); 696 + } 697 + triedFallback = true; 698 + PORT = randomPort(); 699 + if (tokenSource === 'file') { 700 + TOKEN = generateToken(); 701 + tokenSource = 'generated-fallback'; 702 + } 703 + server.listen(PORT, HOST, onListen); 704 + } else { 705 + console.error('Server failed to bind:', err.message); 706 + process.exit(1); 707 + } 708 + }); 709 + server.listen(PORT, HOST, onListen); 710 + } 711 + 712 + if (require.main === module) { 713 + startServer(); 714 + } 715 + 716 + module.exports = { 717 + computeAcceptKey, 718 + encodeFrame, 719 + decodeFrame, 720 + browserLauncherForPlatform, 721 + OPCODES, 722 + MAX_FRAME_PAYLOAD_BYTES 723 + };
+209
.agents/skills/brainstorming/scripts/start-server.sh
··· 1 + #!/usr/bin/env bash 2 + # Start the brainstorm server and output connection info 3 + # Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background] 4 + # 5 + # Starts server on a random high port, outputs JSON with URL. 6 + # Each session gets its own directory to avoid conflicts. 7 + # 8 + # Options: 9 + # --project-dir <path> Store session files under <path>/.superpowers/brainstorm/ 10 + # instead of /tmp. Files persist after server stops. 11 + # --host <bind-host> Host/interface to bind (default: 127.0.0.1). 12 + # Use 0.0.0.0 in remote/containerized environments. 13 + # --url-host <host> Hostname shown in returned URL JSON. 14 + # --idle-timeout-minutes <n> Shut down after n minutes idle (default 240 = 4h). 15 + # --open Auto-open the browser on the first screen (use only 16 + # after the user approves the visual companion). 17 + # --foreground Run server in the current terminal (no backgrounding). 18 + # --background Force background mode (overrides Codex auto-foreground). 19 + 20 + SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" 21 + 22 + # Parse arguments 23 + PROJECT_DIR="" 24 + FOREGROUND="false" 25 + FORCE_BACKGROUND="false" 26 + BIND_HOST="127.0.0.1" 27 + URL_HOST="" 28 + IDLE_TIMEOUT_MINUTES="" 29 + while [[ $# -gt 0 ]]; do 30 + case "$1" in 31 + --project-dir) 32 + PROJECT_DIR="$2" 33 + shift 2 34 + ;; 35 + --host) 36 + BIND_HOST="$2" 37 + shift 2 38 + ;; 39 + --url-host) 40 + URL_HOST="$2" 41 + shift 2 42 + ;; 43 + --idle-timeout-minutes) 44 + IDLE_TIMEOUT_MINUTES="$2" 45 + shift 2 46 + ;; 47 + --open) 48 + export BRAINSTORM_OPEN=1 49 + shift 50 + ;; 51 + --foreground|--no-daemon) 52 + FOREGROUND="true" 53 + shift 54 + ;; 55 + --background|--daemon) 56 + FORCE_BACKGROUND="true" 57 + shift 58 + ;; 59 + *) 60 + echo "{\"error\": \"Unknown argument: $1\"}" 61 + exit 1 62 + ;; 63 + esac 64 + done 65 + 66 + if [[ -z "$URL_HOST" ]]; then 67 + if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then 68 + URL_HOST="localhost" 69 + else 70 + URL_HOST="$BIND_HOST" 71 + fi 72 + fi 73 + 74 + if [[ -n "$IDLE_TIMEOUT_MINUTES" ]]; then 75 + if ! [[ "$IDLE_TIMEOUT_MINUTES" =~ ^[0-9]+$ ]] || [[ "$IDLE_TIMEOUT_MINUTES" -lt 1 ]]; then 76 + echo "{\"error\": \"--idle-timeout-minutes must be a positive integer\"}" 77 + exit 1 78 + fi 79 + export BRAINSTORM_IDLE_TIMEOUT_MS=$(( IDLE_TIMEOUT_MINUTES * 60 * 1000 )) 80 + fi 81 + 82 + is_windows_like_shell() { 83 + case "${OSTYPE:-}" in 84 + msys*|cygwin*|mingw*) return 0 ;; 85 + esac 86 + if [[ -n "${MSYSTEM:-}" ]]; then 87 + return 0 88 + fi 89 + local uname_s 90 + uname_s="$(uname -s 2>/dev/null || true)" 91 + case "$uname_s" in 92 + MSYS*|MINGW*|CYGWIN*) return 0 ;; 93 + esac 94 + return 1 95 + } 96 + 97 + # Some environments reap detached/background processes. Auto-foreground when detected. 98 + if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then 99 + FOREGROUND="true" 100 + fi 101 + 102 + # Windows/Git Bash reaps nohup background processes. Auto-foreground when detected. 103 + if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then 104 + if is_windows_like_shell; then 105 + FOREGROUND="true" 106 + fi 107 + fi 108 + 109 + # Session files (server.log, server-info, .last-token) embed the session key — 110 + # keep everything this script and the server create owner-only. 111 + umask 077 112 + 113 + # Generate unique session directory 114 + SESSION_ID="$$-$(date +%s)" 115 + 116 + if [[ -n "$PROJECT_DIR" ]]; then 117 + SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}" 118 + # Persist the bound port and key per project so a restart reuses them and an 119 + # already-open browser tab reconnects to the same URL with a valid cookie. 120 + export BRAINSTORM_PORT_FILE="${PROJECT_DIR}/.superpowers/brainstorm/.last-port" 121 + export BRAINSTORM_TOKEN_FILE="${PROJECT_DIR}/.superpowers/brainstorm/.last-token" 122 + else 123 + SESSION_DIR="/tmp/brainstorm-${SESSION_ID}" 124 + fi 125 + 126 + STATE_DIR="${SESSION_DIR}/state" 127 + PID_FILE="${STATE_DIR}/server.pid" 128 + LOG_FILE="${STATE_DIR}/server.log" 129 + SERVER_ID_FILE="${STATE_DIR}/server-instance-id" 130 + 131 + # Create fresh session directory with content and state peers 132 + mkdir -p "${SESSION_DIR}/content" "$STATE_DIR" 133 + 134 + SERVER_ID="" 135 + if [[ -r /dev/urandom ]]; then 136 + SERVER_ID="$(od -An -N24 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n' || true)" 137 + fi 138 + if ! [[ "$SERVER_ID" =~ ^[A-Za-z0-9_-]{32,64}$ ]]; then 139 + SERVER_ID="$(printf '%08x%08x%08x%08x' "$$" "$(date +%s)" "${RANDOM:-0}" "${RANDOM:-0}")" 140 + fi 141 + printf '%s\n' "$SERVER_ID" > "$SERVER_ID_FILE" 142 + chmod 600 "$SERVER_ID_FILE" 2>/dev/null || true 143 + 144 + # Kill any existing server 145 + if [[ -f "$PID_FILE" ]]; then 146 + old_pid=$(cat "$PID_FILE") 147 + kill "$old_pid" 2>/dev/null 148 + rm -f "$PID_FILE" 149 + fi 150 + 151 + cd "$SCRIPT_DIR" || exit 1 152 + 153 + # Resolve the harness PID (grandparent of this script). 154 + # $PPID is the ephemeral shell the harness spawned to run us — it dies 155 + # when this script exits. The harness itself is $PPID's parent. 156 + OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')" 157 + if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then 158 + OWNER_PID="$PPID" 159 + fi 160 + 161 + # Windows/MSYS2: Node.js cannot see POSIX PIDs from the MSYS2 namespace. 162 + # Passing a PID node cannot verify causes server to log owner-pid-invalid 163 + # and self-terminate at the 60-second lifecycle check. Clear it so the 164 + # watchdog is disabled and the idle timeout becomes the only shutdown trigger. 165 + if is_windows_like_shell; then 166 + OWNER_PID="" 167 + fi 168 + 169 + # Foreground mode for environments that reap detached/background processes. 170 + if [[ "$FOREGROUND" == "true" ]]; then 171 + env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" & 172 + SERVER_PID=$! 173 + echo "$SERVER_PID" > "$PID_FILE" 174 + wait "$SERVER_PID" 175 + exit $? 176 + fi 177 + 178 + # Start server, capturing output to log file 179 + # Use nohup to survive shell exit; disown to remove from job table 180 + nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" > "$LOG_FILE" 2>&1 & 181 + SERVER_PID=$! 182 + disown "$SERVER_PID" 2>/dev/null 183 + echo "$SERVER_PID" > "$PID_FILE" 184 + 185 + # Wait for server-started message (check log file) 186 + for _ in {1..50}; do 187 + if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then 188 + # Verify server is still alive after a short window (catches process reapers) 189 + alive="true" 190 + for _ in {1..20}; do 191 + if ! kill -0 "$SERVER_PID" 2>/dev/null; then 192 + alive="false" 193 + break 194 + fi 195 + sleep 0.1 196 + done 197 + if [[ "$alive" != "true" ]]; then 198 + echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}" 199 + exit 1 200 + fi 201 + grep "server-started" "$LOG_FILE" | head -1 202 + exit 0 203 + fi 204 + sleep 0.1 205 + done 206 + 207 + # Timeout - server didn't start 208 + echo '{"error": "Server failed to start within 5 seconds"}' 209 + exit 1
+120
.agents/skills/brainstorming/scripts/stop-server.sh
··· 1 + #!/usr/bin/env bash 2 + # Stop the brainstorm server and clean up 3 + # Usage: stop-server.sh <session_dir> 4 + # 5 + # Kills the server process. Only deletes session directory if it's 6 + # under /tmp (ephemeral). Persistent directories (.superpowers/) are 7 + # kept so mockups can be reviewed later. 8 + 9 + SESSION_DIR="$1" 10 + 11 + if [[ -z "$SESSION_DIR" ]]; then 12 + echo '{"error": "Usage: stop-server.sh <session_dir>"}' 13 + exit 1 14 + fi 15 + 16 + STATE_DIR="${SESSION_DIR}/state" 17 + PID_FILE="${STATE_DIR}/server.pid" 18 + SERVER_ID_FILE="${STATE_DIR}/server-instance-id" 19 + 20 + mark_stopped() { 21 + local reason="$1" 22 + rm -f "${STATE_DIR}/server-info" 23 + printf '{"reason":"%s","timestamp":%s}\n' "$reason" "$(date +%s)" > "${STATE_DIR}/server-stopped" 24 + } 25 + 26 + read_expected_server_id() { 27 + [[ -f "$SERVER_ID_FILE" ]] || return 1 28 + local id 29 + id="$(tr -d '\r\n' < "$SERVER_ID_FILE" 2>/dev/null || true)" 30 + [[ "$id" =~ ^[A-Za-z0-9_-]{32,64}$ ]] || return 1 31 + printf '%s\n' "$id" 32 + } 33 + 34 + command_line_for_pid() { 35 + local pid="$1" 36 + if [[ -r "/proc/$pid/cmdline" ]]; then 37 + tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null || true 38 + return 0 39 + fi 40 + ps -ww -p "$pid" -o command= 2>/dev/null || ps -f -p "$pid" 2>/dev/null | sed '1d' || true 41 + } 42 + 43 + command_has_server_id() { 44 + local pid="$1" 45 + local expected="$2" 46 + local expected_arg="--brainstorm-server-id=$expected" 47 + if [[ -r "/proc/$pid/cmdline" ]]; then 48 + local arg 49 + while IFS= read -r -d '' arg || [[ -n "$arg" ]]; do 50 + [[ "$arg" == "$expected_arg" ]] && return 0 51 + done < "/proc/$pid/cmdline" 52 + return 1 53 + fi 54 + local command_line 55 + command_line="$(command_line_for_pid "$pid")" 56 + [[ -n "$command_line" ]] || return 1 57 + case " $command_line " in 58 + *" $expected_arg "*) return 0 ;; 59 + *) return 1 ;; 60 + esac 61 + } 62 + 63 + # Confirm a PID has this session's per-start instance id, not just a familiar 64 + # process name. Ambiguous or legacy metadata fails closed as stale_pid. 65 + is_brainstorm_server() { 66 + kill -0 "$1" 2>/dev/null || return 1 67 + local expected_id 68 + expected_id="$(read_expected_server_id)" || return 1 69 + command_has_server_id "$1" "$expected_id" || return 1 70 + return 0 71 + } 72 + 73 + if [[ -f "$PID_FILE" ]]; then 74 + pid=$(cat "$PID_FILE") 75 + 76 + # Refuse to signal a PID we can't prove is our server. A stale pid file may 77 + # point at an unrelated process after a reboot/PID wraparound. 78 + if ! is_brainstorm_server "$pid"; then 79 + rm -f "$PID_FILE" "$SERVER_ID_FILE" 80 + mark_stopped "stale_pid" 81 + echo '{"status": "stale_pid"}' 82 + exit 0 83 + fi 84 + 85 + # Try to stop gracefully, fallback to force if still alive 86 + kill "$pid" 2>/dev/null || true 87 + 88 + # Wait for graceful shutdown (up to ~2s) 89 + for _ in {1..20}; do 90 + if ! kill -0 "$pid" 2>/dev/null; then 91 + break 92 + fi 93 + sleep 0.1 94 + done 95 + 96 + # If still running, escalate to SIGKILL 97 + if kill -0 "$pid" 2>/dev/null; then 98 + kill -9 "$pid" 2>/dev/null || true 99 + 100 + # Give SIGKILL a moment to take effect 101 + sleep 0.1 102 + fi 103 + 104 + if kill -0 "$pid" 2>/dev/null; then 105 + echo '{"status": "failed", "error": "process still running"}' 106 + exit 1 107 + fi 108 + 109 + rm -f "$PID_FILE" "$SERVER_ID_FILE" "${STATE_DIR}/server.log" 110 + mark_stopped "stop-server.sh" 111 + 112 + # Only delete ephemeral /tmp directories 113 + if [[ "$SESSION_DIR" == /tmp/* ]]; then 114 + rm -rf "$SESSION_DIR" 115 + fi 116 + 117 + echo '{"status": "stopped"}' 118 + else 119 + echo '{"status": "not_running"}' 120 + fi
+49
.agents/skills/brainstorming/spec-document-reviewer-prompt.md
··· 1 + # Spec Document Reviewer Prompt Template 2 + 3 + Use this template when dispatching a spec document reviewer subagent. 4 + 5 + **Purpose:** Verify the spec is complete, consistent, and ready for implementation planning. 6 + 7 + **Dispatch after:** Spec document is written to docs/superpowers/specs/ 8 + 9 + ``` 10 + Subagent (general-purpose): 11 + description: "Review spec document" 12 + prompt: | 13 + You are a spec document reviewer. Verify this spec is complete and ready for planning. 14 + 15 + **Spec to review:** [SPEC_FILE_PATH] 16 + 17 + ## What to Check 18 + 19 + | Category | What to Look For | 20 + |----------|------------------| 21 + | Completeness | TODOs, placeholders, "TBD", incomplete sections | 22 + | Consistency | Internal contradictions, conflicting requirements | 23 + | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing | 24 + | Scope | Focused enough for a single plan — not covering multiple independent subsystems | 25 + | YAGNI | Unrequested features, over-engineering | 26 + 27 + ## Calibration 28 + 29 + **Only flag issues that would cause real problems during implementation planning.** 30 + A missing section, a contradiction, or a requirement so ambiguous it could be 31 + interpreted two different ways — those are issues. Minor wording improvements, 32 + stylistic preferences, and "sections less detailed than others" are not. 33 + 34 + Approve unless there are serious gaps that would lead to a flawed plan. 35 + 36 + ## Output Format 37 + 38 + ## Spec Review 39 + 40 + **Status:** Approved | Issues Found 41 + 42 + **Issues (if any):** 43 + - [Section X]: [specific issue] - [why it matters for planning] 44 + 45 + **Recommendations (advisory, do not block approval):** 46 + - [suggestions for improvement] 47 + ``` 48 + 49 + **Reviewer returns:** Status, Issues (if any), Recommendations
+291
.agents/skills/brainstorming/visual-companion.md
··· 1 + # Visual Companion Guide 2 + 3 + Browser-based visual brainstorming companion for showing mockups, diagrams, and options. 4 + 5 + ## When to Use 6 + 7 + Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?** 8 + 9 + **Use the browser** when the content itself is visual: 10 + 11 + - **UI mockups** — wireframes, layouts, navigation structures, component designs 12 + - **Architecture diagrams** — system components, data flow, relationship maps 13 + - **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions 14 + - **Design polish** — when the question is about look and feel, spacing, visual hierarchy 15 + - **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams 16 + 17 + **Use the terminal** when the content is text or tabular: 18 + 19 + - **Requirements and scope questions** — "what does X mean?", "which features are in scope?" 20 + - **Conceptual A/B/C choices** — picking between approaches described in words 21 + - **Tradeoff lists** — pros/cons, comparison tables 22 + - **Technical decisions** — API design, data modeling, architectural approach selection 23 + - **Clarifying questions** — anything where the answer is words, not a visual preference 24 + 25 + A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser. 26 + 27 + ## How It Works 28 + 29 + The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn. 30 + 31 + **Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, connection status, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page. 32 + 33 + ## Starting a Session 34 + 35 + ```bash 36 + # Start AFTER the user approves the companion. --open auto-opens their browser on 37 + # the first screen; --project-dir persists mockups and enables same-port restart. 38 + scripts/start-server.sh --project-dir /path/to/project --open 39 + 40 + # Returns: {"type":"server-started","port":52341, 41 + # "url":"http://localhost:52341/?key=ab12…", 42 + # "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content", 43 + # "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"} 44 + ``` 45 + 46 + Save `screen_dir` and `state_dir` from the response. With `--open`, the browser opens itself when you push the first screen — you don't need to ask the user to open it, but still share the URL as a fallback (headless/remote setups won't auto-open). 47 + 48 + **The URL contains a session key (`?key=…`).** The server rejects any request 49 + without it, so always give the user the **complete** URL from the `url` field — 50 + never strip the query string, and never hand out a bare `http://host:port`. The 51 + key gates HTTP and WebSocket access so a stray browser tab or another machine on 52 + the network can't read the screens or inject events. After the first load the 53 + browser remembers the key via a cookie, so reloads and `/files/*` assets work 54 + without repeating it. 55 + 56 + **Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory. 57 + 58 + **Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there. 59 + 60 + **Launching the server by platform:** 61 + 62 + **Claude Code:** 63 + ```bash 64 + # Default mode works — the script backgrounds the server itself. 65 + scripts/start-server.sh --project-dir /path/to/project --open 66 + ``` 67 + 68 + On Windows, the script auto-detects and switches to foreground mode (which blocks the tool call). Use `run_in_background: true` on the Bash tool call so the server survives across conversation turns, then read `$STATE_DIR/server-info` on the next turn to get the URL and port. 69 + 70 + **Codex:** 71 + ```bash 72 + # Codex reaps background processes. The script auto-detects CODEX_CI and 73 + # switches to foreground mode. Run it normally — no extra flags needed. 74 + scripts/start-server.sh --project-dir /path/to/project --open 75 + ``` 76 + 77 + **Copilot CLI:** 78 + ```bash 79 + # Use --foreground and start the server via the bash tool with mode: "async" 80 + # so the process survives across turns. Capture the returned shellId for 81 + # read_bash / stop_bash if you need to interact with it later. 82 + scripts/start-server.sh --project-dir /path/to/project --open --foreground 83 + ``` 84 + 85 + **Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism. 86 + 87 + If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host: 88 + 89 + ```bash 90 + scripts/start-server.sh \ 91 + --project-dir /path/to/project \ 92 + --host 0.0.0.0 \ 93 + --url-host localhost 94 + ``` 95 + 96 + Use `--url-host` to control what hostname is printed in the returned URL JSON. 97 + 98 + ## The Loop 99 + 100 + 1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`: 101 + - **Required: confirm the server is alive before referring to the URL or pushing a screen.** Check that `$STATE_DIR/server-info` exists and `$STATE_DIR/server-stopped` does not. If it has shut down, restart it with `start-server.sh` using the **same `--project-dir`** — it reuses the same port, so the user's open tab reconnects on its own (it shows a "paused" overlay while the server is down) and you don't need to send a new URL. The server auto-exits after 4 hours idle (configurable with `--idle-timeout-minutes`). 102 + - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html` 103 + - **Never reuse filenames** — each screen gets a fresh file 104 + - Use your file-creation tool — **never use cat/heredoc** (dumps noise into terminal) 105 + - Server automatically serves the newest file 106 + 107 + 2. **Tell user what to expect and end your turn:** 108 + - Remind them of the URL (every step, not just first) 109 + - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage") 110 + - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like." 111 + 112 + 3. **On your next turn** — after the user responds in the terminal: 113 + - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines 114 + - Merge with the user's terminal text to get the full picture 115 + - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data 116 + 117 + 4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated. 118 + 119 + 5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content: 120 + 121 + ```html 122 + <!-- filename: waiting.html (or waiting-2.html, etc.) --> 123 + <div style="display:flex;align-items:center;justify-content:center;min-height:60vh"> 124 + <p class="subtitle">Continuing in terminal...</p> 125 + </div> 126 + ``` 127 + 128 + This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual. 129 + 130 + 6. Repeat until done. 131 + 132 + ## Writing Content Fragments 133 + 134 + Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, connection status, and all interactive infrastructure). 135 + 136 + **Minimal example:** 137 + 138 + ```html 139 + <h2>Which layout works better?</h2> 140 + <p class="subtitle">Consider readability and visual hierarchy</p> 141 + 142 + <div class="options"> 143 + <div class="option" data-choice="a" onclick="toggleSelect(this)"> 144 + <div class="letter">A</div> 145 + <div class="content"> 146 + <h3>Single Column</h3> 147 + <p>Clean, focused reading experience</p> 148 + </div> 149 + </div> 150 + <div class="option" data-choice="b" onclick="toggleSelect(this)"> 151 + <div class="letter">B</div> 152 + <div class="content"> 153 + <h3>Two Column</h3> 154 + <p>Sidebar navigation with main content</p> 155 + </div> 156 + </div> 157 + </div> 158 + ``` 159 + 160 + That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that. 161 + 162 + ## CSS Classes Available 163 + 164 + The frame template provides these CSS classes for your content: 165 + 166 + ### Options (A/B/C choices) 167 + 168 + ```html 169 + <div class="options"> 170 + <div class="option" data-choice="a" onclick="toggleSelect(this)"> 171 + <div class="letter">A</div> 172 + <div class="content"> 173 + <h3>Title</h3> 174 + <p>Description</p> 175 + </div> 176 + </div> 177 + </div> 178 + ``` 179 + 180 + **Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item's selected styling. 181 + 182 + ```html 183 + <div class="options" data-multiselect> 184 + <!-- same option markup — users can select/deselect multiple --> 185 + </div> 186 + ``` 187 + 188 + ### Cards (visual designs) 189 + 190 + ```html 191 + <div class="cards"> 192 + <div class="card" data-choice="design1" onclick="toggleSelect(this)"> 193 + <div class="card-image"><!-- mockup content --></div> 194 + <div class="card-body"> 195 + <h3>Name</h3> 196 + <p>Description</p> 197 + </div> 198 + </div> 199 + </div> 200 + ``` 201 + 202 + ### Mockup container 203 + 204 + ```html 205 + <div class="mockup"> 206 + <div class="mockup-header">Preview: Dashboard Layout</div> 207 + <div class="mockup-body"><!-- your mockup HTML --></div> 208 + </div> 209 + ``` 210 + 211 + ### Split view (side-by-side) 212 + 213 + ```html 214 + <div class="split"> 215 + <div class="mockup"><!-- left --></div> 216 + <div class="mockup"><!-- right --></div> 217 + </div> 218 + ``` 219 + 220 + ### Pros/Cons 221 + 222 + ```html 223 + <div class="pros-cons"> 224 + <div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div> 225 + <div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div> 226 + </div> 227 + ``` 228 + 229 + ### Mock elements (wireframe building blocks) 230 + 231 + ```html 232 + <div class="mock-nav">Logo | Home | About | Contact</div> 233 + <div style="display: flex;"> 234 + <div class="mock-sidebar">Navigation</div> 235 + <div class="mock-content">Main content area</div> 236 + </div> 237 + <button class="mock-button">Action Button</button> 238 + <input class="mock-input" placeholder="Input field"> 239 + <div class="placeholder">Placeholder area</div> 240 + ``` 241 + 242 + ### Typography and sections 243 + 244 + - `h2` — page title 245 + - `h3` — section heading 246 + - `.subtitle` — secondary text below title 247 + - `.section` — content block with bottom margin 248 + - `.label` — small uppercase label text 249 + 250 + ## Browser Events Format 251 + 252 + When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen. 253 + 254 + ```jsonl 255 + {"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101} 256 + {"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108} 257 + {"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115} 258 + ``` 259 + 260 + The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about. 261 + 262 + If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text. 263 + 264 + ## Design Tips 265 + 266 + - **Scale fidelity to the question** — wireframes for layout, polish for polish questions 267 + - **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one" 268 + - **Iterate before advancing** — if feedback changes current screen, write a new version 269 + - **2-4 options max** per screen 270 + - **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues. 271 + - **Keep mockups simple** — focus on layout and structure, not pixel-perfect design 272 + 273 + ## File Naming 274 + 275 + - Use semantic names: `platform.html`, `visual-style.html`, `layout.html` 276 + - Never reuse filenames — each screen must be a new file 277 + - For iterations: append version suffix like `layout-v2.html`, `layout-v3.html` 278 + - Server serves newest file by modification time 279 + 280 + ## Cleaning Up 281 + 282 + ```bash 283 + scripts/stop-server.sh $SESSION_DIR 284 + ``` 285 + 286 + If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop. 287 + 288 + ## Reference 289 + 290 + - Frame template (CSS reference): `scripts/frame-template.html` 291 + - Helper script (client-side): `scripts/helper.js`
+202
.agents/skills/using-git-worktrees/SKILL.md
··· 1 + --- 2 + name: using-git-worktrees 3 + description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback 4 + --- 5 + 6 + # Using Git Worktrees 7 + 8 + ## Overview 9 + 10 + Ensure work happens in an isolated workspace. Prefer your platform's native worktree tools. Fall back to manual git worktrees only when no native tool is available. 11 + 12 + **Core principle:** Detect existing isolation first. Then use native tools. Then fall back to git. Never fight the harness. 13 + 14 + **Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace." 15 + 16 + ## Step 0: Detect Existing Isolation 17 + 18 + **Before creating anything, check if you are already in an isolated workspace.** 19 + 20 + ```bash 21 + GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P) 22 + GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P) 23 + BRANCH=$(git branch --show-current) 24 + ``` 25 + 26 + **Submodule guard:** `GIT_DIR != GIT_COMMON` is also true inside git submodules. Before concluding "already in a worktree," verify you are not in a submodule: 27 + 28 + ```bash 29 + # If this returns a path, you're in a submodule, not a worktree — treat as normal repo 30 + git rev-parse --show-superproject-working-tree 2>/dev/null 31 + ``` 32 + 33 + **If `GIT_DIR != GIT_COMMON` (and not a submodule):** You are already in a linked worktree. Skip to Step 2 (Project Setup). Do NOT create another worktree. 34 + 35 + Report with branch state: 36 + - On a branch: "Already in isolated workspace at `<path>` on branch `<name>`." 37 + - Detached HEAD: "Already in isolated workspace at `<path>` (detached HEAD, externally managed). Branch creation needed at finish time." 38 + 39 + **If `GIT_DIR == GIT_COMMON` (or in a submodule):** You are in a normal repo checkout. 40 + 41 + Has the user already indicated their worktree preference in your instructions? If not, ask for consent before creating a worktree: 42 + 43 + > "Would you like me to set up an isolated worktree? It protects your current branch from changes." 44 + 45 + Honor any existing declared preference without asking. If the user declines consent, work in place and skip to Step 2. 46 + 47 + ## Step 1: Create Isolated Workspace 48 + 49 + **You have two mechanisms. Try them in this order.** 50 + 51 + ### 1a. Native Worktree Tools (preferred) 52 + 53 + The user has asked for an isolated workspace (Step 0 consent). Do you already have a way to create a worktree? It might be a tool with a name like `EnterWorktree`, `WorktreeCreate`, a `/worktree` command, or a `--worktree` flag. If you do, use it and skip to Step 2. 54 + 55 + Native tools handle directory placement, branch creation, and cleanup automatically. Using `git worktree add` when you have a native tool creates phantom state your harness can't see or manage. 56 + 57 + Only proceed to Step 1b if you have no native worktree tool available. 58 + 59 + ### 1b. Git Worktree Fallback 60 + 61 + **Only use this if Step 1a does not apply** — you have no native worktree tool available. Create a worktree manually using git. 62 + 63 + #### Directory Selection 64 + 65 + Follow this priority order. Explicit user preference always beats observed filesystem state. 66 + 67 + 1. **Check your instructions for a declared worktree directory preference.** If the user has already specified one, use it without asking. 68 + 69 + 2. **Check for an existing project-local worktree directory:** 70 + ```bash 71 + ls -d .worktrees 2>/dev/null # Preferred (hidden) 72 + ls -d worktrees 2>/dev/null # Alternative 73 + ``` 74 + If found, use it. If both exist, `.worktrees` wins. 75 + 76 + 3. **If there is no other guidance available**, default to `.worktrees/` at the project root. 77 + 78 + #### Safety Verification (project-local directories only) 79 + 80 + **MUST verify directory is ignored before creating worktree:** 81 + 82 + ```bash 83 + git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null 84 + ``` 85 + 86 + **If NOT ignored:** Add to .gitignore, commit the change, then proceed. 87 + 88 + **Why critical:** Prevents accidentally committing worktree contents to repository. 89 + 90 + #### Create the Worktree 91 + 92 + ```bash 93 + # Determine path based on chosen location 94 + path="$LOCATION/$BRANCH_NAME" 95 + 96 + git worktree add "$path" -b "$BRANCH_NAME" 97 + cd "$path" 98 + ``` 99 + 100 + **Sandbox fallback:** If `git worktree add` fails with a permission error (sandbox denial), tell the user the sandbox blocked worktree creation and you're working in the current directory instead. Then run setup and baseline tests in place. 101 + 102 + ## Step 2: Project Setup 103 + 104 + Auto-detect and run appropriate setup: 105 + 106 + ```bash 107 + # Node.js 108 + if [ -f package.json ]; then npm install; fi 109 + 110 + # Rust 111 + if [ -f Cargo.toml ]; then cargo build; fi 112 + 113 + # Python 114 + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 115 + if [ -f pyproject.toml ]; then poetry install; fi 116 + 117 + # Go 118 + if [ -f go.mod ]; then go mod download; fi 119 + ``` 120 + 121 + ## Step 3: Verify Clean Baseline 122 + 123 + Run tests to ensure workspace starts clean: 124 + 125 + ```bash 126 + # Use project-appropriate command 127 + npm test / cargo test / pytest / go test ./... 128 + ``` 129 + 130 + **If tests fail:** Report failures, ask whether to proceed or investigate. 131 + 132 + **If tests pass:** Report ready. 133 + 134 + ### Report 135 + 136 + ``` 137 + Worktree ready at <full-path> 138 + Tests passing (<N> tests, 0 failures) 139 + Ready to implement <feature-name> 140 + ``` 141 + 142 + ## Quick Reference 143 + 144 + | Situation | Action | 145 + |-----------|--------| 146 + | Already in linked worktree | Skip creation (Step 0) | 147 + | In a submodule | Treat as normal repo (Step 0 guard) | 148 + | Native worktree tool available | Use it (Step 1a) | 149 + | No native tool | Git worktree fallback (Step 1b) | 150 + | `.worktrees/` exists | Use it (verify ignored) | 151 + | `worktrees/` exists | Use it (verify ignored) | 152 + | Both exist | Use `.worktrees/` | 153 + | Neither exists | Check instruction file, then default `.worktrees/` | 154 + | Directory not ignored | Add to .gitignore + commit | 155 + | Permission error on create | Sandbox fallback, work in place | 156 + | Tests fail during baseline | Report failures + ask | 157 + | No package.json/Cargo.toml | Skip dependency install | 158 + 159 + ## Common Mistakes 160 + 161 + ### Fighting the harness 162 + 163 + - **Problem:** Using `git worktree add` when the platform already provides isolation 164 + - **Fix:** Step 0 detects existing isolation. Step 1a defers to native tools. 165 + 166 + ### Skipping detection 167 + 168 + - **Problem:** Creating a nested worktree inside an existing one 169 + - **Fix:** Always run Step 0 before creating anything 170 + 171 + ### Skipping ignore verification 172 + 173 + - **Problem:** Worktree contents get tracked, pollute git status 174 + - **Fix:** Always use `git check-ignore` before creating project-local worktree 175 + 176 + ### Assuming directory location 177 + 178 + - **Problem:** Creates inconsistency, violates project conventions 179 + - **Fix:** Follow priority: explicit instructions > existing project-local directory > default 180 + 181 + ### Proceeding with failing tests 182 + 183 + - **Problem:** Can't distinguish new bugs from pre-existing issues 184 + - **Fix:** Report failures, get explicit permission to proceed 185 + 186 + ## Red Flags 187 + 188 + **Never:** 189 + - Create a worktree when Step 0 detects existing isolation 190 + - Use `git worktree add` when you have a native worktree tool (e.g., `EnterWorktree`). This is the #1 mistake — if you have it, use it. 191 + - Skip Step 1a by jumping straight to Step 1b's git commands 192 + - Create worktree without verifying it's ignored (project-local) 193 + - Skip baseline test verification 194 + - Proceed with failing tests without asking 195 + 196 + **Always:** 197 + - Run Step 0 detection first 198 + - Prefer native tools over git fallback 199 + - Follow directory priority: explicit instructions > existing project-local directory > default 200 + - Verify directory is ignored for project-local 201 + - Auto-detect and run project setup 202 + - Verify clean test baseline
+62
.agents/skills/using-superpowers/SKILL.md
··· 1 + --- 2 + name: using-superpowers 3 + description: Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions 4 + --- 5 + 6 + <SUBAGENT-STOP> 7 + If you were dispatched as a subagent to execute a specific task, ignore this skill. 8 + </SUBAGENT-STOP> 9 + 10 + <EXTREMELY-IMPORTANT> 11 + If you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill. 12 + 13 + IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT. 14 + 15 + This is not negotiable. You cannot rationalize your way out of this. 16 + </EXTREMELY-IMPORTANT> 17 + 18 + ## The Rule 19 + 20 + **Invoke relevant or requested skills BEFORE any response or action** — including clarifying questions, exploring the codebase, or checking files. If it turns out wrong for the situation, you don't have to use it. 21 + 22 + **Before entering plan mode:** if you haven't already brainstormed, invoke the brainstorming skill first. 23 + 24 + Then announce "Using [skill] to [purpose]" and follow the skill exactly. If it has a checklist, create a todo per item. 25 + 26 + ## Skill Priority 27 + 28 + When multiple skills apply, process skills come first — they set the approach, then implementation skills (frontend-design, etc.) carry it out. Brainstorming and systematic-debugging are Superpowers' most common process skills, but the rule holds for any of them. 29 + 30 + - "Let's build X" → superpowers:brainstorming first, then implementation skills. 31 + - "Fix this bug" → superpowers:systematic-debugging first, then domain skills. 32 + 33 + ## Red Flags 34 + 35 + These thoughts mean STOP—you're rationalizing: 36 + 37 + | Thought | Reality | 38 + |---------|---------| 39 + | "This is just a simple question" | Questions are tasks. Check for skills. | 40 + | "I need more context first" | Skill check comes BEFORE clarifying questions. | 41 + | "Let me explore the codebase first" | Skills tell you HOW to explore. Check first. | 42 + | "I can check git/files quickly" | Files lack conversation context. Check for skills. | 43 + | "Let me gather information first" | Skills tell you HOW to gather information. | 44 + | "This doesn't need a formal skill" | If a skill exists, use it. | 45 + | "I remember this skill" | Skills evolve. Read current version. | 46 + | "This doesn't count as a task" | Action = task. Check for skills. | 47 + | "The skill is overkill" | Simple things become complex. Use it. | 48 + | "I'll just do this one thing first" | Check BEFORE doing anything. | 49 + | "This feels productive" | Undisciplined action wastes time. Skills prevent this. | 50 + | "I know what that means" | Knowing the concept ≠ using the skill. Invoke it. | 51 + 52 + ## Platform Adaptation 53 + 54 + If your harness appears here, read its reference file for special instructions: 55 + 56 + - Codex: `references/codex-tools.md` 57 + - Pi: `references/pi-tools.md` 58 + - Antigravity: `references/antigravity-tools.md` 59 + 60 + ## User Instructions 61 + 62 + User instructions (CLAUDE.md, AGENTS.md, GEMINI.md, etc, direct requests) take precedence over skills, which in turn override default behavior. Only skip skill workflows or instructions when your human partner has explicitly told you to.
+23
.agents/skills/using-superpowers/references/antigravity-tools.md
··· 1 + # Antigravity CLI (`agy`) Tool Mapping 2 + 3 + Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On the Antigravity CLI (`agy`) these resolve to the tools below. 4 + 5 + | Action skills request | Antigravity CLI equivalent | 6 + |----------------------|----------------------| 7 + | Dispatch a subagent (`Subagent (general-purpose):` template) | `invoke_subagent` with a built-in `TypeName` — `self` for full-capability work, `research` for read-only (see [Subagent support](#subagent-support)) | 8 + | Task tracking ("create a todo", "mark complete") | a **task artifact** — `write_to_file` with `IsArtifact: true` and `ArtifactType: "task"` (see [Task tracking](#task-tracking)). **Not** `manage_task`, which manages background processes. | 9 + 10 + ## Task tracking 11 + 12 + Antigravity has **no todo tool** (`manage_task` manages background 13 + processes — `list`/`kill`/`status`/`send_input` — it is *not* a checklist). When a 14 + skill says to create a todo list or track tasks, maintain a **task artifact**: a 15 + markdown checklist saved with `write_to_file` (`IsArtifact: true`, 16 + `ArtifactMetadata.ArtifactType: "task"`), edited with `replace_file_content` / 17 + `multi_replace_file_content` as you go. 18 + 19 + At the start of any multi-step task, create the task artifact listing every step of 20 + your plan. As you complete each step, edit the artifact to mark it done (`- [x]`). 21 + If the plan changes, update the checklist. Keep it current — it is your source of 22 + truth for what remains; once the conversation gets long, re-read it before starting 23 + each step.
+39
.agents/skills/using-superpowers/references/codex-tools.md
··· 1 + ## Subagent dispatch requires multi-agent support 2 + 3 + Add to your Codex config (`~/.codex/config.toml`): 4 + 5 + ```toml 6 + [features] 7 + multi_agent = true 8 + ``` 9 + 10 + This enables `spawn_agent`, `wait_agent`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`. When using subagent-driven-development, you should always close implementer and reviewer subagents when they have finished all their work. 11 + 12 + ## Environment Detection 13 + 14 + Skills that create worktrees or finish branches should detect their 15 + environment with read-only git commands before proceeding: 16 + 17 + ```bash 18 + GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P) 19 + GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P) 20 + BRANCH=$(git branch --show-current) 21 + ``` 22 + 23 + - `GIT_DIR != GIT_COMMON` → already in a linked worktree (skip creation) 24 + - `BRANCH` empty → detached HEAD (cannot branch/push/PR from sandbox) 25 + 26 + See `using-git-worktrees` Step 0 and `finishing-a-development-branch` 27 + Step 1 for how each skill uses these signals. 28 + 29 + ## Codex App Finishing 30 + 31 + When the sandbox blocks branch/push operations (detached HEAD in an 32 + externally managed worktree), the agent commits all work and informs 33 + the user to use the App's native controls: 34 + 35 + - **"Create branch"** — names the branch, then commit/push/PR via App UI 36 + - **"Hand off to local"** — transfers work to the user's local checkout 37 + 38 + The agent can still run tests, stage files, and output suggested branch 39 + names, commit messages, and PR descriptions for the user to copy.
+16
.agents/skills/using-superpowers/references/pi-tools.md
··· 1 + # Pi Tool Mapping 2 + 3 + Skills speak in actions ("dispatch a subagent", "create a todo", "read a file"). On Pi these resolve to the tools below. 4 + 5 + | Action skills request | Pi equivalent | 6 + | --- | --- | 7 + | Dispatch a subagent (`Subagent (general-purpose):` template) | Use an installed subagent tool such as `subagent` from `pi-subagents` if available | 8 + | Task tracking ("create a todo", "mark complete") | Use an installed todo/task tool if available, otherwise track tasks in the plan or `TODO.md` | 9 + 10 + ## Subagents 11 + 12 + Pi core does not ship a standard subagent tool. The `pi-subagents` package is a strong optional companion and provides a `subagent` tool with single-agent, chain, parallel, async, forked-context, and resume/status workflows. If no subagent tool is available, do not fabricate `Task` calls; execute sequentially in the current session or explain that the optional subagent capability is not installed. 13 + 14 + ## Task lists 15 + 16 + Pi core does not ship a standard task-list tool. If a todo/task extension is installed, use its documented tool. Otherwise use Superpowers plan files, checklists in Markdown, or a repo-local `TODO.md` for task tracking. Older Superpowers docs may refer to `TodoWrite`; treat that as the task-tracking action above.
+139
.agents/skills/verification-before-completion/SKILL.md
··· 1 + --- 2 + name: verification-before-completion 3 + description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always 4 + --- 5 + 6 + # Verification Before Completion 7 + 8 + ## Overview 9 + 10 + Claiming work is complete without verification is dishonesty, not efficiency. 11 + 12 + **Core principle:** Evidence before claims, always. 13 + 14 + **Violating the letter of this rule is violating the spirit of this rule.** 15 + 16 + ## The Iron Law 17 + 18 + ``` 19 + NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE 20 + ``` 21 + 22 + If you haven't run the verification command in this message, you cannot claim it passes. 23 + 24 + ## The Gate Function 25 + 26 + ``` 27 + BEFORE claiming any status or expressing satisfaction: 28 + 29 + 1. IDENTIFY: What command proves this claim? 30 + 2. RUN: Execute the FULL command (fresh, complete) 31 + 3. READ: Full output, check exit code, count failures 32 + 4. VERIFY: Does output confirm the claim? 33 + - If NO: State actual status with evidence 34 + - If YES: State claim WITH evidence 35 + 5. ONLY THEN: Make the claim 36 + 37 + Skip any step = lying, not verifying 38 + ``` 39 + 40 + ## Common Failures 41 + 42 + | Claim | Requires | Not Sufficient | 43 + |-------|----------|----------------| 44 + | Tests pass | Test command output: 0 failures | Previous run, "should pass" | 45 + | Linter clean | Linter output: 0 errors | Partial check, extrapolation | 46 + | Build succeeds | Build command: exit 0 | Linter passing, logs look good | 47 + | Bug fixed | Test original symptom: passes | Code changed, assumed fixed | 48 + | Regression test works | Red-green cycle verified | Test passes once | 49 + | Agent completed | VCS diff shows changes | Agent reports "success" | 50 + | Requirements met | Line-by-line checklist | Tests passing | 51 + 52 + ## Red Flags - STOP 53 + 54 + - Using "should", "probably", "seems to" 55 + - Expressing satisfaction before verification ("Great!", "Perfect!", "Done!", etc.) 56 + - About to commit/push/PR without verification 57 + - Trusting agent success reports 58 + - Relying on partial verification 59 + - Thinking "just this once" 60 + - Tired and wanting work over 61 + - **ANY wording implying success without having run verification** 62 + 63 + ## Rationalization Prevention 64 + 65 + | Excuse | Reality | 66 + |--------|---------| 67 + | "Should work now" | RUN the verification | 68 + | "I'm confident" | Confidence ≠ evidence | 69 + | "Just this once" | No exceptions | 70 + | "Linter passed" | Linter ≠ compiler | 71 + | "Agent said success" | Verify independently | 72 + | "I'm tired" | Exhaustion ≠ excuse | 73 + | "Partial check is enough" | Partial proves nothing | 74 + | "Different words so rule doesn't apply" | Spirit over letter | 75 + 76 + ## Key Patterns 77 + 78 + **Tests:** 79 + ``` 80 + ✅ [Run test command] [See: 34/34 pass] "All tests pass" 81 + ❌ "Should pass now" / "Looks correct" 82 + ``` 83 + 84 + **Regression tests (TDD Red-Green):** 85 + ``` 86 + ✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass) 87 + ❌ "I've written a regression test" (without red-green verification) 88 + ``` 89 + 90 + **Build:** 91 + ``` 92 + ✅ [Run build] [See: exit 0] "Build passes" 93 + ❌ "Linter passed" (linter doesn't check compilation) 94 + ``` 95 + 96 + **Requirements:** 97 + ``` 98 + ✅ Re-read plan → Create checklist → Verify each → Report gaps or completion 99 + ❌ "Tests pass, phase complete" 100 + ``` 101 + 102 + **Agent delegation:** 103 + ``` 104 + ✅ Agent reports success → Check VCS diff → Verify changes → Report actual state 105 + ❌ Trust agent report 106 + ``` 107 + 108 + ## Why This Matters 109 + 110 + From 24 failure memories: 111 + - your human partner said "I don't believe you" - trust broken 112 + - Undefined functions shipped - would crash 113 + - Missing requirements shipped - incomplete features 114 + - Time wasted on false completion → redirect → rework 115 + - Violates: "Honesty is a core value. If you lie, you'll be replaced." 116 + 117 + ## When To Apply 118 + 119 + **ALWAYS before:** 120 + - ANY variation of success/completion claims 121 + - ANY expression of satisfaction 122 + - ANY positive statement about work state 123 + - Committing, PR creation, task completion 124 + - Moving to next task 125 + - Delegating to agents 126 + 127 + **Rule applies to:** 128 + - Exact phrases 129 + - Paraphrases and synonyms 130 + - Implications of success 131 + - ANY communication suggesting completion/correctness 132 + 133 + ## The Bottom Line 134 + 135 + **No shortcuts for verification.** 136 + 137 + Run the command. Read the output. THEN claim the result. 138 + 139 + This is non-negotiable.
+24
skills-lock.json
··· 1 1 { 2 2 "version": 1, 3 3 "skills": { 4 + "brainstorming": { 5 + "source": "obra/superpowers", 6 + "sourceType": "github", 7 + "skillPath": "skills/brainstorming/SKILL.md", 8 + "computedHash": "253570c46990ea018dd4520dba80cd77c35f9e5a8654057da1812face7be30cd" 9 + }, 4 10 "caveman": { 5 11 "source": "juliusbrussee/caveman", 6 12 "sourceType": "github", ··· 257 263 "sourceType": "github", 258 264 "skillPath": "skills/tui-qa/SKILL.md", 259 265 "computedHash": "8787639e27d36553490bc1ba25273eba29776bd66e4dedec752413ff3821cdee" 266 + }, 267 + "using-git-worktrees": { 268 + "source": "obra/superpowers", 269 + "sourceType": "github", 270 + "skillPath": "skills/using-git-worktrees/SKILL.md", 271 + "computedHash": "212ad917e5543e84ea3adf4e3fab537675db976fdab05d4de432870e38b49e80" 272 + }, 273 + "using-superpowers": { 274 + "source": "obra/superpowers", 275 + "sourceType": "github", 276 + "skillPath": "skills/using-superpowers/SKILL.md", 277 + "computedHash": "e94af48fd52e1c329952fae638bde84671997744901c780281aff6e6986b8f1d" 278 + }, 279 + "verification-before-completion": { 280 + "source": "obra/superpowers", 281 + "sourceType": "github", 282 + "skillPath": "skills/verification-before-completion/SKILL.md", 283 + "computedHash": "9b446f0c7fe1cfb560b1d34439523b1a76d5f177290007b2c053a1c749a4a8ba" 260 284 } 261 285 } 262 286 }