From 1e29c6d1afef6412aacd0da91e46f1577b578a46 Mon Sep 17 00:00:00 2001 From: Mathias Date: Sat, 4 Jul 2026 00:10:14 +0200 Subject: [PATCH] feat(skills): import 17 skills from local-dev; fix stale host Consolidating the divergence between this repo and local-dev's embedded ~/dev/.skills/ (the two had drifted; the 19 overlapping skills were byte-identical). - Import the 17 skills that existed only in local-dev: discovery-framing, stage-gate-review, web-shot, and the 14 superpowers-* skills. This repo is now the superset / single source of truth. - SKILLS_INDEX.md: add rows for the 17. - install.sh + Taskfile.yml: git.d-ma.be host (was stale gitea.d-ma.be, which broke the one-line curl|bash installer post-rename). Co-Authored-By: Claude Opus 4.8 (1M context) --- SKILLS_INDEX.md | 17 + Taskfile.yml | 2 +- discovery-framing/SKILL.md | 151 +++ install.sh | 4 +- stage-gate-review/SKILL.md | 147 +++ superpowers-brainstorming/SKILL.md | 164 +++ .../scripts/frame-template.html | 214 +++ superpowers-brainstorming/scripts/helper.js | 88 ++ superpowers-brainstorming/scripts/server.cjs | 354 +++++ .../scripts/start-server.sh | 148 +++ .../scripts/stop-server.sh | 56 + .../spec-document-reviewer-prompt.md | 49 + superpowers-brainstorming/visual-companion.md | 287 ++++ .../SKILL.md | 182 +++ superpowers-executing-plans/SKILL.md | 70 + .../SKILL.md | 251 ++++ superpowers-receiving-code-review/SKILL.md | 213 +++ superpowers-requesting-code-review/SKILL.md | 103 ++ .../code-reviewer.md | 168 +++ .../SKILL.md | 279 ++++ .../code-quality-reviewer-prompt.md | 25 + .../implementer-prompt.md | 113 ++ .../spec-reviewer-prompt.md | 61 + .../CREATION-LOG.md | 119 ++ superpowers-systematic-debugging/SKILL.md | 296 +++++ .../condition-based-waiting-example.ts | 158 +++ .../condition-based-waiting.md | 115 ++ .../defense-in-depth.md | 122 ++ .../find-polluter.sh | 63 + .../root-cause-tracing.md | 169 +++ .../test-academic.md | 14 + .../test-pressure-1.md | 58 + .../test-pressure-2.md | 68 + .../test-pressure-3.md | 69 + superpowers-test-driven-development/SKILL.md | 371 ++++++ .../testing-anti-patterns.md | 299 +++++ superpowers-using-git-worktrees/SKILL.md | 215 +++ superpowers-using-superpowers/SKILL.md | 117 ++ .../references/codex-tools.md | 59 + .../references/copilot-tools.md | 42 + .../references/gemini-tools.md | 51 + .../SKILL.md | 139 ++ superpowers-writing-plans/SKILL.md | 152 +++ .../plan-document-reviewer-prompt.md | 49 + superpowers-writing-skills/SKILL.md | 655 ++++++++++ .../anthropic-best-practices.md | 1150 +++++++++++++++++ .../examples/CLAUDE_MD_TESTING.md | 189 +++ .../graphviz-conventions.dot | 172 +++ .../persuasion-principles.md | 187 +++ superpowers-writing-skills/render-graphs.js | 168 +++ .../testing-skills-with-subagents.md | 384 ++++++ web-shot/SKILL.md | 67 + web-shot/shot.sh | 181 +++ 53 files changed, 9041 insertions(+), 3 deletions(-) create mode 100644 discovery-framing/SKILL.md create mode 100644 stage-gate-review/SKILL.md create mode 100644 superpowers-brainstorming/SKILL.md create mode 100644 superpowers-brainstorming/scripts/frame-template.html create mode 100644 superpowers-brainstorming/scripts/helper.js create mode 100644 superpowers-brainstorming/scripts/server.cjs create mode 100755 superpowers-brainstorming/scripts/start-server.sh create mode 100755 superpowers-brainstorming/scripts/stop-server.sh create mode 100644 superpowers-brainstorming/spec-document-reviewer-prompt.md create mode 100644 superpowers-brainstorming/visual-companion.md create mode 100644 superpowers-dispatching-parallel-agents/SKILL.md create mode 100644 superpowers-executing-plans/SKILL.md create mode 100644 superpowers-finishing-a-development-branch/SKILL.md create mode 100644 superpowers-receiving-code-review/SKILL.md create mode 100644 superpowers-requesting-code-review/SKILL.md create mode 100644 superpowers-requesting-code-review/code-reviewer.md create mode 100644 superpowers-subagent-driven-development/SKILL.md create mode 100644 superpowers-subagent-driven-development/code-quality-reviewer-prompt.md create mode 100644 superpowers-subagent-driven-development/implementer-prompt.md create mode 100644 superpowers-subagent-driven-development/spec-reviewer-prompt.md create mode 100644 superpowers-systematic-debugging/CREATION-LOG.md create mode 100644 superpowers-systematic-debugging/SKILL.md create mode 100644 superpowers-systematic-debugging/condition-based-waiting-example.ts create mode 100644 superpowers-systematic-debugging/condition-based-waiting.md create mode 100644 superpowers-systematic-debugging/defense-in-depth.md create mode 100755 superpowers-systematic-debugging/find-polluter.sh create mode 100644 superpowers-systematic-debugging/root-cause-tracing.md create mode 100644 superpowers-systematic-debugging/test-academic.md create mode 100644 superpowers-systematic-debugging/test-pressure-1.md create mode 100644 superpowers-systematic-debugging/test-pressure-2.md create mode 100644 superpowers-systematic-debugging/test-pressure-3.md create mode 100644 superpowers-test-driven-development/SKILL.md create mode 100644 superpowers-test-driven-development/testing-anti-patterns.md create mode 100644 superpowers-using-git-worktrees/SKILL.md create mode 100644 superpowers-using-superpowers/SKILL.md create mode 100644 superpowers-using-superpowers/references/codex-tools.md create mode 100644 superpowers-using-superpowers/references/copilot-tools.md create mode 100644 superpowers-using-superpowers/references/gemini-tools.md create mode 100644 superpowers-verification-before-completion/SKILL.md create mode 100644 superpowers-writing-plans/SKILL.md create mode 100644 superpowers-writing-plans/plan-document-reviewer-prompt.md create mode 100644 superpowers-writing-skills/SKILL.md create mode 100644 superpowers-writing-skills/anthropic-best-practices.md create mode 100644 superpowers-writing-skills/examples/CLAUDE_MD_TESTING.md create mode 100644 superpowers-writing-skills/graphviz-conventions.dot create mode 100644 superpowers-writing-skills/persuasion-principles.md create mode 100755 superpowers-writing-skills/render-graphs.js create mode 100644 superpowers-writing-skills/testing-skills-with-subagents.md create mode 100644 web-shot/SKILL.md create mode 100755 web-shot/shot.sh diff --git a/SKILLS_INDEX.md b/SKILLS_INDEX.md index 9268d08..bca23a0 100644 --- a/SKILLS_INDEX.md +++ b/SKILLS_INDEX.md @@ -25,6 +25,23 @@ This index lists all available engineering skills. Load the full SKILL.md on dem | `grill-me` | Structured plan interrogation — Quick Poke, Full Grill, Pre-mortem | Stress-testing a plan before committing; end of Diamond 1; before promoting to pre-prod | | `telos-load` | Load TELOS intention substrate at session start | Starting any koala session; before architectural decisions; CAD pipeline entry | | `regulatory-risk-assessment` | Structured risk register for regulated-industry features | Filing a CAD issue (needs Risk: level); features touching payments, auth, external APIs, user data | +| `discovery-framing` | Problem-before-solution discovery/framing method | Framing/validating a problem before any solution; opportunity sizing | +| `stage-gate-review` | Stage-gate product governance (go/no-go council) | Preparing a Product Council ask; building a go/no-go checklist; gate review | +| `web-shot` | Screenshot a running web UI via a koala k3s Playwright job | Visual verification of a running UI when no local browser exists | +| `superpowers-brainstorming` | Structured divergent brainstorming | Generating or expanding a set of ideas | +| `superpowers-writing-plans` | Writing implementation plans | Planning substantial work before coding | +| `superpowers-executing-plans` | Executing a written plan step by step | Running an approved plan to completion | +| `superpowers-dispatching-parallel-agents` | Fan work out across parallel subagents | Decomposing work for concurrent agents | +| `superpowers-subagent-driven-development` | Subagent-driven development workflow | Building via orchestrated subagents | +| `superpowers-systematic-debugging` | Hypothesis-first systematic debugging | Diagnosing a failure methodically | +| `superpowers-test-driven-development` | TDD discipline (superpowers variant) | Red → green → refactor on a change | +| `superpowers-verification-before-completion` | Verify behavior before claiming done | Before marking any task complete | +| `superpowers-requesting-code-review` | Requesting a code review well | Asking another agent/human to review | +| `superpowers-receiving-code-review` | Acting on received review feedback | Responding to review comments | +| `superpowers-finishing-a-development-branch` | Cleanly finishing/landing a dev branch | Wrapping a branch → merge/PR | +| `superpowers-using-git-worktrees` | Isolating work with git worktrees | Parallel/isolated work in a worktree | +| `superpowers-writing-skills` | Authoring new SKILL.md skills | Creating a new reusable skill | +| `superpowers-using-superpowers` | Meta: orienting in the superpowers set | Learning how to use the superpowers skills | ## Wiring into tools diff --git a/Taskfile.yml b/Taskfile.yml index ca2c871..fc8cb0d 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -9,7 +9,7 @@ version: '3' # install.sh during the post-clone wire step. vars: - REPO_URL: 'https://gitea.d-ma.be/mathias/skills.git' + REPO_URL: 'https://git.d-ma.be/mathias/skills.git' CHECKOUT_DIR: '{{.HOME}}/.local/share/skills' CLAUDE_GLOBAL_DIR: '{{.HOME}}/.claude/skills' CRUSH_DIR: '{{.HOME}}/.config/crush/skills' diff --git a/discovery-framing/SKILL.md b/discovery-framing/SKILL.md new file mode 100644 index 0000000..8c9d171 --- /dev/null +++ b/discovery-framing/SKILL.md @@ -0,0 +1,151 @@ +--- +name: discovery-framing +description: Run the discovery / framing phase of product innovation — define and quantify a focused customer problem BEFORE any solution exists. Four movements: understand the problem space, learn about customers, identify and size problems, decide pursue/table/kill. Produces a problem brief per prioritized opportunity. Use when an idea is still vague, when someone is jumping to solutions before the problem is validated, when scoping early research, or when deciding which problems are worth pursuing. Trigger phrases include "frame the problem", "discovery", "problem statement", "is this worth building", "early research", "opportunity sizing", "we have an idea for", "how might we", "what problem are we solving". +--- + +# Discovery / Framing + +The phase before solutioning. Goal: **define and quantify a focused customer problem, +tied to a specific target segment, validated with external evidence** — so that later +investment rides on a real problem, not a pet idea. Products built on a validated problem +have a materially higher success rate; solving an unvalidated problem builds something +that solves nothing. + +This is the de-identified pattern. When run for a named client, the wrapper (their phase +names, internal tools, region structure, named teams) stays in the client boundary. + +> Pairs with [[stage-gate-review]] (this is the Frame→Concept gate's content) and the brain +> principle on solutions-looking-for-problems. Killing a bad problem here is the cheapest +> kill you will ever make. + +--- + +## The four movements + +``` +1. Understand the problem space → 2. Learn about customers + ↓ ↓ +4. Decide: pursue / table / kill ← 3. Identify & size problems +``` + +Typical envelope: weeks, not months; cheap. The whole point is to de-risk before spend. + +### 1. Understand the problem space (the ecosystem) +Map the field before judging any idea. You are not validating a solution — you are +learning the terrain. +- **Ecosystem analysis** — top trends, market size (the whole pie, not your slice), + key players (end users, customers, intermediaries), competitors and their gaps. +- **Value-exchange map** — list every player; for each, the qualitative + quantitative + value flowing to/from them; score it. **A scalable ecosystem has roughly equal value + per player** — lopsided value = it won't scale across the chain. This is the single + most overlooked check. +- **External-forces scan (PESTL + localization)** — Political, Economic, Social, + Technological, Legal, plus local/regulatory constraints that break the business model + in a given market. + +### 2. Learn about customers and end-customers +- **Personas / design targets** — behaviours, needs & values, pain points, gains. Keep + them universal where possible (cut across segments), specific where it matters. +- **Journey maps** — steps & touchpoints, emotional valence per step, pain points and + opportunity areas. Separate the customer journey from the end-customer journey. +- **Assumptions → hypotheses** — dump everything you believe true about the target + (quantity over quality), then prioritize on a **risk × certainty grid**: attack the + assumptions that are *high risk AND low certainty* first. Sort each into + **Desirability** (do they want it?), **Feasibility** (can we build it?), + **Viability** (can we make money?). Convert each prioritized assumption into a testable + hypothesis: *"If we do X, then Y will happen"* — falsifiable, specific outcome. +- **Validate externally** — research with real customers/end-customers (interviews, + focus groups, surveys, diaries). Record per persona: assumption → learning → + validated/invalidated. **External validation is non-negotiable** — a problem confirmed + only internally is not confirmed. + +### 3. Identify and size the problems +- **Problem statement** — one tight form: *"[who] needs a way to [need], but [compelling + insight from research]."* The insight cites where/how the opportunity actually manifests, + not a guess. +- **Total Addressable Problem (TAP)** — *not* market size. Market size is the pie-in-the-sky + figure. TAP = (what would they pay to solve *this specific problem*) × (how many have it), + summed across use cases. A subset of the market, honestly bounded. Sizing the problem — + not the market — is what makes prioritization real. + +### 4. Determine next steps +- **Prioritize** by TAP × strategic fit. +- **Pursue / table / kill** — every problem gets one verdict. *Kill* is a first-class + output, not a failure; a tabled problem is parked with its reason. +- **How-Might-We** — reframe each pursued pain point as an open question to spark + solution ideation. **Use verbs, not nouns — never pre-pack a solution into the HMW.** + ("HMW increase awareness…" not "HMW build an app that…"). +- **Problem brief** — one per pursued opportunity (see below). This is the deliverable that + carries into the solutioning gate. + +--- + +## The Problem Brief (required deliverable) + +A problem brief, not a solution brief. Fields: + +1. **Problem** — "We believe [user/customer/market] needs a way to [need], because/but/ + surprisingly [insight]." Quantitative proof where possible. +2. **Customer** — who has it; segment specifics; their pain points / desired gains. +3. **End-customer** (if different) — who you're ultimately innovating for. +4. **Why it matters** — to them and to you; what you observed that makes this a priority. +5. **Ecosystem** — relevant signals, localization needs, competitive/comparative landscape. +6. **Total Addressable Problem** — the bounded value of the problem. +7. **Thought-starters / HMW** — reframed questions, no solutions. +8. **Desired value & outcomes** — impact if the problem were solved. +9. **Strategic benefit** — how success is measured for the business; strategy fit. + +If a brief drifts into describing a solution, it has failed — send it back to the problem. + +--- + +## Anti-patterns + +- **Solution smuggling** — an HMW or brief that already names the answer. The discovery + is over before it began. +- **Internal-only validation** — "we all agree it's a problem." That is conviction, not + evidence. See [[stage-gate-gate-killers]]. +- **Market size as problem size** — quoting a $XXbn TAM to justify a narrow bet. +- **Skipping the kill** — every idea "has potential." A discovery phase that never kills a + problem is theatre. +- **Lopsided value exchange** — a solution that enriches one player and starves another; + it will not scale no matter how good the UX. + +--- + +## Operator judgment (hard-won) + +### Compressing discovery by stakes +- **High-stakes bet:** run all four movements hard — especially external customer research + and the riskiest-assumption tests. Don't thin the validation. +- **Low-stakes bet:** keep movement 1 (ecosystem) + movement 3 (problem statement + a rough + size). Size with **TAM / SAM / SOM** instead of a full Total Addressable Problem build. +- **Customer research can be skipped or AI-simulated for low stakes** — a well-framed agent, + prompted *as* the target persona, can give a directional read fast. Treat this as a + cheap directional signal only — it is **not** external validation and never clears a + high-stakes desirability assumption. Use it to decide whether real research is worth doing. + +### The bar for "externally validated" +No fixed floor — case by case. The invariant is the *posture*, not the count: **go looking +for disproving evidence, not reinforcing evidence.** A problem survives discovery when you +tried to kill it with real external input and couldn't — not when N people nodded along. +(Same disease as a faked gate — see [[stage-gate-gate-killers]].) + +### Tell for solution smuggling +The solution is described **crisply and confidently**, but the moment you ask *whose* problem +and *how do you know*, the answer goes **fuzzy** — the need is vague, the validation is +hand-wavy. Crisp solution + fuzzy problem = reverse-engineered justification. Stop and reframe. + +### War-story patterns (de-identified) +- **Sized big, fizzled in reality.** A problem that scored a large TAP/TAM but never + converted to sustained real-world usage. Lesson: **problem size ≠ adoption.** A big + addressable problem measures willingness to *care*, not willingness to *change behavior*. + Add a "would they actually switch/use it repeatedly?" test before trusting a large size. +- **Tabled/iceboxed a valid problem others then won.** A real problem killed or parked on + weak conviction or bad timing, which competitors later executed well. Lesson: **the kill + is not free.** Killing protects against sunk cost, but a wrong table is also a cost — + record *why* you tabled and a signal that would reopen it, so a right problem killed for + the wrong reason can come back. + +> Named instances of both war stories are client-tagged and held out of this public skill +> pending client-store decision. The transferable lesson lives here; the wrapper stays out. diff --git a/install.sh b/install.sh index 97a5454..fb58678 100755 --- a/install.sh +++ b/install.sh @@ -2,7 +2,7 @@ # install.sh — bootstrap installer for the skills library. # # Usage (one-liner, hosts without Task): -# curl -fsSL https://gitea.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash +# curl -fsSL https://git.d-ma.be/mathias/skills/raw/branch/main/install.sh | bash # # Pinned to a specific tag: # SKILLS_REF=v0.1.0 bash install.sh @@ -13,7 +13,7 @@ set -euo pipefail -REPO_URL="${SKILLS_REPO_URL:-https://gitea.d-ma.be/mathias/skills.git}" +REPO_URL="${SKILLS_REPO_URL:-https://git.d-ma.be/mathias/skills.git}" REF="${SKILLS_REF:-main}" CHECKOUT_DIR="${SKILLS_CHECKOUT_DIR:-$HOME/.local/share/skills}" CLAUDE_GLOBAL_DIR="${CLAUDE_SKILLS_DIR:-$HOME/.claude/skills}" diff --git a/stage-gate-review/SKILL.md b/stage-gate-review/SKILL.md new file mode 100644 index 0000000..d2f9514 --- /dev/null +++ b/stage-gate-review/SKILL.md @@ -0,0 +1,147 @@ +--- +name: stage-gate-review +description: Run or prepare a stage-gate product governance review — the go/no-go checkpoint where a council approves an initiative to advance through fixed innovation stages (Frame → Concept → Prototype → Validate → Scale), each gate guarded by a per-discipline readiness checklist. Use when preparing a Product Council / steering-group ask, building a go/no-go checklist, designing an innovation governance process, or auditing whether an initiative is genuinely ready to advance vs faking the gate. Trigger phrases include "stage gate", "product council", "go/no-go", "advance to the next stage", "is this ready to progress", "gate review", "phase gate", "innovation governance". +--- + +# Stage-Gate Review + +A governance pattern for moving product/innovation initiatives through fixed stages +under explicit go/no-go control. A standing council (or steering group) approves each +advance; every gate is guarded by a **per-discipline readiness checklist**. The point +is not bureaucracy — it is to kill weak bets early and fund strong ones with conviction. + +This skill is the **transferable pattern**, stripped of any client instance. When a real +engagement uses it, the client's council names, internal tooling, stage labels, and named +contacts stay inside the client boundary (see *Client instances* below) — never bake them +into this skill. + +--- + +## The gate ladder + +Five stages, escalating commitment. Each arrow is a council ask. + +| Stage | Question it answers | Funding posture | +|-------|---------------------|-----------------| +| **Frame** | Is this opportunity worth exploring? | Cheap time only | +| **Concept** | Is there a solution worth prototyping? | Small dedicated resource | +| **Prototype** | Does the solution work and is the business case real? | Build budget | +| **Validate** (market test) | Will a real customer pay / adopt? | Pilot budget + infra | +| **Scale** (commercialize) | Should we invest to grow this? | Full commercial investment | + +Key rule: **the earliest gate (Frame → Concept) is usually feedback-only**, not approval. +You bring it to the council to sharpen thinking, not to pass judgment — killing ideas at +Frame teaches teams to stop framing. Approval pressure starts at Concept. + +The bar rises each gate: hypothesis → tested hypothesis → validated evidence + business +case → signed pilot commitment → full commercial commitment. + +--- + +## The discipline checklist + +Every gate is a matrix: **the same disciplines, a higher bar each stage.** A gate ask is +"ready" only when every applicable discipline clears its bar for that stage. Adapt the +discipline set to the domain; this is the default spine. + +| Discipline | What it guards | Rises from Frame → Scale | +|------------|----------------|---------------------------| +| **Ownership** | A named, committed product owner exists | identified → secured → full commitment to commercialize | +| **Strategy fit** | Aligns with org strategy & objectives | alignment asserted → tie to portfolio confirmed | +| **Economics** | Revenue + fully-loaded cost through the horizon | rough estimate → validated business case, approved | +| **Customer/market evidence** | Real demand, tested with real people | hypotheses commissioned → tested → signed pilot partner | +| **Experience / design** | Desirability and usability validated | design lead secured → evaluative testing + quality score | +| **Technical feasibility** | Build assumptions reviewed by engineering | assumptions noted → reviewed → infra cost approved | +| **Legal / risk / compliance** | Regulatory and contractual exposure surfaced | initial review → SME overviews → docs initiated | +| **Go-to-market / region** | Launch market and support model identified | market aware → aligned → support & business model agreed | +| **Timeline** | A credible plan to complete the next stage | — | +| **System of record** | The initiative is tracked in the canonical tool | — | + +A discipline that clearly doesn't apply gets **explicitly waived** ("no regulatory surface — +legal waived"), never silently dropped. Silent omission is the most common way a gate rots. + +--- + +## Running a gate review + +**Preparing an ask (you are the team):** +1. Identify the target gate and pull its column from the matrix. +2. For each discipline, gather the evidence that clears *this stage's* bar — evidence, not + intent. "We will test" does not clear a "tested" bar. +3. Mark every discipline: cleared / waived (with reason) / gap. +4. If any gap is on a discipline that gates the whole bet, **do not bring the ask** — close + the gap or bring a feedback-only ask instead. + +**Chairing a review (you are the council):** +1. Ask for the evidence behind each "cleared", not the claim. Claims are theatre. +2. Probe the one discipline most likely to be faked for this stage (see anti-patterns). +3. Decide: advance / hold (named gaps, re-ask) / kill. A council that never kills is a + rubber stamp and the gate is worthless. + +--- + +## Anti-patterns (gate theatre) + +- **Checklist completion ≠ readiness.** Every box ticked, zero evidence. Demand artifacts. +- **The pre-approved gate.** Decision made in the hallway; council ratifies. The gate adds + cost and zero filtering. +- **Evidence inflation.** "Validated" demand that is one friendly customer's enthusiasm. +- **Skipping the kill.** Weak bets get "hold and re-ask" forever instead of a clean death. +- **Frame-stage judgment.** Approving/rejecting at Frame teaches teams to stop exploring. +- **Bar that never rises.** Same evidence accepted at Prototype as at Frame — the ladder + collapses into one gate. + +--- + +## Operator judgment (hard-won) + +The matrix above is generic best practice. This section is the part that comes from running +real reviews — apply it over the spine. + +### Which gates to collapse, and when +- **Low uncertainty + high strategic fit** (you already know the customer wants it): collapse + **Prototype + Validate** — build the real thing *as* the pilot. The separate prototype gate + buys nothing when desirability isn't the risk. +- **Moonshot / high uncertainty**: never skip **Validate** — that's the whole bet. You can + skip the formal **Concept** gate (run it feedback-only) but you cannot skip proving demand. + +### Where the gate gets faked — tells by stage +- **Concept:** "customer research" that's really 3 friendly stakeholder chats with no + disconfirming evidence sought. Worse and more common: a Concept backed only by **selective + external research carried over from Frame** — the team cherry-picks the framing-stage + evidence that flatters the idea and runs no fresh test. Reused evidence is not validation. +- **Validate:** a "signed" pilot that is actually a warm LOI — no money committed, no go-live + date. Intent dressed as commitment. + +### Minimum real evidence — calibrate to what the stage *can* know +Don't demand certainty a stage can't yield. The honest question is "how much **can** we know +at this point?" — and against that bar, **any genuine external signal beats internal +conviction**. Often the highest-value move at an early gate is simply getting *the first real +evidence at all*, where before there was only opinion. So: +- Reject "cleared" that rests purely on internal belief or reused framing evidence. +- Accept directional external evidence early; raise the bar to **committed** evidence (paid + pilot, money down, a date) by Validate. +- **Economics:** distrust a polished Year-3 revenue model. Trust fully-loaded cost plus one + defensible near-term number over a confident long-horizon fiction. + +### The two killers (what actually defeats a gate) +- **Political pre-commitment.** Some bets management simply *wants*, regardless of evidence. + A gate cannot kill what leadership has already decided. Name it when you see it — the gate + is theatre on that bet, and pretending otherwise corrodes every other gate. +- **Sunk-cost attachment.** You advance the wrong concept, then get too vested to kill it. + The antidote is a **scientific mindset with no emotional attachment to the solution**. The + disease is **solutions looking for problems to solve** — fall in love with the problem, stay + ruthless about the solution. A gate's deepest job is to enforce exactly this detachment. + +> Validated under fire — these belong in the brain as a standalone principle too, so they +> outlive this one skill. See [[solution-looking-for-problem]], [[stage-gate-sunk-cost]]. + +--- + +## Client instances + +When this pattern is instantiated for a named client, the instance is **confidential and +stays in the client boundary**: +- Council/forum names, internal stage labels, internal tooling, named contacts, strategy + specifics, deal terms → client dir/org only, local models only, never the public brain. +- This skill carries the **pattern**; the client carries the **wrapper**. Never merge them. diff --git a/superpowers-brainstorming/SKILL.md b/superpowers-brainstorming/SKILL.md new file mode 100644 index 0000000..06cd0a2 --- /dev/null +++ b/superpowers-brainstorming/SKILL.md @@ -0,0 +1,164 @@ +--- +name: brainstorming +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." +--- + +# Brainstorming Ideas Into Designs + +Help turn ideas into fully formed designs and specs through natural collaborative dialogue. + +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. + + +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. + + +## Anti-Pattern: "This Is Too Simple To Need A Design" + +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. + +## Checklist + +You MUST create a task for each of these items and complete them in order: + +1. **Explore project context** — check files, docs, recent commits +2. **Offer visual companion** (if topic will involve visual questions) — this is its own message, not combined with a clarifying question. See the Visual Companion section below. +3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria +4. **Propose 2-3 approaches** — with trade-offs and your recommendation +5. **Present design** — in sections scaled to their complexity, get user approval after each section +6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD--design.md` and commit +7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below) +8. **User reviews written spec** — ask user to review the spec file before proceeding +9. **Transition to implementation** — invoke writing-plans skill to create implementation plan + +## Process Flow + +```dot +digraph brainstorming { + "Explore project context" [shape=box]; + "Visual questions ahead?" [shape=diamond]; + "Offer Visual Companion\n(own message, no other content)" [shape=box]; + "Ask clarifying questions" [shape=box]; + "Propose 2-3 approaches" [shape=box]; + "Present design sections" [shape=box]; + "User approves design?" [shape=diamond]; + "Write design doc" [shape=box]; + "Spec self-review\n(fix inline)" [shape=box]; + "User reviews spec?" [shape=diamond]; + "Invoke writing-plans skill" [shape=doublecircle]; + + "Explore project context" -> "Visual questions ahead?"; + "Visual questions ahead?" -> "Offer Visual Companion\n(own message, no other content)" [label="yes"]; + "Visual questions ahead?" -> "Ask clarifying questions" [label="no"]; + "Offer Visual Companion\n(own message, no other content)" -> "Ask clarifying questions"; + "Ask clarifying questions" -> "Propose 2-3 approaches"; + "Propose 2-3 approaches" -> "Present design sections"; + "Present design sections" -> "User approves design?"; + "User approves design?" -> "Present design sections" [label="no, revise"]; + "User approves design?" -> "Write design doc" [label="yes"]; + "Write design doc" -> "Spec self-review\n(fix inline)"; + "Spec self-review\n(fix inline)" -> "User reviews spec?"; + "User reviews spec?" -> "Write design doc" [label="changes requested"]; + "User reviews spec?" -> "Invoke writing-plans skill" [label="approved"]; +} +``` + +**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. + +## The Process + +**Understanding the idea:** + +- Check out the current project state first (files, docs, recent commits) +- 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. +- 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. +- For appropriately-scoped projects, ask questions one at a time to refine the idea +- Prefer multiple choice questions when possible, but open-ended is fine too +- Only one question per message - if a topic needs more exploration, break it into multiple questions +- Focus on understanding: purpose, constraints, success criteria + +**Exploring approaches:** + +- Propose 2-3 different approaches with trade-offs +- Present options conversationally with your recommendation and reasoning +- Lead with your recommended option and explain why + +**Presenting the design:** + +- Once you believe you understand what you're building, present the design +- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced +- Ask after each section whether it looks right so far +- Cover: architecture, components, data flow, error handling, testing +- Be ready to go back and clarify if something doesn't make sense + +**Design for isolation and clarity:** + +- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently +- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on? +- 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. +- 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. + +**Working in existing codebases:** + +- Explore the current structure before proposing changes. Follow existing patterns. +- 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. +- Don't propose unrelated refactoring. Stay focused on what serves the current goal. + +## After the Design + +**Documentation:** + +- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD--design.md` + - (User preferences for spec location override this default) +- Use elements-of-style:writing-clearly-and-concisely skill if available +- Commit the design document to git + +**Spec Self-Review:** +After writing the spec document, look at it with fresh eyes: + +1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them. +2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions? +3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition? +4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit. + +Fix any issues inline. No need to re-review — just fix and move on. + +**User Review Gate:** +After the spec review loop passes, ask the user to review the written spec before proceeding: + +> "Spec written and committed to ``. Please review it and let me know if you want to make any changes before we start writing out the implementation plan." + +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. + +**Implementation:** + +- Invoke the writing-plans skill to create a detailed implementation plan +- Do NOT invoke any other skill. writing-plans is the next step. + +## Key Principles + +- **One question at a time** - Don't overwhelm with multiple questions +- **Multiple choice preferred** - Easier to answer than open-ended when possible +- **YAGNI ruthlessly** - Remove unnecessary features from all designs +- **Explore alternatives** - Always propose 2-3 approaches before settling +- **Incremental validation** - Present design, get approval before moving on +- **Be flexible** - Go back and clarify when something doesn't make sense + +## Visual Companion + +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. + +**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent: +> "Some of what we're working on might be easier to explain if I can show it to you in a web browser. I can put together mockups, diagrams, comparisons, and other visuals as we go. This feature is still new and can be token-intensive. Want to try it? (Requires opening a local URL)" + +**This offer MUST be its own message.** Do not combine it with clarifying questions, context summaries, or any other content. The message should contain ONLY the offer above and nothing else. Wait for the user's response before continuing. If they decline, proceed with text-only brainstorming. + +**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?** + +- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs +- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions + +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. + +If they agree to the companion, read the detailed guide before proceeding: +`skills/brainstorming/visual-companion.md` diff --git a/superpowers-brainstorming/scripts/frame-template.html b/superpowers-brainstorming/scripts/frame-template.html new file mode 100644 index 0000000..dcfe018 --- /dev/null +++ b/superpowers-brainstorming/scripts/frame-template.html @@ -0,0 +1,214 @@ + + + + + Superpowers Brainstorming + + + +
+

Superpowers Brainstorming

+
Connected
+
+ +
+
+ +
+
+ +
+ Click an option above, then return to the terminal +
+ + + diff --git a/superpowers-brainstorming/scripts/helper.js b/superpowers-brainstorming/scripts/helper.js new file mode 100644 index 0000000..111f97f --- /dev/null +++ b/superpowers-brainstorming/scripts/helper.js @@ -0,0 +1,88 @@ +(function() { + const WS_URL = 'ws://' + window.location.host; + let ws = null; + let eventQueue = []; + + function connect() { + ws = new WebSocket(WS_URL); + + ws.onopen = () => { + eventQueue.forEach(e => ws.send(JSON.stringify(e))); + eventQueue = []; + }; + + ws.onmessage = (msg) => { + const data = JSON.parse(msg.data); + if (data.type === 'reload') { + window.location.reload(); + } + }; + + ws.onclose = () => { + setTimeout(connect, 1000); + }; + } + + function sendEvent(event) { + event.timestamp = Date.now(); + if (ws && ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify(event)); + } else { + eventQueue.push(event); + } + } + + // Capture clicks on choice elements + document.addEventListener('click', (e) => { + const target = e.target.closest('[data-choice]'); + if (!target) return; + + sendEvent({ + type: 'click', + text: target.textContent.trim(), + choice: target.dataset.choice, + id: target.id || null + }); + + // Update indicator bar (defer so toggleSelect runs first) + setTimeout(() => { + const indicator = document.getElementById('indicator-text'); + if (!indicator) return; + const container = target.closest('.options') || target.closest('.cards'); + const selected = container ? container.querySelectorAll('.selected') : []; + if (selected.length === 0) { + indicator.textContent = 'Click an option above, then return to the terminal'; + } else if (selected.length === 1) { + const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice; + indicator.innerHTML = '' + label + ' selected — return to terminal to continue'; + } else { + indicator.innerHTML = '' + selected.length + ' selected — return to terminal to continue'; + } + }, 0); + }); + + // Frame UI: selection tracking + window.selectedChoice = null; + + window.toggleSelect = function(el) { + const container = el.closest('.options') || el.closest('.cards'); + const multi = container && container.dataset.multiselect !== undefined; + if (container && !multi) { + container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected')); + } + if (multi) { + el.classList.toggle('selected'); + } else { + el.classList.add('selected'); + } + window.selectedChoice = el.dataset.choice; + }; + + // Expose API for explicit use + window.brainstorm = { + send: sendEvent, + choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata }) + }; + + connect(); +})(); diff --git a/superpowers-brainstorming/scripts/server.cjs b/superpowers-brainstorming/scripts/server.cjs new file mode 100644 index 0000000..562c17f --- /dev/null +++ b/superpowers-brainstorming/scripts/server.cjs @@ -0,0 +1,354 @@ +const crypto = require('crypto'); +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +// ========== WebSocket Protocol (RFC 6455) ========== + +const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A }; +const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + +function computeAcceptKey(clientKey) { + return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64'); +} + +function encodeFrame(opcode, payload) { + const fin = 0x80; + const len = payload.length; + let header; + + if (len < 126) { + header = Buffer.alloc(2); + header[0] = fin | opcode; + header[1] = len; + } else if (len < 65536) { + header = Buffer.alloc(4); + header[0] = fin | opcode; + header[1] = 126; + header.writeUInt16BE(len, 2); + } else { + header = Buffer.alloc(10); + header[0] = fin | opcode; + header[1] = 127; + header.writeBigUInt64BE(BigInt(len), 2); + } + + return Buffer.concat([header, payload]); +} + +function decodeFrame(buffer) { + if (buffer.length < 2) return null; + + const secondByte = buffer[1]; + const opcode = buffer[0] & 0x0F; + const masked = (secondByte & 0x80) !== 0; + let payloadLen = secondByte & 0x7F; + let offset = 2; + + if (!masked) throw new Error('Client frames must be masked'); + + if (payloadLen === 126) { + if (buffer.length < 4) return null; + payloadLen = buffer.readUInt16BE(2); + offset = 4; + } else if (payloadLen === 127) { + if (buffer.length < 10) return null; + payloadLen = Number(buffer.readBigUInt64BE(2)); + offset = 10; + } + + const maskOffset = offset; + const dataOffset = offset + 4; + const totalLen = dataOffset + payloadLen; + if (buffer.length < totalLen) return null; + + const mask = buffer.slice(maskOffset, dataOffset); + const data = Buffer.alloc(payloadLen); + for (let i = 0; i < payloadLen; i++) { + data[i] = buffer[dataOffset + i] ^ mask[i % 4]; + } + + return { opcode, payload: data, bytesConsumed: totalLen }; +} + +// ========== Configuration ========== + +const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383)); +const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1'; +const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST); +const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm'; +const CONTENT_DIR = path.join(SESSION_DIR, 'content'); +const STATE_DIR = path.join(SESSION_DIR, 'state'); +let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null; + +const MIME_TYPES = { + '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', + '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml' +}; + +// ========== Templates and Constants ========== + +const WAITING_PAGE = ` + +Brainstorm Companion + + +

Brainstorm Companion

+

Waiting for the agent to push a screen...

`; + +const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8'); +const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8'); +const helperInjection = ''; + +// ========== Helper Functions ========== + +function isFullDocument(html) { + const trimmed = html.trimStart().toLowerCase(); + return trimmed.startsWith('', content); +} + +function getNewestScreen() { + const files = fs.readdirSync(CONTENT_DIR) + .filter(f => f.endsWith('.html')) + .map(f => { + const fp = path.join(CONTENT_DIR, f); + return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }; + }) + .sort((a, b) => b.mtime - a.mtime); + return files.length > 0 ? files[0].path : null; +} + +// ========== HTTP Request Handler ========== + +function handleRequest(req, res) { + touchActivity(); + if (req.method === 'GET' && req.url === '/') { + const screenFile = getNewestScreen(); + let html = screenFile + ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8')) + : WAITING_PAGE; + + if (html.includes('')) { + html = html.replace('', helperInjection + '\n'); + } else { + html += helperInjection; + } + + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(html); + } else if (req.method === 'GET' && req.url.startsWith('/files/')) { + const fileName = req.url.slice(7); + const filePath = path.join(CONTENT_DIR, path.basename(fileName)); + if (!fs.existsSync(filePath)) { + res.writeHead(404); + res.end('Not found'); + return; + } + const ext = path.extname(filePath).toLowerCase(); + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + res.writeHead(200, { 'Content-Type': contentType }); + res.end(fs.readFileSync(filePath)); + } else { + res.writeHead(404); + res.end('Not found'); + } +} + +// ========== WebSocket Connection Handling ========== + +const clients = new Set(); + +function handleUpgrade(req, socket) { + const key = req.headers['sec-websocket-key']; + if (!key) { socket.destroy(); return; } + + const accept = computeAcceptKey(key); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n' + ); + + let buffer = Buffer.alloc(0); + clients.add(socket); + + socket.on('data', (chunk) => { + buffer = Buffer.concat([buffer, chunk]); + while (buffer.length > 0) { + let result; + try { + result = decodeFrame(buffer); + } catch (e) { + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); + clients.delete(socket); + return; + } + if (!result) break; + buffer = buffer.slice(result.bytesConsumed); + + switch (result.opcode) { + case OPCODES.TEXT: + handleMessage(result.payload.toString()); + break; + case OPCODES.CLOSE: + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); + clients.delete(socket); + return; + case OPCODES.PING: + socket.write(encodeFrame(OPCODES.PONG, result.payload)); + break; + case OPCODES.PONG: + break; + default: { + const closeBuf = Buffer.alloc(2); + closeBuf.writeUInt16BE(1003); + socket.end(encodeFrame(OPCODES.CLOSE, closeBuf)); + clients.delete(socket); + return; + } + } + } + }); + + socket.on('close', () => clients.delete(socket)); + socket.on('error', () => clients.delete(socket)); +} + +function handleMessage(text) { + let event; + try { + event = JSON.parse(text); + } catch (e) { + console.error('Failed to parse WebSocket message:', e.message); + return; + } + touchActivity(); + console.log(JSON.stringify({ source: 'user-event', ...event })); + if (event.choice) { + const eventsFile = path.join(STATE_DIR, 'events'); + fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n'); + } +} + +function broadcast(msg) { + const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg))); + for (const socket of clients) { + try { socket.write(frame); } catch (e) { clients.delete(socket); } + } +} + +// ========== Activity Tracking ========== + +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes +let lastActivity = Date.now(); + +function touchActivity() { + lastActivity = Date.now(); +} + +// ========== File Watching ========== + +const debounceTimers = new Map(); + +// ========== Server Startup ========== + +function startServer() { + if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true }); + if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true }); + + // Track known files to distinguish new screens from updates. + // macOS fs.watch reports 'rename' for both new files and overwrites, + // so we can't rely on eventType alone. + const knownFiles = new Set( + fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html')) + ); + + const server = http.createServer(handleRequest); + server.on('upgrade', handleUpgrade); + + const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => { + if (!filename || !filename.endsWith('.html')) return; + + if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename)); + debounceTimers.set(filename, setTimeout(() => { + debounceTimers.delete(filename); + const filePath = path.join(CONTENT_DIR, filename); + + if (!fs.existsSync(filePath)) return; // file was deleted + touchActivity(); + + if (!knownFiles.has(filename)) { + knownFiles.add(filename); + const eventsFile = path.join(STATE_DIR, 'events'); + if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile); + console.log(JSON.stringify({ type: 'screen-added', file: filePath })); + } else { + console.log(JSON.stringify({ type: 'screen-updated', file: filePath })); + } + + broadcast({ type: 'reload' }); + }, 100)); + }); + watcher.on('error', (err) => console.error('fs.watch error:', err.message)); + + function shutdown(reason) { + console.log(JSON.stringify({ type: 'server-stopped', reason })); + const infoFile = path.join(STATE_DIR, 'server-info'); + if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile); + fs.writeFileSync( + path.join(STATE_DIR, 'server-stopped'), + JSON.stringify({ reason, timestamp: Date.now() }) + '\n' + ); + watcher.close(); + clearInterval(lifecycleCheck); + server.close(() => process.exit(0)); + } + + function ownerAlive() { + if (!ownerPid) return true; + try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; } + } + + // Check every 60s: exit if owner process died or idle for 30 minutes + const lifecycleCheck = setInterval(() => { + if (!ownerAlive()) shutdown('owner process exited'); + else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout'); + }, 60 * 1000); + lifecycleCheck.unref(); + + // Validate owner PID at startup. If it's already dead, the PID resolution + // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios). + // Disable monitoring and rely on the idle timeout instead. + if (ownerPid) { + try { process.kill(ownerPid, 0); } + catch (e) { + if (e.code !== 'EPERM') { + console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' })); + ownerPid = null; + } + } + } + + server.listen(PORT, HOST, () => { + const info = JSON.stringify({ + type: 'server-started', port: Number(PORT), host: HOST, + url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT, + screen_dir: CONTENT_DIR, state_dir: STATE_DIR + }); + console.log(info); + fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n'); + }); +} + +if (require.main === module) { + startServer(); +} + +module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES }; diff --git a/superpowers-brainstorming/scripts/start-server.sh b/superpowers-brainstorming/scripts/start-server.sh new file mode 100755 index 0000000..9ef6dcb --- /dev/null +++ b/superpowers-brainstorming/scripts/start-server.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Start the brainstorm server and output connection info +# Usage: start-server.sh [--project-dir ] [--host ] [--url-host ] [--foreground] [--background] +# +# Starts server on a random high port, outputs JSON with URL. +# Each session gets its own directory to avoid conflicts. +# +# Options: +# --project-dir Store session files under /.superpowers/brainstorm/ +# instead of /tmp. Files persist after server stops. +# --host Host/interface to bind (default: 127.0.0.1). +# Use 0.0.0.0 in remote/containerized environments. +# --url-host Hostname shown in returned URL JSON. +# --foreground Run server in the current terminal (no backgrounding). +# --background Force background mode (overrides Codex auto-foreground). + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# Parse arguments +PROJECT_DIR="" +FOREGROUND="false" +FORCE_BACKGROUND="false" +BIND_HOST="127.0.0.1" +URL_HOST="" +while [[ $# -gt 0 ]]; do + case "$1" in + --project-dir) + PROJECT_DIR="$2" + shift 2 + ;; + --host) + BIND_HOST="$2" + shift 2 + ;; + --url-host) + URL_HOST="$2" + shift 2 + ;; + --foreground|--no-daemon) + FOREGROUND="true" + shift + ;; + --background|--daemon) + FORCE_BACKGROUND="true" + shift + ;; + *) + echo "{\"error\": \"Unknown argument: $1\"}" + exit 1 + ;; + esac +done + +if [[ -z "$URL_HOST" ]]; then + if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then + URL_HOST="localhost" + else + URL_HOST="$BIND_HOST" + fi +fi + +# Some environments reap detached/background processes. Auto-foreground when detected. +if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then + FOREGROUND="true" +fi + +# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected. +if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then + case "${OSTYPE:-}" in + msys*|cygwin*|mingw*) FOREGROUND="true" ;; + esac + if [[ -n "${MSYSTEM:-}" ]]; then + FOREGROUND="true" + fi +fi + +# Generate unique session directory +SESSION_ID="$$-$(date +%s)" + +if [[ -n "$PROJECT_DIR" ]]; then + SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}" +else + SESSION_DIR="/tmp/brainstorm-${SESSION_ID}" +fi + +STATE_DIR="${SESSION_DIR}/state" +PID_FILE="${STATE_DIR}/server.pid" +LOG_FILE="${STATE_DIR}/server.log" + +# Create fresh session directory with content and state peers +mkdir -p "${SESSION_DIR}/content" "$STATE_DIR" + +# Kill any existing server +if [[ -f "$PID_FILE" ]]; then + old_pid=$(cat "$PID_FILE") + kill "$old_pid" 2>/dev/null + rm -f "$PID_FILE" +fi + +cd "$SCRIPT_DIR" + +# Resolve the harness PID (grandparent of this script). +# $PPID is the ephemeral shell the harness spawned to run us — it dies +# when this script exits. The harness itself is $PPID's parent. +OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')" +if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then + OWNER_PID="$PPID" +fi + +# Foreground mode for environments that reap detached/background processes. +if [[ "$FOREGROUND" == "true" ]]; then + echo "$$" > "$PID_FILE" + env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs + exit $? +fi + +# Start server, capturing output to log file +# Use nohup to survive shell exit; disown to remove from job table +nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 & +SERVER_PID=$! +disown "$SERVER_PID" 2>/dev/null +echo "$SERVER_PID" > "$PID_FILE" + +# Wait for server-started message (check log file) +for i in {1..50}; do + if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then + # Verify server is still alive after a short window (catches process reapers) + alive="true" + for _ in {1..20}; do + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + alive="false" + break + fi + sleep 0.1 + done + if [[ "$alive" != "true" ]]; then + 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\"}" + exit 1 + fi + grep "server-started" "$LOG_FILE" | head -1 + exit 0 + fi + sleep 0.1 +done + +# Timeout - server didn't start +echo '{"error": "Server failed to start within 5 seconds"}' +exit 1 diff --git a/superpowers-brainstorming/scripts/stop-server.sh b/superpowers-brainstorming/scripts/stop-server.sh new file mode 100755 index 0000000..a6b94e6 --- /dev/null +++ b/superpowers-brainstorming/scripts/stop-server.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Stop the brainstorm server and clean up +# Usage: stop-server.sh +# +# Kills the server process. Only deletes session directory if it's +# under /tmp (ephemeral). Persistent directories (.superpowers/) are +# kept so mockups can be reviewed later. + +SESSION_DIR="$1" + +if [[ -z "$SESSION_DIR" ]]; then + echo '{"error": "Usage: stop-server.sh "}' + exit 1 +fi + +STATE_DIR="${SESSION_DIR}/state" +PID_FILE="${STATE_DIR}/server.pid" + +if [[ -f "$PID_FILE" ]]; then + pid=$(cat "$PID_FILE") + + # Try to stop gracefully, fallback to force if still alive + kill "$pid" 2>/dev/null || true + + # Wait for graceful shutdown (up to ~2s) + for i in {1..20}; do + if ! kill -0 "$pid" 2>/dev/null; then + break + fi + sleep 0.1 + done + + # If still running, escalate to SIGKILL + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + + # Give SIGKILL a moment to take effect + sleep 0.1 + fi + + if kill -0 "$pid" 2>/dev/null; then + echo '{"status": "failed", "error": "process still running"}' + exit 1 + fi + + rm -f "$PID_FILE" "${STATE_DIR}/server.log" + + # Only delete ephemeral /tmp directories + if [[ "$SESSION_DIR" == /tmp/* ]]; then + rm -rf "$SESSION_DIR" + fi + + echo '{"status": "stopped"}' +else + echo '{"status": "not_running"}' +fi diff --git a/superpowers-brainstorming/spec-document-reviewer-prompt.md b/superpowers-brainstorming/spec-document-reviewer-prompt.md new file mode 100644 index 0000000..35acbb6 --- /dev/null +++ b/superpowers-brainstorming/spec-document-reviewer-prompt.md @@ -0,0 +1,49 @@ +# Spec Document Reviewer Prompt Template + +Use this template when dispatching a spec document reviewer subagent. + +**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning. + +**Dispatch after:** Spec document is written to docs/superpowers/specs/ + +``` +Task tool (general-purpose): + description: "Review spec document" + prompt: | + You are a spec document reviewer. Verify this spec is complete and ready for planning. + + **Spec to review:** [SPEC_FILE_PATH] + + ## What to Check + + | Category | What to Look For | + |----------|------------------| + | Completeness | TODOs, placeholders, "TBD", incomplete sections | + | Consistency | Internal contradictions, conflicting requirements | + | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing | + | Scope | Focused enough for a single plan — not covering multiple independent subsystems | + | YAGNI | Unrequested features, over-engineering | + + ## Calibration + + **Only flag issues that would cause real problems during implementation planning.** + A missing section, a contradiction, or a requirement so ambiguous it could be + interpreted two different ways — those are issues. Minor wording improvements, + stylistic preferences, and "sections less detailed than others" are not. + + Approve unless there are serious gaps that would lead to a flawed plan. + + ## Output Format + + ## Spec Review + + **Status:** Approved | Issues Found + + **Issues (if any):** + - [Section X]: [specific issue] - [why it matters for planning] + + **Recommendations (advisory, do not block approval):** + - [suggestions for improvement] +``` + +**Reviewer returns:** Status, Issues (if any), Recommendations diff --git a/superpowers-brainstorming/visual-companion.md b/superpowers-brainstorming/visual-companion.md new file mode 100644 index 0000000..2113863 --- /dev/null +++ b/superpowers-brainstorming/visual-companion.md @@ -0,0 +1,287 @@ +# Visual Companion Guide + +Browser-based visual brainstorming companion for showing mockups, diagrams, and options. + +## When to Use + +Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?** + +**Use the browser** when the content itself is visual: + +- **UI mockups** — wireframes, layouts, navigation structures, component designs +- **Architecture diagrams** — system components, data flow, relationship maps +- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions +- **Design polish** — when the question is about look and feel, spacing, visual hierarchy +- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams + +**Use the terminal** when the content is text or tabular: + +- **Requirements and scope questions** — "what does X mean?", "which features are in scope?" +- **Conceptual A/B/C choices** — picking between approaches described in words +- **Tradeoff lists** — pros/cons, comparison tables +- **Technical decisions** — API design, data modeling, architectural approach selection +- **Clarifying questions** — anything where the answer is words, not a visual preference + +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. + +## How It Works + +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. + +**Content fragments vs full documents:** If your HTML file starts with `/.superpowers/brainstorm/` for the session directory. + +**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. + +**Launching the server by platform:** + +**Claude Code (macOS / Linux):** +```bash +# Default mode works — the script backgrounds the server itself +scripts/start-server.sh --project-dir /path/to/project +``` + +**Claude Code (Windows):** +```bash +# Windows auto-detects and uses foreground mode, which blocks the tool call. +# Use run_in_background: true on the Bash tool call so the server survives +# across conversation turns. +scripts/start-server.sh --project-dir /path/to/project +``` +When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port. + +**Codex:** +```bash +# Codex reaps background processes. The script auto-detects CODEX_CI and +# switches to foreground mode. Run it normally — no extra flags needed. +scripts/start-server.sh --project-dir /path/to/project +``` + +**Gemini CLI:** +```bash +# Use --foreground and set is_background: true on your shell tool call +# so the process survives across turns +scripts/start-server.sh --project-dir /path/to/project --foreground +``` + +**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. + +If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host: + +```bash +scripts/start-server.sh \ + --project-dir /path/to/project \ + --host 0.0.0.0 \ + --url-host localhost +``` + +Use `--url-host` to control what hostname is printed in the returned URL JSON. + +## The Loop + +1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`: + - Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity. + - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html` + - **Never reuse filenames** — each screen gets a fresh file + - Use Write tool — **never use cat/heredoc** (dumps noise into terminal) + - Server automatically serves the newest file + +2. **Tell user what to expect and end your turn:** + - Remind them of the URL (every step, not just first) + - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage") + - 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." + +3. **On your next turn** — after the user responds in the terminal: + - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines + - Merge with the user's terminal text to get the full picture + - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data + +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. + +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: + + ```html + +
+

Continuing in terminal...

+
+ ``` + + 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. + +6. Repeat until done. + +## Writing Content Fragments + +Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure). + +**Minimal example:** + +```html +

Which layout works better?

+

Consider readability and visual hierarchy

+ +
+
+
A
+
+

Single Column

+

Clean, focused reading experience

+
+
+
+
B
+
+

Two Column

+

Sidebar navigation with main content

+
+
+
+``` + +That's it. No ``, no CSS, no `