[
  {
    "path": ".claude-plugin/marketplace.json",
    "content": "{\n  \"name\": \"superpowers-dev\",\n  \"description\": \"Development marketplace for Superpowers core skills library\",\n  \"owner\": {\n    \"name\": \"Jesse Vincent\",\n    \"email\": \"jesse@fsck.com\"\n  },\n  \"plugins\": [\n    {\n      \"name\": \"superpowers\",\n      \"description\": \"Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques\",\n      \"version\": \"5.0.5\",\n      \"source\": \"./\",\n      \"author\": {\n        \"name\": \"Jesse Vincent\",\n        \"email\": \"jesse@fsck.com\"\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": ".claude-plugin/plugin.json",
    "content": "{\n  \"name\": \"superpowers\",\n  \"description\": \"Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques\",\n  \"version\": \"5.0.5\",\n  \"author\": {\n    \"name\": \"Jesse Vincent\",\n    \"email\": \"jesse@fsck.com\"\n  },\n  \"homepage\": \"https://github.com/obra/superpowers\",\n  \"repository\": \"https://github.com/obra/superpowers\",\n  \"license\": \"MIT\",\n  \"keywords\": [\"skills\", \"tdd\", \"debugging\", \"collaboration\", \"best-practices\", \"workflows\"]\n}\n"
  },
  {
    "path": ".codex/INSTALL.md",
    "content": "# Installing Superpowers for Codex\n\nEnable superpowers skills in Codex via native skill discovery. Just clone and symlink.\n\n## Prerequisites\n\n- Git\n\n## Installation\n\n1. **Clone the superpowers repository:**\n   ```bash\n   git clone https://github.com/obra/superpowers.git ~/.codex/superpowers\n   ```\n\n2. **Create the skills symlink:**\n   ```bash\n   mkdir -p ~/.agents/skills\n   ln -s ~/.codex/superpowers/skills ~/.agents/skills/superpowers\n   ```\n\n   **Windows (PowerShell):**\n   ```powershell\n   New-Item -ItemType Directory -Force -Path \"$env:USERPROFILE\\.agents\\skills\"\n   cmd /c mklink /J \"$env:USERPROFILE\\.agents\\skills\\superpowers\" \"$env:USERPROFILE\\.codex\\superpowers\\skills\"\n   ```\n\n3. **Restart Codex** (quit and relaunch the CLI) to discover the skills.\n\n## Migrating from old bootstrap\n\nIf you installed superpowers before native skill discovery, you need to:\n\n1. **Update the repo:**\n   ```bash\n   cd ~/.codex/superpowers && git pull\n   ```\n\n2. **Create the skills symlink** (step 2 above) — this is the new discovery mechanism.\n\n3. **Remove the old bootstrap block** from `~/.codex/AGENTS.md` — any block referencing `superpowers-codex bootstrap` is no longer needed.\n\n4. **Restart Codex.**\n\n## Verify\n\n```bash\nls -la ~/.agents/skills/superpowers\n```\n\nYou should see a symlink (or junction on Windows) pointing to your superpowers skills directory.\n\n## Updating\n\n```bash\ncd ~/.codex/superpowers && git pull\n```\n\nSkills update instantly through the symlink.\n\n## Uninstalling\n\n```bash\nrm ~/.agents/skills/superpowers\n```\n\nOptionally delete the clone: `rm -rf ~/.codex/superpowers`.\n"
  },
  {
    "path": ".cursor-plugin/plugin.json",
    "content": "{\n  \"name\": \"superpowers\",\n  \"displayName\": \"Superpowers\",\n  \"description\": \"Core skills library: TDD, debugging, collaboration patterns, and proven techniques\",\n  \"version\": \"5.0.5\",\n  \"author\": {\n    \"name\": \"Jesse Vincent\",\n    \"email\": \"jesse@fsck.com\"\n  },\n  \"homepage\": \"https://github.com/obra/superpowers\",\n  \"repository\": \"https://github.com/obra/superpowers\",\n  \"license\": \"MIT\",\n  \"keywords\": [\"skills\", \"tdd\", \"debugging\", \"collaboration\", \"best-practices\", \"workflows\"],\n  \"skills\": \"./skills/\",\n  \"agents\": \"./agents/\",\n  \"commands\": \"./commands/\",\n  \"hooks\": \"./hooks/hooks-cursor.json\"\n}\n"
  },
  {
    "path": ".gitattributes",
    "content": "# Ensure shell scripts always have LF line endings\n*.sh text eol=lf\nhooks/session-start text eol=lf\n\n# Ensure the polyglot wrapper keeps LF (it's parsed by both cmd and bash)\n*.cmd text eol=lf\n\n# Common text files\n*.md text eol=lf\n*.json text eol=lf\n*.js text eol=lf\n*.mjs text eol=lf\n*.ts text eol=lf\n\n# Explicitly mark binary files\n*.png binary\n*.jpg binary\n*.gif binary\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: [obra]\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug Report\nabout: Something isn't working as expected\nlabels: bug\n---\n\n<!--\nBEFORE FILING: Search open AND closed issues. The Windows SessionStart\nhook alone has been reported 29 times. If your issue already exists,\nadd a comment or reaction to the existing one instead.\n-->\n\n- [ ] I searched existing issues and this is not a duplicate\n\n## Environment\n\n| Field | Value |\n|-------|-------|\n| Superpowers version | |\n| Harness (Claude Code, Cursor, etc.) | |\n| Harness version | |\n| Model | |\n| OS + shell | |\n\n## Is this a Superpowers issue or a platform issue?\n<!-- Superpowers is a plugin. Some reported \"bugs\" are actually issues\n     in the underlying platform or model. If you're not sure, try\n     reproducing without Superpowers installed.\n\n     If the problem persists without Superpowers, file the issue with\n     your platform instead. -->\n\n- [ ] I confirmed this issue does not occur without Superpowers installed\n\n## What happened?\n<!-- Be specific. \"It doesn't work\" is not a bug report. -->\n\n## Steps to reproduce\n1.\n2.\n3.\n\n## Expected behavior\n<!-- What should have happened? -->\n\n## Actual behavior\n<!-- What happened instead? -->\n\n## Debug log or conversation transcript\n<!-- A debug log or conversation transcript showing the issue is the\n     single most helpful thing you can include. Without one, we're\n     guessing. Screenshots of error output are also useful. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Questions & Help\n    url: https://discord.gg/Jd8Vphy9jq\n    about: For usage questions, troubleshooting help, and general discussion, please visit our Discord instead of opening an issue.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature Request\nabout: Propose a change or addition to Superpowers\nlabels: enhancement\n---\n\n<!--\nBEFORE FILING: Search open AND closed issues. Many features have been\nrequested before — some were implemented differently, some are in\nprogress, and some were intentionally declined.\n-->\n\n- [ ] I searched existing issues and this has not been proposed before\n\n## What problem does this solve?\n<!-- Describe the problem from your own experience. What were you doing,\n     what went wrong or was missing, and why did it matter?\n\n     \"It would be cool if...\" is not a problem statement. -->\n\n## Proposed solution\n<!-- What specifically do you want to happen? Be concrete. -->\n\n## What alternatives did you consider?\n<!-- What other approaches could solve the same problem? Why is your\n     proposal better? -->\n\n## Is this appropriate for core Superpowers?\n<!-- Would this benefit someone working on a completely different kind\n     of project? If this is specific to your domain, workflow, or a\n     third-party tool, it may belong as its own plugin instead. -->\n\n## Context\n<!-- Optional: version info, harness, model, workflow where you hit this. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/platform_support.md",
    "content": "---\nname: IDE / Platform Support Request\nabout: Request support for a new IDE, editor, or AI coding tool\nlabels: platform-support\n---\n\n<!--\nBEFORE FILING: Search existing issues — your IDE may already be\nrequested or discussed.\n-->\n\n- [ ] I searched existing issues for this IDE/platform\n\n## Which IDE or platform?\n<!-- Name and link -->\n\n## Does this tool have a plugin or extension system?\n<!-- If yes, link to the docs. If no, explain how third-party\n     integrations typically work with this tool. -->\n\n## Have you tried manual installation?\n<!-- Many tools work with Superpowers through manual setup even without\n     official support. Did you try? What happened? -->\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!--\nBEFORE SUBMITTING: Read every word of this template. PRs that leave\nsections blank, contain multiple unrelated changes, or show no evidence\nof human involvement will be closed without review.\n-->\n\n## What problem are you trying to solve?\n<!-- Describe the specific problem you encountered. If this was a session\n     issue, include: what you were doing, what went wrong, the model's\n     exact failure mode, and ideally a transcript or session log.\n\n     \"Improving\" something is not a problem statement. What broke? What\n     failed? What was the user experience that motivated this? -->\n\n## What does this PR change?\n<!-- 1-3 sentences. What, not why — the \"why\" belongs above. -->\n\n## Is this change appropriate for the core library?\n<!-- Superpowers core contains general-purpose skills and infrastructure\n     that benefit all users. Ask yourself:\n\n     - Would this be useful to someone working on a completely different\n       kind of project than yours?\n     - Is this project-specific, team-specific, or tool-specific?\n     - Does this integrate or promote a third-party service?\n\n     If your change is a new skill for a specific domain, workflow tool,\n     or third-party integration, it belongs in its own plugin — not here.\n     See the plugin development docs for how to publish it separately. -->\n\n## What alternatives did you consider?\n<!-- What other approaches did you try or evaluate before landing on this\n     one? Why were they worse? If you didn't consider alternatives, say so\n     — but know that's a red flag. -->\n\n## Does this PR contain multiple unrelated changes?\n<!-- If yes: stop. Split it into separate PRs. Bundled PRs will be closed.\n     If you believe the changes are related, explain the dependency. -->\n\n## Existing PRs\n- [ ] I have reviewed all open AND closed PRs for duplicates or prior art\n- Related PRs: <!-- #number, #number, or \"none found\" -->\n\n<!-- If a related closed PR exists, explain what's different about your\n     approach and why it should succeed where the other didn't. -->\n\n## Environment tested\n\n| Harness (e.g. Claude Code, Cursor) | Harness version | Model | Model version/ID |\n|-------------------------------------|-----------------|-------|------------------|\n|                                     |                 |       |                  |\n\n## Evaluation\n- What was the initial prompt you (or your human partner) used to start\n  the session that led to this change?\n- How many eval sessions did you run AFTER making the change?\n- How did outcomes change compared to before the change?\n\n<!-- \"It works\" is not evaluation. Describe the before/after difference\n     you observed across multiple sessions. -->\n\n## Rigor\n\n- [ ] If this is a skills change: I used `superpowers:writing-skills` and\n      completed adversarial pressure testing (paste results below)\n- [ ] This change was tested adversarially, not just on the happy path\n- [ ] I did not modify carefully-tuned content (Red Flags table,\n      rationalizations, \"human partner\" language) without extensive evals\n      showing the change is an improvement\n\n<!-- If you changed wording in skills that shape agent behavior, show your\n     eval methodology and results. These are not prose — they are code. -->\n\n## Human review\n- [ ] A human has reviewed the COMPLETE proposed diff before submission\n\n<!--\nSTOP. If the checkbox above is not checked, do not submit this PR.\n\nPRs will be closed without review if they:\n- Show no evidence of human involvement\n- Contain multiple unrelated changes\n- Promote or integrate third-party services or tools\n- Submit project-specific or personal configuration as core changes\n- Leave required sections blank or use placeholder text\n- Modify behavior-shaping content without eval evidence\n-->\n"
  },
  {
    "path": ".gitignore",
    "content": ".worktrees/\n.private-journal/\n.claude/\n.DS_Store\nnode_modules/\ninspo\ntriage/\n"
  },
  {
    "path": ".opencode/INSTALL.md",
    "content": "# Installing Superpowers for OpenCode\n\n## Prerequisites\n\n- [OpenCode.ai](https://opencode.ai) installed\n\n## Installation\n\nAdd superpowers to the `plugin` array in your `opencode.json` (global or project-level):\n\n```json\n{\n  \"plugin\": [\"superpowers@git+https://github.com/obra/superpowers.git\"]\n}\n```\n\nRestart OpenCode. That's it — the plugin auto-installs and registers all skills.\n\nVerify by asking: \"Tell me about your superpowers\"\n\n## Migrating from the old symlink-based install\n\nIf you previously installed superpowers using `git clone` and symlinks, remove the old setup:\n\n```bash\n# Remove old symlinks\nrm -f ~/.config/opencode/plugins/superpowers.js\nrm -rf ~/.config/opencode/skills/superpowers\n\n# Optionally remove the cloned repo\nrm -rf ~/.config/opencode/superpowers\n\n# Remove skills.paths from opencode.json if you added one for superpowers\n```\n\nThen follow the installation steps above.\n\n## Usage\n\nUse OpenCode's native `skill` tool:\n\n```\nuse skill tool to list skills\nuse skill tool to load superpowers/brainstorming\n```\n\n## Updating\n\nSuperpowers updates automatically when you restart OpenCode.\n\nTo pin a specific version:\n\n```json\n{\n  \"plugin\": [\"superpowers@git+https://github.com/obra/superpowers.git#v5.0.3\"]\n}\n```\n\n## Troubleshooting\n\n### Plugin not loading\n\n1. Check logs: `opencode run --print-logs \"hello\" 2>&1 | grep -i superpowers`\n2. Verify the plugin line in your `opencode.json`\n3. Make sure you're running a recent version of OpenCode\n\n### Skills not found\n\n1. Use `skill` tool to list what's discovered\n2. Check that the plugin is loading (see above)\n\n### Tool mapping\n\nWhen skills reference Claude Code tools:\n- `TodoWrite` → `todowrite`\n- `Task` with subagents → `@mention` syntax\n- `Skill` tool → OpenCode's native `skill` tool\n- File operations → your native tools\n\n## Getting Help\n\n- Report issues: https://github.com/obra/superpowers/issues\n- Full documentation: https://github.com/obra/superpowers/blob/main/docs/README.opencode.md\n"
  },
  {
    "path": ".opencode/plugins/superpowers.js",
    "content": "/**\n * Superpowers plugin for OpenCode.ai\n *\n * Injects superpowers bootstrap context via system prompt transform.\n * Auto-registers skills directory via config hook (no symlinks needed).\n */\n\nimport path from 'path';\nimport fs from 'fs';\nimport os from 'os';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\n// Simple frontmatter extraction (avoid dependency on skills-core for bootstrap)\nconst extractAndStripFrontmatter = (content) => {\n  const match = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n  if (!match) return { frontmatter: {}, content };\n\n  const frontmatterStr = match[1];\n  const body = match[2];\n  const frontmatter = {};\n\n  for (const line of frontmatterStr.split('\\n')) {\n    const colonIdx = line.indexOf(':');\n    if (colonIdx > 0) {\n      const key = line.slice(0, colonIdx).trim();\n      const value = line.slice(colonIdx + 1).trim().replace(/^[\"']|[\"']$/g, '');\n      frontmatter[key] = value;\n    }\n  }\n\n  return { frontmatter, content: body };\n};\n\n// Normalize a path: trim whitespace, expand ~, resolve to absolute\nconst normalizePath = (p, homeDir) => {\n  if (!p || typeof p !== 'string') return null;\n  let normalized = p.trim();\n  if (!normalized) return null;\n  if (normalized.startsWith('~/')) {\n    normalized = path.join(homeDir, normalized.slice(2));\n  } else if (normalized === '~') {\n    normalized = homeDir;\n  }\n  return path.resolve(normalized);\n};\n\nexport const SuperpowersPlugin = async ({ client, directory }) => {\n  const homeDir = os.homedir();\n  const superpowersSkillsDir = path.resolve(__dirname, '../../skills');\n  const envConfigDir = normalizePath(process.env.OPENCODE_CONFIG_DIR, homeDir);\n  const configDir = envConfigDir || path.join(homeDir, '.config/opencode');\n\n  // Helper to generate bootstrap content\n  const getBootstrapContent = () => {\n    // Try to load using-superpowers skill\n    const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md');\n    if (!fs.existsSync(skillPath)) return null;\n\n    const fullContent = fs.readFileSync(skillPath, 'utf8');\n    const { content } = extractAndStripFrontmatter(fullContent);\n\n    const toolMapping = `**Tool Mapping for OpenCode:**\nWhen skills reference tools you don't have, substitute OpenCode equivalents:\n- \\`TodoWrite\\` → \\`todowrite\\`\n- \\`Task\\` tool with subagents → Use OpenCode's subagent system (@mention)\n- \\`Skill\\` tool → OpenCode's native \\`skill\\` tool\n- \\`Read\\`, \\`Write\\`, \\`Edit\\`, \\`Bash\\` → Your native tools\n\n**Skills location:**\nSuperpowers skills are in \\`${configDir}/skills/superpowers/\\`\nUse OpenCode's native \\`skill\\` tool to list and load skills.`;\n\n    return `<EXTREMELY_IMPORTANT>\nYou have superpowers.\n\n**IMPORTANT: The using-superpowers skill content is included below. It is ALREADY LOADED - you are currently following it. Do NOT use the skill tool to load \"using-superpowers\" again - that would be redundant.**\n\n${content}\n\n${toolMapping}\n</EXTREMELY_IMPORTANT>`;\n  };\n\n  return {\n    // Inject skills path into live config so OpenCode discovers superpowers skills\n    // without requiring manual symlinks or config file edits.\n    // This works because Config.get() returns a cached singleton — modifications\n    // here are visible when skills are lazily discovered later.\n    config: async (config) => {\n      config.skills = config.skills || {};\n      config.skills.paths = config.skills.paths || [];\n      if (!config.skills.paths.includes(superpowersSkillsDir)) {\n        config.skills.paths.push(superpowersSkillsDir);\n      }\n    },\n\n    // Use system prompt transform to inject bootstrap (fixes #226 agent reset bug)\n    'experimental.chat.system.transform': async (_input, output) => {\n      const bootstrap = getBootstrapContent();\n      if (bootstrap) {\n        (output.system ||= []).push(bootstrap);\n      }\n    }\n  };\n};\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\n## [5.0.5] - 2026-03-17\n\n### Fixed\n\n- **Brainstorm server ESM fix**: Renamed `server.js` → `server.cjs` so the brainstorming server starts correctly on Node.js 22+ where the root `package.json` `\"type\": \"module\"` caused `require()` to fail. ([PR #784](https://github.com/obra/superpowers/pull/784) by @sarbojitrana, fixes [#774](https://github.com/obra/superpowers/issues/774), [#780](https://github.com/obra/superpowers/issues/780), [#783](https://github.com/obra/superpowers/issues/783))\n- **Brainstorm owner-PID on Windows**: Skip `BRAINSTORM_OWNER_PID` lifecycle monitoring on Windows/MSYS2 where the PID namespace is invisible to Node.js. Prevents the server from self-terminating after 60 seconds. The 30-minute idle timeout remains as the safety net. ([#770](https://github.com/obra/superpowers/issues/770), docs from [PR #768](https://github.com/obra/superpowers/pull/768) by @lucasyhzhu-debug)\n- **stop-server.sh reliability**: Verify the server process actually died before reporting success. Waits up to 2 seconds for graceful shutdown, escalates to `SIGKILL`, and reports failure if the process survives. ([#723](https://github.com/obra/superpowers/issues/723))\n\n### Changed\n\n- **Execution handoff**: Restore user choice between subagent-driven-development and executing-plans after plan writing. Subagent-driven is recommended but no longer mandatory. (Reverts `5e51c3e`)\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\njesse@primeradiant.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "GEMINI.md",
    "content": "@./skills/using-superpowers/SKILL.md\n@./skills/using-superpowers/references/gemini-tools.md\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2025 Jesse Vincent\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Superpowers\n\nSuperpowers is a complete software development workflow for your coding agents, built on top of a set of composable \"skills\" and some initial instructions that make sure your agent uses them.\n\n## How it works\n\nIt starts from the moment you fire up your coding agent. As soon as it sees that you're building something, it *doesn't* just jump into trying to write code. Instead, it steps back and asks you what you're really trying to do. \n\nOnce it's teased a spec out of the conversation, it shows it to you in chunks short enough to actually read and digest. \n\nAfter you've signed off on the design, your agent puts together an implementation plan that's clear enough for an enthusiastic junior engineer with poor taste, no judgement, no project context, and an aversion to testing to follow. It emphasizes true red/green TDD, YAGNI (You Aren't Gonna Need It), and DRY. \n\nNext up, once you say \"go\", it launches a *subagent-driven-development* process, having agents work through each engineering task, inspecting and reviewing their work, and continuing forward. It's not uncommon for Claude to be able to work autonomously for a couple hours at a time without deviating from the plan you put together.\n\nThere's a bunch more to it, but that's the core of the system. And because the skills trigger automatically, you don't need to do anything special. Your coding agent just has Superpowers.\n\n\n## Sponsorship\n\nIf Superpowers has helped you do stuff that makes money and you are so inclined, I'd greatly appreciate it if you'd consider [sponsoring my opensource work](https://github.com/sponsors/obra).\n\nThanks! \n\n- Jesse\n\n\n## Installation\n\n**Note:** Installation differs by platform. Claude Code or Cursor have built-in plugin marketplaces. Codex and OpenCode require manual setup.\n\n### Claude Code Official Marketplace\n\nSuperpowers is available via the [official Claude plugin marketplace](https://claude.com/plugins/superpowers)\n\nInstall the plugin from Claude marketplace:\n\n```bash\n/plugin install superpowers@claude-plugins-official\n```\n\n### Claude Code (via Plugin Marketplace)\n\nIn Claude Code, register the marketplace first:\n\n```bash\n/plugin marketplace add obra/superpowers-marketplace\n```\n\nThen install the plugin from this marketplace:\n\n```bash\n/plugin install superpowers@superpowers-marketplace\n```\n\n### Cursor (via Plugin Marketplace)\n\nIn Cursor Agent chat, install from marketplace:\n\n```text\n/add-plugin superpowers\n```\n\nor search for \"superpowers\" in the plugin marketplace.\n\n### Codex\n\nTell Codex:\n\n```\nFetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.codex/INSTALL.md\n```\n\n**Detailed docs:** [docs/README.codex.md](docs/README.codex.md)\n\n### OpenCode\n\nTell OpenCode:\n\n```\nFetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.opencode/INSTALL.md\n```\n\n**Detailed docs:** [docs/README.opencode.md](docs/README.opencode.md)\n\n### Gemini CLI\n\n```bash\ngemini extensions install https://github.com/obra/superpowers\n```\n\nTo update:\n\n```bash\ngemini extensions update superpowers\n```\n\n### Verify Installation\n\nStart a new session in your chosen platform and ask for something that should trigger a skill (for example, \"help me plan this feature\" or \"let's debug this issue\"). The agent should automatically invoke the relevant superpowers skill.\n\n## The Basic Workflow\n\n1. **brainstorming** - Activates before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. Saves design document.\n\n2. **using-git-worktrees** - Activates after design approval. Creates isolated workspace on new branch, runs project setup, verifies clean test baseline.\n\n3. **writing-plans** - Activates with approved design. Breaks work into bite-sized tasks (2-5 minutes each). Every task has exact file paths, complete code, verification steps.\n\n4. **subagent-driven-development** or **executing-plans** - Activates with plan. Dispatches fresh subagent per task with two-stage review (spec compliance, then code quality), or executes in batches with human checkpoints.\n\n5. **test-driven-development** - Activates during implementation. Enforces RED-GREEN-REFACTOR: write failing test, watch it fail, write minimal code, watch it pass, commit. Deletes code written before tests.\n\n6. **requesting-code-review** - Activates between tasks. Reviews against plan, reports issues by severity. Critical issues block progress.\n\n7. **finishing-a-development-branch** - Activates when tasks complete. Verifies tests, presents options (merge/PR/keep/discard), cleans up worktree.\n\n**The agent checks for relevant skills before any task.** Mandatory workflows, not suggestions.\n\n## What's Inside\n\n### Skills Library\n\n**Testing**\n- **test-driven-development** - RED-GREEN-REFACTOR cycle (includes testing anti-patterns reference)\n\n**Debugging**\n- **systematic-debugging** - 4-phase root cause process (includes root-cause-tracing, defense-in-depth, condition-based-waiting techniques)\n- **verification-before-completion** - Ensure it's actually fixed\n\n**Collaboration** \n- **brainstorming** - Socratic design refinement\n- **writing-plans** - Detailed implementation plans\n- **executing-plans** - Batch execution with checkpoints\n- **dispatching-parallel-agents** - Concurrent subagent workflows\n- **requesting-code-review** - Pre-review checklist\n- **receiving-code-review** - Responding to feedback\n- **using-git-worktrees** - Parallel development branches\n- **finishing-a-development-branch** - Merge/PR decision workflow\n- **subagent-driven-development** - Fast iteration with two-stage review (spec compliance, then code quality)\n\n**Meta**\n- **writing-skills** - Create new skills following best practices (includes testing methodology)\n- **using-superpowers** - Introduction to the skills system\n\n## Philosophy\n\n- **Test-Driven Development** - Write tests first, always\n- **Systematic over ad-hoc** - Process over guessing\n- **Complexity reduction** - Simplicity as primary goal\n- **Evidence over claims** - Verify before declaring success\n\nRead more: [Superpowers for Claude Code](https://blog.fsck.com/2025/10/09/superpowers/)\n\n## Contributing\n\nSkills live directly in this repository. To contribute:\n\n1. Fork the repository\n2. Create a branch for your skill\n3. Follow the `writing-skills` skill for creating and testing new skills\n4. Submit a PR\n\nSee `skills/writing-skills/SKILL.md` for the complete guide.\n\n## Updating\n\nSkills update automatically when you update the plugin:\n\n```bash\n/plugin update superpowers\n```\n\n## License\n\nMIT License - see LICENSE file for details\n\n## Community\n\nSuperpowers is built by [Jesse Vincent](https://blog.fsck.com) and the rest of the folks at [Prime Radiant](https://primeradiant.com).\n\nFor community support, questions, and sharing what you're building with Superpowers, join us on [Discord](https://discord.gg/Jd8Vphy9jq).\n\n## Support\n\n- **Discord**: [Join us on Discord](https://discord.gg/Jd8Vphy9jq)\n- **Issues**: https://github.com/obra/superpowers/issues\n- **Marketplace**: https://github.com/obra/superpowers-marketplace\n"
  },
  {
    "path": "RELEASE-NOTES.md",
    "content": "# Superpowers Release Notes\n\n## v5.0.5 (2026-03-17)\n\n### Bug Fixes\n\n- **Brainstorm server ESM fix** — renamed `server.js` → `server.cjs` so the brainstorming server starts correctly on Node.js 22+ where the root `package.json` `\"type\": \"module\"` caused `require()` to fail. (PR #784 by @sarbojitrana, fixes #774, #780, #783)\n- **Brainstorm owner-PID on Windows** — skip PID lifecycle monitoring on Windows/MSYS2 where the PID namespace is invisible to Node.js, preventing the server from self-terminating after 60 seconds. (#770, docs from PR #768 by @lucasyhzlu-debug)\n- **stop-server.sh reliability** — verify the server process actually died before reporting success. SIGTERM + 2s wait + SIGKILL fallback. (#723)\n\n### Changed\n\n- **Execution handoff** — restore user choice between subagent-driven and inline execution after plan writing. Subagent-driven is recommended but no longer mandatory.\n\n## v5.0.4 (2026-03-16)\n\n### Review Loop Refinements\n\nDramatically reduces token usage and speeds up spec and plan reviews by eliminating unnecessary review passes and tightening reviewer focus.\n\n- **Single whole-plan review** — plan reviewer now reviews the complete plan in one pass instead of chunk-by-chunk. Removed all chunk-related concepts (`## Chunk N:` headings, 1000-line chunk limits, per-chunk dispatch).\n- **Raised the bar for blocking issues** — both spec and plan reviewer prompts now include a \"Calibration\" section: only flag issues that would cause real problems during implementation. Minor wording, stylistic preferences, and formatting quibbles should not block approval.\n- **Reduced max review iterations** — from 5 to 3 for both spec and plan review loops. If the reviewer is calibrated correctly, 3 rounds is plenty.\n- **Streamlined reviewer checklists** — spec reviewer trimmed from 7 categories to 5; plan reviewer from 7 to 4. Removed formatting-focused checks (task syntax, chunk size) in favor of substance (buildability, spec alignment).\n\n### OpenCode\n\n- **One-line plugin install** — OpenCode plugin now auto-registers the skills directory via a `config` hook. No symlinks or `skills.paths` config needed. Install is just adding one line to `opencode.json`. (PR #753)\n- **Added `package.json`** so OpenCode can install superpowers as an npm package from git.\n\n### Bug Fixes\n\n- **Verify server actually stopped** — `stop-server.sh` now confirms the process is dead before reporting success. SIGTERM + 2s wait + SIGKILL fallback. Reports failure if the process survives. (PR #751)\n- **Generic agent language** — brainstorm companion waiting page now says \"the agent\" instead of \"Claude\".\n\n## v5.0.3 (2026-03-15)\n\n### Cursor Support\n\n- **Cursor hooks** — added `hooks/hooks-cursor.json` with Cursor's camelCase format (`sessionStart`, `version: 1`) and updated `.cursor-plugin/plugin.json` to reference it. Fixed platform detection in `session-start` to check `CURSOR_PLUGIN_ROOT` first (Cursor may also set `CLAUDE_PLUGIN_ROOT`). (Based on PR #709)\n\n### Bug Fixes\n\n- **Stop firing SessionStart hook on `--resume`** — the startup hook was re-injecting context on resumed sessions, which already have the context in their conversation history. The hook now fires only on `startup`, `clear`, and `compact`.\n- **Bash 5.3+ hook hang** — replaced heredoc (`cat <<EOF`) with `printf` in `hooks/session-start`. Fixes indefinite hang on macOS with Homebrew bash 5.3+ caused by a bash regression with large variable expansion in heredocs. (#572, #571)\n- **POSIX-safe hook script** — replaced `${BASH_SOURCE[0]:-$0}` with `$0` in `hooks/session-start`. Fixes \"Bad substitution\" error on Ubuntu/Debian where `/bin/sh` is dash. (#553)\n- **Portable shebangs** — replaced `#!/bin/bash` with `#!/usr/bin/env bash` in all shell scripts. Fixes execution on NixOS, FreeBSD, and macOS with Homebrew bash where `/bin/bash` is outdated or missing. (#700)\n- **Brainstorm server on Windows** — auto-detect Windows/Git Bash (`OSTYPE=msys*`, `MSYSTEM`) and switch to foreground mode, fixing silent server failure caused by `nohup`/`disown` process reaping. (#737)\n- **Codex docs fix** — replaced deprecated `collab` flag with `multi_agent` in Codex documentation. (PR #749)\n\n## v5.0.2 (2026-03-11)\n\n### Zero-Dependency Brainstorm Server\n\n**Removed all vendored node_modules — server.js is now fully self-contained**\n\n- Replaced Express/Chokidar/WebSocket dependencies with zero-dependency Node.js server using built-in `http`, `fs`, and `crypto` modules\n- Removed ~1,200 lines of vendored `node_modules/`, `package.json`, and `package-lock.json`\n- Custom WebSocket protocol implementation (RFC 6455 framing, ping/pong, proper close handshake)\n- Native `fs.watch()` file watching replaces Chokidar\n- Full test suite: HTTP serving, WebSocket protocol, file watching, and integration tests\n\n### Brainstorm Server Reliability\n\n- **Auto-exit after 30 minutes idle** — server shuts down when no clients are connected, preventing orphaned processes\n- **Owner process tracking** — server monitors the parent harness PID and exits when the owning session dies\n- **Liveness check** — skill verifies server is responsive before reusing an existing instance\n- **Encoding fix** — proper `<meta charset=\"utf-8\">` on served HTML pages\n\n### Subagent Context Isolation\n\n- All delegation skills (brainstorming, dispatching-parallel-agents, requesting-code-review, subagent-driven-development, writing-plans) now include context isolation principle\n- Subagents receive only the context they need, preventing context window pollution\n\n## v5.0.1 (2026-03-10)\n\n### Agentskills Compliance\n\n**Brainstorm-server moved into skill directory**\n\n- Moved `lib/brainstorm-server/` → `skills/brainstorming/scripts/` per the [agentskills.io](https://agentskills.io) specification\n- All `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/` references replaced with relative `scripts/` paths\n- Skills are now fully portable across platforms — no platform-specific env vars needed to locate scripts\n- `lib/` directory removed (was the last remaining content)\n\n### New Features\n\n**Gemini CLI extension**\n\n- Native Gemini CLI extension support via `gemini-extension.json` and `GEMINI.md` at repo root\n- `GEMINI.md` @imports `using-superpowers` skill and tool mapping table at session start\n- Gemini CLI tool mapping reference (`skills/using-superpowers/references/gemini-tools.md`) — translates Claude Code tool names (Read, Write, Edit, Bash, etc.) to Gemini CLI equivalents (read_file, write_file, replace, etc.)\n- Documents Gemini CLI limitations: no subagent support, skills fall back to `executing-plans`\n- Extension root at repo root for cross-platform compatibility (avoids Windows symlink issues)\n- Install instructions added to README\n\n### Improvements\n\n**Multi-platform brainstorm server launch**\n\n- Per-platform launch instructions in visual-companion.md: Claude Code (default mode), Codex (auto-foreground via `CODEX_CI`), Gemini CLI (`--foreground` with `is_background`), and fallback for other environments\n- Server now writes startup JSON to `$SCREEN_DIR/.server-info` so agents can find the URL and port even when stdout is hidden by background execution\n\n**Brainstorm server dependencies bundled**\n\n- `node_modules` vendored into the repo so the brainstorm server works immediately on fresh plugin installs without requiring `npm` at runtime\n- Removed `fsevents` from bundled deps (macOS-only native binary; chokidar falls back gracefully without it)\n- Fallback auto-install via `npm install` if `node_modules` is missing\n\n**OpenCode tool mapping fix**\n\n- `TodoWrite` → `todowrite` (was incorrectly mapped to `update_plan`); verified against OpenCode source\n\n### Bug Fixes\n\n**Windows/Linux: single quotes break SessionStart hook** (#577, #529, #644, PR #585)\n\n- Single quotes around `${CLAUDE_PLUGIN_ROOT}` in hooks.json fail on Windows (cmd.exe doesn't recognize single quotes as path delimiters) and on Linux (single quotes prevent variable expansion)\n- Fix: replaced single quotes with escaped double quotes — works across macOS bash, Windows cmd.exe, Windows Git Bash, and Linux, with and without spaces in paths\n- Verified on Windows 11 (NT 10.0.26200.0) with Claude Code 2.1.72 and Git for Windows\n\n**Brainstorming spec review loop skipped** (#677)\n\n- The spec review loop (dispatch spec-document-reviewer subagent, iterate until approved) existed in the prose \"After the Design\" section but was missing from the checklist and process flow diagram\n- Since agents follow the diagram and checklist more reliably than prose, the spec review step was being skipped entirely\n- Added step 7 (spec review loop) to the checklist and corresponding nodes to the dot graph\n- Tested with `claude --plugin-dir` and `claude-session-driver`: worker now correctly dispatches the reviewer\n\n**Cursor install command** (PR #676)\n\n- Fixed Cursor install command in README: `/plugin-add` → `/add-plugin` (confirmed via Cursor 2.5 release announcement)\n\n**User review gate in brainstorming** (#565)\n\n- Added explicit user review step between spec completion and writing-plans handoff\n- User must approve the spec before implementation planning begins\n- Checklist, process flow, and prose updated with the new gate\n\n**Session-start hook emits context only once per platform**\n\n- Hook now detects whether it's running in Claude Code or another platform\n- Emits `hookSpecificOutput` for Claude Code, `additional_context` for others — prevents double context injection\n\n**Linting fix in token analysis script**\n\n- `except:` → `except Exception:` in `tests/claude-code/analyze-token-usage.py`\n\n### Maintenance\n\n**Removed dead code**\n\n- Deleted `lib/skills-core.js` and its test (`tests/opencode/test-skills-core.js`) — unused since February 2026\n- Removed skills-core existence check from `tests/opencode/test-plugin-loading.sh`\n\n### Community\n\n- @karuturi — Claude Code official marketplace install instructions (PR #610)\n- @mvanhorn — session-start hook dual-emit fix, OpenCode tool mapping fix\n- @daniel-graham — linting fix for bare except\n- PR #585 author — Windows/Linux hooks quoting fix\n\n---\n\n## v5.0.0 (2026-03-09)\n\n### Breaking Changes\n\n**Specs and plans directory restructured**\n\n- Specs (brainstorming output) now save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`\n- Plans (writing-plans output) now save to `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`\n- User preferences for spec/plan locations override these defaults\n- All internal skill references, test files, and example paths updated to match\n- Migration: move existing files from `docs/plans/` to new locations if desired\n\n**Subagent-driven development mandatory on capable harnesses**\n\nWriting-plans no longer offers a choice between subagent-driven and executing-plans. On harnesses with subagent support (Claude Code, Codex), subagent-driven-development is required. Executing-plans is reserved for harnesses without subagent capability, and now tells the user that Superpowers works better on a subagent-capable platform.\n\n**Executing-plans no longer batches**\n\nRemoved the \"execute 3 tasks then stop for review\" pattern. Plans now execute continuously, stopping only for blockers.\n\n**Slash commands deprecated**\n\n`/brainstorm`, `/write-plan`, and `/execute-plan` now show deprecation notices pointing users to the corresponding skills. Commands will be removed in the next major release.\n\n### New Features\n\n**Visual brainstorming companion**\n\nOptional browser-based companion for brainstorming sessions. When a topic would benefit from visuals, the brainstorming skill offers to show mockups, diagrams, comparisons, and other content in a browser window alongside terminal conversation.\n\n- `lib/brainstorm-server/` — WebSocket server with browser helper library, session management scripts, and dark/light themed frame template (\"Superpowers Brainstorming\" with GitHub link)\n- `skills/brainstorming/visual-companion.md` — Progressive disclosure guide for server workflow, screen authoring, and feedback collection\n- Brainstorming skill adds a visual companion decision point to its process flow: after exploring project context, the skill evaluates whether upcoming questions involve visual content and offers the companion in its own message\n- Per-question decision: even after accepting, each question is evaluated for whether browser or terminal is more appropriate\n- Integration tests in `tests/brainstorm-server/`\n\n**Document review system**\n\nAutomated review loops for spec and plan documents using subagent dispatch:\n\n- `skills/brainstorming/spec-document-reviewer-prompt.md` — Reviewer checks completeness, consistency, architecture, and YAGNI\n- `skills/writing-plans/plan-document-reviewer-prompt.md` — Reviewer checks spec alignment, task decomposition, file structure, and file size\n- Brainstorming dispatches spec reviewer after writing the design doc\n- Writing-plans includes chunk-based plan review loop after each section\n- Review loops repeat until approved or escalate after 5 iterations\n- End-to-end tests in `tests/claude-code/test-document-review-system.sh`\n- Design spec and implementation plan in `docs/superpowers/`\n\n**Architecture guidance across the skill pipeline**\n\nDesign-for-isolation and file-size-awareness guidance added to brainstorming, writing-plans, and subagent-driven-development:\n\n- **Brainstorming** — New sections: \"Design for isolation and clarity\" (clear boundaries, well-defined interfaces, independently testable units) and \"Working in existing codebases\" (follow existing patterns, targeted improvements only)\n- **Writing-plans** — New \"File Structure\" section: map out files and responsibilities before defining tasks. New \"Scope Check\" backstop: catch multi-subsystem specs that should have been decomposed during brainstorming\n- **SDD implementer** — New \"Code Organization\" section (follow plan's file structure, report concerns about growing files) and \"When You're in Over Your Head\" escalation guidance\n- **SDD code quality reviewer** — Now checks architecture, unit decomposition, plan conformance, and file growth\n- **Spec/plan reviewers** — Architecture and file size added to review criteria\n- **Scope assessment** — Brainstorming now assesses whether a project is too large for a single spec. Multi-subsystem requests are flagged early and decomposed into sub-projects, each with its own spec → plan → implementation cycle\n\n**Subagent-driven development improvements**\n\n- **Model selection** — Guidance for choosing model capability by task type: cheap models for mechanical implementation, standard for integration, capable for architecture and review\n- **Implementer status protocol** — Subagents now report DONE, DONE_WITH_CONCERNS, BLOCKED, or NEEDS_CONTEXT. Controller handles each status appropriately: re-dispatching with more context, upgrading model capability, breaking tasks apart, or escalating to human\n\n### Improvements\n\n**Instruction priority hierarchy**\n\nAdded explicit priority ordering to using-superpowers:\n\n1. User's explicit instructions (CLAUDE.md, AGENTS.md, direct requests) — highest priority\n2. Superpowers skills — override default system behavior\n3. Default system prompt — lowest priority\n\nIf CLAUDE.md or AGENTS.md says \"don't use TDD\" and a skill says \"always use TDD,\" the user's instructions win.\n\n**SUBAGENT-STOP gate**\n\nAdded `<SUBAGENT-STOP>` block to using-superpowers. Subagents dispatched for specific tasks now skip the skill instead of activating the 1% rule and invoking full skill workflows.\n\n**Multi-platform improvements**\n\n- Codex tool mapping moved to progressive disclosure reference file (`references/codex-tools.md`)\n- Platform Adaptation pointer added so non-Claude-Code platforms can find tool equivalents\n- Plan headers now address \"agentic workers\" instead of \"Claude\" specifically\n- Collab feature requirement documented in `docs/README.codex.md`\n\n**Writing-plans template updates**\n\n- Plan steps now use checkbox syntax (`- [ ] **Step N:**`) for progress tracking\n- Plan header references both subagent-driven-development and executing-plans with platform-aware routing\n\n---\n\n## v4.3.1 (2026-02-21)\n\n### Added\n\n**Cursor support**\n\nSuperpowers now works with Cursor's plugin system. Includes a `.cursor-plugin/plugin.json` manifest and Cursor-specific installation instructions in the README. The SessionStart hook output now includes an `additional_context` field alongside the existing `hookSpecificOutput.additionalContext` for Cursor hook compatibility.\n\n### Fixed\n\n**Windows: Restored polyglot wrapper for reliable hook execution (#518, #504, #491, #487, #466, #440)**\n\nClaude Code's `.sh` auto-detection on Windows was prepending `bash` to the hook command, breaking execution. The fix:\n\n- Renamed `session-start.sh` to `session-start` (extensionless) so auto-detection doesn't interfere\n- Restored `run-hook.cmd` polyglot wrapper with multi-location bash discovery (standard Git for Windows paths, then PATH fallback)\n- Exits silently if no bash is found rather than erroring\n- On Unix, the wrapper runs the script directly via `exec bash`\n- Uses POSIX-safe `dirname \"$0\"` path resolution (works on dash/sh, not just bash)\n\nThis fixes SessionStart failures on Windows with spaces in paths, missing WSL, `set -euo pipefail` fragility on MSYS, and backslash mangling.\n\n## v4.3.0 (2026-02-12)\n\nThis fix should dramatically improve superpowers skills compliance and should reduce the chances of Claude entering its native plan mode unintentionally.\n\n### Changed\n\n**Brainstorming skill now enforces its workflow instead of describing it**\n\nModels were skipping the design phase and jumping straight to implementation skills like frontend-design, or collapsing the entire brainstorming process into a single text block. The skill now uses hard gates, a mandatory checklist, and a graphviz process flow to enforce compliance:\n\n- `<HARD-GATE>`: no implementation skills, code, or scaffolding until design is presented and user approves\n- Explicit checklist (6 items) that must be created as tasks and completed in order\n- Graphviz process flow with `writing-plans` as the only valid terminal state\n- Anti-pattern callout for \"this is too simple to need a design\" — the exact rationalization models use to skip the process\n- Design section sizing based on section complexity, not project complexity\n\n**Using-superpowers workflow graph intercepts EnterPlanMode**\n\nAdded an `EnterPlanMode` intercept to the skill flow graph. When the model is about to enter Claude's native plan mode, it checks whether brainstorming has happened and routes through the brainstorming skill instead. Plan mode is never entered.\n\n### Fixed\n\n**SessionStart hook now runs synchronously**\n\nChanged `async: true` to `async: false` in hooks.json. When async, the hook could fail to complete before the model's first turn, meaning using-superpowers instructions weren't in context for the first message.\n\n## v4.2.0 (2026-02-05)\n\n### Breaking Changes\n\n**Codex: Replaced bootstrap CLI with native skill discovery**\n\nThe `superpowers-codex` bootstrap CLI, Windows `.cmd` wrapper, and related bootstrap content file have been removed. Codex now uses native skill discovery via `~/.agents/skills/superpowers/` symlink, so the old `use_skill`/`find_skills` CLI tools are no longer needed.\n\nInstallation is now just clone + symlink (documented in INSTALL.md). No Node.js dependency required. The old `~/.codex/skills/` path is deprecated.\n\n### Fixes\n\n**Windows: Fixed Claude Code 2.1.x hook execution (#331)**\n\nClaude Code 2.1.x changed how hooks execute on Windows: it now auto-detects `.sh` files in commands and prepends `bash`. This broke the polyglot wrapper pattern because `bash \"run-hook.cmd\" session-start.sh` tries to execute the `.cmd` file as a bash script.\n\nFix: hooks.json now calls session-start.sh directly. Claude Code 2.1.x handles the bash invocation automatically. Also added .gitattributes to enforce LF line endings for shell scripts (fixes CRLF issues on Windows checkout).\n\n**Windows: SessionStart hook runs async to prevent terminal freeze (#404, #413, #414, #419)**\n\nThe synchronous SessionStart hook blocked the TUI from entering raw mode on Windows, freezing all keyboard input. Running the hook async prevents the freeze while still injecting superpowers context.\n\n**Windows: Fixed O(n^2) `escape_for_json` performance**\n\nThe character-by-character loop using `${input:$i:1}` was O(n^2) in bash due to substring copy overhead. On Windows Git Bash this took 60+ seconds. Replaced with bash parameter substitution (`${s//old/new}`) which runs each pattern as a single C-level pass — 7x faster on macOS, dramatically faster on Windows.\n\n**Codex: Fixed Windows/PowerShell invocation (#285, #243)**\n\n- Windows doesn't respect shebangs, so directly invoking the extensionless `superpowers-codex` script triggered an \"Open with\" dialog. All invocations now prefixed with `node`.\n- Fixed `~/` path expansion on Windows — PowerShell doesn't expand `~` when passed as an argument to `node`. Changed to `$HOME` which expands correctly in both bash and PowerShell.\n\n**Codex: Fixed path resolution in installer**\n\nUsed `fileURLToPath()` instead of manual URL pathname parsing to correctly handle paths with spaces and special characters on all platforms.\n\n**Codex: Fixed stale skills path in writing-skills**\n\nUpdated `~/.codex/skills/` reference (deprecated) to `~/.agents/skills/` for native discovery.\n\n### Improvements\n\n**Worktree isolation now required before implementation**\n\nAdded `using-git-worktrees` as a required skill for both `subagent-driven-development` and `executing-plans`. Implementation workflows now explicitly require setting up an isolated worktree before starting work, preventing accidental work directly on main.\n\n**Main branch protection softened to require explicit consent**\n\nInstead of prohibiting main branch work entirely, the skills now allow it with explicit user consent. More flexible while still ensuring users are aware of the implications.\n\n**Simplified installation verification**\n\nRemoved `/help` command check and specific slash command list from verification steps. Skills are primarily invoked by describing what you want to do, not by running specific commands.\n\n**Codex: Clarified subagent tool mapping in bootstrap**\n\nImproved documentation of how Codex tools map to Claude Code equivalents for subagent workflows.\n\n### Tests\n\n- Added worktree requirement test for subagent-driven-development\n- Added main branch red flag warning test\n- Fixed case sensitivity in skill recognition test assertions\n\n---\n\n## v4.1.1 (2026-01-23)\n\n### Fixes\n\n**OpenCode: Standardized on `plugins/` directory per official docs (#343)**\n\nOpenCode's official documentation uses `~/.config/opencode/plugins/` (plural). Our docs previously used `plugin/` (singular). While OpenCode accepts both forms, we've standardized on the official convention to avoid confusion.\n\nChanges:\n- Renamed `.opencode/plugin/` to `.opencode/plugins/` in repo structure\n- Updated all installation docs (INSTALL.md, README.opencode.md) across all platforms\n- Updated test scripts to match\n\n**OpenCode: Fixed symlink instructions (#339, #342)**\n\n- Added explicit `rm` before `ln -s` (fixes \"file already exists\" errors on reinstall)\n- Added missing skills symlink step that was absent from INSTALL.md\n- Updated from deprecated `use_skill`/`find_skills` to native `skill` tool references\n\n---\n\n## v4.1.0 (2026-01-23)\n\n### Breaking Changes\n\n**OpenCode: Switched to native skills system**\n\nSuperpowers for OpenCode now uses OpenCode's native `skill` tool instead of custom `use_skill`/`find_skills` tools. This is a cleaner integration that works with OpenCode's built-in skill discovery.\n\n**Migration required:** Skills must be symlinked to `~/.config/opencode/skills/superpowers/` (see updated installation docs).\n\n### Fixes\n\n**OpenCode: Fixed agent reset on session start (#226)**\n\nThe previous bootstrap injection method using `session.prompt({ noReply: true })` caused OpenCode to reset the selected agent to \"build\" on first message. Now uses `experimental.chat.system.transform` hook which modifies the system prompt directly without side effects.\n\n**OpenCode: Fixed Windows installation (#232)**\n\n- Removed dependency on `skills-core.js` (eliminates broken relative imports when file is copied instead of symlinked)\n- Added comprehensive Windows installation docs for cmd.exe, PowerShell, and Git Bash\n- Documented proper symlink vs junction usage for each platform\n\n**Claude Code: Fixed Windows hook execution for Claude Code 2.1.x**\n\nClaude Code 2.1.x changed how hooks execute on Windows: it now auto-detects `.sh` files in commands and prepends `bash `. This broke the polyglot wrapper pattern because `bash \"run-hook.cmd\" session-start.sh` tries to execute the .cmd file as a bash script.\n\nFix: hooks.json now calls session-start.sh directly. Claude Code 2.1.x handles the bash invocation automatically. Also added .gitattributes to enforce LF line endings for shell scripts (fixes CRLF issues on Windows checkout).\n\n---\n\n## v4.0.3 (2025-12-26)\n\n### Improvements\n\n**Strengthened using-superpowers skill for explicit skill requests**\n\nAddressed a failure mode where Claude would skip invoking a skill even when the user explicitly requested it by name (e.g., \"subagent-driven-development, please\"). Claude would think \"I know what that means\" and start working directly instead of loading the skill.\n\nChanges:\n- Updated \"The Rule\" to say \"Invoke relevant or requested skills\" instead of \"Check for skills\" - emphasizing active invocation over passive checking\n- Added \"BEFORE any response or action\" - the original wording only mentioned \"response\" but Claude would sometimes take action without responding first\n- Added reassurance that invoking a wrong skill is okay - reduces hesitation\n- Added new red flag: \"I know what that means\" → Knowing the concept ≠ using the skill\n\n**Added explicit skill request tests**\n\nNew test suite in `tests/explicit-skill-requests/` that verifies Claude correctly invokes skills when users request them by name. Includes single-turn and multi-turn test scenarios.\n\n## v4.0.2 (2025-12-23)\n\n### Fixes\n\n**Slash commands now user-only**\n\nAdded `disable-model-invocation: true` to all three slash commands (`/brainstorm`, `/execute-plan`, `/write-plan`). Claude can no longer invoke these commands via the Skill tool—they're restricted to manual user invocation only.\n\nThe underlying skills (`superpowers:brainstorming`, `superpowers:executing-plans`, `superpowers:writing-plans`) remain available for Claude to invoke autonomously. This change prevents confusion when Claude would invoke a command that just redirects to a skill anyway.\n\n## v4.0.1 (2025-12-23)\n\n### Fixes\n\n**Clarified how to access skills in Claude Code**\n\nFixed a confusing pattern where Claude would invoke a skill via the Skill tool, then try to Read the skill file separately. The `using-superpowers` skill now explicitly states that the Skill tool loads skill content directly—no need to read files.\n\n- Added \"How to Access Skills\" section to `using-superpowers`\n- Changed \"read the skill\" → \"invoke the skill\" in instructions\n- Updated slash commands to use fully qualified skill names (e.g., `superpowers:brainstorming`)\n\n**Added GitHub thread reply guidance to receiving-code-review** (h/t @ralphbean)\n\nAdded a note about replying to inline review comments in the original thread rather than as top-level PR comments.\n\n**Added automation-over-documentation guidance to writing-skills** (h/t @EthanJStark)\n\nAdded guidance that mechanical constraints should be automated, not documented—save skills for judgment calls.\n\n## v4.0.0 (2025-12-17)\n\n### New Features\n\n**Two-stage code review in subagent-driven-development**\n\nSubagent workflows now use two separate review stages after each task:\n\n1. **Spec compliance review** - Skeptical reviewer verifies implementation matches spec exactly. Catches missing requirements AND over-building. Won't trust implementer's report—reads actual code.\n\n2. **Code quality review** - Only runs after spec compliance passes. Reviews for clean code, test coverage, maintainability.\n\nThis catches the common failure mode where code is well-written but doesn't match what was requested. Reviews are loops, not one-shot: if reviewer finds issues, implementer fixes them, then reviewer checks again.\n\nOther subagent workflow improvements:\n- Controller provides full task text to workers (not file references)\n- Workers can ask clarifying questions before AND during work\n- Self-review checklist before reporting completion\n- Plan read once at start, extracted to TodoWrite\n\nNew prompt templates in `skills/subagent-driven-development/`:\n- `implementer-prompt.md` - Includes self-review checklist, encourages questions\n- `spec-reviewer-prompt.md` - Skeptical verification against requirements\n- `code-quality-reviewer-prompt.md` - Standard code review\n\n**Debugging techniques consolidated with tools**\n\n`systematic-debugging` now bundles supporting techniques and tools:\n- `root-cause-tracing.md` - Trace bugs backward through call stack\n- `defense-in-depth.md` - Add validation at multiple layers\n- `condition-based-waiting.md` - Replace arbitrary timeouts with condition polling\n- `find-polluter.sh` - Bisection script to find which test creates pollution\n- `condition-based-waiting-example.ts` - Complete implementation from real debugging session\n\n**Testing anti-patterns reference**\n\n`test-driven-development` now includes `testing-anti-patterns.md` covering:\n- Testing mock behavior instead of real behavior\n- Adding test-only methods to production classes\n- Mocking without understanding dependencies\n- Incomplete mocks that hide structural assumptions\n\n**Skill test infrastructure**\n\nThree new test frameworks for validating skill behavior:\n\n`tests/skill-triggering/` - Validates skills trigger from naive prompts without explicit naming. Tests 6 skills to ensure descriptions alone are sufficient.\n\n`tests/claude-code/` - Integration tests using `claude -p` for headless testing. Verifies skill usage via session transcript (JSONL) analysis. Includes `analyze-token-usage.py` for cost tracking.\n\n`tests/subagent-driven-dev/` - End-to-end workflow validation with two complete test projects:\n- `go-fractals/` - CLI tool with Sierpinski/Mandelbrot (10 tasks)\n- `svelte-todo/` - CRUD app with localStorage and Playwright (12 tasks)\n\n### Major Changes\n\n**DOT flowcharts as executable specifications**\n\nRewrote key skills using DOT/GraphViz flowcharts as the authoritative process definition. Prose becomes supporting content.\n\n**The Description Trap** (documented in `writing-skills`): Discovered that skill descriptions override flowchart content when descriptions contain workflow summaries. Claude follows the short description instead of reading the detailed flowchart. Fix: descriptions must be trigger-only (\"Use when X\") with no process details.\n\n**Skill priority in using-superpowers**\n\nWhen multiple skills apply, process skills (brainstorming, debugging) now explicitly come before implementation skills. \"Build X\" triggers brainstorming first, then domain skills.\n\n**brainstorming trigger strengthened**\n\nDescription changed to imperative: \"You MUST use this before any creative work—creating features, building components, adding functionality, or modifying behavior.\"\n\n### Breaking Changes\n\n**Skill consolidation** - Six standalone skills merged:\n- `root-cause-tracing`, `defense-in-depth`, `condition-based-waiting` → bundled in `systematic-debugging/`\n- `testing-skills-with-subagents` → bundled in `writing-skills/`\n- `testing-anti-patterns` → bundled in `test-driven-development/`\n- `sharing-skills` removed (obsolete)\n\n### Other Improvements\n\n- **render-graphs.js** - Tool to extract DOT diagrams from skills and render to SVG\n- **Rationalizations table** in using-superpowers - Scannable format including new entries: \"I need more context first\", \"Let me explore first\", \"This feels productive\"\n- **docs/testing.md** - Guide to testing skills with Claude Code integration tests\n\n---\n\n## v3.6.2 (2025-12-03)\n\n### Fixed\n\n- **Linux Compatibility**: Fixed polyglot hook wrapper (`run-hook.cmd`) to use POSIX-compliant syntax\n  - Replaced bash-specific `${BASH_SOURCE[0]:-$0}` with standard `$0` on line 16\n  - Resolves \"Bad substitution\" error on Ubuntu/Debian systems where `/bin/sh` is dash\n  - Fixes #141\n\n---\n\n## v3.5.1 (2025-11-24)\n\n### Changed\n\n- **OpenCode Bootstrap Refactor**: Switched from `chat.message` hook to `session.created` event for bootstrap injection\n  - Bootstrap now injects at session creation via `session.prompt()` with `noReply: true`\n  - Explicitly tells the model that using-superpowers is already loaded to prevent redundant skill loading\n  - Consolidated bootstrap content generation into shared `getBootstrapContent()` helper\n  - Cleaner single-implementation approach (removed fallback pattern)\n\n---\n\n## v3.5.0 (2025-11-23)\n\n### Added\n\n- **OpenCode Support**: Native JavaScript plugin for OpenCode.ai\n  - Custom tools: `use_skill` and `find_skills`\n  - Message insertion pattern for skill persistence across context compaction\n  - Automatic context injection via chat.message hook\n  - Auto re-injection on session.compacted events\n  - Three-tier skill priority: project > personal > superpowers\n  - Project-local skills support (`.opencode/skills/`)\n  - Shared core module (`lib/skills-core.js`) for code reuse with Codex\n  - Automated test suite with proper isolation (`tests/opencode/`)\n  - Platform-specific documentation (`docs/README.opencode.md`, `docs/README.codex.md`)\n\n### Changed\n\n- **Refactored Codex Implementation**: Now uses shared `lib/skills-core.js` ES module\n  - Eliminates code duplication between Codex and OpenCode\n  - Single source of truth for skill discovery and parsing\n  - Codex successfully loads ES modules via Node.js interop\n\n- **Improved Documentation**: Rewrote README to explain problem/solution clearly\n  - Removed duplicate sections and conflicting information\n  - Added complete workflow description (brainstorm → plan → execute → finish)\n  - Simplified platform installation instructions\n  - Emphasized skill-checking protocol over automatic activation claims\n\n---\n\n## v3.4.1 (2025-10-31)\n\n### Improvements\n\n- Optimized superpowers bootstrap to eliminate redundant skill execution. The `using-superpowers` skill content is now provided directly in session context, with clear guidance to use the Skill tool only for other skills. This reduces overhead and prevents the confusing loop where agents would execute `using-superpowers` manually despite already having the content from session start.\n\n## v3.4.0 (2025-10-30)\n\n### Improvements\n\n- Simplified `brainstorming` skill to return to original conversational vision. Removed heavyweight 6-phase process with formal checklists in favor of natural dialogue: ask questions one at a time, then present design in 200-300 word sections with validation. Keeps documentation and implementation handoff features.\n\n## v3.3.1 (2025-10-28)\n\n### Improvements\n\n- Updated `brainstorming` skill to require autonomous recon before questioning, encourage recommendation-driven decisions, and prevent agents from delegating prioritization back to humans.\n- Applied writing clarity improvements to `brainstorming` skill following Strunk's \"Elements of Style\" principles (omitted needless words, converted negative to positive form, improved parallel construction).\n\n### Bug Fixes\n\n- Clarified `writing-skills` guidance so it points to the correct agent-specific personal skill directories (`~/.claude/skills` for Claude Code, `~/.codex/skills` for Codex).\n\n## v3.3.0 (2025-10-28)\n\n### New Features\n\n**Experimental Codex Support**\n- Added unified `superpowers-codex` script with bootstrap/use-skill/find-skills commands\n- Cross-platform Node.js implementation (works on Windows, macOS, Linux)\n- Namespaced skills: `superpowers:skill-name` for superpowers skills, `skill-name` for personal\n- Personal skills override superpowers skills when names match\n- Clean skill display: shows name/description without raw frontmatter\n- Helpful context: shows supporting files directory for each skill\n- Tool mapping for Codex: TodoWrite→update_plan, subagents→manual fallback, etc.\n- Bootstrap integration with minimal AGENTS.md for automatic startup\n- Complete installation guide and bootstrap instructions specific to Codex\n\n**Key differences from Claude Code integration:**\n- Single unified script instead of separate tools\n- Tool substitution system for Codex-specific equivalents\n- Simplified subagent handling (manual work instead of delegation)\n- Updated terminology: \"Superpowers skills\" instead of \"Core skills\"\n\n### Files Added\n- `.codex/INSTALL.md` - Installation guide for Codex users\n- `.codex/superpowers-bootstrap.md` - Bootstrap instructions with Codex adaptations\n- `.codex/superpowers-codex` - Unified Node.js executable with all functionality\n\n**Note:** Codex support is experimental. The integration provides core superpowers functionality but may require refinement based on user feedback.\n\n## v3.2.3 (2025-10-23)\n\n### Improvements\n\n**Updated using-superpowers skill to use Skill tool instead of Read tool**\n- Changed skill invocation instructions from Read tool to Skill tool\n- Updated description: \"using Read tool\" → \"using Skill tool\"\n- Updated step 3: \"Use the Read tool\" → \"Use the Skill tool to read and run\"\n- Updated rationalization list: \"Read the current version\" → \"Run the current version\"\n\nThe Skill tool is the proper mechanism for invoking skills in Claude Code. This update corrects the bootstrap instructions to guide agents toward the correct tool.\n\n### Files Changed\n- Updated: `skills/using-superpowers/SKILL.md` - Changed tool references from Read to Skill\n\n## v3.2.2 (2025-10-21)\n\n### Improvements\n\n**Strengthened using-superpowers skill against agent rationalization**\n- Added EXTREMELY-IMPORTANT block with absolute language about mandatory skill checking\n  - \"If even 1% chance a skill applies, you MUST read it\"\n  - \"You do not have a choice. You cannot rationalize your way out.\"\n- Added MANDATORY FIRST RESPONSE PROTOCOL checklist\n  - 5-step process agents must complete before any response\n  - Explicit \"responding without this = failure\" consequence\n- Added Common Rationalizations section with 8 specific evasion patterns\n  - \"This is just a simple question\" → WRONG\n  - \"I can check files quickly\" → WRONG\n  - \"Let me gather information first\" → WRONG\n  - Plus 5 more common patterns observed in agent behavior\n\nThese changes address observed agent behavior where they rationalize around skill usage despite clear instructions. The forceful language and pre-emptive counter-arguments aim to make non-compliance harder.\n\n### Files Changed\n- Updated: `skills/using-superpowers/SKILL.md` - Added three layers of enforcement to prevent skill-skipping rationalization\n\n## v3.2.1 (2025-10-20)\n\n### New Features\n\n**Code reviewer agent now included in plugin**\n- Added `superpowers:code-reviewer` agent to plugin's `agents/` directory\n- Agent provides systematic code review against plans and coding standards\n- Previously required users to have personal agent configuration\n- All skill references updated to use namespaced `superpowers:code-reviewer`\n- Fixes #55\n\n### Files Changed\n- New: `agents/code-reviewer.md` - Agent definition with review checklist and output format\n- Updated: `skills/requesting-code-review/SKILL.md` - References to `superpowers:code-reviewer`\n- Updated: `skills/subagent-driven-development/SKILL.md` - References to `superpowers:code-reviewer`\n\n## v3.2.0 (2025-10-18)\n\n### New Features\n\n**Design documentation in brainstorming workflow**\n- Added Phase 4: Design Documentation to brainstorming skill\n- Design documents now written to `docs/plans/YYYY-MM-DD-<topic>-design.md` before implementation\n- Restores functionality from original brainstorming command that was lost during skill conversion\n- Documents written before worktree setup and implementation planning\n- Tested with subagent to verify compliance under time pressure\n\n### Breaking Changes\n\n**Skill reference namespace standardization**\n- All internal skill references now use `superpowers:` namespace prefix\n- Updated format: `superpowers:test-driven-development` (previously just `test-driven-development`)\n- Affects all REQUIRED SUB-SKILL, RECOMMENDED SUB-SKILL, and REQUIRED BACKGROUND references\n- Aligns with how skills are invoked using the Skill tool\n- Files updated: brainstorming, executing-plans, subagent-driven-development, systematic-debugging, testing-skills-with-subagents, writing-plans, writing-skills\n\n### Improvements\n\n**Design vs implementation plan naming**\n- Design documents use `-design.md` suffix to prevent filename collisions\n- Implementation plans continue using existing `YYYY-MM-DD-<feature-name>.md` format\n- Both stored in `docs/plans/` directory with clear naming distinction\n\n## v3.1.1 (2025-10-17)\n\n### Bug Fixes\n\n- **Fixed command syntax in README** (#44) - Updated all command references to use correct namespaced syntax (`/superpowers:brainstorm` instead of `/brainstorm`). Plugin-provided commands are automatically namespaced by Claude Code to avoid conflicts between plugins.\n\n## v3.1.0 (2025-10-17)\n\n### Breaking Changes\n\n**Skill names standardized to lowercase**\n- All skill frontmatter `name:` fields now use lowercase kebab-case matching directory names\n- Examples: `brainstorming`, `test-driven-development`, `using-git-worktrees`\n- All skill announcements and cross-references updated to lowercase format\n- This ensures consistent naming across directory names, frontmatter, and documentation\n\n### New Features\n\n**Enhanced brainstorming skill**\n- Added Quick Reference table showing phases, activities, and tool usage\n- Added copyable workflow checklist for tracking progress\n- Added decision flowchart for when to revisit earlier phases\n- Added comprehensive AskUserQuestion tool guidance with concrete examples\n- Added \"Question Patterns\" section explaining when to use structured vs open-ended questions\n- Restructured Key Principles as scannable table\n\n**Anthropic best practices integration**\n- Added `skills/writing-skills/anthropic-best-practices.md` - Official Anthropic skill authoring guide\n- Referenced in writing-skills SKILL.md for comprehensive guidance\n- Provides patterns for progressive disclosure, workflows, and evaluation\n\n### Improvements\n\n**Skill cross-reference clarity**\n- All skill references now use explicit requirement markers:\n  - `**REQUIRED BACKGROUND:**` - Prerequisites you must understand\n  - `**REQUIRED SUB-SKILL:**` - Skills that must be used in workflow\n  - `**Complementary skills:**` - Optional but helpful related skills\n- Removed old path format (`skills/collaboration/X` → just `X`)\n- Updated Integration sections with categorized relationships (Required vs Complementary)\n- Updated cross-reference documentation with best practices\n\n**Alignment with Anthropic best practices**\n- Fixed description grammar and voice (fully third-person)\n- Added Quick Reference tables for scanning\n- Added workflow checklists Claude can copy and track\n- Appropriate use of flowcharts for non-obvious decision points\n- Improved scannable table formats\n- All skills well under 500-line recommendation\n\n### Bug Fixes\n\n- **Re-added missing command redirects** - Restored `commands/brainstorm.md` and `commands/write-plan.md` that were accidentally removed in v3.0 migration\n- Fixed `defense-in-depth` name mismatch (was `Defense-in-Depth-Validation`)\n- Fixed `receiving-code-review` name mismatch (was `Code-Review-Reception`)\n- Fixed `commands/brainstorm.md` reference to correct skill name\n- Removed references to non-existent related skills\n\n### Documentation\n\n**writing-skills improvements**\n- Updated cross-referencing guidance with explicit requirement markers\n- Added reference to Anthropic's official best practices\n- Improved examples showing proper skill reference format\n\n## v3.0.1 (2025-10-16)\n\n### Changes\n\nWe now use Anthropic's first-party skills system!\n\n## v2.0.2 (2025-10-12)\n\n### Bug Fixes\n\n- **Fixed false warning when local skills repo is ahead of upstream** - The initialization script was incorrectly warning \"New skills available from upstream\" when the local repository had commits ahead of upstream. The logic now correctly distinguishes between three git states: local behind (should update), local ahead (no warning), and diverged (should warn).\n\n## v2.0.1 (2025-10-12)\n\n### Bug Fixes\n\n- **Fixed session-start hook execution in plugin context** (#8, PR #9) - The hook was failing silently with \"Plugin hook error\" preventing skills context from loading. Fixed by:\n  - Using `${BASH_SOURCE[0]:-$0}` fallback when BASH_SOURCE is unbound in Claude Code's execution context\n  - Adding `|| true` to handle empty grep results gracefully when filtering status flags\n\n---\n\n# Superpowers v2.0.0 Release Notes\n\n## Overview\n\nSuperpowers v2.0 makes skills more accessible, maintainable, and community-driven through a major architectural shift.\n\nThe headline change is **skills repository separation**: all skills, scripts, and documentation have moved from the plugin into a dedicated repository ([obra/superpowers-skills](https://github.com/obra/superpowers-skills)). This transforms superpowers from a monolithic plugin into a lightweight shim that manages a local clone of the skills repository. Skills auto-update on session start. Users fork and contribute improvements via standard git workflows. The skills library versions independently from the plugin.\n\nBeyond infrastructure, this release adds nine new skills focused on problem-solving, research, and architecture. We rewrote the core **using-skills** documentation with imperative tone and clearer structure, making it easier for Claude to understand when and how to use skills. **find-skills** now outputs paths you can paste directly into the Read tool, eliminating friction in the skills discovery workflow.\n\nUsers experience seamless operation: the plugin handles cloning, forking, and updating automatically. Contributors find the new architecture makes improving and sharing skills trivial. This release lays the foundation for skills to evolve rapidly as a community resource.\n\n## Breaking Changes\n\n### Skills Repository Separation\n\n**The biggest change:** Skills no longer live in the plugin. They've been moved to a separate repository at [obra/superpowers-skills](https://github.com/obra/superpowers-skills).\n\n**What this means for you:**\n\n- **First install:** Plugin automatically clones skills to `~/.config/superpowers/skills/`\n- **Forking:** During setup, you'll be offered the option to fork the skills repo (if `gh` is installed)\n- **Updates:** Skills auto-update on session start (fast-forward when possible)\n- **Contributing:** Work on branches, commit locally, submit PRs to upstream\n- **No more shadowing:** Old two-tier system (personal/core) replaced with single-repo branch workflow\n\n**Migration:**\n\nIf you have an existing installation:\n1. Your old `~/.config/superpowers/.git` will be backed up to `~/.config/superpowers/.git.bak`\n2. Old skills will be backed up to `~/.config/superpowers/skills.bak`\n3. Fresh clone of obra/superpowers-skills will be created at `~/.config/superpowers/skills/`\n\n### Removed Features\n\n- **Personal superpowers overlay system** - Replaced with git branch workflow\n- **setup-personal-superpowers hook** - Replaced by initialize-skills.sh\n\n## New Features\n\n### Skills Repository Infrastructure\n\n**Automatic Clone & Setup** (`lib/initialize-skills.sh`)\n- Clones obra/superpowers-skills on first run\n- Offers fork creation if GitHub CLI is installed\n- Sets up upstream/origin remotes correctly\n- Handles migration from old installation\n\n**Auto-Update**\n- Fetches from tracking remote on every session start\n- Auto-merges with fast-forward when possible\n- Notifies when manual sync needed (branch diverged)\n- Uses pulling-updates-from-skills-repository skill for manual sync\n\n### New Skills\n\n**Problem-Solving Skills** (`skills/problem-solving/`)\n- **collision-zone-thinking** - Force unrelated concepts together for emergent insights\n- **inversion-exercise** - Flip assumptions to reveal hidden constraints\n- **meta-pattern-recognition** - Spot universal principles across domains\n- **scale-game** - Test at extremes to expose fundamental truths\n- **simplification-cascades** - Find insights that eliminate multiple components\n- **when-stuck** - Dispatch to right problem-solving technique\n\n**Research Skills** (`skills/research/`)\n- **tracing-knowledge-lineages** - Understand how ideas evolved over time\n\n**Architecture Skills** (`skills/architecture/`)\n- **preserving-productive-tensions** - Keep multiple valid approaches instead of forcing premature resolution\n\n### Skills Improvements\n\n**using-skills (formerly getting-started)**\n- Renamed from getting-started to using-skills\n- Complete rewrite with imperative tone (v4.0.0)\n- Front-loaded critical rules\n- Added \"Why\" explanations for all workflows\n- Always includes /SKILL.md suffix in references\n- Clearer distinction between rigid rules and flexible patterns\n\n**writing-skills**\n- Cross-referencing guidance moved from using-skills\n- Added token efficiency section (word count targets)\n- Improved CSO (Claude Search Optimization) guidance\n\n**sharing-skills**\n- Updated for new branch-and-PR workflow (v2.0.0)\n- Removed personal/core split references\n\n**pulling-updates-from-skills-repository** (new)\n- Complete workflow for syncing with upstream\n- Replaces old \"updating-skills\" skill\n\n### Tools Improvements\n\n**find-skills**\n- Now outputs full paths with /SKILL.md suffix\n- Makes paths directly usable with Read tool\n- Updated help text\n\n**skill-run**\n- Moved from scripts/ to skills/using-skills/\n- Improved documentation\n\n### Plugin Infrastructure\n\n**Session Start Hook**\n- Now loads from skills repository location\n- Shows full skills list at session start\n- Prints skills location info\n- Shows update status (updated successfully / behind upstream)\n- Moved \"skills behind\" warning to end of output\n\n**Environment Variables**\n- `SUPERPOWERS_SKILLS_ROOT` set to `~/.config/superpowers/skills`\n- Used consistently throughout all paths\n\n## Bug Fixes\n\n- Fixed duplicate upstream remote addition when forking\n- Fixed find-skills double \"skills/\" prefix in output\n- Removed obsolete setup-personal-superpowers call from session-start\n- Fixed path references throughout hooks and commands\n\n## Documentation\n\n### README\n- Updated for new skills repository architecture\n- Prominent link to superpowers-skills repo\n- Updated auto-update description\n- Fixed skill names and references\n- Updated Meta skills list\n\n### Testing Documentation\n- Added comprehensive testing checklist (`docs/TESTING-CHECKLIST.md`)\n- Created local marketplace config for testing\n- Documented manual testing scenarios\n\n## Technical Details\n\n### File Changes\n\n**Added:**\n- `lib/initialize-skills.sh` - Skills repo initialization and auto-update\n- `docs/TESTING-CHECKLIST.md` - Manual testing scenarios\n- `.claude-plugin/marketplace.json` - Local testing config\n\n**Removed:**\n- `skills/` directory (82 files) - Now in obra/superpowers-skills\n- `scripts/` directory - Now in obra/superpowers-skills/skills/using-skills/\n- `hooks/setup-personal-superpowers.sh` - Obsolete\n\n**Modified:**\n- `hooks/session-start.sh` - Use skills from ~/.config/superpowers/skills\n- `commands/brainstorm.md` - Updated paths to SUPERPOWERS_SKILLS_ROOT\n- `commands/write-plan.md` - Updated paths to SUPERPOWERS_SKILLS_ROOT\n- `commands/execute-plan.md` - Updated paths to SUPERPOWERS_SKILLS_ROOT\n- `README.md` - Complete rewrite for new architecture\n\n### Commit History\n\nThis release includes:\n- 20+ commits for skills repository separation\n- PR #1: Amplifier-inspired problem-solving and research skills\n- PR #2: Personal superpowers overlay system (later replaced)\n- Multiple skill refinements and documentation improvements\n\n## Upgrade Instructions\n\n### Fresh Install\n\n```bash\n# In Claude Code\n/plugin marketplace add obra/superpowers-marketplace\n/plugin install superpowers@superpowers-marketplace\n```\n\nThe plugin handles everything automatically.\n\n### Upgrading from v1.x\n\n1. **Backup your personal skills** (if you have any):\n   ```bash\n   cp -r ~/.config/superpowers/skills ~/superpowers-skills-backup\n   ```\n\n2. **Update the plugin:**\n   ```bash\n   /plugin update superpowers\n   ```\n\n3. **On next session start:**\n   - Old installation will be backed up automatically\n   - Fresh skills repo will be cloned\n   - If you have GitHub CLI, you'll be offered the option to fork\n\n4. **Migrate personal skills** (if you had any):\n   - Create a branch in your local skills repo\n   - Copy your personal skills from backup\n   - Commit and push to your fork\n   - Consider contributing back via PR\n\n## What's Next\n\n### For Users\n\n- Explore the new problem-solving skills\n- Try the branch-based workflow for skill improvements\n- Contribute skills back to the community\n\n### For Contributors\n\n- Skills repository is now at https://github.com/obra/superpowers-skills\n- Fork → Branch → PR workflow\n- See skills/meta/writing-skills/SKILL.md for TDD approach to documentation\n\n## Known Issues\n\nNone at this time.\n\n## Credits\n\n- Problem-solving skills inspired by Amplifier patterns\n- Community contributions and feedback\n- Extensive testing and iteration on skill effectiveness\n\n---\n\n**Full Changelog:** https://github.com/obra/superpowers/compare/dd013f6...main\n**Skills Repository:** https://github.com/obra/superpowers-skills\n**Issues:** https://github.com/obra/superpowers/issues\n"
  },
  {
    "path": "agents/code-reviewer.md",
    "content": "---\nname: code-reviewer\ndescription: |\n  Use this agent when a major project step has been completed and needs to be reviewed against the original plan and coding standards. Examples: <example>Context: The user is creating a code-review agent that should be called after a logical chunk of code is written. user: \"I've finished implementing the user authentication system as outlined in step 3 of our plan\" assistant: \"Great work! Now let me use the code-reviewer agent to review the implementation against our plan and coding standards\" <commentary>Since a major project step has been completed, use the code-reviewer agent to validate the work against the plan and identify any issues.</commentary></example> <example>Context: User has completed a significant feature implementation. user: \"The API endpoints for the task management system are now complete - that covers step 2 from our architecture document\" assistant: \"Excellent! Let me have the code-reviewer agent examine this implementation to ensure it aligns with our plan and follows best practices\" <commentary>A numbered step from the planning document has been completed, so the code-reviewer agent should review the work.</commentary></example>\nmodel: inherit\n---\n\nYou are a Senior Code Reviewer with expertise in software architecture, design patterns, and best practices. Your role is to review completed project steps against original plans and ensure code quality standards are met.\n\nWhen reviewing completed work, you will:\n\n1. **Plan Alignment Analysis**:\n   - Compare the implementation against the original planning document or step description\n   - Identify any deviations from the planned approach, architecture, or requirements\n   - Assess whether deviations are justified improvements or problematic departures\n   - Verify that all planned functionality has been implemented\n\n2. **Code Quality Assessment**:\n   - Review code for adherence to established patterns and conventions\n   - Check for proper error handling, type safety, and defensive programming\n   - Evaluate code organization, naming conventions, and maintainability\n   - Assess test coverage and quality of test implementations\n   - Look for potential security vulnerabilities or performance issues\n\n3. **Architecture and Design Review**:\n   - Ensure the implementation follows SOLID principles and established architectural patterns\n   - Check for proper separation of concerns and loose coupling\n   - Verify that the code integrates well with existing systems\n   - Assess scalability and extensibility considerations\n\n4. **Documentation and Standards**:\n   - Verify that code includes appropriate comments and documentation\n   - Check that file headers, function documentation, and inline comments are present and accurate\n   - Ensure adherence to project-specific coding standards and conventions\n\n5. **Issue Identification and Recommendations**:\n   - Clearly categorize issues as: Critical (must fix), Important (should fix), or Suggestions (nice to have)\n   - For each issue, provide specific examples and actionable recommendations\n   - When you identify plan deviations, explain whether they're problematic or beneficial\n   - Suggest specific improvements with code examples when helpful\n\n6. **Communication Protocol**:\n   - If you find significant deviations from the plan, ask the coding agent to review and confirm the changes\n   - If you identify issues with the original plan itself, recommend plan updates\n   - For implementation problems, provide clear guidance on fixes needed\n   - Always acknowledge what was done well before highlighting issues\n\nYour output should be structured, actionable, and focused on helping maintain high code quality while ensuring project goals are met. Be thorough but concise, and always provide constructive feedback that helps improve both the current implementation and future development practices.\n"
  },
  {
    "path": "commands/brainstorm.md",
    "content": "---\ndescription: \"Deprecated - use the superpowers:brainstorming skill instead\"\n---\n\nTell your human partner that this command is deprecated and will be removed in the next major release. They should ask you to use the \"superpowers brainstorming\" skill instead.\n"
  },
  {
    "path": "commands/execute-plan.md",
    "content": "---\ndescription: \"Deprecated - use the superpowers:executing-plans skill instead\"\n---\n\nTell your human partner that this command is deprecated and will be removed in the next major release. They should ask you to use the \"superpowers executing-plans\" skill instead.\n"
  },
  {
    "path": "commands/write-plan.md",
    "content": "---\ndescription: \"Deprecated - use the superpowers:writing-plans skill instead\"\n---\n\nTell your human partner that this command is deprecated and will be removed in the next major release. They should ask you to use the \"superpowers writing-plans\" skill instead.\n"
  },
  {
    "path": "docs/README.codex.md",
    "content": "# Superpowers for Codex\n\nGuide for using Superpowers with OpenAI Codex via native skill discovery.\n\n## Quick Install\n\nTell Codex:\n\n```\nFetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.codex/INSTALL.md\n```\n\n## Manual Installation\n\n### Prerequisites\n\n- OpenAI Codex CLI\n- Git\n\n### Steps\n\n1. Clone the repo:\n   ```bash\n   git clone https://github.com/obra/superpowers.git ~/.codex/superpowers\n   ```\n\n2. Create the skills symlink:\n   ```bash\n   mkdir -p ~/.agents/skills\n   ln -s ~/.codex/superpowers/skills ~/.agents/skills/superpowers\n   ```\n\n3. Restart Codex.\n\n4. **For subagent skills** (optional): Skills like `dispatching-parallel-agents` and `subagent-driven-development` require Codex's multi-agent feature. Add to your Codex config:\n   ```toml\n   [features]\n   multi_agent = true\n   ```\n\n### Windows\n\nUse a junction instead of a symlink (works without Developer Mode):\n\n```powershell\nNew-Item -ItemType Directory -Force -Path \"$env:USERPROFILE\\.agents\\skills\"\ncmd /c mklink /J \"$env:USERPROFILE\\.agents\\skills\\superpowers\" \"$env:USERPROFILE\\.codex\\superpowers\\skills\"\n```\n\n## How It Works\n\nCodex has native skill discovery — it scans `~/.agents/skills/` at startup, parses SKILL.md frontmatter, and loads skills on demand. Superpowers skills are made visible through a single symlink:\n\n```\n~/.agents/skills/superpowers/ → ~/.codex/superpowers/skills/\n```\n\nThe `using-superpowers` skill is discovered automatically and enforces skill usage discipline — no additional configuration needed.\n\n## Usage\n\nSkills are discovered automatically. Codex activates them when:\n- You mention a skill by name (e.g., \"use brainstorming\")\n- The task matches a skill's description\n- The `using-superpowers` skill directs Codex to use one\n\n### Personal Skills\n\nCreate your own skills in `~/.agents/skills/`:\n\n```bash\nmkdir -p ~/.agents/skills/my-skill\n```\n\nCreate `~/.agents/skills/my-skill/SKILL.md`:\n\n```markdown\n---\nname: my-skill\ndescription: Use when [condition] - [what it does]\n---\n\n# My Skill\n\n[Your skill content here]\n```\n\nThe `description` field is how Codex decides when to activate a skill automatically — write it as a clear trigger condition.\n\n## Updating\n\n```bash\ncd ~/.codex/superpowers && git pull\n```\n\nSkills update instantly through the symlink.\n\n## Uninstalling\n\n```bash\nrm ~/.agents/skills/superpowers\n```\n\n**Windows (PowerShell):**\n```powershell\nRemove-Item \"$env:USERPROFILE\\.agents\\skills\\superpowers\"\n```\n\nOptionally delete the clone: `rm -rf ~/.codex/superpowers` (Windows: `Remove-Item -Recurse -Force \"$env:USERPROFILE\\.codex\\superpowers\"`).\n\n## Troubleshooting\n\n### Skills not showing up\n\n1. Verify the symlink: `ls -la ~/.agents/skills/superpowers`\n2. Check skills exist: `ls ~/.codex/superpowers/skills`\n3. Restart Codex — skills are discovered at startup\n\n### Windows junction issues\n\nJunctions normally work without special permissions. If creation fails, try running PowerShell as administrator.\n\n## Getting Help\n\n- Report issues: https://github.com/obra/superpowers/issues\n- Main documentation: https://github.com/obra/superpowers\n"
  },
  {
    "path": "docs/README.opencode.md",
    "content": "# Superpowers for OpenCode\n\nComplete guide for using Superpowers with [OpenCode.ai](https://opencode.ai).\n\n## Installation\n\nAdd superpowers to the `plugin` array in your `opencode.json` (global or project-level):\n\n```json\n{\n  \"plugin\": [\"superpowers@git+https://github.com/obra/superpowers.git\"]\n}\n```\n\nRestart OpenCode. The plugin auto-installs via Bun and registers all skills automatically.\n\nVerify by asking: \"Tell me about your superpowers\"\n\n### Migrating from the old symlink-based install\n\nIf you previously installed superpowers using `git clone` and symlinks, remove the old setup:\n\n```bash\n# Remove old symlinks\nrm -f ~/.config/opencode/plugins/superpowers.js\nrm -rf ~/.config/opencode/skills/superpowers\n\n# Optionally remove the cloned repo\nrm -rf ~/.config/opencode/superpowers\n\n# Remove skills.paths from opencode.json if you added one for superpowers\n```\n\nThen follow the installation steps above.\n\n## Usage\n\n### Finding Skills\n\nUse OpenCode's native `skill` tool to list all available skills:\n\n```\nuse skill tool to list skills\n```\n\n### Loading a Skill\n\n```\nuse skill tool to load superpowers/brainstorming\n```\n\n### Personal Skills\n\nCreate your own skills in `~/.config/opencode/skills/`:\n\n```bash\nmkdir -p ~/.config/opencode/skills/my-skill\n```\n\nCreate `~/.config/opencode/skills/my-skill/SKILL.md`:\n\n```markdown\n---\nname: my-skill\ndescription: Use when [condition] - [what it does]\n---\n\n# My Skill\n\n[Your skill content here]\n```\n\n### Project Skills\n\nCreate project-specific skills in `.opencode/skills/` within your project.\n\n**Skill Priority:** Project skills > Personal skills > Superpowers skills\n\n## Updating\n\nSuperpowers updates automatically when you restart OpenCode. The plugin is re-installed from the git repository on each launch.\n\nTo pin a specific version, use a branch or tag:\n\n```json\n{\n  \"plugin\": [\"superpowers@git+https://github.com/obra/superpowers.git#v5.0.3\"]\n}\n```\n\n## How It Works\n\nThe plugin does two things:\n\n1. **Injects bootstrap context** via the `experimental.chat.system.transform` hook, adding superpowers awareness to every conversation.\n2. **Registers the skills directory** via the `config` hook, so OpenCode discovers all superpowers skills without symlinks or manual config.\n\n### Tool Mapping\n\nSkills written for Claude Code are automatically adapted for OpenCode:\n\n- `TodoWrite` → `todowrite`\n- `Task` with subagents → OpenCode's `@mention` system\n- `Skill` tool → OpenCode's native `skill` tool\n- File operations → Native OpenCode tools\n\n## Troubleshooting\n\n### Plugin not loading\n\n1. Check OpenCode logs: `opencode run --print-logs \"hello\" 2>&1 | grep -i superpowers`\n2. Verify the plugin line in your `opencode.json` is correct\n3. Make sure you're running a recent version of OpenCode\n\n### Skills not found\n\n1. Use OpenCode's `skill` tool to list available skills\n2. Check that the plugin is loading (see above)\n3. Each skill needs a `SKILL.md` file with valid YAML frontmatter\n\n### Bootstrap not appearing\n\n1. Check OpenCode version supports `experimental.chat.system.transform` hook\n2. Restart OpenCode after config changes\n\n## Getting Help\n\n- Report issues: https://github.com/obra/superpowers/issues\n- Main documentation: https://github.com/obra/superpowers\n- OpenCode docs: https://opencode.ai/docs/\n"
  },
  {
    "path": "docs/plans/2025-11-22-opencode-support-design.md",
    "content": "# OpenCode Support Design\n\n**Date:** 2025-11-22\n**Author:** Bot & Jesse\n**Status:** Design Complete, Awaiting Implementation\n\n## Overview\n\nAdd full superpowers support for OpenCode.ai using a native OpenCode plugin architecture that shares core functionality with the existing Codex implementation.\n\n## Background\n\nOpenCode.ai is a coding agent similar to Claude Code and Codex. Previous attempts to port superpowers to OpenCode (PR #93, PR #116) used file-copying approaches. This design takes a different approach: building a native OpenCode plugin using their JavaScript/TypeScript plugin system while sharing code with the Codex implementation.\n\n### Key Differences Between Platforms\n\n- **Claude Code**: Native Anthropic plugin system + file-based skills\n- **Codex**: No plugin system → bootstrap markdown + CLI script\n- **OpenCode**: JavaScript/TypeScript plugins with event hooks and custom tools API\n\n### OpenCode's Agent System\n\n- **Primary agents**: Build (default, full access) and Plan (restricted, read-only)\n- **Subagents**: General (research, searching, multi-step tasks)\n- **Invocation**: Automatic dispatch by primary agents OR manual `@mention` syntax\n- **Configuration**: Custom agents in `opencode.json` or `~/.config/opencode/agent/`\n\n## Architecture\n\n### High-Level Structure\n\n1. **Shared Core Module** (`lib/skills-core.js`)\n   - Common skill discovery and parsing logic\n   - Used by both Codex and OpenCode implementations\n\n2. **Platform-Specific Wrappers**\n   - Codex: CLI script (`.codex/superpowers-codex`)\n   - OpenCode: Plugin module (`.opencode/plugin/superpowers.js`)\n\n3. **Skill Directories**\n   - Core: `~/.config/opencode/superpowers/skills/` (or installed location)\n   - Personal: `~/.config/opencode/skills/` (shadows core skills)\n\n### Code Reuse Strategy\n\nExtract common functionality from `.codex/superpowers-codex` into shared module:\n\n```javascript\n// lib/skills-core.js\nmodule.exports = {\n  extractFrontmatter(filePath),      // Parse name + description from YAML\n  findSkillsInDir(dir, maxDepth),    // Recursive SKILL.md discovery\n  findAllSkills(dirs),                // Scan multiple directories\n  resolveSkillPath(skillName, dirs), // Handle shadowing (personal > core)\n  checkForUpdates(repoDir)           // Git fetch/status check\n};\n```\n\n### Skill Frontmatter Format\n\nCurrent format (no `when_to_use` field):\n\n```yaml\n---\nname: skill-name\ndescription: Use when [condition] - [what it does]; [additional context]\n---\n```\n\n## OpenCode Plugin Implementation\n\n### Custom Tools\n\n**Tool 1: `use_skill`**\n\nLoads a specific skill's content into the conversation (equivalent to Claude's Skill tool).\n\n```javascript\n{\n  name: 'use_skill',\n  description: 'Load and read a specific skill to guide your work',\n  schema: z.object({\n    skill_name: z.string().describe('Name of skill (e.g., \"superpowers:brainstorming\")')\n  }),\n  execute: async ({ skill_name }) => {\n    const { skillPath, content, frontmatter } = resolveAndReadSkill(skill_name);\n    const skillDir = path.dirname(skillPath);\n\n    return `# ${frontmatter.name}\n# ${frontmatter.description}\n# Supporting tools and docs are in ${skillDir}\n# ============================================\n\n${content}`;\n  }\n}\n```\n\n**Tool 2: `find_skills`**\n\nLists all available skills with metadata.\n\n```javascript\n{\n  name: 'find_skills',\n  description: 'List all available skills',\n  schema: z.object({}),\n  execute: async () => {\n    const skills = discoverAllSkills();\n    return skills.map(s =>\n      `${s.namespace}:${s.name}\n  ${s.description}\n  Directory: ${s.directory}\n`).join('\\n');\n  }\n}\n```\n\n### Session Startup Hook\n\nWhen a new session starts (`session.started` event):\n\n1. **Inject using-superpowers content**\n   - Full content of the using-superpowers skill\n   - Establishes mandatory workflows\n\n2. **Run find_skills automatically**\n   - Display full list of available skills upfront\n   - Include skill directories for each\n\n3. **Inject tool mapping instructions**\n   ```markdown\n   **Tool Mapping for OpenCode:**\n   When skills reference tools you don't have, substitute:\n   - `TodoWrite` → `update_plan`\n   - `Task` with subagents → Use OpenCode subagent system (@mention)\n   - `Skill` tool → `use_skill` custom tool\n   - Read, Write, Edit, Bash → Your native equivalents\n\n   **Skill directories contain:**\n   - Supporting scripts (run with bash)\n   - Additional documentation (read with read tool)\n   - Utilities specific to that skill\n   ```\n\n4. **Check for updates** (non-blocking)\n   - Quick git fetch with timeout\n   - Notify if updates available\n\n### Plugin Structure\n\n```javascript\n// .opencode/plugin/superpowers.js\nconst skillsCore = require('../../lib/skills-core');\nconst path = require('path');\nconst fs = require('fs');\nconst { z } = require('zod');\n\nexport const SuperpowersPlugin = async ({ client, directory, $ }) => {\n  const superpowersDir = path.join(process.env.HOME, '.config/opencode/superpowers');\n  const personalDir = path.join(process.env.HOME, '.config/opencode/skills');\n\n  return {\n    'session.started': async () => {\n      const usingSuperpowers = await readSkill('using-superpowers');\n      const skillsList = await findAllSkills();\n      const toolMapping = getToolMappingInstructions();\n\n      return {\n        context: `${usingSuperpowers}\\n\\n${skillsList}\\n\\n${toolMapping}`\n      };\n    },\n\n    tools: [\n      {\n        name: 'use_skill',\n        description: 'Load and read a specific skill',\n        schema: z.object({\n          skill_name: z.string()\n        }),\n        execute: async ({ skill_name }) => {\n          // Implementation using skillsCore\n        }\n      },\n      {\n        name: 'find_skills',\n        description: 'List all available skills',\n        schema: z.object({}),\n        execute: async () => {\n          // Implementation using skillsCore\n        }\n      }\n    ]\n  };\n};\n```\n\n## File Structure\n\n```\nsuperpowers/\n├── lib/\n│   └── skills-core.js           # NEW: Shared skill logic\n├── .codex/\n│   ├── superpowers-codex        # UPDATED: Use skills-core\n│   ├── superpowers-bootstrap.md\n│   └── INSTALL.md\n├── .opencode/\n│   ├── plugin/\n│   │   └── superpowers.js       # NEW: OpenCode plugin\n│   └── INSTALL.md               # NEW: Installation guide\n└── skills/                       # Unchanged\n```\n\n## Implementation Plan\n\n### Phase 1: Refactor Shared Core\n\n1. Create `lib/skills-core.js`\n   - Extract frontmatter parsing from `.codex/superpowers-codex`\n   - Extract skill discovery logic\n   - Extract path resolution (with shadowing)\n   - Update to use only `name` and `description` (no `when_to_use`)\n\n2. Update `.codex/superpowers-codex` to use shared core\n   - Import from `../lib/skills-core.js`\n   - Remove duplicated code\n   - Keep CLI wrapper logic\n\n3. Test Codex implementation still works\n   - Verify bootstrap command\n   - Verify use-skill command\n   - Verify find-skills command\n\n### Phase 2: Build OpenCode Plugin\n\n1. Create `.opencode/plugin/superpowers.js`\n   - Import shared core from `../../lib/skills-core.js`\n   - Implement plugin function\n   - Define custom tools (use_skill, find_skills)\n   - Implement session.started hook\n\n2. Create `.opencode/INSTALL.md`\n   - Installation instructions\n   - Directory setup\n   - Configuration guidance\n\n3. Test OpenCode implementation\n   - Verify session startup bootstrap\n   - Verify use_skill tool works\n   - Verify find_skills tool works\n   - Verify skill directories are accessible\n\n### Phase 3: Documentation & Polish\n\n1. Update README with OpenCode support\n2. Add OpenCode installation to main docs\n3. Update RELEASE-NOTES\n4. Test both Codex and OpenCode work correctly\n\n## Next Steps\n\n1. **Create isolated workspace** (using git worktrees)\n   - Branch: `feature/opencode-support`\n\n2. **Follow TDD where applicable**\n   - Test shared core functions\n   - Test skill discovery and parsing\n   - Integration tests for both platforms\n\n3. **Incremental implementation**\n   - Phase 1: Refactor shared core + update Codex\n   - Verify Codex still works before moving on\n   - Phase 2: Build OpenCode plugin\n   - Phase 3: Documentation and polish\n\n4. **Testing strategy**\n   - Manual testing with real OpenCode installation\n   - Verify skill loading, directories, scripts work\n   - Test both Codex and OpenCode side-by-side\n   - Verify tool mappings work correctly\n\n5. **PR and merge**\n   - Create PR with complete implementation\n   - Test in clean environment\n   - Merge to main\n\n## Benefits\n\n- **Code reuse**: Single source of truth for skill discovery/parsing\n- **Maintainability**: Bug fixes apply to both platforms\n- **Extensibility**: Easy to add future platforms (Cursor, Windsurf, etc.)\n- **Native integration**: Uses OpenCode's plugin system properly\n- **Consistency**: Same skill experience across all platforms\n"
  },
  {
    "path": "docs/plans/2025-11-22-opencode-support-implementation.md",
    "content": "# OpenCode Support Implementation Plan\n\n> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.\n\n**Goal:** Add full superpowers support for OpenCode.ai with a native JavaScript plugin that shares core functionality with the existing Codex implementation.\n\n**Architecture:** Extract common skill discovery/parsing logic into `lib/skills-core.js`, refactor Codex to use it, then build OpenCode plugin using their native plugin API with custom tools and session hooks.\n\n**Tech Stack:** Node.js, JavaScript, OpenCode Plugin API, Git worktrees\n\n---\n\n## Phase 1: Create Shared Core Module\n\n### Task 1: Extract Frontmatter Parsing\n\n**Files:**\n- Create: `lib/skills-core.js`\n- Reference: `.codex/superpowers-codex` (lines 40-74)\n\n**Step 1: Create lib/skills-core.js with extractFrontmatter function**\n\n```javascript\n#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\n\n/**\n * Extract YAML frontmatter from a skill file.\n * Current format:\n * ---\n * name: skill-name\n * description: Use when [condition] - [what it does]\n * ---\n *\n * @param {string} filePath - Path to SKILL.md file\n * @returns {{name: string, description: string}}\n */\nfunction extractFrontmatter(filePath) {\n    try {\n        const content = fs.readFileSync(filePath, 'utf8');\n        const lines = content.split('\\n');\n\n        let inFrontmatter = false;\n        let name = '';\n        let description = '';\n\n        for (const line of lines) {\n            if (line.trim() === '---') {\n                if (inFrontmatter) break;\n                inFrontmatter = true;\n                continue;\n            }\n\n            if (inFrontmatter) {\n                const match = line.match(/^(\\w+):\\s*(.*)$/);\n                if (match) {\n                    const [, key, value] = match;\n                    switch (key) {\n                        case 'name':\n                            name = value.trim();\n                            break;\n                        case 'description':\n                            description = value.trim();\n                            break;\n                    }\n                }\n            }\n        }\n\n        return { name, description };\n    } catch (error) {\n        return { name: '', description: '' };\n    }\n}\n\nmodule.exports = {\n    extractFrontmatter\n};\n```\n\n**Step 2: Verify file was created**\n\nRun: `ls -l lib/skills-core.js`\nExpected: File exists\n\n**Step 3: Commit**\n\n```bash\ngit add lib/skills-core.js\ngit commit -m \"feat: create shared skills core module with frontmatter parser\"\n```\n\n---\n\n### Task 2: Extract Skill Discovery Logic\n\n**Files:**\n- Modify: `lib/skills-core.js`\n- Reference: `.codex/superpowers-codex` (lines 97-136)\n\n**Step 1: Add findSkillsInDir function to skills-core.js**\n\nAdd before `module.exports`:\n\n```javascript\n/**\n * Find all SKILL.md files in a directory recursively.\n *\n * @param {string} dir - Directory to search\n * @param {string} sourceType - 'personal' or 'superpowers' for namespacing\n * @param {number} maxDepth - Maximum recursion depth (default: 3)\n * @returns {Array<{path: string, name: string, description: string, sourceType: string}>}\n */\nfunction findSkillsInDir(dir, sourceType, maxDepth = 3) {\n    const skills = [];\n\n    if (!fs.existsSync(dir)) return skills;\n\n    function recurse(currentDir, depth) {\n        if (depth > maxDepth) return;\n\n        const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n\n        for (const entry of entries) {\n            const fullPath = path.join(currentDir, entry.name);\n\n            if (entry.isDirectory()) {\n                // Check for SKILL.md in this directory\n                const skillFile = path.join(fullPath, 'SKILL.md');\n                if (fs.existsSync(skillFile)) {\n                    const { name, description } = extractFrontmatter(skillFile);\n                    skills.push({\n                        path: fullPath,\n                        skillFile: skillFile,\n                        name: name || entry.name,\n                        description: description || '',\n                        sourceType: sourceType\n                    });\n                }\n\n                // Recurse into subdirectories\n                recurse(fullPath, depth + 1);\n            }\n        }\n    }\n\n    recurse(dir, 0);\n    return skills;\n}\n```\n\n**Step 2: Update module.exports**\n\nReplace the exports line with:\n\n```javascript\nmodule.exports = {\n    extractFrontmatter,\n    findSkillsInDir\n};\n```\n\n**Step 3: Verify syntax**\n\nRun: `node -c lib/skills-core.js`\nExpected: No output (success)\n\n**Step 4: Commit**\n\n```bash\ngit add lib/skills-core.js\ngit commit -m \"feat: add skill discovery function to core module\"\n```\n\n---\n\n### Task 3: Extract Skill Resolution Logic\n\n**Files:**\n- Modify: `lib/skills-core.js`\n- Reference: `.codex/superpowers-codex` (lines 212-280)\n\n**Step 1: Add resolveSkillPath function**\n\nAdd before `module.exports`:\n\n```javascript\n/**\n * Resolve a skill name to its file path, handling shadowing\n * (personal skills override superpowers skills).\n *\n * @param {string} skillName - Name like \"superpowers:brainstorming\" or \"my-skill\"\n * @param {string} superpowersDir - Path to superpowers skills directory\n * @param {string} personalDir - Path to personal skills directory\n * @returns {{skillFile: string, sourceType: string, skillPath: string} | null}\n */\nfunction resolveSkillPath(skillName, superpowersDir, personalDir) {\n    // Strip superpowers: prefix if present\n    const forceSuperpowers = skillName.startsWith('superpowers:');\n    const actualSkillName = forceSuperpowers ? skillName.replace(/^superpowers:/, '') : skillName;\n\n    // Try personal skills first (unless explicitly superpowers:)\n    if (!forceSuperpowers && personalDir) {\n        const personalPath = path.join(personalDir, actualSkillName);\n        const personalSkillFile = path.join(personalPath, 'SKILL.md');\n        if (fs.existsSync(personalSkillFile)) {\n            return {\n                skillFile: personalSkillFile,\n                sourceType: 'personal',\n                skillPath: actualSkillName\n            };\n        }\n    }\n\n    // Try superpowers skills\n    if (superpowersDir) {\n        const superpowersPath = path.join(superpowersDir, actualSkillName);\n        const superpowersSkillFile = path.join(superpowersPath, 'SKILL.md');\n        if (fs.existsSync(superpowersSkillFile)) {\n            return {\n                skillFile: superpowersSkillFile,\n                sourceType: 'superpowers',\n                skillPath: actualSkillName\n            };\n        }\n    }\n\n    return null;\n}\n```\n\n**Step 2: Update module.exports**\n\n```javascript\nmodule.exports = {\n    extractFrontmatter,\n    findSkillsInDir,\n    resolveSkillPath\n};\n```\n\n**Step 3: Verify syntax**\n\nRun: `node -c lib/skills-core.js`\nExpected: No output\n\n**Step 4: Commit**\n\n```bash\ngit add lib/skills-core.js\ngit commit -m \"feat: add skill path resolution with shadowing support\"\n```\n\n---\n\n### Task 4: Extract Update Check Logic\n\n**Files:**\n- Modify: `lib/skills-core.js`\n- Reference: `.codex/superpowers-codex` (lines 16-38)\n\n**Step 1: Add checkForUpdates function**\n\nAdd at top after requires:\n\n```javascript\nconst { execSync } = require('child_process');\n```\n\nAdd before `module.exports`:\n\n```javascript\n/**\n * Check if a git repository has updates available.\n *\n * @param {string} repoDir - Path to git repository\n * @returns {boolean} - True if updates are available\n */\nfunction checkForUpdates(repoDir) {\n    try {\n        // Quick check with 3 second timeout to avoid delays if network is down\n        const output = execSync('git fetch origin && git status --porcelain=v1 --branch', {\n            cwd: repoDir,\n            timeout: 3000,\n            encoding: 'utf8',\n            stdio: 'pipe'\n        });\n\n        // Parse git status output to see if we're behind\n        const statusLines = output.split('\\n');\n        for (const line of statusLines) {\n            if (line.startsWith('## ') && line.includes('[behind ')) {\n                return true; // We're behind remote\n            }\n        }\n        return false; // Up to date\n    } catch (error) {\n        // Network down, git error, timeout, etc. - don't block bootstrap\n        return false;\n    }\n}\n```\n\n**Step 2: Update module.exports**\n\n```javascript\nmodule.exports = {\n    extractFrontmatter,\n    findSkillsInDir,\n    resolveSkillPath,\n    checkForUpdates\n};\n```\n\n**Step 3: Verify syntax**\n\nRun: `node -c lib/skills-core.js`\nExpected: No output\n\n**Step 4: Commit**\n\n```bash\ngit add lib/skills-core.js\ngit commit -m \"feat: add git update checking to core module\"\n```\n\n---\n\n## Phase 2: Refactor Codex to Use Shared Core\n\n### Task 5: Update Codex to Import Shared Core\n\n**Files:**\n- Modify: `.codex/superpowers-codex` (add import at top)\n\n**Step 1: Add import statement**\n\nAfter the existing requires at top of file (around line 6), add:\n\n```javascript\nconst skillsCore = require('../lib/skills-core');\n```\n\n**Step 2: Verify syntax**\n\nRun: `node -c .codex/superpowers-codex`\nExpected: No output\n\n**Step 3: Commit**\n\n```bash\ngit add .codex/superpowers-codex\ngit commit -m \"refactor: import shared skills core in codex\"\n```\n\n---\n\n### Task 6: Replace extractFrontmatter with Core Version\n\n**Files:**\n- Modify: `.codex/superpowers-codex` (lines 40-74)\n\n**Step 1: Remove local extractFrontmatter function**\n\nDelete lines 40-74 (the entire extractFrontmatter function definition).\n\n**Step 2: Update all extractFrontmatter calls**\n\nFind and replace all calls from `extractFrontmatter(` to `skillsCore.extractFrontmatter(`\n\nAffected lines approximately: 90, 310\n\n**Step 3: Verify script still works**\n\nRun: `.codex/superpowers-codex find-skills | head -20`\nExpected: Shows list of skills\n\n**Step 4: Commit**\n\n```bash\ngit add .codex/superpowers-codex\ngit commit -m \"refactor: use shared extractFrontmatter in codex\"\n```\n\n---\n\n### Task 7: Replace findSkillsInDir with Core Version\n\n**Files:**\n- Modify: `.codex/superpowers-codex` (lines 97-136, approximately)\n\n**Step 1: Remove local findSkillsInDir function**\n\nDelete the entire `findSkillsInDir` function definition (approximately lines 97-136).\n\n**Step 2: Update all findSkillsInDir calls**\n\nReplace calls from `findSkillsInDir(` to `skillsCore.findSkillsInDir(`\n\n**Step 3: Verify script still works**\n\nRun: `.codex/superpowers-codex find-skills | head -20`\nExpected: Shows list of skills\n\n**Step 4: Commit**\n\n```bash\ngit add .codex/superpowers-codex\ngit commit -m \"refactor: use shared findSkillsInDir in codex\"\n```\n\n---\n\n### Task 8: Replace checkForUpdates with Core Version\n\n**Files:**\n- Modify: `.codex/superpowers-codex` (lines 16-38, approximately)\n\n**Step 1: Remove local checkForUpdates function**\n\nDelete the entire `checkForUpdates` function definition.\n\n**Step 2: Update all checkForUpdates calls**\n\nReplace calls from `checkForUpdates(` to `skillsCore.checkForUpdates(`\n\n**Step 3: Verify script still works**\n\nRun: `.codex/superpowers-codex bootstrap | head -50`\nExpected: Shows bootstrap content\n\n**Step 4: Commit**\n\n```bash\ngit add .codex/superpowers-codex\ngit commit -m \"refactor: use shared checkForUpdates in codex\"\n```\n\n---\n\n## Phase 3: Build OpenCode Plugin\n\n### Task 9: Create OpenCode Plugin Directory Structure\n\n**Files:**\n- Create: `.opencode/plugin/superpowers.js`\n\n**Step 1: Create directory**\n\nRun: `mkdir -p .opencode/plugin`\n\n**Step 2: Create basic plugin file**\n\n```javascript\n#!/usr/bin/env node\n\n/**\n * Superpowers plugin for OpenCode.ai\n *\n * Provides custom tools for loading and discovering skills,\n * with automatic bootstrap on session start.\n */\n\nconst skillsCore = require('../../lib/skills-core');\nconst path = require('path');\nconst fs = require('fs');\nconst os = require('os');\n\nconst homeDir = os.homedir();\nconst superpowersSkillsDir = path.join(homeDir, '.config/opencode/superpowers/skills');\nconst personalSkillsDir = path.join(homeDir, '.config/opencode/skills');\n\n/**\n * OpenCode plugin entry point\n */\nexport const SuperpowersPlugin = async ({ project, client, $, directory, worktree }) => {\n  return {\n    // Custom tools and hooks will go here\n  };\n};\n```\n\n**Step 3: Verify file was created**\n\nRun: `ls -l .opencode/plugin/superpowers.js`\nExpected: File exists\n\n**Step 4: Commit**\n\n```bash\ngit add .opencode/plugin/superpowers.js\ngit commit -m \"feat: create opencode plugin scaffold\"\n```\n\n---\n\n### Task 10: Implement use_skill Tool\n\n**Files:**\n- Modify: `.opencode/plugin/superpowers.js`\n\n**Step 1: Add use_skill tool implementation**\n\nReplace the plugin return statement with:\n\n```javascript\nexport const SuperpowersPlugin = async ({ project, client, $, directory, worktree }) => {\n  // Import zod for schema validation\n  const { z } = await import('zod');\n\n  return {\n    tools: [\n      {\n        name: 'use_skill',\n        description: 'Load and read a specific skill to guide your work. Skills contain proven workflows, mandatory processes, and expert techniques.',\n        schema: z.object({\n          skill_name: z.string().describe('Name of the skill to load (e.g., \"superpowers:brainstorming\" or \"my-custom-skill\")')\n        }),\n        execute: async ({ skill_name }) => {\n          // Resolve skill path (handles shadowing: personal > superpowers)\n          const resolved = skillsCore.resolveSkillPath(\n            skill_name,\n            superpowersSkillsDir,\n            personalSkillsDir\n          );\n\n          if (!resolved) {\n            return `Error: Skill \"${skill_name}\" not found.\\n\\nRun find_skills to see available skills.`;\n          }\n\n          // Read skill content\n          const fullContent = fs.readFileSync(resolved.skillFile, 'utf8');\n          const { name, description } = skillsCore.extractFrontmatter(resolved.skillFile);\n\n          // Extract content after frontmatter\n          const lines = fullContent.split('\\n');\n          let inFrontmatter = false;\n          let frontmatterEnded = false;\n          const contentLines = [];\n\n          for (const line of lines) {\n            if (line.trim() === '---') {\n              if (inFrontmatter) {\n                frontmatterEnded = true;\n                continue;\n              }\n              inFrontmatter = true;\n              continue;\n            }\n\n            if (frontmatterEnded || !inFrontmatter) {\n              contentLines.push(line);\n            }\n          }\n\n          const content = contentLines.join('\\n').trim();\n          const skillDirectory = path.dirname(resolved.skillFile);\n\n          // Format output similar to Claude Code's Skill tool\n          return `# ${name || skill_name}\n# ${description || ''}\n# Supporting tools and docs are in ${skillDirectory}\n# ============================================\n\n${content}`;\n        }\n      }\n    ]\n  };\n};\n```\n\n**Step 2: Verify syntax**\n\nRun: `node -c .opencode/plugin/superpowers.js`\nExpected: No output\n\n**Step 3: Commit**\n\n```bash\ngit add .opencode/plugin/superpowers.js\ngit commit -m \"feat: implement use_skill tool for opencode\"\n```\n\n---\n\n### Task 11: Implement find_skills Tool\n\n**Files:**\n- Modify: `.opencode/plugin/superpowers.js`\n\n**Step 1: Add find_skills tool to tools array**\n\nAdd after the use_skill tool definition, before closing the tools array:\n\n```javascript\n      {\n        name: 'find_skills',\n        description: 'List all available skills in the superpowers and personal skill libraries.',\n        schema: z.object({}),\n        execute: async () => {\n          // Find skills in both directories\n          const superpowersSkills = skillsCore.findSkillsInDir(\n            superpowersSkillsDir,\n            'superpowers',\n            3\n          );\n          const personalSkills = skillsCore.findSkillsInDir(\n            personalSkillsDir,\n            'personal',\n            3\n          );\n\n          // Combine and format skills list\n          const allSkills = [...personalSkills, ...superpowersSkills];\n\n          if (allSkills.length === 0) {\n            return 'No skills found. Install superpowers skills to ~/.config/opencode/superpowers/skills/';\n          }\n\n          let output = 'Available skills:\\n\\n';\n\n          for (const skill of allSkills) {\n            const namespace = skill.sourceType === 'personal' ? '' : 'superpowers:';\n            const skillName = skill.name || path.basename(skill.path);\n\n            output += `${namespace}${skillName}\\n`;\n            if (skill.description) {\n              output += `  ${skill.description}\\n`;\n            }\n            output += `  Directory: ${skill.path}\\n\\n`;\n          }\n\n          return output;\n        }\n      }\n```\n\n**Step 2: Verify syntax**\n\nRun: `node -c .opencode/plugin/superpowers.js`\nExpected: No output\n\n**Step 3: Commit**\n\n```bash\ngit add .opencode/plugin/superpowers.js\ngit commit -m \"feat: implement find_skills tool for opencode\"\n```\n\n---\n\n### Task 12: Implement Session Start Hook\n\n**Files:**\n- Modify: `.opencode/plugin/superpowers.js`\n\n**Step 1: Add session.started hook**\n\nAfter the tools array, add:\n\n```javascript\n    'session.started': async () => {\n      // Read using-superpowers skill content\n      const usingSuperpowersPath = skillsCore.resolveSkillPath(\n        'using-superpowers',\n        superpowersSkillsDir,\n        personalSkillsDir\n      );\n\n      let usingSuperpowersContent = '';\n      if (usingSuperpowersPath) {\n        const fullContent = fs.readFileSync(usingSuperpowersPath.skillFile, 'utf8');\n        // Strip frontmatter\n        const lines = fullContent.split('\\n');\n        let inFrontmatter = false;\n        let frontmatterEnded = false;\n        const contentLines = [];\n\n        for (const line of lines) {\n          if (line.trim() === '---') {\n            if (inFrontmatter) {\n              frontmatterEnded = true;\n              continue;\n            }\n            inFrontmatter = true;\n            continue;\n          }\n\n          if (frontmatterEnded || !inFrontmatter) {\n            contentLines.push(line);\n          }\n        }\n\n        usingSuperpowersContent = contentLines.join('\\n').trim();\n      }\n\n      // Tool mapping instructions\n      const toolMapping = `\n**Tool Mapping for OpenCode:**\nWhen skills reference tools you don't have, substitute OpenCode equivalents:\n- \\`TodoWrite\\` → \\`update_plan\\` (your planning/task tracking tool)\n- \\`Task\\` tool with subagents → Use OpenCode's subagent system (@mention syntax or automatic dispatch)\n- \\`Skill\\` tool → \\`use_skill\\` custom tool (already available)\n- \\`Read\\`, \\`Write\\`, \\`Edit\\`, \\`Bash\\` → Use your native tools\n\n**Skill directories contain supporting files:**\n- Scripts you can run with bash tool\n- Additional documentation you can read\n- Utilities and helpers specific to that skill\n\n**Skills naming:**\n- Superpowers skills: \\`superpowers:skill-name\\` (from ~/.config/opencode/superpowers/skills/)\n- Personal skills: \\`skill-name\\` (from ~/.config/opencode/skills/)\n- Personal skills override superpowers skills when names match\n`;\n\n      // Check for updates (non-blocking)\n      const hasUpdates = skillsCore.checkForUpdates(\n        path.join(homeDir, '.config/opencode/superpowers')\n      );\n\n      const updateNotice = hasUpdates ?\n        '\\n\\n⚠️ **Updates available!** Run `cd ~/.config/opencode/superpowers && git pull` to update superpowers.' :\n        '';\n\n      // Return context to inject into session\n      return {\n        context: `<EXTREMELY_IMPORTANT>\nYou have superpowers.\n\n**Below is the full content of your 'superpowers:using-superpowers' skill - your introduction to using skills. For all other skills, use the 'use_skill' tool:**\n\n${usingSuperpowersContent}\n\n${toolMapping}${updateNotice}\n</EXTREMELY_IMPORTANT>`\n      };\n    }\n```\n\n**Step 2: Verify syntax**\n\nRun: `node -c .opencode/plugin/superpowers.js`\nExpected: No output\n\n**Step 3: Commit**\n\n```bash\ngit add .opencode/plugin/superpowers.js\ngit commit -m \"feat: implement session.started hook for opencode\"\n```\n\n---\n\n## Phase 4: Documentation\n\n### Task 13: Create OpenCode Installation Guide\n\n**Files:**\n- Create: `.opencode/INSTALL.md`\n\n**Step 1: Create installation guide**\n\n```markdown\n# Installing Superpowers for OpenCode\n\n## Prerequisites\n\n- [OpenCode.ai](https://opencode.ai) installed\n- Node.js installed\n- Git installed\n\n## Installation Steps\n\n### 1. Install Superpowers Skills\n\n```bash\n# Clone superpowers skills to OpenCode config directory\nmkdir -p ~/.config/opencode/superpowers\ngit clone https://github.com/obra/superpowers.git ~/.config/opencode/superpowers\n```\n\n### 2. Install the Plugin\n\nThe plugin is included in the superpowers repository you just cloned.\n\nOpenCode will automatically discover it from:\n- `~/.config/opencode/superpowers/.opencode/plugin/superpowers.js`\n\nOr you can link it to the project-local plugin directory:\n\n```bash\n# In your OpenCode project\nmkdir -p .opencode/plugin\nln -s ~/.config/opencode/superpowers/.opencode/plugin/superpowers.js .opencode/plugin/superpowers.js\n```\n\n### 3. Restart OpenCode\n\nRestart OpenCode to load the plugin. On the next session, you should see:\n\n```\nYou have superpowers.\n```\n\n## Usage\n\n### Finding Skills\n\nUse the `find_skills` tool to list all available skills:\n\n```\nuse find_skills tool\n```\n\n### Loading a Skill\n\nUse the `use_skill` tool to load a specific skill:\n\n```\nuse use_skill tool with skill_name: \"superpowers:brainstorming\"\n```\n\n### Personal Skills\n\nCreate your own skills in `~/.config/opencode/skills/`:\n\n```bash\nmkdir -p ~/.config/opencode/skills/my-skill\n```\n\nCreate `~/.config/opencode/skills/my-skill/SKILL.md`:\n\n```markdown\n---\nname: my-skill\ndescription: Use when [condition] - [what it does]\n---\n\n# My Skill\n\n[Your skill content here]\n```\n\nPersonal skills override superpowers skills with the same name.\n\n## Updating\n\n```bash\ncd ~/.config/opencode/superpowers\ngit pull\n```\n\n## Troubleshooting\n\n### Plugin not loading\n\n1. Check plugin file exists: `ls ~/.config/opencode/superpowers/.opencode/plugin/superpowers.js`\n2. Check OpenCode logs for errors\n3. Verify Node.js is installed: `node --version`\n\n### Skills not found\n\n1. Verify skills directory exists: `ls ~/.config/opencode/superpowers/skills`\n2. Use `find_skills` tool to see what's discovered\n3. Check file structure: each skill should have a `SKILL.md` file\n\n### Tool mapping issues\n\nWhen a skill references a Claude Code tool you don't have:\n- `TodoWrite` → use `update_plan`\n- `Task` with subagents → use `@mention` syntax to invoke OpenCode subagents\n- `Skill` → use `use_skill` tool\n- File operations → use your native tools\n\n## Getting Help\n\n- Report issues: https://github.com/obra/superpowers/issues\n- Documentation: https://github.com/obra/superpowers\n```\n\n**Step 2: Verify file created**\n\nRun: `ls -l .opencode/INSTALL.md`\nExpected: File exists\n\n**Step 3: Commit**\n\n```bash\ngit add .opencode/INSTALL.md\ngit commit -m \"docs: add opencode installation guide\"\n```\n\n---\n\n### Task 14: Update Main README\n\n**Files:**\n- Modify: `README.md`\n\n**Step 1: Add OpenCode section**\n\nFind the section about supported platforms (search for \"Codex\" in the file), and add after it:\n\n```markdown\n### OpenCode\n\nSuperpowers works with [OpenCode.ai](https://opencode.ai) through a native JavaScript plugin.\n\n**Installation:** See [.opencode/INSTALL.md](.opencode/INSTALL.md)\n\n**Features:**\n- Custom tools: `use_skill` and `find_skills`\n- Automatic session bootstrap\n- Personal skills with shadowing\n- Supporting files and scripts access\n```\n\n**Step 2: Verify formatting**\n\nRun: `grep -A 10 \"### OpenCode\" README.md`\nExpected: Shows the section you added\n\n**Step 3: Commit**\n\n```bash\ngit add README.md\ngit commit -m \"docs: add opencode support to readme\"\n```\n\n---\n\n### Task 15: Update Release Notes\n\n**Files:**\n- Modify: `RELEASE-NOTES.md`\n\n**Step 1: Add entry for OpenCode support**\n\nAt the top of the file (after the header), add:\n\n```markdown\n## [Unreleased]\n\n### Added\n\n- **OpenCode Support**: Native JavaScript plugin for OpenCode.ai\n  - Custom tools: `use_skill` and `find_skills`\n  - Automatic session bootstrap with tool mapping instructions\n  - Shared core module (`lib/skills-core.js`) for code reuse\n  - Installation guide in `.opencode/INSTALL.md`\n\n### Changed\n\n- **Refactored Codex Implementation**: Now uses shared `lib/skills-core.js` module\n  - Eliminates code duplication between Codex and OpenCode\n  - Single source of truth for skill discovery and parsing\n\n---\n\n```\n\n**Step 2: Verify formatting**\n\nRun: `head -30 RELEASE-NOTES.md`\nExpected: Shows your new section\n\n**Step 3: Commit**\n\n```bash\ngit add RELEASE-NOTES.md\ngit commit -m \"docs: add opencode support to release notes\"\n```\n\n---\n\n## Phase 5: Final Verification\n\n### Task 16: Test Codex Still Works\n\n**Files:**\n- Test: `.codex/superpowers-codex`\n\n**Step 1: Test find-skills command**\n\nRun: `.codex/superpowers-codex find-skills | head -20`\nExpected: Shows list of skills with names and descriptions\n\n**Step 2: Test use-skill command**\n\nRun: `.codex/superpowers-codex use-skill superpowers:brainstorming | head -20`\nExpected: Shows brainstorming skill content\n\n**Step 3: Test bootstrap command**\n\nRun: `.codex/superpowers-codex bootstrap | head -30`\nExpected: Shows bootstrap content with instructions\n\n**Step 4: If all tests pass, record success**\n\nNo commit needed - this is verification only.\n\n---\n\n### Task 17: Verify File Structure\n\n**Files:**\n- Check: All new files exist\n\n**Step 1: Verify all files created**\n\nRun:\n```bash\nls -l lib/skills-core.js\nls -l .opencode/plugin/superpowers.js\nls -l .opencode/INSTALL.md\n```\n\nExpected: All files exist\n\n**Step 2: Verify directory structure**\n\nRun: `tree -L 2 .opencode/` (or `find .opencode -type f` if tree not available)\nExpected:\n```\n.opencode/\n├── INSTALL.md\n└── plugin/\n    └── superpowers.js\n```\n\n**Step 3: If structure correct, proceed**\n\nNo commit needed - this is verification only.\n\n---\n\n### Task 18: Final Commit and Summary\n\n**Files:**\n- Check: `git status`\n\n**Step 1: Check git status**\n\nRun: `git status`\nExpected: Working tree clean, all changes committed\n\n**Step 2: Review commit log**\n\nRun: `git log --oneline -20`\nExpected: Shows all commits from this implementation\n\n**Step 3: Create summary document**\n\nCreate a completion summary showing:\n- Total commits made\n- Files created: `lib/skills-core.js`, `.opencode/plugin/superpowers.js`, `.opencode/INSTALL.md`\n- Files modified: `.codex/superpowers-codex`, `README.md`, `RELEASE-NOTES.md`\n- Testing performed: Codex commands verified\n- Ready for: Testing with actual OpenCode installation\n\n**Step 4: Report completion**\n\nPresent summary to user and offer to:\n1. Push to remote\n2. Create pull request\n3. Test with real OpenCode installation (requires OpenCode installed)\n\n---\n\n## Testing Guide (Manual - Requires OpenCode)\n\nThese steps require OpenCode to be installed and are not part of the automated implementation:\n\n1. **Install skills**: Follow `.opencode/INSTALL.md`\n2. **Start OpenCode session**: Verify bootstrap appears\n3. **Test find_skills**: Should list all available skills\n4. **Test use_skill**: Load a skill and verify content appears\n5. **Test supporting files**: Verify skill directory paths are accessible\n6. **Test personal skills**: Create a personal skill and verify it shadows core\n7. **Test tool mapping**: Verify TodoWrite → update_plan mapping works\n\n## Success Criteria\n\n- [ ] `lib/skills-core.js` created with all core functions\n- [ ] `.codex/superpowers-codex` refactored to use shared core\n- [ ] Codex commands still work (find-skills, use-skill, bootstrap)\n- [ ] `.opencode/plugin/superpowers.js` created with tools and hooks\n- [ ] Installation guide created\n- [ ] README and RELEASE-NOTES updated\n- [ ] All changes committed\n- [ ] Working tree clean\n"
  },
  {
    "path": "docs/plans/2025-11-28-skills-improvements-from-user-feedback.md",
    "content": "# Skills Improvements from User Feedback\n\n**Date:** 2025-11-28\n**Status:** Draft\n**Source:** Two Claude instances using superpowers in real development scenarios\n\n---\n\n## Executive Summary\n\nTwo Claude instances provided detailed feedback from actual development sessions. Their feedback reveals **systematic gaps** in current skills that allowed preventable bugs to ship despite following the skills.\n\n**Critical insight:** These are problem reports, not just solution proposals. The problems are real; the solutions need careful evaluation.\n\n**Key themes:**\n1. **Verification gaps** - We verify operations succeed but not that they achieve intended outcomes\n2. **Process hygiene** - Background processes accumulate and interfere across subagents\n3. **Context optimization** - Subagents get too much irrelevant information\n4. **Self-reflection missing** - No prompt to critique own work before handoff\n5. **Mock safety** - Mocks can drift from interfaces without detection\n6. **Skill activation** - Skills exist but aren't being read/used\n\n---\n\n## Problems Identified\n\n### Problem 1: Configuration Change Verification Gap\n\n**What happened:**\n- Subagent tested \"OpenAI integration\"\n- Set `OPENAI_API_KEY` env var\n- Got status 200 responses\n- Reported \"OpenAI integration working\"\n- **BUT** response contained `\"model\": \"claude-sonnet-4-20250514\"` - was actually using Anthropic\n\n**Root cause:**\n`verification-before-completion` checks operations succeed but not that outcomes reflect intended configuration changes.\n\n**Impact:** High - False confidence in integration tests, bugs ship to production\n\n**Example failure pattern:**\n- Switch LLM provider → verify status 200 but don't check model name\n- Enable feature flag → verify no errors but don't check feature is active\n- Change environment → verify deployment succeeds but don't check environment vars\n\n---\n\n### Problem 2: Background Process Accumulation\n\n**What happened:**\n- Multiple subagents dispatched during session\n- Each started background server processes\n- Processes accumulated (4+ servers running)\n- Stale processes still bound to ports\n- Later E2E test hit stale server with wrong config\n- Confusing/incorrect test results\n\n**Root cause:**\nSubagents are stateless - don't know about previous subagents' processes. No cleanup protocol.\n\n**Impact:** Medium-High - Tests hit wrong server, false passes/failures, debugging confusion\n\n---\n\n### Problem 3: Context Bloat in Subagent Prompts\n\n**What happened:**\n- Standard approach: give subagent full plan file to read\n- Experiment: give only task + pattern + file + verify command\n- Result: Faster, more focused, single-attempt completion more common\n\n**Root cause:**\nSubagents waste tokens and attention on irrelevant plan sections.\n\n**Impact:** Medium - Slower execution, more failed attempts\n\n**What worked:**\n```\nYou are adding a single E2E test to packnplay's test suite.\n\n**Your task:** Add `TestE2E_FeaturePrivilegedMode` to `pkg/runner/e2e_test.go`\n\n**What to test:** A local devcontainer feature that requests `\"privileged\": true`\nin its metadata should result in the container running with `--privileged` flag.\n\n**Follow the exact pattern of TestE2E_FeatureOptionValidation** (at the end of the file)\n\n**After writing, run:** `go test -v ./pkg/runner -run TestE2E_FeaturePrivilegedMode -timeout 5m`\n```\n\n---\n\n### Problem 4: No Self-Reflection Before Handoff\n\n**What happened:**\n- Added self-reflection prompt: \"Look at your work with fresh eyes - what could be better?\"\n- Implementer for Task 5 identified failing test was due to implementation bug, not test bug\n- Traced to line 99: `strings.Join(metadata.Entrypoint, \" \")` creating invalid Docker syntax\n- Without self-reflection, would have just reported \"test fails\" without root cause\n\n**Root cause:**\nImplementers don't naturally step back and critique their own work before reporting completion.\n\n**Impact:** Medium - Bugs handed off to reviewer that implementer could have caught\n\n---\n\n### Problem 5: Mock-Interface Drift\n\n**What happened:**\n```typescript\n// Interface defines close()\ninterface PlatformAdapter {\n  close(): Promise<void>;\n}\n\n// Code (BUGGY) calls cleanup()\nawait adapter.cleanup();\n\n// Mock (MATCHES BUG) defines cleanup()\nvi.mock('web-adapter', () => ({\n  WebAdapter: vi.fn().mockImplementation(() => ({\n    cleanup: vi.fn().mockResolvedValue(undefined),  // Wrong!\n  })),\n}));\n```\n- Tests passed\n- Runtime crashed: \"adapter.cleanup is not a function\"\n\n**Root cause:**\nMock derived from what buggy code calls, not from interface definition. TypeScript can't catch inline mocks with wrong method names.\n\n**Impact:** High - Tests give false confidence, runtime crashes\n\n**Why testing-anti-patterns didn't prevent this:**\nThe skill covers testing mock behavior and mocking without understanding, but not the specific pattern of \"derive mock from interface, not implementation.\"\n\n---\n\n### Problem 6: Code Reviewer File Access\n\n**What happened:**\n- Code reviewer subagent dispatched\n- Couldn't find test file: \"The file doesn't appear to exist in the repository\"\n- File actually exists\n- Reviewer didn't know to explicitly read it first\n\n**Root cause:**\nReviewer prompts don't include explicit file reading instructions.\n\n**Impact:** Low-Medium - Reviews fail or incomplete\n\n---\n\n### Problem 7: Fix Workflow Latency\n\n**What happened:**\n- Implementer identifies bug during self-reflection\n- Implementer knows the fix\n- Current workflow: report → I dispatch fixer → fixer fixes → I verify\n- Extra round-trip adds latency without adding value\n\n**Root cause:**\nRigid separation between implementer and fixer roles when implementer has already diagnosed.\n\n**Impact:** Low - Latency, but no correctness issue\n\n---\n\n### Problem 8: Skills Not Being Read\n\n**What happened:**\n- `testing-anti-patterns` skill exists\n- Neither human nor subagents read it before writing tests\n- Would have prevented some issues (though not all - see Problem 5)\n\n**Root cause:**\nNo enforcement that subagents read relevant skills. No prompt includes skill reading.\n\n**Impact:** Medium - Skill investment wasted if not used\n\n---\n\n## Proposed Improvements\n\n### 1. verification-before-completion: Add Configuration Change Verification\n\n**Add new section:**\n\n```markdown\n## Verifying Configuration Changes\n\nWhen testing changes to configuration, providers, feature flags, or environment:\n\n**Don't just verify the operation succeeded. Verify the output reflects the intended change.**\n\n### Common Failure Pattern\n\nOperation succeeds because *some* valid config exists, but it's not the config you intended to test.\n\n### Examples\n\n| Change | Insufficient | Required |\n|--------|-------------|----------|\n| Switch LLM provider | Status 200 | Response contains expected model name |\n| Enable feature flag | No errors | Feature behavior actually active |\n| Change environment | Deploy succeeds | Logs/vars reference new environment |\n| Set credentials | Auth succeeds | Authenticated user/context is correct |\n\n### Gate Function\n\n```\nBEFORE claiming configuration change works:\n\n1. IDENTIFY: What should be DIFFERENT after this change?\n2. LOCATE: Where is that difference observable?\n   - Response field (model name, user ID)\n   - Log line (environment, provider)\n   - Behavior (feature active/inactive)\n3. RUN: Command that shows the observable difference\n4. VERIFY: Output contains expected difference\n5. ONLY THEN: Claim configuration change works\n\nRed flags:\n  - \"Request succeeded\" without checking content\n  - Checking status code but not response body\n  - Verifying no errors but not positive confirmation\n```\n\n**Why this works:**\nForces verification of INTENT, not just operation success.\n\n---\n\n### 2. subagent-driven-development: Add Process Hygiene for E2E Tests\n\n**Add new section:**\n\n```markdown\n## Process Hygiene for E2E Tests\n\nWhen dispatching subagents that start services (servers, databases, message queues):\n\n### Problem\n\nSubagents are stateless - they don't know about processes started by previous subagents. Background processes persist and can interfere with later tests.\n\n### Solution\n\n**Before dispatching E2E test subagent, include cleanup in prompt:**\n\n```\nBEFORE starting any services:\n1. Kill existing processes: pkill -f \"<service-pattern>\" 2>/dev/null || true\n2. Wait for cleanup: sleep 1\n3. Verify port free: lsof -i :<port> && echo \"ERROR: Port still in use\" || echo \"Port free\"\n\nAFTER tests complete:\n1. Kill the process you started\n2. Verify cleanup: pgrep -f \"<service-pattern>\" || echo \"Cleanup successful\"\n```\n\n### Example\n\n```\nTask: Run E2E test of API server\n\nPrompt includes:\n\"Before starting the server:\n- Kill any existing servers: pkill -f 'node.*server.js' 2>/dev/null || true\n- Verify port 3001 is free: lsof -i :3001 && exit 1 || echo 'Port available'\n\nAfter tests:\n- Kill the server you started\n- Verify: pgrep -f 'node.*server.js' || echo 'Cleanup verified'\"\n```\n\n### Why This Matters\n\n- Stale processes serve requests with wrong config\n- Port conflicts cause silent failures\n- Process accumulation slows system\n- Confusing test results (hitting wrong server)\n```\n\n**Trade-off analysis:**\n- Adds boilerplate to prompts\n- But prevents very confusing debugging\n- Worth it for E2E test subagents\n\n---\n\n### 3. subagent-driven-development: Add Lean Context Option\n\n**Modify Step 2: Execute Task with Subagent**\n\n**Before:**\n```\nRead that task carefully from [plan-file].\n```\n\n**After:**\n```\n## Context Approaches\n\n**Full Plan (default):**\nUse when tasks are complex or have dependencies:\n```\nRead Task N from [plan-file] carefully.\n```\n\n**Lean Context (for independent tasks):**\nUse when task is standalone and pattern-based:\n```\nYou are implementing: [1-2 sentence task description]\n\nFile to modify: [exact path]\nPattern to follow: [reference to existing function/test]\nWhat to implement: [specific requirement]\nVerification: [exact command to run]\n\n[Do NOT include full plan file]\n```\n\n**Use lean context when:**\n- Task follows existing pattern (add similar test, implement similar feature)\n- Task is self-contained (doesn't need context from other tasks)\n- Pattern reference is sufficient (e.g., \"follow TestE2E_FeatureOptionValidation\")\n\n**Use full plan when:**\n- Task has dependencies on other tasks\n- Requires understanding of overall architecture\n- Complex logic that needs context\n```\n\n**Example:**\n```\nLean context prompt:\n\n\"You are adding a test for privileged mode in devcontainer features.\n\nFile: pkg/runner/e2e_test.go\nPattern: Follow TestE2E_FeatureOptionValidation (at end of file)\nTest: Feature with `\"privileged\": true` in metadata results in `--privileged` flag\nVerify: go test -v ./pkg/runner -run TestE2E_FeaturePrivilegedMode -timeout 5m\n\nReport: Implementation, test results, any issues.\"\n```\n\n**Why this works:**\nReduces token usage, increases focus, faster completion when appropriate.\n\n---\n\n### 4. subagent-driven-development: Add Self-Reflection Step\n\n**Modify Step 2: Execute Task with Subagent**\n\n**Add to prompt template:**\n\n```\nWhen done, BEFORE reporting back:\n\nTake a step back and review your work with fresh eyes.\n\nAsk yourself:\n- Does this actually solve the task as specified?\n- Are there edge cases I didn't consider?\n- Did I follow the pattern correctly?\n- If tests are failing, what's the ROOT CAUSE (implementation bug vs test bug)?\n- What could be better about this implementation?\n\nIf you identify issues during this reflection, fix them now.\n\nThen report:\n- What you implemented\n- Self-reflection findings (if any)\n- Test results\n- Files changed\n```\n\n**Why this works:**\nCatches bugs implementer can find themselves before handoff. Documented case: identified entrypoint bug through self-reflection.\n\n**Trade-off:**\nAdds ~30 seconds per task, but catches issues before review.\n\n---\n\n### 5. requesting-code-review: Add Explicit File Reading\n\n**Modify the code-reviewer template:**\n\n**Add at the beginning:**\n\n```markdown\n## Files to Review\n\nBEFORE analyzing, read these files:\n\n1. [List specific files that changed in the diff]\n2. [Files referenced by changes but not modified]\n\nUse Read tool to load each file.\n\nIf you cannot find a file:\n- Check exact path from diff\n- Try alternate locations\n- Report: \"Cannot locate [path] - please verify file exists\"\n\nDO NOT proceed with review until you've read the actual code.\n```\n\n**Why this works:**\nExplicit instruction prevents \"file not found\" issues.\n\n---\n\n### 6. testing-anti-patterns: Add Mock-Interface Drift Anti-Pattern\n\n**Add new Anti-Pattern 6:**\n\n```markdown\n## Anti-Pattern 6: Mocks Derived from Implementation\n\n**The violation:**\n```typescript\n// Code (BUGGY) calls cleanup()\nawait adapter.cleanup();\n\n// Mock (MATCHES BUG) has cleanup()\nconst mock = {\n  cleanup: vi.fn().mockResolvedValue(undefined)\n};\n\n// Interface (CORRECT) defines close()\ninterface PlatformAdapter {\n  close(): Promise<void>;\n}\n```\n\n**Why this is wrong:**\n- Mock encodes the bug into the test\n- TypeScript can't catch inline mocks with wrong method names\n- Test passes because both code and mock are wrong\n- Runtime crashes when real object is used\n\n**The fix:**\n```typescript\n// ✅ GOOD: Derive mock from interface\n\n// Step 1: Open interface definition (PlatformAdapter)\n// Step 2: List methods defined there (close, initialize, etc.)\n// Step 3: Mock EXACTLY those methods\n\nconst mock = {\n  initialize: vi.fn().mockResolvedValue(undefined),\n  close: vi.fn().mockResolvedValue(undefined),  // From interface!\n};\n\n// Now test FAILS because code calls cleanup() which doesn't exist\n// That failure reveals the bug BEFORE runtime\n```\n\n### Gate Function\n\n```\nBEFORE writing any mock:\n\n  1. STOP - Do NOT look at the code under test yet\n  2. FIND: The interface/type definition for the dependency\n  3. READ: The interface file\n  4. LIST: Methods defined in the interface\n  5. MOCK: ONLY those methods with EXACTLY those names\n  6. DO NOT: Look at what your code calls\n\n  IF your test fails because code calls something not in mock:\n    ✅ GOOD - The test found a bug in your code\n    Fix the code to call the correct interface method\n    NOT the mock\n\n  Red flags:\n    - \"I'll mock what the code calls\"\n    - Copying method names from implementation\n    - Mock written without reading interface\n    - \"The test is failing so I'll add this method to the mock\"\n```\n\n**Detection:**\n\nWhen you see runtime error \"X is not a function\" and tests pass:\n1. Check if X is mocked\n2. Compare mock methods to interface methods\n3. Look for method name mismatches\n```\n\n**Why this works:**\nDirectly addresses the failure pattern from feedback.\n\n---\n\n### 7. subagent-driven-development: Require Skills Reading for Test Subagents\n\n**Add to prompt template when task involves testing:**\n\n```markdown\nBEFORE writing any tests:\n\n1. Read testing-anti-patterns skill:\n   Use Skill tool: superpowers:testing-anti-patterns\n\n2. Apply gate functions from that skill when:\n   - Writing mocks\n   - Adding methods to production classes\n   - Mocking dependencies\n\nThis is NOT optional. Tests that violate anti-patterns will be rejected in review.\n```\n\n**Why this works:**\nEnsures skills are actually used, not just exist.\n\n**Trade-off:**\nAdds time to each task, but prevents entire classes of bugs.\n\n---\n\n### 8. subagent-driven-development: Allow Implementer to Fix Self-Identified Issues\n\n**Modify Step 2:**\n\n**Current:**\n```\nSubagent reports back with summary of work.\n```\n\n**Proposed:**\n```\nSubagent performs self-reflection, then:\n\nIF self-reflection identifies fixable issues:\n  1. Fix the issues\n  2. Re-run verification\n  3. Report: \"Initial implementation + self-reflection fix\"\n\nELSE:\n  Report: \"Implementation complete\"\n\nInclude in report:\n- Self-reflection findings\n- Whether fixes were applied\n- Final verification results\n```\n\n**Why this works:**\nReduces latency when implementer already knows the fix. Documented case: would have saved one round-trip for entrypoint bug.\n\n**Trade-off:**\nSlightly more complex prompt, but faster end-to-end.\n\n---\n\n## Implementation Plan\n\n### Phase 1: High-Impact, Low-Risk (Do First)\n\n1. **verification-before-completion: Configuration change verification**\n   - Clear addition, doesn't change existing content\n   - Addresses high-impact problem (false confidence in tests)\n   - File: `skills/verification-before-completion/SKILL.md`\n\n2. **testing-anti-patterns: Mock-interface drift**\n   - Adds new anti-pattern, doesn't modify existing\n   - Addresses high-impact problem (runtime crashes)\n   - File: `skills/testing-anti-patterns/SKILL.md`\n\n3. **requesting-code-review: Explicit file reading**\n   - Simple addition to template\n   - Fixes concrete problem (reviewers can't find files)\n   - File: `skills/requesting-code-review/SKILL.md`\n\n### Phase 2: Moderate Changes (Test Carefully)\n\n4. **subagent-driven-development: Process hygiene**\n   - Adds new section, doesn't change workflow\n   - Addresses medium-high impact (test reliability)\n   - File: `skills/subagent-driven-development/SKILL.md`\n\n5. **subagent-driven-development: Self-reflection**\n   - Changes prompt template (higher risk)\n   - But documented to catch bugs\n   - File: `skills/subagent-driven-development/SKILL.md`\n\n6. **subagent-driven-development: Skills reading requirement**\n   - Adds prompt overhead\n   - But ensures skills are actually used\n   - File: `skills/subagent-driven-development/SKILL.md`\n\n### Phase 3: Optimization (Validate First)\n\n7. **subagent-driven-development: Lean context option**\n   - Adds complexity (two approaches)\n   - Needs validation that it doesn't cause confusion\n   - File: `skills/subagent-driven-development/SKILL.md`\n\n8. **subagent-driven-development: Allow implementer to fix**\n   - Changes workflow (higher risk)\n   - Optimization, not bug fix\n   - File: `skills/subagent-driven-development/SKILL.md`\n\n---\n\n## Open Questions\n\n1. **Lean context approach:**\n   - Should we make it the default for pattern-based tasks?\n   - How do we decide which approach to use?\n   - Risk of being too lean and missing important context?\n\n2. **Self-reflection:**\n   - Will this slow down simple tasks significantly?\n   - Should it only apply to complex tasks?\n   - How do we prevent \"reflection fatigue\" where it becomes rote?\n\n3. **Process hygiene:**\n   - Should this be in subagent-driven-development or a separate skill?\n   - Does it apply to other workflows beyond E2E tests?\n   - How do we handle cases where process SHOULD persist (dev servers)?\n\n4. **Skills reading enforcement:**\n   - Should we require ALL subagents to read relevant skills?\n   - How do we keep prompts from becoming too long?\n   - Risk of over-documenting and losing focus?\n\n---\n\n## Success Metrics\n\nHow do we know these improvements work?\n\n1. **Configuration verification:**\n   - Zero instances of \"test passed but wrong config was used\"\n   - Jesse doesn't say \"that's not actually testing what you think\"\n\n2. **Process hygiene:**\n   - Zero instances of \"test hit wrong server\"\n   - No port conflict errors during E2E test runs\n\n3. **Mock-interface drift:**\n   - Zero instances of \"tests pass but runtime crashes on missing method\"\n   - No method name mismatches between mocks and interfaces\n\n4. **Self-reflection:**\n   - Measurable: Do implementer reports include self-reflection findings?\n   - Qualitative: Do fewer bugs make it to code review?\n\n5. **Skills reading:**\n   - Subagent reports reference skill gate functions\n   - Fewer anti-pattern violations in code review\n\n---\n\n## Risks and Mitigations\n\n### Risk: Prompt Bloat\n**Problem:** Adding all these requirements makes prompts overwhelming\n**Mitigation:**\n- Phase implementation (don't add everything at once)\n- Make some additions conditional (E2E hygiene only for E2E tests)\n- Consider templates for different task types\n\n### Risk: Analysis Paralysis\n**Problem:** Too much reflection/verification slows execution\n**Mitigation:**\n- Keep gate functions quick (seconds, not minutes)\n- Make lean context opt-in initially\n- Monitor task completion times\n\n### Risk: False Sense of Security\n**Problem:** Following checklist doesn't guarantee correctness\n**Mitigation:**\n- Emphasize gate functions are minimums, not maximums\n- Keep \"use judgment\" language in skills\n- Document that skills catch common failures, not all failures\n\n### Risk: Skill Divergence\n**Problem:** Different skills give conflicting advice\n**Mitigation:**\n- Review changes across all skills for consistency\n- Document how skills interact (Integration sections)\n- Test with real scenarios before deployment\n\n---\n\n## Recommendation\n\n**Proceed with Phase 1 immediately:**\n- verification-before-completion: Configuration change verification\n- testing-anti-patterns: Mock-interface drift\n- requesting-code-review: Explicit file reading\n\n**Test Phase 2 with Jesse before finalizing:**\n- Get feedback on self-reflection impact\n- Validate process hygiene approach\n- Confirm skills reading requirement is worth overhead\n\n**Hold Phase 3 pending validation:**\n- Lean context needs real-world testing\n- Implementer-fix workflow change needs careful evaluation\n\nThese changes address real problems documented by users while minimizing risk of making skills worse.\n"
  },
  {
    "path": "docs/plans/2026-01-17-visual-brainstorming.md",
    "content": "# Visual Brainstorming Companion Implementation Plan\n\n> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.\n\n**Goal:** Give Claude a browser-based visual companion for brainstorming sessions - show mockups, prototypes, and interactive choices alongside terminal conversation.\n\n**Architecture:** Claude writes HTML to a temp file. A local Node.js server watches that file and serves it with an auto-injected helper library. User interactions flow via WebSocket to server stdout, which Claude sees in background task output.\n\n**Tech Stack:** Node.js, Express, ws (WebSocket), chokidar (file watching)\n\n---\n\n## Task 1: Create the Server Foundation\n\n**Files:**\n- Create: `lib/brainstorm-server/index.js`\n- Create: `lib/brainstorm-server/package.json`\n\n**Step 1: Create package.json**\n\n```json\n{\n  \"name\": \"brainstorm-server\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Visual brainstorming companion server for Claude Code\",\n  \"main\": \"index.js\",\n  \"dependencies\": {\n    \"chokidar\": \"^3.5.3\",\n    \"express\": \"^4.18.2\",\n    \"ws\": \"^8.14.2\"\n  }\n}\n```\n\n**Step 2: Create minimal server that starts**\n\n```javascript\nconst express = require('express');\nconst http = require('http');\nconst WebSocket = require('ws');\nconst chokidar = require('chokidar');\nconst fs = require('fs');\nconst path = require('path');\n\nconst PORT = process.env.BRAINSTORM_PORT || 3333;\nconst SCREEN_FILE = process.env.BRAINSTORM_SCREEN || '/tmp/brainstorm/screen.html';\nconst SCREEN_DIR = path.dirname(SCREEN_FILE);\n\n// Ensure screen directory exists\nif (!fs.existsSync(SCREEN_DIR)) {\n  fs.mkdirSync(SCREEN_DIR, { recursive: true });\n}\n\n// Create default screen if none exists\nif (!fs.existsSync(SCREEN_FILE)) {\n  fs.writeFileSync(SCREEN_FILE, `<!DOCTYPE html>\n<html>\n<head>\n  <title>Brainstorm Companion</title>\n  <style>\n    body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }\n    h1 { color: #333; }\n    p { color: #666; }\n  </style>\n</head>\n<body>\n  <h1>Brainstorm Companion</h1>\n  <p>Waiting for Claude to push a screen...</p>\n</body>\n</html>`);\n}\n\nconst app = express();\nconst server = http.createServer(app);\nconst wss = new WebSocket.Server({ server });\n\n// Track connected browsers for reload notifications\nconst clients = new Set();\n\nwss.on('connection', (ws) => {\n  clients.add(ws);\n  ws.on('close', () => clients.delete(ws));\n\n  ws.on('message', (data) => {\n    // User interaction event - write to stdout for Claude\n    const event = JSON.parse(data.toString());\n    console.log(JSON.stringify({ type: 'user-event', ...event }));\n  });\n});\n\n// Serve current screen with helper.js injected\napp.get('/', (req, res) => {\n  let html = fs.readFileSync(SCREEN_FILE, 'utf-8');\n\n  // Inject helper script before </body>\n  const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');\n  const injection = `<script>\\n${helperScript}\\n</script>`;\n\n  if (html.includes('</body>')) {\n    html = html.replace('</body>', `${injection}\\n</body>`);\n  } else {\n    html += injection;\n  }\n\n  res.type('html').send(html);\n});\n\n// Watch for screen file changes\nchokidar.watch(SCREEN_FILE).on('change', () => {\n  console.log(JSON.stringify({ type: 'screen-updated', file: SCREEN_FILE }));\n  // Notify all browsers to reload\n  clients.forEach(ws => {\n    if (ws.readyState === WebSocket.OPEN) {\n      ws.send(JSON.stringify({ type: 'reload' }));\n    }\n  });\n});\n\nserver.listen(PORT, '127.0.0.1', () => {\n  console.log(JSON.stringify({ type: 'server-started', port: PORT, url: `http://localhost:${PORT}` }));\n});\n```\n\n**Step 3: Run npm install**\n\nRun: `cd lib/brainstorm-server && npm install`\nExpected: Dependencies installed\n\n**Step 4: Test server starts**\n\nRun: `cd lib/brainstorm-server && timeout 3 node index.js || true`\nExpected: See JSON with `server-started` and port info\n\n**Step 5: Commit**\n\n```bash\ngit add lib/brainstorm-server/\ngit commit -m \"feat: add brainstorm server foundation\"\n```\n\n---\n\n## Task 2: Create the Helper Library\n\n**Files:**\n- Create: `lib/brainstorm-server/helper.js`\n\n**Step 1: Create helper.js with event auto-capture**\n\n```javascript\n(function() {\n  const WS_URL = 'ws://' + window.location.host;\n  let ws = null;\n  let eventQueue = [];\n\n  function connect() {\n    ws = new WebSocket(WS_URL);\n\n    ws.onopen = () => {\n      // Send any queued events\n      eventQueue.forEach(e => ws.send(JSON.stringify(e)));\n      eventQueue = [];\n    };\n\n    ws.onmessage = (msg) => {\n      const data = JSON.parse(msg.data);\n      if (data.type === 'reload') {\n        window.location.reload();\n      }\n    };\n\n    ws.onclose = () => {\n      // Reconnect after 1 second\n      setTimeout(connect, 1000);\n    };\n  }\n\n  function send(event) {\n    event.timestamp = Date.now();\n    if (ws && ws.readyState === WebSocket.OPEN) {\n      ws.send(JSON.stringify(event));\n    } else {\n      eventQueue.push(event);\n    }\n  }\n\n  // Auto-capture clicks on interactive elements\n  document.addEventListener('click', (e) => {\n    const target = e.target.closest('button, a, [data-choice], [role=\"button\"], input[type=\"submit\"]');\n    if (!target) return;\n\n    // Don't capture regular link navigation\n    if (target.tagName === 'A' && !target.dataset.choice) return;\n\n    e.preventDefault();\n\n    send({\n      type: 'click',\n      text: target.textContent.trim(),\n      choice: target.dataset.choice || null,\n      id: target.id || null,\n      className: target.className || null\n    });\n  });\n\n  // Auto-capture form submissions\n  document.addEventListener('submit', (e) => {\n    e.preventDefault();\n    const form = e.target;\n    const formData = new FormData(form);\n    const data = {};\n    formData.forEach((value, key) => { data[key] = value; });\n\n    send({\n      type: 'submit',\n      formId: form.id || null,\n      formName: form.name || null,\n      data: data\n    });\n  });\n\n  // Auto-capture input changes (debounced)\n  let inputTimeout = null;\n  document.addEventListener('input', (e) => {\n    const target = e.target;\n    if (!target.matches('input, textarea, select')) return;\n\n    clearTimeout(inputTimeout);\n    inputTimeout = setTimeout(() => {\n      send({\n        type: 'input',\n        name: target.name || null,\n        id: target.id || null,\n        value: target.value,\n        inputType: target.type || target.tagName.toLowerCase()\n      });\n    }, 500); // 500ms debounce\n  });\n\n  // Expose for explicit use if needed\n  window.brainstorm = {\n    send: send,\n    choice: (value, metadata = {}) => send({ type: 'choice', value, ...metadata })\n  };\n\n  connect();\n})();\n```\n\n**Step 2: Verify helper.js is syntactically valid**\n\nRun: `node -c lib/brainstorm-server/helper.js`\nExpected: No syntax errors\n\n**Step 3: Commit**\n\n```bash\ngit add lib/brainstorm-server/helper.js\ngit commit -m \"feat: add browser helper library for event capture\"\n```\n\n---\n\n## Task 3: Write Tests for the Server\n\n**Files:**\n- Create: `tests/brainstorm-server/server.test.js`\n- Create: `tests/brainstorm-server/package.json`\n\n**Step 1: Create test package.json**\n\n```json\n{\n  \"name\": \"brainstorm-server-tests\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"test\": \"node server.test.js\"\n  }\n}\n```\n\n**Step 2: Write server tests**\n\n```javascript\nconst { spawn } = require('child_process');\nconst http = require('http');\nconst WebSocket = require('ws');\nconst fs = require('fs');\nconst path = require('path');\nconst assert = require('assert');\n\nconst SERVER_PATH = path.join(__dirname, '../../lib/brainstorm-server/index.js');\nconst TEST_PORT = 3334;\nconst TEST_SCREEN = '/tmp/brainstorm-test/screen.html';\n\n// Clean up test directory\nfunction cleanup() {\n  if (fs.existsSync(path.dirname(TEST_SCREEN))) {\n    fs.rmSync(path.dirname(TEST_SCREEN), { recursive: true });\n  }\n}\n\nasync function sleep(ms) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nasync function fetch(url) {\n  return new Promise((resolve, reject) => {\n    http.get(url, (res) => {\n      let data = '';\n      res.on('data', chunk => data += chunk);\n      res.on('end', () => resolve({ status: res.statusCode, body: data }));\n    }).on('error', reject);\n  });\n}\n\nasync function runTests() {\n  cleanup();\n\n  // Start server\n  const server = spawn('node', [SERVER_PATH], {\n    env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_SCREEN: TEST_SCREEN }\n  });\n\n  let stdout = '';\n  server.stdout.on('data', (data) => { stdout += data.toString(); });\n  server.stderr.on('data', (data) => { console.error('Server stderr:', data.toString()); });\n\n  await sleep(1000); // Wait for server to start\n\n  try {\n    // Test 1: Server starts and outputs JSON\n    console.log('Test 1: Server startup message');\n    assert(stdout.includes('server-started'), 'Should output server-started');\n    assert(stdout.includes(TEST_PORT.toString()), 'Should include port');\n    console.log('  PASS');\n\n    // Test 2: GET / returns HTML with helper injected\n    console.log('Test 2: Serves HTML with helper injected');\n    const res = await fetch(`http://localhost:${TEST_PORT}/`);\n    assert.strictEqual(res.status, 200);\n    assert(res.body.includes('brainstorm'), 'Should include brainstorm content');\n    assert(res.body.includes('WebSocket'), 'Should have helper.js injected');\n    console.log('  PASS');\n\n    // Test 3: WebSocket connection and event relay\n    console.log('Test 3: WebSocket relays events to stdout');\n    stdout = ''; // Reset stdout capture\n    const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n    await new Promise(resolve => ws.on('open', resolve));\n\n    ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));\n    await sleep(100);\n\n    assert(stdout.includes('user-event'), 'Should relay user events');\n    assert(stdout.includes('Test Button'), 'Should include event data');\n    ws.close();\n    console.log('  PASS');\n\n    // Test 4: File change triggers reload notification\n    console.log('Test 4: File change notifies browsers');\n    const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);\n    await new Promise(resolve => ws2.on('open', resolve));\n\n    let gotReload = false;\n    ws2.on('message', (data) => {\n      const msg = JSON.parse(data.toString());\n      if (msg.type === 'reload') gotReload = true;\n    });\n\n    // Modify the screen file\n    fs.writeFileSync(TEST_SCREEN, '<html><body>Updated</body></html>');\n    await sleep(500);\n\n    assert(gotReload, 'Should send reload message on file change');\n    ws2.close();\n    console.log('  PASS');\n\n    console.log('\\nAll tests passed!');\n\n  } finally {\n    server.kill();\n    cleanup();\n  }\n}\n\nrunTests().catch(err => {\n  console.error('Test failed:', err);\n  process.exit(1);\n});\n```\n\n**Step 3: Run tests**\n\nRun: `cd tests/brainstorm-server && npm install ws && node server.test.js`\nExpected: All tests pass\n\n**Step 4: Commit**\n\n```bash\ngit add tests/brainstorm-server/\ngit commit -m \"test: add brainstorm server integration tests\"\n```\n\n---\n\n## Task 4: Add Visual Companion to Brainstorming Skill\n\n**Files:**\n- Modify: `skills/brainstorming/SKILL.md`\n- Create: `skills/brainstorming/visual-companion.md` (supporting doc)\n\n**Step 1: Create the supporting documentation**\n\nCreate `skills/brainstorming/visual-companion.md`:\n\n```markdown\n# Visual Companion Reference\n\n## Starting the Server\n\nRun as a background job:\n\n```bash\nnode ${PLUGIN_ROOT}/lib/brainstorm-server/index.js\n```\n\nTell the user: \"I've started a visual companion at http://localhost:3333 - open it in a browser.\"\n\n## Pushing Screens\n\nWrite HTML to `/tmp/brainstorm/screen.html`. The server watches this file and auto-refreshes the browser.\n\n## Reading User Responses\n\nCheck the background task output for JSON events:\n\n```json\n{\"type\":\"user-event\",\"type\":\"click\",\"text\":\"Option A\",\"choice\":\"optionA\",\"timestamp\":1234567890}\n{\"type\":\"user-event\",\"type\":\"submit\",\"data\":{\"notes\":\"My feedback\"},\"timestamp\":1234567891}\n```\n\nEvent types:\n- **click**: User clicked button or `data-choice` element\n- **submit**: User submitted form (includes all form data)\n- **input**: User typed in field (debounced 500ms)\n\n## HTML Patterns\n\n### Choice Cards\n\n```html\n<div class=\"options\">\n  <button data-choice=\"optionA\">\n    <h3>Option A</h3>\n    <p>Description</p>\n  </button>\n  <button data-choice=\"optionB\">\n    <h3>Option B</h3>\n    <p>Description</p>\n  </button>\n</div>\n```\n\n### Interactive Mockup\n\n```html\n<div class=\"mockup\">\n  <header data-choice=\"header\">App Header</header>\n  <nav data-choice=\"nav\">Navigation</nav>\n  <main data-choice=\"main\">Content</main>\n</div>\n```\n\n### Form with Notes\n\n```html\n<form>\n  <label>Priority: <input type=\"range\" name=\"priority\" min=\"1\" max=\"5\"></label>\n  <textarea name=\"notes\" placeholder=\"Additional thoughts...\"></textarea>\n  <button type=\"submit\">Submit</button>\n</form>\n```\n\n### Explicit JavaScript\n\n```html\n<button onclick=\"brainstorm.choice('custom', {extra: 'data'})\">Custom</button>\n```\n```\n\n**Step 2: Add visual companion section to brainstorming skill**\n\nAdd after \"Key Principles\" in `skills/brainstorming/SKILL.md`:\n\n```markdown\n\n## Visual Companion (Optional)\n\nWhen brainstorming involves visual elements - UI mockups, wireframes, interactive prototypes - use the browser-based visual companion.\n\n**When to use:**\n- Presenting UI/UX options that benefit from visual comparison\n- Showing wireframes or layout options\n- Gathering structured feedback (ratings, forms)\n- Prototyping click interactions\n\n**How it works:**\n1. Start the server as a background job\n2. Tell user to open http://localhost:3333\n3. Write HTML to `/tmp/brainstorm/screen.html` (auto-refreshes)\n4. Check background task output for user interactions\n\nThe terminal remains the primary conversation interface. The browser is a visual aid.\n\n**Reference:** See `visual-companion.md` in this skill directory for HTML patterns and API details.\n```\n\n**Step 3: Verify the edits**\n\nRun: `grep -A5 \"Visual Companion\" skills/brainstorming/SKILL.md`\nExpected: Shows the new section\n\n**Step 4: Commit**\n\n```bash\ngit add skills/brainstorming/\ngit commit -m \"feat: add visual companion to brainstorming skill\"\n```\n\n---\n\n## Task 5: Add Server to Plugin Ignore (Optional Cleanup)\n\n**Files:**\n- Check if `.gitignore` needs node_modules exclusion for lib/brainstorm-server\n\n**Step 1: Check current gitignore**\n\nRun: `cat .gitignore 2>/dev/null || echo \"No .gitignore\"`\n\n**Step 2: Add node_modules if needed**\n\nIf not already present, add:\n```\nlib/brainstorm-server/node_modules/\n```\n\n**Step 3: Commit if changed**\n\n```bash\ngit add .gitignore\ngit commit -m \"chore: ignore brainstorm-server node_modules\"\n```\n\n---\n\n## Summary\n\nAfter completing all tasks:\n\n1. **Server** at `lib/brainstorm-server/` - Node.js server that watches HTML file and relays events\n2. **Helper library** auto-injected - captures clicks, forms, inputs\n3. **Tests** at `tests/brainstorm-server/` - verifies server behavior\n4. **Brainstorming skill** updated with visual companion section and `visual-companion.md` reference doc\n\n**To use:**\n1. Start server as background job: `node lib/brainstorm-server/index.js &`\n2. Tell user to open `http://localhost:3333`\n3. Write HTML to `/tmp/brainstorm/screen.html`\n4. Check task output for user events\n"
  },
  {
    "path": "docs/superpowers/plans/2026-01-22-document-review-system.md",
    "content": "# Document Review System Implementation Plan\n\n> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan.\n\n**Goal:** Add spec and plan document review loops to the brainstorming and writing-plans skills.\n\n**Architecture:** Create reviewer prompt templates in each skill directory. Modify skill files to add review loops after document creation. Use Task tool with general-purpose subagent for reviewer dispatch.\n\n**Tech Stack:** Markdown skill files, subagent dispatch via Task tool\n\n**Spec:** docs/superpowers/specs/2026-01-22-document-review-system-design.md\n\n---\n\n## Chunk 1: Spec Document Reviewer\n\nThis chunk adds the spec document reviewer to the brainstorming skill.\n\n### Task 1: Create Spec Document Reviewer Prompt Template\n\n**Files:**\n- Create: `skills/brainstorming/spec-document-reviewer-prompt.md`\n\n- [ ] **Step 1:** Create the reviewer prompt template file\n\n```markdown\n# Spec Document Reviewer Prompt Template\n\nUse this template when dispatching a spec document reviewer subagent.\n\n**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.\n\n**Dispatch after:** Spec document is written to docs/superpowers/specs/\n\n```\nTask tool (general-purpose):\n  description: \"Review spec document\"\n  prompt: |\n    You are a spec document reviewer. Verify this spec is complete and ready for planning.\n\n    **Spec to review:** [SPEC_FILE_PATH]\n\n    ## What to Check\n\n    | Category | What to Look For |\n    |----------|------------------|\n    | Completeness | TODOs, placeholders, \"TBD\", incomplete sections |\n    | Coverage | Missing error handling, edge cases, integration points |\n    | Consistency | Internal contradictions, conflicting requirements |\n    | Clarity | Ambiguous requirements |\n    | YAGNI | Unrequested features, over-engineering |\n\n    ## CRITICAL\n\n    Look especially hard for:\n    - Any TODO markers or placeholder text\n    - Sections saying \"to be defined later\" or \"will spec when X is done\"\n    - Sections noticeably less detailed than others\n\n    ## Output Format\n\n    ## Spec Review\n\n    **Status:** ✅ Approved | ❌ Issues Found\n\n    **Issues (if any):**\n    - [Section X]: [specific issue] - [why it matters]\n\n    **Recommendations (advisory):**\n    - [suggestions that don't block approval]\n```\n\n**Reviewer returns:** Status, Issues (if any), Recommendations\n```\n\n- [ ] **Step 2:** Verify the file was created correctly\n\nRun: `cat skills/brainstorming/spec-document-reviewer-prompt.md | head -20`\nExpected: Shows the header and purpose section\n\n- [ ] **Step 3:** Commit\n\n```bash\ngit add skills/brainstorming/spec-document-reviewer-prompt.md\ngit commit -m \"feat: add spec document reviewer prompt template\"\n```\n\n---\n\n### Task 2: Add Review Loop to Brainstorming Skill\n\n**Files:**\n- Modify: `skills/brainstorming/SKILL.md`\n\n- [ ] **Step 1:** Read the current brainstorming skill\n\nRun: `cat skills/brainstorming/SKILL.md`\n\n- [ ] **Step 2:** Add the review loop section after \"After the Design\"\n\nFind the \"After the Design\" section and add a new \"Spec Review Loop\" section after documentation but before implementation:\n\n```markdown\n**Spec Review Loop:**\nAfter writing the spec document:\n1. Dispatch spec-document-reviewer subagent (see spec-document-reviewer-prompt.md)\n2. If ❌ Issues Found:\n   - Fix the issues in the spec document\n   - Re-dispatch reviewer\n   - Repeat until ✅ Approved\n3. If ✅ Approved: proceed to implementation setup\n\n**Review loop guidance:**\n- Same agent that wrote the spec fixes it (preserves context)\n- If loop exceeds 5 iterations, surface to human for guidance\n- Reviewers are advisory - explain disagreements if you believe feedback is incorrect\n```\n\n- [ ] **Step 3:** Verify the changes\n\nRun: `grep -A 15 \"Spec Review Loop\" skills/brainstorming/SKILL.md`\nExpected: Shows the new review loop section\n\n- [ ] **Step 4:** Commit\n\n```bash\ngit add skills/brainstorming/SKILL.md\ngit commit -m \"feat: add spec review loop to brainstorming skill\"\n```\n\n---\n\n## Chunk 2: Plan Document Reviewer\n\nThis chunk adds the plan document reviewer to the writing-plans skill.\n\n### Task 3: Create Plan Document Reviewer Prompt Template\n\n**Files:**\n- Create: `skills/writing-plans/plan-document-reviewer-prompt.md`\n\n- [ ] **Step 1:** Create the reviewer prompt template file\n\n```markdown\n# Plan Document Reviewer Prompt Template\n\nUse this template when dispatching a plan document reviewer subagent.\n\n**Purpose:** Verify the plan chunk is complete, matches the spec, and has proper task decomposition.\n\n**Dispatch after:** Each plan chunk is written\n\n```\nTask tool (general-purpose):\n  description: \"Review plan chunk N\"\n  prompt: |\n    You are a plan document reviewer. Verify this plan chunk is complete and ready for implementation.\n\n    **Plan chunk to review:** [PLAN_FILE_PATH] - Chunk N only\n    **Spec for reference:** [SPEC_FILE_PATH]\n\n    ## What to Check\n\n    | Category | What to Look For |\n    |----------|------------------|\n    | Completeness | TODOs, placeholders, incomplete tasks, missing steps |\n    | Spec Alignment | Chunk covers relevant spec requirements, no scope creep |\n    | Task Decomposition | Tasks atomic, clear boundaries, steps actionable |\n    | Task Syntax | Checkbox syntax (`- [ ]`) on tasks and steps |\n    | Chunk Size | Each chunk under 1000 lines |\n\n    ## CRITICAL\n\n    Look especially hard for:\n    - Any TODO markers or placeholder text\n    - Steps that say \"similar to X\" without actual content\n    - Incomplete task definitions\n    - Missing verification steps or expected outputs\n\n    ## Output Format\n\n    ## Plan Review - Chunk N\n\n    **Status:** ✅ Approved | ❌ Issues Found\n\n    **Issues (if any):**\n    - [Task X, Step Y]: [specific issue] - [why it matters]\n\n    **Recommendations (advisory):**\n    - [suggestions that don't block approval]\n```\n\n**Reviewer returns:** Status, Issues (if any), Recommendations\n```\n\n- [ ] **Step 2:** Verify the file was created\n\nRun: `cat skills/writing-plans/plan-document-reviewer-prompt.md | head -20`\nExpected: Shows the header and purpose section\n\n- [ ] **Step 3:** Commit\n\n```bash\ngit add skills/writing-plans/plan-document-reviewer-prompt.md\ngit commit -m \"feat: add plan document reviewer prompt template\"\n```\n\n---\n\n### Task 4: Add Review Loop to Writing-Plans Skill\n\n**Files:**\n- Modify: `skills/writing-plans/SKILL.md`\n\n- [ ] **Step 1:** Read current skill file\n\nRun: `cat skills/writing-plans/SKILL.md`\n\n- [ ] **Step 2:** Add chunk-by-chunk review section\n\nAdd before the \"Execution Handoff\" section:\n\n```markdown\n## Plan Review Loop\n\nAfter completing each chunk of the plan:\n\n1. Dispatch plan-document-reviewer subagent for the current chunk\n   - Provide: chunk content, path to spec document\n2. If ❌ Issues Found:\n   - Fix the issues in the chunk\n   - Re-dispatch reviewer for that chunk\n   - Repeat until ✅ Approved\n3. If ✅ Approved: proceed to next chunk (or execution handoff if last chunk)\n\n**Chunk boundaries:** Use `## Chunk N: <name>` headings to delimit chunks. Each chunk should be ≤1000 lines and logically self-contained.\n```\n\n- [ ] **Step 3:** Update task syntax examples to use checkboxes\n\nChange the Task Structure section to show checkbox syntax:\n\n```markdown\n### Task N: [Component Name]\n\n- [ ] **Step 1:** Write the failing test\n  - File: `tests/path/test.py`\n  ...\n```\n\n- [ ] **Step 4:** Verify the review loop section was added\n\nRun: `grep -A 15 \"Plan Review Loop\" skills/writing-plans/SKILL.md`\nExpected: Shows the new review loop section\n\n- [ ] **Step 5:** Verify the task syntax examples were updated\n\nRun: `grep -A 5 \"Task N:\" skills/writing-plans/SKILL.md`\nExpected: Shows checkbox syntax `### Task N:`\n\n- [ ] **Step 6:** Commit\n\n```bash\ngit add skills/writing-plans/SKILL.md\ngit commit -m \"feat: add plan review loop and checkbox syntax to writing-plans skill\"\n```\n\n---\n\n## Chunk 3: Update Plan Document Header\n\nThis chunk updates the plan document header template to reference the new checkbox syntax requirements.\n\n### Task 5: Update Plan Header Template in Writing-Plans Skill\n\n**Files:**\n- Modify: `skills/writing-plans/SKILL.md`\n\n- [ ] **Step 1:** Read current plan header template\n\nRun: `grep -A 20 \"Plan Document Header\" skills/writing-plans/SKILL.md`\n\n- [ ] **Step 2:** Update the header template to reference checkbox syntax\n\nThe plan header should note that tasks and steps use checkbox syntax. Update the header comment:\n\n```markdown\n> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Tasks and steps use checkbox (`- [ ]`) syntax for tracking.\n```\n\n- [ ] **Step 3:** Verify the change\n\nRun: `grep -A 5 \"For agentic workers:\" skills/writing-plans/SKILL.md`\nExpected: Shows updated header with checkbox syntax mention\n\n- [ ] **Step 4:** Commit\n\n```bash\ngit add skills/writing-plans/SKILL.md\ngit commit -m \"docs: update plan header to reference checkbox syntax\"\n```\n"
  },
  {
    "path": "docs/superpowers/plans/2026-02-19-visual-brainstorming-refactor.md",
    "content": "# Visual Brainstorming Refactor Implementation Plan\n\n> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.\n\n**Goal:** Refactor visual brainstorming from blocking TUI feedback model to non-blocking \"Browser Displays, Terminal Commands\" architecture.\n\n**Architecture:** Browser becomes an interactive display; terminal stays the conversation channel. Server writes user events to a per-screen `.events` file that Claude reads on its next turn. Eliminates `wait-for-feedback.sh` and all `TaskOutput` blocking.\n\n**Tech Stack:** Node.js (Express, ws, chokidar), vanilla HTML/CSS/JS\n\n**Spec:** `docs/superpowers/specs/2026-02-19-visual-brainstorming-refactor-design.md`\n\n---\n\n## File Map\n\n| File | Action | Responsibility |\n|------|--------|---------------|\n| `lib/brainstorm-server/index.js` | Modify | Server: add `.events` file writing, clear on new screen, replace `wrapInFrame` |\n| `lib/brainstorm-server/frame-template.html` | Modify | Template: remove feedback footer, add content placeholder + selection indicator |\n| `lib/brainstorm-server/helper.js` | Modify | Client JS: remove send/feedback functions, narrow to click capture + indicator updates |\n| `lib/brainstorm-server/wait-for-feedback.sh` | Delete | No longer needed |\n| `skills/brainstorming/visual-companion.md` | Modify | Skill instructions: rewrite loop to non-blocking flow |\n| `tests/brainstorm-server/server.test.js` | Modify | Tests: update for new template structure and helper.js API |\n\n---\n\n## Chunk 1: Server, Template, Client, Tests, Skill\n\n### Task 1: Update `frame-template.html`\n\n**Files:**\n- Modify: `lib/brainstorm-server/frame-template.html`\n\n- [ ] **Step 1: Remove the feedback footer HTML**\n\nReplace the feedback-footer div (lines 227-233) with a selection indicator bar:\n\n```html\n  <div class=\"indicator-bar\">\n    <span id=\"indicator-text\">Click an option above, then return to the terminal</span>\n  </div>\n```\n\nAlso replace the default content inside `#claude-content` (lines 220-223) with the content placeholder:\n\n```html\n    <div id=\"claude-content\">\n      <!-- CONTENT -->\n    </div>\n```\n\n- [ ] **Step 2: Replace feedback footer CSS with indicator bar CSS**\n\nRemove the `.feedback-footer`, `.feedback-footer label`, `.feedback-row`, and the textarea/button styles within `.feedback-footer` (lines 82-112).\n\nAdd indicator bar CSS:\n\n```css\n    .indicator-bar {\n      background: var(--bg-secondary);\n      border-top: 1px solid var(--border);\n      padding: 0.5rem 1.5rem;\n      flex-shrink: 0;\n      text-align: center;\n    }\n    .indicator-bar span {\n      font-size: 0.75rem;\n      color: var(--text-secondary);\n    }\n    .indicator-bar .selected-text {\n      color: var(--accent);\n      font-weight: 500;\n    }\n```\n\n- [ ] **Step 3: Verify template renders**\n\nRun the test suite to check the template still loads:\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: Tests 1-5 should still pass. Tests 6-8 may fail (expected — they assert old structure).\n\n- [ ] **Step 4: Commit**\n\n```bash\ngit add lib/brainstorm-server/frame-template.html\ngit commit -m \"Replace feedback footer with selection indicator bar in brainstorm template\"\n```\n\n---\n\n### Task 2: Update `index.js` — content injection and `.events` file\n\n**Files:**\n- Modify: `lib/brainstorm-server/index.js`\n\n- [ ] **Step 1: Write failing test for `.events` file writing**\n\nAdd to `tests/brainstorm-server/server.test.js` after Test 4 area — a new test that sends a WebSocket event with a `choice` field and verifies `.events` file is written:\n\n```javascript\n    // Test: Choice events written to .events file\n    console.log('Test: Choice events written to .events file');\n    const ws3 = new WebSocket(`ws://localhost:${TEST_PORT}`);\n    await new Promise(resolve => ws3.on('open', resolve));\n\n    ws3.send(JSON.stringify({ type: 'click', choice: 'a', text: 'Option A' }));\n    await sleep(300);\n\n    const eventsFile = path.join(TEST_DIR, '.events');\n    assert(fs.existsSync(eventsFile), '.events file should exist after choice click');\n    const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\\n');\n    const event = JSON.parse(lines[lines.length - 1]);\n    assert.strictEqual(event.choice, 'a', 'Event should contain choice');\n    assert.strictEqual(event.text, 'Option A', 'Event should contain text');\n    ws3.close();\n    console.log('  PASS');\n```\n\n- [ ] **Step 2: Run test to verify it fails**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: New test FAILS — `.events` file doesn't exist yet.\n\n- [ ] **Step 3: Write failing test for `.events` file clearing on new screen**\n\nAdd another test:\n\n```javascript\n    // Test: .events cleared on new screen\n    console.log('Test: .events cleared on new screen');\n    // .events file should still exist from previous test\n    assert(fs.existsSync(path.join(TEST_DIR, '.events')), '.events should exist before new screen');\n    fs.writeFileSync(path.join(TEST_DIR, 'new-screen.html'), '<h2>New screen</h2>');\n    await sleep(500);\n    assert(!fs.existsSync(path.join(TEST_DIR, '.events')), '.events should be cleared after new screen');\n    console.log('  PASS');\n```\n\n- [ ] **Step 4: Run test to verify it fails**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: New test FAILS — `.events` not cleared on screen push.\n\n- [ ] **Step 5: Implement `.events` file writing in `index.js`**\n\nIn the WebSocket `message` handler (line 74-77 of `index.js`), after the `console.log`, add:\n\n```javascript\n    // Write user events to .events file for Claude to read\n    if (event.choice) {\n      const eventsFile = path.join(SCREEN_DIR, '.events');\n      fs.appendFileSync(eventsFile, JSON.stringify(event) + '\\n');\n    }\n```\n\nIn the chokidar `add` handler (line 104-111), add `.events` clearing:\n\n```javascript\n    if (filePath.endsWith('.html')) {\n      // Clear events from previous screen\n      const eventsFile = path.join(SCREEN_DIR, '.events');\n      if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);\n\n      console.log(JSON.stringify({ type: 'screen-added', file: filePath }));\n      // ... existing reload broadcast\n    }\n```\n\n- [ ] **Step 6: Replace `wrapInFrame` with comment placeholder injection**\n\nReplace the `wrapInFrame` function (lines 27-32 of `index.js`):\n\n```javascript\nfunction wrapInFrame(content) {\n  return frameTemplate.replace('<!-- CONTENT -->', content);\n}\n```\n\n- [ ] **Step 7: Run all tests**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: New `.events` tests PASS. Existing tests may still have failures from old assertions (fixed in Task 4).\n\n- [ ] **Step 8: Commit**\n\n```bash\ngit add lib/brainstorm-server/index.js tests/brainstorm-server/server.test.js\ngit commit -m \"Add .events file writing and comment-based content injection to brainstorm server\"\n```\n\n---\n\n### Task 3: Simplify `helper.js`\n\n**Files:**\n- Modify: `lib/brainstorm-server/helper.js`\n\n- [ ] **Step 1: Remove `sendToClaude` function**\n\nDelete the `sendToClaude` function (lines 92-106) — the function body and the page takeover HTML.\n\n- [ ] **Step 2: Remove `window.send` function**\n\nDelete the `window.send` function (lines 120-129) — was tied to the removed Send button.\n\n- [ ] **Step 3: Remove form submission and input change handlers**\n\nDelete the form submission handler (lines 57-71) and the input change handler (lines 73-89) including the `inputTimeout` variable.\n\n- [ ] **Step 4: Remove `pageshow` event listener**\n\nDelete the `pageshow` listener we added earlier (no textarea to clear anymore).\n\n- [ ] **Step 5: Narrow click handler to `[data-choice]` only**\n\nReplace the click handler (lines 36-55) with a narrower version:\n\n```javascript\n  // Capture clicks on choice elements\n  document.addEventListener('click', (e) => {\n    const target = e.target.closest('[data-choice]');\n    if (!target) return;\n\n    sendEvent({\n      type: 'click',\n      text: target.textContent.trim(),\n      choice: target.dataset.choice,\n      id: target.id || null\n    });\n  });\n```\n\n- [ ] **Step 6: Add indicator bar update on choice click**\n\nAfter the `sendEvent` call in the click handler, add:\n\n```javascript\n    // Update indicator bar\n    const indicator = document.getElementById('indicator-text');\n    if (indicator) {\n      const label = target.querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || target.dataset.choice;\n      indicator.innerHTML = '<span class=\"selected-text\">' + label + ' selected</span> — return to terminal to continue';\n    }\n```\n\n- [ ] **Step 7: Remove `sendToClaude` from `window.brainstorm` API**\n\nUpdate the `window.brainstorm` object (lines 132-136) to remove `sendToClaude`:\n\n```javascript\n  window.brainstorm = {\n    send: sendEvent,\n    choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })\n  };\n```\n\n- [ ] **Step 8: Run tests**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\n\n- [ ] **Step 9: Commit**\n\n```bash\ngit add lib/brainstorm-server/helper.js\ngit commit -m \"Simplify helper.js: remove feedback functions, narrow to choice capture + indicator\"\n```\n\n---\n\n### Task 4: Update tests for new structure\n\n**Files:**\n- Modify: `tests/brainstorm-server/server.test.js`\n\n**Note:** Line references below are from the _original_ file. Task 2 inserted new tests earlier in the file, so actual line numbers will be shifted. Find tests by their `console.log` labels (e.g., \"Test 5:\", \"Test 6:\").\n\n- [ ] **Step 1: Update Test 5 (full document assertion)**\n\nFind the Test 5 assertion `!fullRes.body.includes('feedback-footer')`. Change it to: Full documents should NOT have the indicator bar either (they're served as-is):\n\n```javascript\n    assert(!fullRes.body.includes('indicator-bar') || fullDoc.includes('indicator-bar'),\n      'Should not wrap full documents in frame template');\n```\n\n- [ ] **Step 2: Update Test 6 (fragment wrapping)**\n\nLine 125: Replace `feedback-footer` assertion with indicator bar assertion:\n\n```javascript\n    assert(fragRes.body.includes('indicator-bar'), 'Fragment should get indicator bar from frame');\n```\n\nAlso verify content placeholder was replaced (fragment content appears, placeholder comment doesn't):\n\n```javascript\n    assert(!fragRes.body.includes('<!-- CONTENT -->'), 'Content placeholder should be replaced');\n```\n\n- [ ] **Step 3: Update Test 7 (helper.js API)**\n\nLines 140-142: Update assertions to reflect the new API surface:\n\n```javascript\n    assert(helperContent.includes('toggleSelect'), 'helper.js should define toggleSelect');\n    assert(helperContent.includes('sendEvent'), 'helper.js should define sendEvent');\n    assert(helperContent.includes('selectedChoice'), 'helper.js should track selectedChoice');\n    assert(helperContent.includes('brainstorm'), 'helper.js should expose brainstorm API');\n    assert(!helperContent.includes('sendToClaude'), 'helper.js should not contain sendToClaude');\n```\n\n- [ ] **Step 4: Replace Test 8 (sendToClaude theming) with indicator bar test**\n\nReplace Test 8 (lines 145-149) — `sendToClaude` no longer exists. Test the indicator bar instead:\n\n```javascript\n    // Test 8: Indicator bar uses CSS variables (theme support)\n    console.log('Test 8: Indicator bar uses CSS variables');\n    const templateContent = fs.readFileSync(\n      path.join(__dirname, '../../lib/brainstorm-server/frame-template.html'), 'utf-8'\n    );\n    assert(templateContent.includes('indicator-bar'), 'Template should have indicator bar');\n    assert(templateContent.includes('indicator-text'), 'Template should have indicator text element');\n    console.log('  PASS');\n```\n\n- [ ] **Step 5: Run full test suite**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: ALL tests PASS.\n\n- [ ] **Step 6: Commit**\n\n```bash\ngit add tests/brainstorm-server/server.test.js\ngit commit -m \"Update brainstorm server tests for new template structure and helper.js API\"\n```\n\n---\n\n### Task 5: Delete `wait-for-feedback.sh`\n\n**Files:**\n- Delete: `lib/brainstorm-server/wait-for-feedback.sh`\n\n- [ ] **Step 1: Verify no other files import or reference `wait-for-feedback.sh`**\n\nSearch the codebase:\n```bash\ngrep -r \"wait-for-feedback\" /Users/drewritter/prime-rad/superpowers/ --include=\"*.js\" --include=\"*.md\" --include=\"*.sh\" --include=\"*.json\"\n```\n\nExpected references: only `visual-companion.md` (rewritten in Task 6) and possibly release notes (historical, leave as-is).\n\n- [ ] **Step 2: Delete the file**\n\n```bash\nrm lib/brainstorm-server/wait-for-feedback.sh\n```\n\n- [ ] **Step 3: Run tests to confirm nothing breaks**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: All tests PASS (no test referenced this file).\n\n- [ ] **Step 4: Commit**\n\n```bash\ngit add -u lib/brainstorm-server/wait-for-feedback.sh\ngit commit -m \"Delete wait-for-feedback.sh: replaced by .events file\"\n```\n\n---\n\n### Task 6: Rewrite `visual-companion.md`\n\n**Files:**\n- Modify: `skills/brainstorming/visual-companion.md`\n\n- [ ] **Step 1: Update \"How It Works\" description (line 18)**\n\nReplace the sentence about receiving feedback \"as JSON\" with:\n\n```markdown\nThe server watches a directory for HTML files and serves the newest one to the browser. You write HTML content, the user sees it in their browser and can click to select options. Selections are recorded to a `.events` file that you read on your next turn.\n```\n\n- [ ] **Step 2: Update fragment description (line 20)**\n\nRemove \"feedback footer\" from the description of what the frame template provides:\n\n```markdown\n**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, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.\n```\n\n- [ ] **Step 3: Rewrite \"The Loop\" section (lines 36-61)**\n\nReplace the entire \"The Loop\" section with:\n\n```markdown\n## The Loop\n\n1. **Write HTML** to a new file in `screen_dir`:\n   - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`\n   - **Never reuse filenames** — each screen gets a fresh file\n   - Use Write tool — **never use cat/heredoc** (dumps noise into terminal)\n   - Server automatically serves the newest file\n\n2. **Tell user what to expect and end your turn:**\n   - Remind them of the URL (every step, not just first)\n   - Give a brief text summary of what's on screen (e.g., \"Showing 3 layout options for the homepage\")\n   - 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.\"\n\n3. **On your next turn** — after the user responds in the terminal:\n   - Read `$SCREEN_DIR/.events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines\n   - Merge with the user's terminal text to get the full picture\n   - The terminal message is the primary feedback; `.events` provides structured interaction data\n\n4. **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.\n\n5. Repeat until done.\n```\n\n- [ ] **Step 4: Replace \"User Feedback Format\" section (lines 165-174)**\n\nReplace with:\n\n```markdown\n## Browser Events Format\n\nWhen the user clicks options in the browser, their interactions are recorded to `$SCREEN_DIR/.events` (one JSON object per line). The file is cleared automatically when you push a new screen.\n\n```jsonl\n{\"type\":\"click\",\"choice\":\"a\",\"text\":\"Option A - Simple Layout\",\"timestamp\":1706000101}\n{\"type\":\"click\",\"choice\":\"c\",\"text\":\"Option C - Complex Grid\",\"timestamp\":1706000108}\n{\"type\":\"click\",\"choice\":\"b\",\"text\":\"Option B - Hybrid\",\"timestamp\":1706000115}\n```\n\nThe 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.\n\nIf `.events` doesn't exist, the user didn't interact with the browser — use only their terminal text.\n```\n\n- [ ] **Step 5: Update \"Writing Content Fragments\" description (line 65)**\n\nRemove \"feedback footer\" reference:\n\n```markdown\nWrite 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).\n```\n\n- [ ] **Step 6: Update Reference section (lines 200-203)**\n\nRemove the helper.js reference description about \"JS API\" — the API is now minimal. Keep the path reference:\n\n```markdown\n## Reference\n\n- Frame template (CSS reference): `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/frame-template.html`\n- Helper script (client-side): `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/helper.js`\n```\n\n- [ ] **Step 7: Commit**\n\n```bash\ngit add skills/brainstorming/visual-companion.md\ngit commit -m \"Rewrite visual-companion.md for non-blocking browser-displays-terminal-commands flow\"\n```\n\n---\n\n### Task 7: Final verification\n\n- [ ] **Step 1: Run full test suite**\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js\n```\nExpected: ALL tests PASS.\n\n- [ ] **Step 2: Manual smoke test**\n\nStart the server manually and verify the flow works end-to-end:\n\n```bash\ncd /Users/drewritter/prime-rad/superpowers && lib/brainstorm-server/start-server.sh --project-dir /tmp/brainstorm-smoke-test\n```\n\nWrite a test fragment, open in browser, click an option, verify `.events` file is written, verify indicator bar updates. Then stop the server:\n\n```bash\nlib/brainstorm-server/stop-server.sh <screen_dir from start output>\n```\n\n- [ ] **Step 3: Verify no stale references remain**\n\n```bash\ngrep -r \"wait-for-feedback\\|sendToClaude\\|feedback-footer\\|send-to-claude\\|TaskOutput.*block.*true\" /Users/drewritter/prime-rad/superpowers/ --include=\"*.js\" --include=\"*.md\" --include=\"*.sh\" --include=\"*.html\" | grep -v node_modules | grep -v RELEASE-NOTES | grep -v \"\\.md:.*spec\\|plan\"\n```\n\nExpected: No hits outside of release notes and the spec/plan docs (which are historical).\n\n- [ ] **Step 4: Final commit if any cleanup needed**\n\n```bash\ngit status\n# Review untracked/modified files, stage specific files as needed, commit if clean\n```\n"
  },
  {
    "path": "docs/superpowers/plans/2026-03-11-zero-dep-brainstorm-server.md",
    "content": "# Zero-Dependency Brainstorm Server Implementation Plan\n\n> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.\n\n**Goal:** Replace the brainstorm server's vendored node_modules with a single zero-dependency `server.js` using Node built-ins.\n\n**Architecture:** Single file with WebSocket protocol (RFC 6455 text frames), HTTP server (`http` module), and file watching (`fs.watch`). Exports protocol functions for unit testing when required as a module.\n\n**Tech Stack:** Node.js built-ins only: `http`, `crypto`, `fs`, `path`\n\n**Spec:** `docs/superpowers/specs/2026-03-11-zero-dep-brainstorm-server-design.md`\n\n**Existing tests:** `tests/brainstorm-server/ws-protocol.test.js` (unit), `tests/brainstorm-server/server.test.js` (integration)\n\n---\n\n## File Map\n\n- **Create:** `skills/brainstorming/scripts/server.js` — the zero-dep replacement\n- **Modify:** `skills/brainstorming/scripts/start-server.sh:94,100` — change `index.js` to `server.js`\n- **Modify:** `.gitignore:6` — remove the `!skills/brainstorming/scripts/node_modules/` exception\n- **Delete:** `skills/brainstorming/scripts/index.js`\n- **Delete:** `skills/brainstorming/scripts/package.json`\n- **Delete:** `skills/brainstorming/scripts/package-lock.json`\n- **Delete:** `skills/brainstorming/scripts/node_modules/` (714 files)\n- **No changes:** `skills/brainstorming/scripts/helper.js`, `skills/brainstorming/scripts/frame-template.html`, `skills/brainstorming/scripts/stop-server.sh`\n\n---\n\n## Chunk 1: WebSocket Protocol Layer\n\n### Task 1: Implement WebSocket protocol exports\n\n**Files:**\n- Create: `skills/brainstorming/scripts/server.js`\n- Test: `tests/brainstorm-server/ws-protocol.test.js` (already exists)\n\n- [ ] **Step 1: Create server.js with OPCODES constant and computeAcceptKey**\n\n```js\nconst crypto = require('crypto');\n\nconst OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };\nconst WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';\n\nfunction computeAcceptKey(clientKey) {\n  return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');\n}\n```\n\n- [ ] **Step 2: Implement encodeFrame**\n\nServer frames are never masked. Three length encodings:\n- payload < 126: 2-byte header (FIN+opcode, length)\n- 126-65535: 4-byte header (FIN+opcode, 126, 16-bit length)\n- &gt; 65535: 10-byte header (FIN+opcode, 127, 64-bit length)\n\n```js\nfunction encodeFrame(opcode, payload) {\n  const fin = 0x80;\n  const len = payload.length;\n  let header;\n\n  if (len < 126) {\n    header = Buffer.alloc(2);\n    header[0] = fin | opcode;\n    header[1] = len;\n  } else if (len < 65536) {\n    header = Buffer.alloc(4);\n    header[0] = fin | opcode;\n    header[1] = 126;\n    header.writeUInt16BE(len, 2);\n  } else {\n    header = Buffer.alloc(10);\n    header[0] = fin | opcode;\n    header[1] = 127;\n    header.writeBigUInt64BE(BigInt(len), 2);\n  }\n\n  return Buffer.concat([header, payload]);\n}\n```\n\n- [ ] **Step 3: Implement decodeFrame**\n\nClient frames are always masked. Returns `{ opcode, payload, bytesConsumed }` or `null` for incomplete. Throws on unmasked frames.\n\n```js\nfunction decodeFrame(buffer) {\n  if (buffer.length < 2) return null;\n\n  const firstByte = buffer[0];\n  const secondByte = buffer[1];\n  const opcode = firstByte & 0x0F;\n  const masked = (secondByte & 0x80) !== 0;\n  let payloadLen = secondByte & 0x7F;\n  let offset = 2;\n\n  if (!masked) throw new Error('Client frames must be masked');\n\n  if (payloadLen === 126) {\n    if (buffer.length < 4) return null;\n    payloadLen = buffer.readUInt16BE(2);\n    offset = 4;\n  } else if (payloadLen === 127) {\n    if (buffer.length < 10) return null;\n    payloadLen = Number(buffer.readBigUInt64BE(2));\n    offset = 10;\n  }\n\n  const maskOffset = offset;\n  const dataOffset = offset + 4;\n  const totalLen = dataOffset + payloadLen;\n  if (buffer.length < totalLen) return null;\n\n  const mask = buffer.slice(maskOffset, dataOffset);\n  const data = Buffer.alloc(payloadLen);\n  for (let i = 0; i < payloadLen; i++) {\n    data[i] = buffer[dataOffset + i] ^ mask[i % 4];\n  }\n\n  return { opcode, payload: data, bytesConsumed: totalLen };\n}\n```\n\n- [ ] **Step 4: Add module exports at the bottom of the file**\n\n```js\nmodule.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };\n```\n\n- [ ] **Step 5: Run unit tests**\n\nRun: `cd tests/brainstorm-server && node ws-protocol.test.js`\nExpected: All tests pass (handshake, encoding, decoding, boundaries, edge cases)\n\n- [ ] **Step 6: Commit**\n\n```bash\ngit add skills/brainstorming/scripts/server.js\ngit commit -m \"Add WebSocket protocol layer for zero-dep brainstorm server\"\n```\n\n---\n\n## Chunk 2: HTTP Server and Application Logic\n\n### Task 2: Add HTTP server, file watching, and WebSocket connection handling\n\n**Files:**\n- Modify: `skills/brainstorming/scripts/server.js`\n- Test: `tests/brainstorm-server/server.test.js` (already exists)\n\n- [ ] **Step 1: Add configuration and constants at top of server.js (after requires)**\n\n```js\nconst http = require('http');\nconst fs = require('fs');\nconst path = require('path');\n\nconst PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));\nconst HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';\nconst URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);\nconst SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';\n\nconst MIME_TYPES = {\n  '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',\n  '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',\n  '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'\n};\n```\n\n- [ ] **Step 2: Add WAITING_PAGE, template loading at module scope, and helper functions**\n\nLoad `frameTemplate` and `helperInjection` at module scope so they're accessible to `wrapInFrame` and `handleRequest`. They only read files from `__dirname` (the scripts directory), which is valid whether the module is required or run directly.\n\n```js\nconst WAITING_PAGE = `<!DOCTYPE html>\n<html>\n<head><title>Brainstorm Companion</title>\n<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }\nh1 { color: #333; } p { color: #666; }</style>\n</head>\n<body><h1>Brainstorm Companion</h1>\n<p>Waiting for Claude to push a screen...</p></body></html>`;\n\nconst frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');\nconst helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');\nconst helperInjection = '<script>\\n' + helperScript + '\\n</script>';\n\nfunction isFullDocument(html) {\n  const trimmed = html.trimStart().toLowerCase();\n  return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');\n}\n\nfunction wrapInFrame(content) {\n  return frameTemplate.replace('<!-- CONTENT -->', content);\n}\n\nfunction getNewestScreen() {\n  const files = fs.readdirSync(SCREEN_DIR)\n    .filter(f => f.endsWith('.html'))\n    .map(f => {\n      const fp = path.join(SCREEN_DIR, f);\n      return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };\n    })\n    .sort((a, b) => b.mtime - a.mtime);\n  return files.length > 0 ? files[0].path : null;\n}\n```\n\n- [ ] **Step 3: Add HTTP request handler**\n\n```js\nfunction handleRequest(req, res) {\n  if (req.method === 'GET' && req.url === '/') {\n    const screenFile = getNewestScreen();\n    let html = screenFile\n      ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))\n      : WAITING_PAGE;\n\n    if (html.includes('</body>')) {\n      html = html.replace('</body>', helperInjection + '\\n</body>');\n    } else {\n      html += helperInjection;\n    }\n\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end(html);\n  } else if (req.method === 'GET' && req.url.startsWith('/files/')) {\n    const fileName = req.url.slice(7); // strip '/files/'\n    const filePath = path.join(SCREEN_DIR, path.basename(fileName));\n    if (!fs.existsSync(filePath)) {\n      res.writeHead(404);\n      res.end('Not found');\n      return;\n    }\n    const ext = path.extname(filePath).toLowerCase();\n    const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n    res.writeHead(200, { 'Content-Type': contentType });\n    res.end(fs.readFileSync(filePath));\n  } else {\n    res.writeHead(404);\n    res.end('Not found');\n  }\n}\n```\n\n- [ ] **Step 4: Add WebSocket connection handling**\n\n```js\nconst clients = new Set();\n\nfunction handleUpgrade(req, socket) {\n  const key = req.headers['sec-websocket-key'];\n  if (!key) { socket.destroy(); return; }\n\n  const accept = computeAcceptKey(key);\n  socket.write(\n    'HTTP/1.1 101 Switching Protocols\\r\\n' +\n    'Upgrade: websocket\\r\\n' +\n    'Connection: Upgrade\\r\\n' +\n    'Sec-WebSocket-Accept: ' + accept + '\\r\\n\\r\\n'\n  );\n\n  let buffer = Buffer.alloc(0);\n  clients.add(socket);\n\n  socket.on('data', (chunk) => {\n    buffer = Buffer.concat([buffer, chunk]);\n    while (buffer.length > 0) {\n      let result;\n      try {\n        result = decodeFrame(buffer);\n      } catch (e) {\n        socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));\n        clients.delete(socket);\n        return;\n      }\n      if (!result) break;\n      buffer = buffer.slice(result.bytesConsumed);\n\n      switch (result.opcode) {\n        case OPCODES.TEXT:\n          handleMessage(result.payload.toString());\n          break;\n        case OPCODES.CLOSE:\n          socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));\n          clients.delete(socket);\n          return;\n        case OPCODES.PING:\n          socket.write(encodeFrame(OPCODES.PONG, result.payload));\n          break;\n        case OPCODES.PONG:\n          break;\n        default:\n          // Unsupported opcode — close with 1003\n          const closeBuf = Buffer.alloc(2);\n          closeBuf.writeUInt16BE(1003);\n          socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));\n          clients.delete(socket);\n          return;\n      }\n    }\n  });\n\n  socket.on('close', () => clients.delete(socket));\n  socket.on('error', () => clients.delete(socket));\n}\n\nfunction handleMessage(text) {\n  let event;\n  try {\n    event = JSON.parse(text);\n  } catch (e) {\n    console.error('Failed to parse WebSocket message:', e.message);\n    return;\n  }\n  console.log(JSON.stringify({ source: 'user-event', ...event }));\n  if (event.choice) {\n    const eventsFile = path.join(SCREEN_DIR, '.events');\n    fs.appendFileSync(eventsFile, JSON.stringify(event) + '\\n');\n  }\n}\n\nfunction broadcast(msg) {\n  const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));\n  for (const socket of clients) {\n    try { socket.write(frame); } catch (e) { clients.delete(socket); }\n  }\n}\n```\n\n- [ ] **Step 5: Add debounce timer map**\n\n```js\nconst debounceTimers = new Map();\n```\n\nFile watching logic is inlined in `startServer` (Step 6) to keep watcher lifecycle together with server lifecycle and include an `error` handler per spec.\n\n- [ ] **Step 6: Add startServer function and conditional main**\n\n`frameTemplate` and `helperInjection` are already at module scope (Step 2). `startServer` just creates the screen dir, starts the HTTP server, watcher, and logs startup info.\n\n```js\nfunction startServer() {\n  if (!fs.existsSync(SCREEN_DIR)) fs.mkdirSync(SCREEN_DIR, { recursive: true });\n\n  const server = http.createServer(handleRequest);\n  server.on('upgrade', handleUpgrade);\n\n  const watcher = fs.watch(SCREEN_DIR, (eventType, filename) => {\n    if (!filename || !filename.endsWith('.html')) return;\n    if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));\n    debounceTimers.set(filename, setTimeout(() => {\n      debounceTimers.delete(filename);\n      const filePath = path.join(SCREEN_DIR, filename);\n      if (eventType === 'rename' && fs.existsSync(filePath)) {\n        const eventsFile = path.join(SCREEN_DIR, '.events');\n        if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);\n        console.log(JSON.stringify({ type: 'screen-added', file: filePath }));\n      } else if (eventType === 'change') {\n        console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));\n      }\n      broadcast({ type: 'reload' });\n    }, 100));\n  });\n  watcher.on('error', (err) => console.error('fs.watch error:', err.message));\n\n  server.listen(PORT, HOST, () => {\n    const info = JSON.stringify({\n      type: 'server-started', port: Number(PORT), host: HOST,\n      url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,\n      screen_dir: SCREEN_DIR\n    });\n    console.log(info);\n    fs.writeFileSync(path.join(SCREEN_DIR, '.server-info'), info + '\\n');\n  });\n}\n\nif (require.main === module) {\n  startServer();\n}\n```\n\n- [ ] **Step 7: Run integration tests**\n\nThe test directory already has a `package.json` with `ws` as a dependency. Install it if needed, then run tests.\n\nRun: `cd tests/brainstorm-server && npm install && node server.test.js`\nExpected: All tests pass\n\n- [ ] **Step 8: Commit**\n\n```bash\ngit add skills/brainstorming/scripts/server.js\ngit commit -m \"Add HTTP server, WebSocket handling, and file watching to server.js\"\n```\n\n---\n\n## Chunk 3: Swap and Cleanup\n\n### Task 3: Update start-server.sh and remove old files\n\n**Files:**\n- Modify: `skills/brainstorming/scripts/start-server.sh:94,100`\n- Modify: `.gitignore:6`\n- Delete: `skills/brainstorming/scripts/index.js`\n- Delete: `skills/brainstorming/scripts/package.json`\n- Delete: `skills/brainstorming/scripts/package-lock.json`\n- Delete: `skills/brainstorming/scripts/node_modules/` (entire directory)\n\n- [ ] **Step 1: Update start-server.sh — change `index.js` to `server.js`**\n\nTwo lines to change:\n\nLine 94: `env BRAINSTORM_DIR=\"$SCREEN_DIR\" BRAINSTORM_HOST=\"$BIND_HOST\" BRAINSTORM_URL_HOST=\"$URL_HOST\" node server.js`\n\nLine 100: `nohup env BRAINSTORM_DIR=\"$SCREEN_DIR\" BRAINSTORM_HOST=\"$BIND_HOST\" BRAINSTORM_URL_HOST=\"$URL_HOST\" node server.js > \"$LOG_FILE\" 2>&1 &`\n\n- [ ] **Step 2: Remove the gitignore exception for node_modules**\n\nIn `.gitignore`, delete line 6: `!skills/brainstorming/scripts/node_modules/`\n\n- [ ] **Step 3: Delete old files**\n\n```bash\ngit rm skills/brainstorming/scripts/index.js\ngit rm skills/brainstorming/scripts/package.json\ngit rm skills/brainstorming/scripts/package-lock.json\ngit rm -r skills/brainstorming/scripts/node_modules/\n```\n\n- [ ] **Step 4: Run both test suites**\n\nRun: `cd tests/brainstorm-server && node ws-protocol.test.js && node server.test.js`\nExpected: All tests pass\n\n- [ ] **Step 5: Commit**\n\n```bash\ngit add skills/brainstorming/scripts/ .gitignore\ngit commit -m \"Remove vendored node_modules, swap to zero-dep server.js\"\n```\n\n### Task 4: Manual smoke test\n\n- [ ] **Step 1: Start the server manually**\n\n```bash\ncd skills/brainstorming/scripts\nBRAINSTORM_DIR=/tmp/brainstorm-smoke BRAINSTORM_PORT=9876 node server.js\n```\n\nExpected: `server-started` JSON printed with port 9876\n\n- [ ] **Step 2: Open browser to http://localhost:9876**\n\nExpected: Waiting page with \"Waiting for Claude to push a screen...\"\n\n- [ ] **Step 3: Write an HTML file to the screen directory**\n\n```bash\necho '<h2>Hello from smoke test</h2>' > /tmp/brainstorm-smoke/test.html\n```\n\nExpected: Browser reloads and shows \"Hello from smoke test\" wrapped in frame template\n\n- [ ] **Step 4: Verify WebSocket works — check browser console**\n\nOpen browser dev tools. The WebSocket connection should show as connected (no errors in console). The frame template's status indicator should show \"Connected\".\n\n- [ ] **Step 5: Stop server with Ctrl-C, clean up**\n\n```bash\nrm -rf /tmp/brainstorm-smoke\n```\n"
  },
  {
    "path": "docs/superpowers/specs/2026-01-22-document-review-system-design.md",
    "content": "# Document Review System Design\n\n## Overview\n\nAdd two new review stages to the superpowers workflow:\n\n1. **Spec Document Review** - After brainstorming, before writing-plans\n2. **Plan Document Review** - After writing-plans, before implementation\n\nBoth follow the iterative loop pattern used by implementation reviews.\n\n## Spec Document Reviewer\n\n**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.\n\n**Location:** `skills/brainstorming/spec-document-reviewer-prompt.md`\n\n**What it checks for:**\n\n| Category | What to Look For |\n|----------|------------------|\n| Completeness | TODOs, placeholders, \"TBD\", incomplete sections |\n| Coverage | Missing error handling, edge cases, integration points |\n| Consistency | Internal contradictions, conflicting requirements |\n| Clarity | Ambiguous requirements |\n| YAGNI | Unrequested features, over-engineering |\n\n**Output format:**\n```\n## Spec Review\n\n**Status:** Approved | Issues Found\n\n**Issues (if any):**\n- [Section X]: [issue] - [why it matters]\n\n**Recommendations (advisory):**\n- [suggestions that don't block approval]\n```\n\n**Review loop:** Issues found -> brainstorming agent fixes -> re-review -> repeat until approved.\n\n**Dispatch mechanism:** Use the Task tool with `subagent_type: general-purpose`. The reviewer prompt template provides the full prompt. The brainstorming skill's controller dispatches the reviewer.\n\n## Plan Document Reviewer\n\n**Purpose:** Verify the plan is complete, matches the spec, and has proper task decomposition.\n\n**Location:** `skills/writing-plans/plan-document-reviewer-prompt.md`\n\n**What it checks for:**\n\n| Category | What to Look For |\n|----------|------------------|\n| Completeness | TODOs, placeholders, incomplete tasks |\n| Spec Alignment | Plan covers spec requirements, no scope creep |\n| Task Decomposition | Tasks atomic, clear boundaries |\n| Task Syntax | Checkbox syntax on tasks and steps |\n| Chunk Size | Each chunk under 1000 lines |\n\n**Chunk definition:** A chunk is a logical grouping of tasks within the plan document, delimited by `## Chunk N: <name>` headings. The writing-plans skill creates these boundaries based on logical phases (e.g., \"Foundation\", \"Core Features\", \"Integration\"). Each chunk should be self-contained enough to review independently.\n\n**Spec alignment verification:** The reviewer receives both:\n1. The plan document (or current chunk)\n2. The path to the spec document for reference\n\nThe reviewer reads both and compares requirements coverage.\n\n**Output format:** Same as spec reviewer, but scoped to the current chunk.\n\n**Review process (chunk-by-chunk):**\n1. Writing-plans creates chunk N\n2. Controller dispatches plan-document-reviewer with chunk N content and spec path\n3. Reviewer reads chunk and spec, returns verdict\n4. If issues: writing-plans agent fixes chunk N, goto step 2\n5. If approved: proceed to chunk N+1\n6. Repeat until all chunks approved\n\n**Dispatch mechanism:** Same as spec reviewer - Task tool with `subagent_type: general-purpose`.\n\n## Updated Workflow\n\n```\nbrainstorming -> spec -> SPEC REVIEW LOOP -> writing-plans -> plan -> PLAN REVIEW LOOP -> implementation\n```\n\n**Spec Review Loop:**\n1. Spec complete\n2. Dispatch reviewer\n3. If issues: fix -> goto 2\n4. If approved: proceed\n\n**Plan Review Loop:**\n1. Chunk N complete\n2. Dispatch reviewer for chunk N\n3. If issues: fix -> goto 2\n4. If approved: next chunk or implementation\n\n## Markdown Task Syntax\n\nTasks and steps use checkbox syntax:\n\n```markdown\n- [ ] ### Task 1: Name\n\n- [ ] **Step 1:** Description\n  - File: path\n  - Command: cmd\n```\n\n## Error Handling\n\n**Review loop termination:**\n- No hard iteration limit - loops continue until reviewer approves\n- If loop exceeds 5 iterations, the controller should surface this to the human for guidance\n- The human can choose to: continue iterating, approve with known issues, or abort\n\n**Disagreement handling:**\n- Reviewers are advisory - they flag issues but don't block\n- If the agent believes reviewer feedback is incorrect, it should explain why in its fix\n- If disagreement persists after 3 iterations on the same issue, surface to human\n\n**Malformed reviewer output:**\n- Controller should validate reviewer output has required fields (Status, Issues if applicable)\n- If malformed, re-dispatch reviewer with a note about expected format\n- After 2 malformed responses, surface to human\n\n## Files to Change\n\n**New files:**\n- `skills/brainstorming/spec-document-reviewer-prompt.md`\n- `skills/writing-plans/plan-document-reviewer-prompt.md`\n\n**Modified files:**\n- `skills/brainstorming/SKILL.md` - add review loop after spec written\n- `skills/writing-plans/SKILL.md` - add chunk-by-chunk review loop, update task syntax examples\n"
  },
  {
    "path": "docs/superpowers/specs/2026-02-19-visual-brainstorming-refactor-design.md",
    "content": "# Visual Brainstorming Refactor: Browser Displays, Terminal Commands\n\n**Date:** 2026-02-19\n**Status:** Approved\n**Scope:** `lib/brainstorm-server/`, `skills/brainstorming/visual-companion.md`, `tests/brainstorm-server/`\n\n## Problem\n\nDuring visual brainstorming, Claude runs `wait-for-feedback.sh` as a background task and blocks on `TaskOutput(block=true, timeout=600s)`. This seizes the TUI entirely — the user cannot type to Claude while visual brainstorming is running. The browser becomes the only input channel.\n\nClaude Code's execution model is turn-based. There is no way for Claude to listen on two channels simultaneously within a single turn. The blocking `TaskOutput` pattern was the wrong primitive — it simulates event-driven behavior the platform doesn't support.\n\n## Design\n\n### Core Model\n\n**Browser = interactive display.** Shows mockups, lets the user click to select options. Selections are recorded server-side.\n\n**Terminal = conversation channel.** Always unblocked, always available. The user talks to Claude here.\n\n### The Loop\n\n1. Claude writes an HTML file to the session directory\n2. Server detects it via chokidar, pushes WebSocket reload to the browser (unchanged)\n3. Claude ends its turn — tells the user to check the browser and respond in the terminal\n4. User looks at browser, optionally clicks to select an option, then types feedback in the terminal\n5. On the next turn, Claude reads `$SCREEN_DIR/.events` for the browser interaction stream (clicks, selections), merges with the terminal text\n6. Iterate or advance\n\nNo background tasks. No `TaskOutput` blocking. No polling scripts.\n\n### Key Deletion: `wait-for-feedback.sh`\n\nDeleted entirely. Its purpose was to bridge \"server logs events to stdout\" and \"Claude needs to receive those events.\" The `.events` file replaces this — the server writes user interaction events directly, and Claude reads them with whatever file-reading mechanism the platform provides.\n\n### Key Addition: `.events` File (Per-Screen Event Stream)\n\nThe server writes all user interaction events to `$SCREEN_DIR/.events`, one JSON object per line. This gives Claude the full interaction stream for the current screen — not just the final selection, but the user's exploration path (clicked A, then B, settled on C).\n\nExample contents after a user explores options:\n\n```jsonl\n{\"type\":\"click\",\"choice\":\"a\",\"text\":\"Option A - Preset-First Wizard\",\"timestamp\":1706000101}\n{\"type\":\"click\",\"choice\":\"c\",\"text\":\"Option C - Manual Config\",\"timestamp\":1706000108}\n{\"type\":\"click\",\"choice\":\"b\",\"text\":\"Option B - Hybrid Approach\",\"timestamp\":1706000115}\n```\n\n- Append-only within a screen. Each user event is appended as a new line.\n- The file is cleared (deleted) when chokidar detects a new HTML file (new screen pushed), preventing stale events from carrying over.\n- If the file doesn't exist when Claude reads it, no browser interaction occurred — Claude uses only the terminal text.\n- The file contains only user events (`click`, etc.) — not server lifecycle events (`server-started`, `screen-added`). This keeps it small and focused.\n- Claude can read the full stream to understand the user's exploration pattern, or just look at the last `choice` event for the final selection.\n\n## Changes by File\n\n### `index.js` (server)\n\n**A. Write user events to `.events` file.**\n\nIn the WebSocket `message` handler, after logging the event to stdout: append the event as a JSON line to `$SCREEN_DIR/.events` via `fs.appendFileSync`. Only write user interaction events (those with `source: 'user-event'`), not server lifecycle events.\n\n**B. Clear `.events` on new screen.**\n\nIn the chokidar `add` handler (new `.html` file detected), delete `$SCREEN_DIR/.events` if it exists. This is the definitive \"new screen\" signal — better than clearing on GET `/` which fires on every reload.\n\n**C. Replace `wrapInFrame` content injection.**\n\nThe current regex anchors on `<div class=\"feedback-footer\">`, which is being removed. Replace with a comment placeholder: remove the existing default content inside `#claude-content` (the `<h2>Visual Brainstorming</h2>` and subtitle paragraph) and replace with a single `<!-- CONTENT -->` marker. Content injection becomes `frameTemplate.replace('<!-- CONTENT -->', content)`. Simpler and won't break if template formatting changes.\n\n### `frame-template.html` (UI frame)\n\n**Remove:**\n- The `feedback-footer` div (textarea, Send button, label, `.feedback-row`)\n- Associated CSS (`.feedback-footer`, `.feedback-footer label`, `.feedback-row`, textarea and button styles within it)\n\n**Add:**\n- `<!-- CONTENT -->` placeholder inside `#claude-content`, replacing the default text\n- A selection indicator bar where the footer was, with two states:\n  - Default: \"Click an option above, then return to the terminal\"\n  - After selection: \"Option B selected — return to terminal to continue\"\n- CSS for the indicator bar (subtle, similar visual weight to the existing header)\n\n**Keep unchanged:**\n- Header bar with \"Brainstorm Companion\" title and connection status\n- `.main` wrapper and `#claude-content` container\n- All component CSS (`.options`, `.cards`, `.mockup`, `.split`, `.pros-cons`, placeholders, mock elements)\n- Dark/light theme variables and media query\n\n### `helper.js` (client-side script)\n\n**Remove:**\n- `sendToClaude()` function and the \"Sent to Claude\" page takeover\n- `window.send()` function (was tied to the removed Send button)\n- Form submission handler — no purpose without the feedback textarea, adds log noise\n- Input change handler — same reason\n- `pageshow` event listener (was added to fix textarea persistence — no textarea anymore)\n\n**Keep:**\n- WebSocket connection, reconnect logic, event queue\n- Reload handler (`window.location.reload()` on server push)\n- `window.toggleSelect()` for selection highlighting\n- `window.selectedChoice` tracking\n- `window.brainstorm.send()` and `window.brainstorm.choice()` — these are distinct from the removed `window.send()`. They call `sendEvent` which logs to the server via WebSocket. Useful for custom full-document pages.\n\n**Narrow:**\n- Click handler: capture only `[data-choice]` clicks, not all buttons/links. The broad capture was needed when the browser was a feedback channel; now it's just for selection tracking.\n\n**Add:**\n- On `data-choice` click, update the selection indicator bar text to show which option was selected.\n\n**Remove from `window.brainstorm` API:**\n- `brainstorm.sendToClaude` — no longer exists\n\n### `visual-companion.md` (skill instructions)\n\n**Rewrite \"The Loop\" section** to the non-blocking flow described above. Remove all references to:\n- `wait-for-feedback.sh`\n- `TaskOutput` blocking\n- Timeout/retry logic (600s timeout, 30-minute cap)\n- \"User Feedback Format\" section describing `send-to-claude` JSON\n\n**Replace with:**\n- The new loop (write HTML → end turn → user responds in terminal → read `.events` → iterate)\n- `.events` file format documentation\n- Guidance that the terminal message is the primary feedback; `.events` provides the full browser interaction stream for additional context\n\n**Keep:**\n- Server startup/shutdown instructions\n- Content fragment vs full document guidance\n- CSS class reference and available components\n- Design tips (scale fidelity to the question, 2-4 options per screen, etc.)\n\n### `wait-for-feedback.sh`\n\n**Deleted entirely.**\n\n### `tests/brainstorm-server/server.test.js`\n\nTests that need updating:\n- Test asserting `feedback-footer` presence in fragment responses — update to assert the selection indicator bar or `<!-- CONTENT -->` replacement\n- Test asserting `helper.js` contains `send` — update to reflect narrowed API\n- Test asserting `sendToClaude` CSS variable usage — remove (function no longer exists)\n\n## Platform Compatibility\n\nThe server code (`index.js`, `helper.js`, `frame-template.html`) is fully platform-agnostic — pure Node.js and browser JavaScript. No Claude Code-specific references. Already proven to work on Codex via background terminal interaction.\n\nThe skill instructions (`visual-companion.md`) are the platform-adaptive layer. Each platform's Claude uses its own tools to start the server, read `.events`, etc. The non-blocking model works naturally across platforms since it doesn't depend on any platform-specific blocking primitive.\n\n## What This Enables\n\n- **TUI always responsive** during visual brainstorming\n- **Mixed input** — click in browser + type in terminal, naturally merged\n- **Graceful degradation** — browser down or user doesn't open it? Terminal still works\n- **Simpler architecture** — no background tasks, no polling scripts, no timeout management\n- **Cross-platform** — same server code works on Claude Code, Codex, and any future platform\n\n## What This Drops\n\n- **Pure-browser feedback workflow** — user must return to the terminal to continue. The selection indicator bar guides them, but it's one extra step compared to the old click-Send-and-wait flow.\n- **Inline text feedback from browser** — the textarea is gone. All text feedback goes through the terminal. This is intentional — the terminal is a better text input channel than a small textarea in a frame.\n- **Immediate response on browser Send** — the old system had Claude respond the moment the user clicked Send. Now there's a gap while the user switches to the terminal. In practice this is seconds, and the user gets to add context in their terminal message.\n"
  },
  {
    "path": "docs/superpowers/specs/2026-03-11-zero-dep-brainstorm-server-design.md",
    "content": "# Zero-Dependency Brainstorm Server\n\nReplace the brainstorm companion server's vendored node_modules (express, ws, chokidar — 714 tracked files) with a single zero-dependency `server.js` using only Node.js built-ins.\n\n## Motivation\n\nVendoring node_modules into the git repo creates a supply chain risk: frozen dependencies don't get security patches, 714 files of third-party code are committed without audit, and modifications to vendored code look like normal commits. While the actual risk is low (localhost-only dev server), eliminating it is straightforward.\n\n## Architecture\n\nA single `server.js` file (~250-300 lines) using `http`, `crypto`, `fs`, and `path`. The file serves two roles:\n\n- **When run directly** (`node server.js`): starts the HTTP/WebSocket server\n- **When required** (`require('./server.js')`): exports WebSocket protocol functions for unit testing\n\n### WebSocket Protocol\n\nImplements RFC 6455 for text frames only:\n\n**Handshake:** Compute `Sec-WebSocket-Accept` from client's `Sec-WebSocket-Key` using SHA-1 + the RFC 6455 magic GUID. Return 101 Switching Protocols.\n\n**Frame decoding (client to server):** Handle three masked length encodings:\n- Small: payload < 126 bytes\n- Medium: 126-65535 bytes (16-bit extended)\n- Large: > 65535 bytes (64-bit extended)\n\nXOR-unmask payload using 4-byte mask key. Return `{ opcode, payload, bytesConsumed }` or `null` for incomplete buffers. Reject unmasked frames.\n\n**Frame encoding (server to client):** Unmasked frames with the same three length encodings.\n\n**Opcodes handled:** TEXT (0x01), CLOSE (0x08), PING (0x09), PONG (0x0A). Unrecognized opcodes get a close frame with status 1003 (Unsupported Data).\n\n**Deliberately skipped:** Binary frames, fragmented messages, extensions (permessage-deflate), subprotocols. These are unnecessary for small JSON text messages between localhost clients. Extensions and subprotocols are negotiated in the handshake — by not advertising them, they are never active.\n\n**Buffer accumulation:** Each connection maintains a buffer. On `data`, append and loop `decodeFrame` until it returns null or buffer is empty.\n\n### HTTP Server\n\nThree routes:\n\n1. **`GET /`** — Serve newest `.html` from screen directory by mtime. Detect full documents vs fragments, wrap fragments in frame template, inject helper.js. Return `text/html`. When no `.html` files exist, serve a hardcoded waiting page (\"Waiting for Claude to push a screen...\") with helper.js injected.\n2. **`GET /files/*`** — Serve static files from screen directory with MIME type lookup from a hardcoded extension map (html, css, js, png, jpg, gif, svg, json). Return 404 if not found.\n3. **Everything else** — 404.\n\nWebSocket upgrade handled via the `'upgrade'` event on the HTTP server, separate from the request handler.\n\n### Configuration\n\nEnvironment variables (all optional):\n\n- `BRAINSTORM_PORT` — port to bind (default: random high port 49152-65535)\n- `BRAINSTORM_HOST` — interface to bind (default: `127.0.0.1`)\n- `BRAINSTORM_URL_HOST` — hostname for the URL in startup JSON (default: `localhost` when host is `127.0.0.1`, otherwise same as host)\n- `BRAINSTORM_DIR` — screen directory path (default: `/tmp/brainstorm`)\n\n### Startup Sequence\n\n1. Create `SCREEN_DIR` if it doesn't exist (`mkdirSync` recursive)\n2. Load frame template and helper.js from `__dirname`\n3. Start HTTP server on configured host/port\n4. Start `fs.watch` on `SCREEN_DIR`\n5. On successful listen, log `server-started` JSON to stdout: `{ type, port, host, url_host, url, screen_dir }`\n6. Write the same JSON to `SCREEN_DIR/.server-info` so agents can find connection details when stdout is hidden (background execution)\n\n### Application-Level WebSocket Messages\n\nWhen a TEXT frame arrives from a client:\n\n1. Parse as JSON. If parsing fails, log to stderr and continue.\n2. Log to stdout as `{ source: 'user-event', ...event }`.\n3. If the event contains a `choice` property, append the JSON to `SCREEN_DIR/.events` (one line per event).\n\n### File Watching\n\n`fs.watch(SCREEN_DIR)` replaces chokidar. On HTML file events:\n\n- On new file (`rename` event for a file that exists): delete `.events` file if present (`unlinkSync`), log `screen-added` to stdout as JSON\n- On file change (`change` event): log `screen-updated` to stdout as JSON (do NOT clear `.events`)\n- Both events: send `{ type: 'reload' }` to all connected WebSocket clients\n\nDebounce per-filename with ~100ms timeout to prevent duplicate events (common on macOS and Linux).\n\n### Error Handling\n\n- Malformed JSON from WebSocket clients: log to stderr, continue\n- Unhandled opcodes: close with status 1003\n- Client disconnects: remove from broadcast set\n- `fs.watch` errors: log to stderr, continue\n- No graceful shutdown logic — shell scripts handle process lifecycle via SIGTERM\n\n## What Changes\n\n| Before | After |\n|---|---|\n| `index.js` + `package.json` + `package-lock.json` + 714 `node_modules` files | `server.js` (single file) |\n| express, ws, chokidar dependencies | none |\n| No static file serving | `/files/*` serves from screen directory |\n\n## What Stays the Same\n\n- `helper.js` — no changes\n- `frame-template.html` — no changes\n- `start-server.sh` — one-line update: `index.js` to `server.js`\n- `stop-server.sh` — no changes\n- `visual-companion.md` — no changes\n- All existing server behavior and external contract\n\n## Platform Compatibility\n\n- `server.js` uses only cross-platform Node built-ins\n- `fs.watch` is reliable for single flat directories on macOS, Linux, and Windows\n- Shell scripts require bash (Git Bash on Windows, which is required for Claude Code)\n\n## Testing\n\n**Unit tests** (`ws-protocol.test.js`): Test WebSocket frame encoding/decoding, handshake computation, and protocol edge cases directly by requiring `server.js` exports.\n\n**Integration tests** (`server.test.js`): Test full server behavior — HTTP serving, WebSocket communication, file watching, brainstorming workflow. Uses `ws` npm package as a test-only client dependency (not shipped to end users).\n"
  },
  {
    "path": "docs/testing.md",
    "content": "# Testing Superpowers Skills\n\nThis document describes how to test Superpowers skills, particularly the integration tests for complex skills like `subagent-driven-development`.\n\n## Overview\n\nTesting skills that involve subagents, workflows, and complex interactions requires running actual Claude Code sessions in headless mode and verifying their behavior through session transcripts.\n\n## Test Structure\n\n```\ntests/\n├── claude-code/\n│   ├── test-helpers.sh                    # Shared test utilities\n│   ├── test-subagent-driven-development-integration.sh\n│   ├── analyze-token-usage.py             # Token analysis tool\n│   └── run-skill-tests.sh                 # Test runner (if exists)\n```\n\n## Running Tests\n\n### Integration Tests\n\nIntegration tests execute real Claude Code sessions with actual skills:\n\n```bash\n# Run the subagent-driven-development integration test\ncd tests/claude-code\n./test-subagent-driven-development-integration.sh\n```\n\n**Note:** Integration tests can take 10-30 minutes as they execute real implementation plans with multiple subagents.\n\n### Requirements\n\n- Must run from the **superpowers plugin directory** (not from temp directories)\n- Claude Code must be installed and available as `claude` command\n- Local dev marketplace must be enabled: `\"superpowers@superpowers-dev\": true` in `~/.claude/settings.json`\n\n## Integration Test: subagent-driven-development\n\n### What It Tests\n\nThe integration test verifies the `subagent-driven-development` skill correctly:\n\n1. **Plan Loading**: Reads the plan once at the beginning\n2. **Full Task Text**: Provides complete task descriptions to subagents (doesn't make them read files)\n3. **Self-Review**: Ensures subagents perform self-review before reporting\n4. **Review Order**: Runs spec compliance review before code quality review\n5. **Review Loops**: Uses review loops when issues are found\n6. **Independent Verification**: Spec reviewer reads code independently, doesn't trust implementer reports\n\n### How It Works\n\n1. **Setup**: Creates a temporary Node.js project with a minimal implementation plan\n2. **Execution**: Runs Claude Code in headless mode with the skill\n3. **Verification**: Parses the session transcript (`.jsonl` file) to verify:\n   - Skill tool was invoked\n   - Subagents were dispatched (Task tool)\n   - TodoWrite was used for tracking\n   - Implementation files were created\n   - Tests pass\n   - Git commits show proper workflow\n4. **Token Analysis**: Shows token usage breakdown by subagent\n\n### Test Output\n\n```\n========================================\n Integration Test: subagent-driven-development\n========================================\n\nTest project: /tmp/tmp.xyz123\n\n=== Verification Tests ===\n\nTest 1: Skill tool invoked...\n  [PASS] subagent-driven-development skill was invoked\n\nTest 2: Subagents dispatched...\n  [PASS] 7 subagents dispatched\n\nTest 3: Task tracking...\n  [PASS] TodoWrite used 5 time(s)\n\nTest 6: Implementation verification...\n  [PASS] src/math.js created\n  [PASS] add function exists\n  [PASS] multiply function exists\n  [PASS] test/math.test.js created\n  [PASS] Tests pass\n\nTest 7: Git commit history...\n  [PASS] Multiple commits created (3 total)\n\nTest 8: No extra features added...\n  [PASS] No extra features added\n\n=========================================\n Token Usage Analysis\n=========================================\n\nUsage Breakdown:\n----------------------------------------------------------------------------------------------------\nAgent           Description                          Msgs      Input     Output      Cache     Cost\n----------------------------------------------------------------------------------------------------\nmain            Main session (coordinator)             34         27      3,996  1,213,703 $   4.09\n3380c209        implementing Task 1: Create Add Function     1          2        787     24,989 $   0.09\n34b00fde        implementing Task 2: Create Multiply Function     1          4        644     25,114 $   0.09\n3801a732        reviewing whether an implementation matches...   1          5        703     25,742 $   0.09\n4c142934        doing a final code review...                    1          6        854     25,319 $   0.09\n5f017a42        a code reviewer. Review Task 2...               1          6        504     22,949 $   0.08\na6b7fbe4        a code reviewer. Review Task 1...               1          6        515     22,534 $   0.08\nf15837c0        reviewing whether an implementation matches...   1          6        416     22,485 $   0.07\n----------------------------------------------------------------------------------------------------\n\nTOTALS:\n  Total messages:         41\n  Input tokens:           62\n  Output tokens:          8,419\n  Cache creation tokens:  132,742\n  Cache read tokens:      1,382,835\n\n  Total input (incl cache): 1,515,639\n  Total tokens:             1,524,058\n\n  Estimated cost: $4.67\n  (at $3/$15 per M tokens for input/output)\n\n========================================\n Test Summary\n========================================\n\nSTATUS: PASSED\n```\n\n## Token Analysis Tool\n\n### Usage\n\nAnalyze token usage from any Claude Code session:\n\n```bash\npython3 tests/claude-code/analyze-token-usage.py ~/.claude/projects/<project-dir>/<session-id>.jsonl\n```\n\n### Finding Session Files\n\nSession transcripts are stored in `~/.claude/projects/` with the working directory path encoded:\n\n```bash\n# Example for /Users/jesse/Documents/GitHub/superpowers/superpowers\nSESSION_DIR=\"$HOME/.claude/projects/-Users-jesse-Documents-GitHub-superpowers-superpowers\"\n\n# Find recent sessions\nls -lt \"$SESSION_DIR\"/*.jsonl | head -5\n```\n\n### What It Shows\n\n- **Main session usage**: Token usage by the coordinator (you or main Claude instance)\n- **Per-subagent breakdown**: Each Task invocation with:\n  - Agent ID\n  - Description (extracted from prompt)\n  - Message count\n  - Input/output tokens\n  - Cache usage\n  - Estimated cost\n- **Totals**: Overall token usage and cost estimate\n\n### Understanding the Output\n\n- **High cache reads**: Good - means prompt caching is working\n- **High input tokens on main**: Expected - coordinator has full context\n- **Similar costs per subagent**: Expected - each gets similar task complexity\n- **Cost per task**: Typical range is $0.05-$0.15 per subagent depending on task\n\n## Troubleshooting\n\n### Skills Not Loading\n\n**Problem**: Skill not found when running headless tests\n\n**Solutions**:\n1. Ensure you're running FROM the superpowers directory: `cd /path/to/superpowers && tests/...`\n2. Check `~/.claude/settings.json` has `\"superpowers@superpowers-dev\": true` in `enabledPlugins`\n3. Verify skill exists in `skills/` directory\n\n### Permission Errors\n\n**Problem**: Claude blocked from writing files or accessing directories\n\n**Solutions**:\n1. Use `--permission-mode bypassPermissions` flag\n2. Use `--add-dir /path/to/temp/dir` to grant access to test directories\n3. Check file permissions on test directories\n\n### Test Timeouts\n\n**Problem**: Test takes too long and times out\n\n**Solutions**:\n1. Increase timeout: `timeout 1800 claude ...` (30 minutes)\n2. Check for infinite loops in skill logic\n3. Review subagent task complexity\n\n### Session File Not Found\n\n**Problem**: Can't find session transcript after test run\n\n**Solutions**:\n1. Check the correct project directory in `~/.claude/projects/`\n2. Use `find ~/.claude/projects -name \"*.jsonl\" -mmin -60` to find recent sessions\n3. Verify test actually ran (check for errors in test output)\n\n## Writing New Integration Tests\n\n### Template\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nsource \"$SCRIPT_DIR/test-helpers.sh\"\n\n# Create test project\nTEST_PROJECT=$(create_test_project)\ntrap \"cleanup_test_project $TEST_PROJECT\" EXIT\n\n# Set up test files...\ncd \"$TEST_PROJECT\"\n\n# Run Claude with skill\nPROMPT=\"Your test prompt here\"\ncd \"$SCRIPT_DIR/../..\" && timeout 1800 claude -p \"$PROMPT\" \\\n  --allowed-tools=all \\\n  --add-dir \"$TEST_PROJECT\" \\\n  --permission-mode bypassPermissions \\\n  2>&1 | tee output.txt\n\n# Find and analyze session\nWORKING_DIR_ESCAPED=$(echo \"$SCRIPT_DIR/../..\" | sed 's/\\\\//-/g' | sed 's/^-//')\nSESSION_DIR=\"$HOME/.claude/projects/$WORKING_DIR_ESCAPED\"\nSESSION_FILE=$(find \"$SESSION_DIR\" -name \"*.jsonl\" -type f -mmin -60 | sort -r | head -1)\n\n# Verify behavior by parsing session transcript\nif grep -q '\"name\":\"Skill\".*\"skill\":\"your-skill-name\"' \"$SESSION_FILE\"; then\n    echo \"[PASS] Skill was invoked\"\nfi\n\n# Show token analysis\npython3 \"$SCRIPT_DIR/analyze-token-usage.py\" \"$SESSION_FILE\"\n```\n\n### Best Practices\n\n1. **Always cleanup**: Use trap to cleanup temp directories\n2. **Parse transcripts**: Don't grep user-facing output - parse the `.jsonl` session file\n3. **Grant permissions**: Use `--permission-mode bypassPermissions` and `--add-dir`\n4. **Run from plugin dir**: Skills only load when running from the superpowers directory\n5. **Show token usage**: Always include token analysis for cost visibility\n6. **Test real behavior**: Verify actual files created, tests passing, commits made\n\n## Session Transcript Format\n\nSession transcripts are JSONL (JSON Lines) files where each line is a JSON object representing a message or tool result.\n\n### Key Fields\n\n```json\n{\n  \"type\": \"assistant\",\n  \"message\": {\n    \"content\": [...],\n    \"usage\": {\n      \"input_tokens\": 27,\n      \"output_tokens\": 3996,\n      \"cache_read_input_tokens\": 1213703\n    }\n  }\n}\n```\n\n### Tool Results\n\n```json\n{\n  \"type\": \"user\",\n  \"toolUseResult\": {\n    \"agentId\": \"3380c209\",\n    \"usage\": {\n      \"input_tokens\": 2,\n      \"output_tokens\": 787,\n      \"cache_read_input_tokens\": 24989\n    },\n    \"prompt\": \"You are implementing Task 1...\",\n    \"content\": [{\"type\": \"text\", \"text\": \"...\"}]\n  }\n}\n```\n\nThe `agentId` field links to subagent sessions, and the `usage` field contains token usage for that specific subagent invocation.\n"
  },
  {
    "path": "docs/windows/polyglot-hooks.md",
    "content": "# Cross-Platform Polyglot Hooks for Claude Code\n\nClaude Code plugins need hooks that work on Windows, macOS, and Linux. This document explains the polyglot wrapper technique that makes this possible.\n\n## The Problem\n\nClaude Code runs hook commands through the system's default shell:\n- **Windows**: CMD.exe\n- **macOS/Linux**: bash or sh\n\nThis creates several challenges:\n\n1. **Script execution**: Windows CMD can't execute `.sh` files directly - it tries to open them in a text editor\n2. **Path format**: Windows uses backslashes (`C:\\path`), Unix uses forward slashes (`/path`)\n3. **Environment variables**: `$VAR` syntax doesn't work in CMD\n4. **No `bash` in PATH**: Even with Git Bash installed, `bash` isn't in the PATH when CMD runs\n\n## The Solution: Polyglot `.cmd` Wrapper\n\nA polyglot script is valid syntax in multiple languages simultaneously. Our wrapper is valid in both CMD and bash:\n\n```cmd\n: << 'CMDBLOCK'\n@echo off\n\"C:\\Program Files\\Git\\bin\\bash.exe\" -l -c \"\\\"$(cygpath -u \\\"$CLAUDE_PLUGIN_ROOT\\\")/hooks/session-start.sh\\\"\"\nexit /b\nCMDBLOCK\n\n# Unix shell runs from here\n\"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh\"\n```\n\n### How It Works\n\n#### On Windows (CMD.exe)\n\n1. `: << 'CMDBLOCK'` - CMD sees `:` as a label (like `:label`) and ignores `<< 'CMDBLOCK'`\n2. `@echo off` - Suppresses command echoing\n3. The bash.exe command runs with:\n   - `-l` (login shell) to get proper PATH with Unix utilities\n   - `cygpath -u` converts Windows path to Unix format (`C:\\foo` → `/c/foo`)\n4. `exit /b` - Exits the batch script, stopping CMD here\n5. Everything after `CMDBLOCK` is never reached by CMD\n\n#### On Unix (bash/sh)\n\n1. `: << 'CMDBLOCK'` - `:` is a no-op, `<< 'CMDBLOCK'` starts a heredoc\n2. Everything until `CMDBLOCK` is consumed by the heredoc (ignored)\n3. `# Unix shell runs from here` - Comment\n4. The script runs directly with the Unix path\n\n## File Structure\n\n```\nhooks/\n├── hooks.json           # Points to the .cmd wrapper\n├── session-start.cmd    # Polyglot wrapper (cross-platform entry point)\n└── session-start.sh     # Actual hook logic (bash script)\n```\n\n### hooks.json\n\n```json\n{\n  \"hooks\": {\n    \"SessionStart\": [\n      {\n        \"matcher\": \"startup|resume|clear|compact\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.cmd\\\"\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nNote: The path must be quoted because `${CLAUDE_PLUGIN_ROOT}` may contain spaces on Windows (e.g., `C:\\Program Files\\...`).\n\n## Requirements\n\n### Windows\n- **Git for Windows** must be installed (provides `bash.exe` and `cygpath`)\n- Default installation path: `C:\\Program Files\\Git\\bin\\bash.exe`\n- If Git is installed elsewhere, the wrapper needs modification\n\n### Unix (macOS/Linux)\n- Standard bash or sh shell\n- The `.cmd` file must have execute permission (`chmod +x`)\n\n## Writing Cross-Platform Hook Scripts\n\nYour actual hook logic goes in the `.sh` file. To ensure it works on Windows (via Git Bash):\n\n### Do:\n- Use pure bash builtins when possible\n- Use `$(command)` instead of backticks\n- Quote all variable expansions: `\"$VAR\"`\n- Use `printf` or here-docs for output\n\n### Avoid:\n- External commands that may not be in PATH (sed, awk, grep)\n- If you must use them, they're available in Git Bash but ensure PATH is set up (use `bash -l`)\n\n### Example: JSON Escaping Without sed/awk\n\nInstead of:\n```bash\nescaped=$(echo \"$content\" | sed 's/\\\\/\\\\\\\\/g' | sed 's/\"/\\\\\"/g' | awk '{printf \"%s\\\\n\", $0}')\n```\n\nUse pure bash:\n```bash\nescape_for_json() {\n    local input=\"$1\"\n    local output=\"\"\n    local i char\n    for (( i=0; i<${#input}; i++ )); do\n        char=\"${input:$i:1}\"\n        case \"$char\" in\n            $'\\\\') output+='\\\\' ;;\n            '\"') output+='\\\"' ;;\n            $'\\n') output+='\\n' ;;\n            $'\\r') output+='\\r' ;;\n            $'\\t') output+='\\t' ;;\n            *) output+=\"$char\" ;;\n        esac\n    done\n    printf '%s' \"$output\"\n}\n```\n\n## Reusable Wrapper Pattern\n\nFor plugins with multiple hooks, you can create a generic wrapper that takes the script name as an argument:\n\n### run-hook.cmd\n```cmd\n: << 'CMDBLOCK'\n@echo off\nset \"SCRIPT_DIR=%~dp0\"\nset \"SCRIPT_NAME=%~1\"\n\"C:\\Program Files\\Git\\bin\\bash.exe\" -l -c \"cd \\\"$(cygpath -u \\\"%SCRIPT_DIR%\\\")\\\" && \\\"./%SCRIPT_NAME%\\\"\"\nexit /b\nCMDBLOCK\n\n# Unix shell runs from here\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nSCRIPT_NAME=\"$1\"\nshift\n\"${SCRIPT_DIR}/${SCRIPT_NAME}\" \"$@\"\n```\n\n### hooks.json using the reusable wrapper\n```json\n{\n  \"hooks\": {\n    \"SessionStart\": [\n      {\n        \"matcher\": \"startup\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\\\" session-start.sh\"\n          }\n        ]\n      }\n    ],\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\\\" validate-bash.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n## Troubleshooting\n\n### \"bash is not recognized\"\nCMD can't find bash. The wrapper uses the full path `C:\\Program Files\\Git\\bin\\bash.exe`. If Git is installed elsewhere, update the path.\n\n### \"cygpath: command not found\" or \"dirname: command not found\"\nBash isn't running as a login shell. Ensure `-l` flag is used.\n\n### Path has weird `\\/` in it\n`${CLAUDE_PLUGIN_ROOT}` expanded to a Windows path ending with backslash, then `/hooks/...` was appended. Use `cygpath` to convert the entire path.\n\n### Script opens in text editor instead of running\nThe hooks.json is pointing directly to the `.sh` file. Point to the `.cmd` wrapper instead.\n\n### Works in terminal but not as hook\nClaude Code may run hooks differently. Test by simulating the hook environment:\n```powershell\n$env:CLAUDE_PLUGIN_ROOT = \"C:\\path\\to\\plugin\"\ncmd /c \"C:\\path\\to\\plugin\\hooks\\session-start.cmd\"\n```\n\n## Related Issues\n\n- [anthropics/claude-code#9758](https://github.com/anthropics/claude-code/issues/9758) - .sh scripts open in editor on Windows\n- [anthropics/claude-code#3417](https://github.com/anthropics/claude-code/issues/3417) - Hooks don't work on Windows\n- [anthropics/claude-code#6023](https://github.com/anthropics/claude-code/issues/6023) - CLAUDE_PROJECT_DIR not found\n"
  },
  {
    "path": "gemini-extension.json",
    "content": "{\n  \"name\": \"superpowers\",\n  \"description\": \"Core skills library: TDD, debugging, collaboration patterns, and proven techniques\",\n  \"version\": \"5.0.0\",\n  \"contextFileName\": \"GEMINI.md\"\n}\n"
  },
  {
    "path": "hooks/hooks-cursor.json",
    "content": "{\n  \"version\": 1,\n  \"hooks\": {\n    \"sessionStart\": [\n      {\n        \"command\": \"./hooks/session-start\"\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "hooks/hooks.json",
    "content": "{\n  \"hooks\": {\n    \"SessionStart\": [\n      {\n        \"matcher\": \"startup|clear|compact\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\\\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\\\" session-start\",\n            \"async\": false\n          }\n        ]\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "hooks/run-hook.cmd",
    "content": ": << 'CMDBLOCK'\n@echo off\nREM Cross-platform polyglot wrapper for hook scripts.\nREM On Windows: cmd.exe runs the batch portion, which finds and calls bash.\nREM On Unix: the shell interprets this as a script (: is a no-op in bash).\nREM\nREM Hook scripts use extensionless filenames (e.g. \"session-start\" not\nREM \"session-start.sh\") so Claude Code's Windows auto-detection -- which\nREM prepends \"bash\" to any command containing .sh -- doesn't interfere.\nREM\nREM Usage: run-hook.cmd <script-name> [args...]\n\nif \"%~1\"==\"\" (\n    echo run-hook.cmd: missing script name >&2\n    exit /b 1\n)\n\nset \"HOOK_DIR=%~dp0\"\n\nREM Try Git for Windows bash in standard locations\nif exist \"C:\\Program Files\\Git\\bin\\bash.exe\" (\n    \"C:\\Program Files\\Git\\bin\\bash.exe\" \"%HOOK_DIR%%~1\" %2 %3 %4 %5 %6 %7 %8 %9\n    exit /b %ERRORLEVEL%\n)\nif exist \"C:\\Program Files (x86)\\Git\\bin\\bash.exe\" (\n    \"C:\\Program Files (x86)\\Git\\bin\\bash.exe\" \"%HOOK_DIR%%~1\" %2 %3 %4 %5 %6 %7 %8 %9\n    exit /b %ERRORLEVEL%\n)\n\nREM Try bash on PATH (e.g. user-installed Git Bash, MSYS2, Cygwin)\nwhere bash >nul 2>nul\nif %ERRORLEVEL% equ 0 (\n    bash \"%HOOK_DIR%%~1\" %2 %3 %4 %5 %6 %7 %8 %9\n    exit /b %ERRORLEVEL%\n)\n\nREM No bash found - exit silently rather than error\nREM (plugin still works, just without SessionStart context injection)\nexit /b 0\nCMDBLOCK\n\n# Unix: run the named script directly\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nSCRIPT_NAME=\"$1\"\nshift\nexec bash \"${SCRIPT_DIR}/${SCRIPT_NAME}\" \"$@\"\n"
  },
  {
    "path": "hooks/session-start",
    "content": "#!/usr/bin/env bash\n# SessionStart hook for superpowers plugin\n\nset -euo pipefail\n\n# Determine plugin root directory\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nPLUGIN_ROOT=\"$(cd \"${SCRIPT_DIR}/..\" && pwd)\"\n\n# Check if legacy skills directory exists and build warning\nwarning_message=\"\"\nlegacy_skills_dir=\"${HOME}/.config/superpowers/skills\"\nif [ -d \"$legacy_skills_dir\" ]; then\n    warning_message=\"\\n\\n<important-reminder>IN YOUR FIRST REPLY AFTER SEEING THIS MESSAGE YOU MUST TELL THE USER:⚠️ **WARNING:** Superpowers now uses Claude Code's skills system. Custom skills in ~/.config/superpowers/skills will not be read. Move custom skills to ~/.claude/skills instead. To make this message go away, remove ~/.config/superpowers/skills</important-reminder>\"\nfi\n\n# Read using-superpowers content\nusing_superpowers_content=$(cat \"${PLUGIN_ROOT}/skills/using-superpowers/SKILL.md\" 2>&1 || echo \"Error reading using-superpowers skill\")\n\n# Escape string for JSON embedding using bash parameter substitution.\n# Each ${s//old/new} is a single C-level pass - orders of magnitude\n# faster than the character-by-character loop this replaces.\nescape_for_json() {\n    local s=\"$1\"\n    s=\"${s//\\\\/\\\\\\\\}\"\n    s=\"${s//\\\"/\\\\\\\"}\"\n    s=\"${s//$'\\n'/\\\\n}\"\n    s=\"${s//$'\\r'/\\\\r}\"\n    s=\"${s//$'\\t'/\\\\t}\"\n    printf '%s' \"$s\"\n}\n\nusing_superpowers_escaped=$(escape_for_json \"$using_superpowers_content\")\nwarning_escaped=$(escape_for_json \"$warning_message\")\nsession_context=\"<EXTREMELY_IMPORTANT>\\nYou have superpowers.\\n\\n**Below is the full content of your 'superpowers:using-superpowers' skill - your introduction to using skills. For all other skills, use the 'Skill' tool:**\\n\\n${using_superpowers_escaped}\\n\\n${warning_escaped}\\n</EXTREMELY_IMPORTANT>\"\n\n# Output context injection as JSON.\n# Cursor hooks expect additional_context.\n# Claude Code hooks expect hookSpecificOutput.additionalContext.\n# Claude Code reads BOTH fields without deduplication, so we must only\n# emit the field consumed by the current platform to avoid double injection.\n#\n# Uses printf instead of heredoc (cat <<EOF) to work around a bash 5.3+\n# bug where heredoc variable expansion hangs when content exceeds ~512 bytes.\n# See: https://github.com/obra/superpowers/issues/571\nif [ -n \"${CURSOR_PLUGIN_ROOT:-}\" ]; then\n  # Cursor sets CURSOR_PLUGIN_ROOT (may also set CLAUDE_PLUGIN_ROOT) — emit additional_context\n  printf '{\\n  \"additional_context\": \"%s\"\\n}\\n' \"$session_context\"\nelif [ -n \"${CLAUDE_PLUGIN_ROOT:-}\" ]; then\n  # Claude Code sets CLAUDE_PLUGIN_ROOT — emit only hookSpecificOutput\n  printf '{\\n  \"hookSpecificOutput\": {\\n    \"hookEventName\": \"SessionStart\",\\n    \"additionalContext\": \"%s\"\\n  }\\n}\\n' \"$session_context\"\nelse\n  # Other platforms — emit additional_context as fallback\n  printf '{\\n  \"additional_context\": \"%s\"\\n}\\n' \"$session_context\"\nfi\n\nexit 0\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"superpowers\",\n  \"version\": \"5.0.4\",\n  \"type\": \"module\",\n  \"main\": \".opencode/plugins/superpowers.js\"\n}\n"
  },
  {
    "path": "skills/brainstorming/SKILL.md",
    "content": "---\nname: brainstorming\ndescription: \"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.\"\n---\n\n# Brainstorming Ideas Into Designs\n\nHelp turn ideas into fully formed designs and specs through natural collaborative dialogue.\n\nStart 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.\n\n<HARD-GATE>\nDo 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.\n</HARD-GATE>\n\n## Anti-Pattern: \"This Is Too Simple To Need A Design\"\n\nEvery 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.\n\n## Checklist\n\nYou MUST create a task for each of these items and complete them in order:\n\n1. **Explore project context** — check files, docs, recent commits\n2. **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.\n3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria\n4. **Propose 2-3 approaches** — with trade-offs and your recommendation\n5. **Present design** — in sections scaled to their complexity, get user approval after each section\n6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit\n7. **Spec review loop** — dispatch spec-document-reviewer subagent with precisely crafted review context (never your session history); fix issues and re-dispatch until approved (max 3 iterations, then surface to human)\n8. **User reviews written spec** — ask user to review the spec file before proceeding\n9. **Transition to implementation** — invoke writing-plans skill to create implementation plan\n\n## Process Flow\n\n```dot\ndigraph brainstorming {\n    \"Explore project context\" [shape=box];\n    \"Visual questions ahead?\" [shape=diamond];\n    \"Offer Visual Companion\\n(own message, no other content)\" [shape=box];\n    \"Ask clarifying questions\" [shape=box];\n    \"Propose 2-3 approaches\" [shape=box];\n    \"Present design sections\" [shape=box];\n    \"User approves design?\" [shape=diamond];\n    \"Write design doc\" [shape=box];\n    \"Spec review loop\" [shape=box];\n    \"Spec review passed?\" [shape=diamond];\n    \"User reviews spec?\" [shape=diamond];\n    \"Invoke writing-plans skill\" [shape=doublecircle];\n\n    \"Explore project context\" -> \"Visual questions ahead?\";\n    \"Visual questions ahead?\" -> \"Offer Visual Companion\\n(own message, no other content)\" [label=\"yes\"];\n    \"Visual questions ahead?\" -> \"Ask clarifying questions\" [label=\"no\"];\n    \"Offer Visual Companion\\n(own message, no other content)\" -> \"Ask clarifying questions\";\n    \"Ask clarifying questions\" -> \"Propose 2-3 approaches\";\n    \"Propose 2-3 approaches\" -> \"Present design sections\";\n    \"Present design sections\" -> \"User approves design?\";\n    \"User approves design?\" -> \"Present design sections\" [label=\"no, revise\"];\n    \"User approves design?\" -> \"Write design doc\" [label=\"yes\"];\n    \"Write design doc\" -> \"Spec review loop\";\n    \"Spec review loop\" -> \"Spec review passed?\";\n    \"Spec review passed?\" -> \"Spec review loop\" [label=\"issues found,\\nfix and re-dispatch\"];\n    \"Spec review passed?\" -> \"User reviews spec?\" [label=\"approved\"];\n    \"User reviews spec?\" -> \"Write design doc\" [label=\"changes requested\"];\n    \"User reviews spec?\" -> \"Invoke writing-plans skill\" [label=\"approved\"];\n}\n```\n\n**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.\n\n## The Process\n\n**Understanding the idea:**\n\n- Check out the current project state first (files, docs, recent commits)\n- 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.\n- 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.\n- For appropriately-scoped projects, ask questions one at a time to refine the idea\n- Prefer multiple choice questions when possible, but open-ended is fine too\n- Only one question per message - if a topic needs more exploration, break it into multiple questions\n- Focus on understanding: purpose, constraints, success criteria\n\n**Exploring approaches:**\n\n- Propose 2-3 different approaches with trade-offs\n- Present options conversationally with your recommendation and reasoning\n- Lead with your recommended option and explain why\n\n**Presenting the design:**\n\n- Once you believe you understand what you're building, present the design\n- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced\n- Ask after each section whether it looks right so far\n- Cover: architecture, components, data flow, error handling, testing\n- Be ready to go back and clarify if something doesn't make sense\n\n**Design for isolation and clarity:**\n\n- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently\n- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on?\n- 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.\n- 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.\n\n**Working in existing codebases:**\n\n- Explore the current structure before proposing changes. Follow existing patterns.\n- 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.\n- Don't propose unrelated refactoring. Stay focused on what serves the current goal.\n\n## After the Design\n\n**Documentation:**\n\n- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`\n  - (User preferences for spec location override this default)\n- Use elements-of-style:writing-clearly-and-concisely skill if available\n- Commit the design document to git\n\n**Spec Review Loop:**\nAfter writing the spec document:\n\n1. Dispatch spec-document-reviewer subagent (see spec-document-reviewer-prompt.md)\n2. If Issues Found: fix, re-dispatch, repeat until Approved\n3. If loop exceeds 3 iterations, surface to human for guidance\n\n**User Review Gate:**\nAfter the spec review loop passes, ask the user to review the written spec before proceeding:\n\n> \"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.\"\n\nWait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.\n\n**Implementation:**\n\n- Invoke the writing-plans skill to create a detailed implementation plan\n- Do NOT invoke any other skill. writing-plans is the next step.\n\n## Key Principles\n\n- **One question at a time** - Don't overwhelm with multiple questions\n- **Multiple choice preferred** - Easier to answer than open-ended when possible\n- **YAGNI ruthlessly** - Remove unnecessary features from all designs\n- **Explore alternatives** - Always propose 2-3 approaches before settling\n- **Incremental validation** - Present design, get approval before moving on\n- **Be flexible** - Go back and clarify when something doesn't make sense\n\n## Visual Companion\n\nA 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.\n\n**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent:\n> \"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)\"\n\n**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.\n\n**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?**\n\n- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs\n- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions\n\nA 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.\n\nIf they agree to the companion, read the detailed guide before proceeding:\n`skills/brainstorming/visual-companion.md`\n"
  },
  {
    "path": "skills/brainstorming/scripts/frame-template.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <title>Superpowers Brainstorming</title>\n  <style>\n    /*\n     * BRAINSTORM COMPANION FRAME TEMPLATE\n     *\n     * This template provides a consistent frame with:\n     * - OS-aware light/dark theming\n     * - Fixed header and selection indicator bar\n     * - Scrollable main content area\n     * - CSS helpers for common UI patterns\n     *\n     * Content is injected via placeholder comment in #claude-content.\n     */\n\n    * { box-sizing: border-box; margin: 0; padding: 0; }\n    html, body { height: 100%; overflow: hidden; }\n\n    /* ===== THEME VARIABLES ===== */\n    :root {\n      --bg-primary: #f5f5f7;\n      --bg-secondary: #ffffff;\n      --bg-tertiary: #e5e5e7;\n      --border: #d1d1d6;\n      --text-primary: #1d1d1f;\n      --text-secondary: #86868b;\n      --text-tertiary: #aeaeb2;\n      --accent: #0071e3;\n      --accent-hover: #0077ed;\n      --success: #34c759;\n      --warning: #ff9f0a;\n      --error: #ff3b30;\n      --selected-bg: #e8f4fd;\n      --selected-border: #0071e3;\n    }\n\n    @media (prefers-color-scheme: dark) {\n      :root {\n        --bg-primary: #1d1d1f;\n        --bg-secondary: #2d2d2f;\n        --bg-tertiary: #3d3d3f;\n        --border: #424245;\n        --text-primary: #f5f5f7;\n        --text-secondary: #86868b;\n        --text-tertiary: #636366;\n        --accent: #0a84ff;\n        --accent-hover: #409cff;\n        --selected-bg: rgba(10, 132, 255, 0.15);\n        --selected-border: #0a84ff;\n      }\n    }\n\n    body {\n      font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;\n      background: var(--bg-primary);\n      color: var(--text-primary);\n      display: flex;\n      flex-direction: column;\n      line-height: 1.5;\n    }\n\n    /* ===== FRAME STRUCTURE ===== */\n    .header {\n      background: var(--bg-secondary);\n      padding: 0.5rem 1.5rem;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n      border-bottom: 1px solid var(--border);\n      flex-shrink: 0;\n    }\n    .header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }\n    .header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }\n    .header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }\n\n    .main { flex: 1; overflow-y: auto; }\n    #claude-content { padding: 2rem; min-height: 100%; }\n\n    .indicator-bar {\n      background: var(--bg-secondary);\n      border-top: 1px solid var(--border);\n      padding: 0.5rem 1.5rem;\n      flex-shrink: 0;\n      text-align: center;\n    }\n    .indicator-bar span {\n      font-size: 0.75rem;\n      color: var(--text-secondary);\n    }\n    .indicator-bar .selected-text {\n      color: var(--accent);\n      font-weight: 500;\n    }\n\n    /* ===== TYPOGRAPHY ===== */\n    h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }\n    h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }\n    .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }\n    .section { margin-bottom: 2rem; }\n    .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }\n\n    /* ===== OPTIONS (for A/B/C choices) ===== */\n    .options { display: flex; flex-direction: column; gap: 0.75rem; }\n    .option {\n      background: var(--bg-secondary);\n      border: 2px solid var(--border);\n      border-radius: 12px;\n      padding: 1rem 1.25rem;\n      cursor: pointer;\n      transition: all 0.15s ease;\n      display: flex;\n      align-items: flex-start;\n      gap: 1rem;\n    }\n    .option:hover { border-color: var(--accent); }\n    .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }\n    .option .letter {\n      background: var(--bg-tertiary);\n      color: var(--text-secondary);\n      width: 1.75rem; height: 1.75rem;\n      border-radius: 6px;\n      display: flex; align-items: center; justify-content: center;\n      font-weight: 600; font-size: 0.85rem; flex-shrink: 0;\n    }\n    .option.selected .letter { background: var(--accent); color: white; }\n    .option .content { flex: 1; }\n    .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }\n    .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }\n\n    /* ===== CARDS (for showing designs/mockups) ===== */\n    .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }\n    .card {\n      background: var(--bg-secondary);\n      border: 1px solid var(--border);\n      border-radius: 12px;\n      overflow: hidden;\n      cursor: pointer;\n      transition: all 0.15s ease;\n    }\n    .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }\n    .card.selected { border-color: var(--selected-border); border-width: 2px; }\n    .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }\n    .card-body { padding: 1rem; }\n    .card-body h3 { margin-bottom: 0.25rem; }\n    .card-body p { color: var(--text-secondary); font-size: 0.85rem; }\n\n    /* ===== MOCKUP CONTAINER ===== */\n    .mockup {\n      background: var(--bg-secondary);\n      border: 1px solid var(--border);\n      border-radius: 12px;\n      overflow: hidden;\n      margin-bottom: 1.5rem;\n    }\n    .mockup-header {\n      background: var(--bg-tertiary);\n      padding: 0.5rem 1rem;\n      font-size: 0.75rem;\n      color: var(--text-secondary);\n      border-bottom: 1px solid var(--border);\n    }\n    .mockup-body { padding: 1.5rem; }\n\n    /* ===== SPLIT VIEW (side-by-side comparison) ===== */\n    .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }\n    @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }\n\n    /* ===== PROS/CONS ===== */\n    .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }\n    .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }\n    .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }\n    .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }\n    .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }\n    .pros li, .cons li { margin-bottom: 0.25rem; }\n\n    /* ===== PLACEHOLDER (for mockup areas) ===== */\n    .placeholder {\n      background: var(--bg-tertiary);\n      border: 2px dashed var(--border);\n      border-radius: 8px;\n      padding: 2rem;\n      text-align: center;\n      color: var(--text-tertiary);\n    }\n\n    /* ===== INLINE MOCKUP ELEMENTS ===== */\n    .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }\n    .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }\n    .mock-content { padding: 1.5rem; flex: 1; }\n    .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }\n    .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }\n  </style>\n</head>\n<body>\n  <div class=\"header\">\n    <h1><a href=\"https://github.com/obra/superpowers\" style=\"color: inherit; text-decoration: none;\">Superpowers Brainstorming</a></h1>\n    <div class=\"status\">Connected</div>\n  </div>\n\n  <div class=\"main\">\n    <div id=\"claude-content\">\n      <!-- CONTENT -->\n    </div>\n  </div>\n\n  <div class=\"indicator-bar\">\n    <span id=\"indicator-text\">Click an option above, then return to the terminal</span>\n  </div>\n\n</body>\n</html>\n"
  },
  {
    "path": "skills/brainstorming/scripts/helper.js",
    "content": "(function() {\n  const WS_URL = 'ws://' + window.location.host;\n  let ws = null;\n  let eventQueue = [];\n\n  function connect() {\n    ws = new WebSocket(WS_URL);\n\n    ws.onopen = () => {\n      eventQueue.forEach(e => ws.send(JSON.stringify(e)));\n      eventQueue = [];\n    };\n\n    ws.onmessage = (msg) => {\n      const data = JSON.parse(msg.data);\n      if (data.type === 'reload') {\n        window.location.reload();\n      }\n    };\n\n    ws.onclose = () => {\n      setTimeout(connect, 1000);\n    };\n  }\n\n  function sendEvent(event) {\n    event.timestamp = Date.now();\n    if (ws && ws.readyState === WebSocket.OPEN) {\n      ws.send(JSON.stringify(event));\n    } else {\n      eventQueue.push(event);\n    }\n  }\n\n  // Capture clicks on choice elements\n  document.addEventListener('click', (e) => {\n    const target = e.target.closest('[data-choice]');\n    if (!target) return;\n\n    sendEvent({\n      type: 'click',\n      text: target.textContent.trim(),\n      choice: target.dataset.choice,\n      id: target.id || null\n    });\n\n    // Update indicator bar (defer so toggleSelect runs first)\n    setTimeout(() => {\n      const indicator = document.getElementById('indicator-text');\n      if (!indicator) return;\n      const container = target.closest('.options') || target.closest('.cards');\n      const selected = container ? container.querySelectorAll('.selected') : [];\n      if (selected.length === 0) {\n        indicator.textContent = 'Click an option above, then return to the terminal';\n      } else if (selected.length === 1) {\n        const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice;\n        indicator.innerHTML = '<span class=\"selected-text\">' + label + ' selected</span> — return to terminal to continue';\n      } else {\n        indicator.innerHTML = '<span class=\"selected-text\">' + selected.length + ' selected</span> — return to terminal to continue';\n      }\n    }, 0);\n  });\n\n  // Frame UI: selection tracking\n  window.selectedChoice = null;\n\n  window.toggleSelect = function(el) {\n    const container = el.closest('.options') || el.closest('.cards');\n    const multi = container && container.dataset.multiselect !== undefined;\n    if (container && !multi) {\n      container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));\n    }\n    if (multi) {\n      el.classList.toggle('selected');\n    } else {\n      el.classList.add('selected');\n    }\n    window.selectedChoice = el.dataset.choice;\n  };\n\n  // Expose API for explicit use\n  window.brainstorm = {\n    send: sendEvent,\n    choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })\n  };\n\n  connect();\n})();\n"
  },
  {
    "path": "skills/brainstorming/scripts/server.cjs",
    "content": "const crypto = require('crypto');\nconst http = require('http');\nconst fs = require('fs');\nconst path = require('path');\n\n// ========== WebSocket Protocol (RFC 6455) ==========\n\nconst OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };\nconst WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';\n\nfunction computeAcceptKey(clientKey) {\n  return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');\n}\n\nfunction encodeFrame(opcode, payload) {\n  const fin = 0x80;\n  const len = payload.length;\n  let header;\n\n  if (len < 126) {\n    header = Buffer.alloc(2);\n    header[0] = fin | opcode;\n    header[1] = len;\n  } else if (len < 65536) {\n    header = Buffer.alloc(4);\n    header[0] = fin | opcode;\n    header[1] = 126;\n    header.writeUInt16BE(len, 2);\n  } else {\n    header = Buffer.alloc(10);\n    header[0] = fin | opcode;\n    header[1] = 127;\n    header.writeBigUInt64BE(BigInt(len), 2);\n  }\n\n  return Buffer.concat([header, payload]);\n}\n\nfunction decodeFrame(buffer) {\n  if (buffer.length < 2) return null;\n\n  const secondByte = buffer[1];\n  const opcode = buffer[0] & 0x0F;\n  const masked = (secondByte & 0x80) !== 0;\n  let payloadLen = secondByte & 0x7F;\n  let offset = 2;\n\n  if (!masked) throw new Error('Client frames must be masked');\n\n  if (payloadLen === 126) {\n    if (buffer.length < 4) return null;\n    payloadLen = buffer.readUInt16BE(2);\n    offset = 4;\n  } else if (payloadLen === 127) {\n    if (buffer.length < 10) return null;\n    payloadLen = Number(buffer.readBigUInt64BE(2));\n    offset = 10;\n  }\n\n  const maskOffset = offset;\n  const dataOffset = offset + 4;\n  const totalLen = dataOffset + payloadLen;\n  if (buffer.length < totalLen) return null;\n\n  const mask = buffer.slice(maskOffset, dataOffset);\n  const data = Buffer.alloc(payloadLen);\n  for (let i = 0; i < payloadLen; i++) {\n    data[i] = buffer[dataOffset + i] ^ mask[i % 4];\n  }\n\n  return { opcode, payload: data, bytesConsumed: totalLen };\n}\n\n// ========== Configuration ==========\n\nconst PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));\nconst HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';\nconst URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);\nconst SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';\nconst OWNER_PID = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;\n\nconst MIME_TYPES = {\n  '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',\n  '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',\n  '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'\n};\n\n// ========== Templates and Constants ==========\n\nconst WAITING_PAGE = `<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\"><title>Brainstorm Companion</title>\n<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }\nh1 { color: #333; } p { color: #666; }</style>\n</head>\n<body><h1>Brainstorm Companion</h1>\n<p>Waiting for the agent to push a screen...</p></body></html>`;\n\nconst frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');\nconst helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');\nconst helperInjection = '<script>\\n' + helperScript + '\\n</script>';\n\n// ========== Helper Functions ==========\n\nfunction isFullDocument(html) {\n  const trimmed = html.trimStart().toLowerCase();\n  return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');\n}\n\nfunction wrapInFrame(content) {\n  return frameTemplate.replace('<!-- CONTENT -->', content);\n}\n\nfunction getNewestScreen() {\n  const files = fs.readdirSync(SCREEN_DIR)\n    .filter(f => f.endsWith('.html'))\n    .map(f => {\n      const fp = path.join(SCREEN_DIR, f);\n      return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };\n    })\n    .sort((a, b) => b.mtime - a.mtime);\n  return files.length > 0 ? files[0].path : null;\n}\n\n// ========== HTTP Request Handler ==========\n\nfunction handleRequest(req, res) {\n  touchActivity();\n  if (req.method === 'GET' && req.url === '/') {\n    const screenFile = getNewestScreen();\n    let html = screenFile\n      ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))\n      : WAITING_PAGE;\n\n    if (html.includes('</body>')) {\n      html = html.replace('</body>', helperInjection + '\\n</body>');\n    } else {\n      html += helperInjection;\n    }\n\n    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n    res.end(html);\n  } else if (req.method === 'GET' && req.url.startsWith('/files/')) {\n    const fileName = req.url.slice(7);\n    const filePath = path.join(SCREEN_DIR, path.basename(fileName));\n    if (!fs.existsSync(filePath)) {\n      res.writeHead(404);\n      res.end('Not found');\n      return;\n    }\n    const ext = path.extname(filePath).toLowerCase();\n    const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n    res.writeHead(200, { 'Content-Type': contentType });\n    res.end(fs.readFileSync(filePath));\n  } else {\n    res.writeHead(404);\n    res.end('Not found');\n  }\n}\n\n// ========== WebSocket Connection Handling ==========\n\nconst clients = new Set();\n\nfunction handleUpgrade(req, socket) {\n  const key = req.headers['sec-websocket-key'];\n  if (!key) { socket.destroy(); return; }\n\n  const accept = computeAcceptKey(key);\n  socket.write(\n    'HTTP/1.1 101 Switching Protocols\\r\\n' +\n    'Upgrade: websocket\\r\\n' +\n    'Connection: Upgrade\\r\\n' +\n    'Sec-WebSocket-Accept: ' + accept + '\\r\\n\\r\\n'\n  );\n\n  let buffer = Buffer.alloc(0);\n  clients.add(socket);\n\n  socket.on('data', (chunk) => {\n    buffer = Buffer.concat([buffer, chunk]);\n    while (buffer.length > 0) {\n      let result;\n      try {\n        result = decodeFrame(buffer);\n      } catch (e) {\n        socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));\n        clients.delete(socket);\n        return;\n      }\n      if (!result) break;\n      buffer = buffer.slice(result.bytesConsumed);\n\n      switch (result.opcode) {\n        case OPCODES.TEXT:\n          handleMessage(result.payload.toString());\n          break;\n        case OPCODES.CLOSE:\n          socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));\n          clients.delete(socket);\n          return;\n        case OPCODES.PING:\n          socket.write(encodeFrame(OPCODES.PONG, result.payload));\n          break;\n        case OPCODES.PONG:\n          break;\n        default: {\n          const closeBuf = Buffer.alloc(2);\n          closeBuf.writeUInt16BE(1003);\n          socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));\n          clients.delete(socket);\n          return;\n        }\n      }\n    }\n  });\n\n  socket.on('close', () => clients.delete(socket));\n  socket.on('error', () => clients.delete(socket));\n}\n\nfunction handleMessage(text) {\n  let event;\n  try {\n    event = JSON.parse(text);\n  } catch (e) {\n    console.error('Failed to parse WebSocket message:', e.message);\n    return;\n  }\n  touchActivity();\n  console.log(JSON.stringify({ source: 'user-event', ...event }));\n  if (event.choice) {\n    const eventsFile = path.join(SCREEN_DIR, '.events');\n    fs.appendFileSync(eventsFile, JSON.stringify(event) + '\\n');\n  }\n}\n\nfunction broadcast(msg) {\n  const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));\n  for (const socket of clients) {\n    try { socket.write(frame); } catch (e) { clients.delete(socket); }\n  }\n}\n\n// ========== Activity Tracking ==========\n\nconst IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nlet lastActivity = Date.now();\n\nfunction touchActivity() {\n  lastActivity = Date.now();\n}\n\n// ========== File Watching ==========\n\nconst debounceTimers = new Map();\n\n// ========== Server Startup ==========\n\nfunction startServer() {\n  if (!fs.existsSync(SCREEN_DIR)) fs.mkdirSync(SCREEN_DIR, { recursive: true });\n\n  // Track known files to distinguish new screens from updates.\n  // macOS fs.watch reports 'rename' for both new files and overwrites,\n  // so we can't rely on eventType alone.\n  const knownFiles = new Set(\n    fs.readdirSync(SCREEN_DIR).filter(f => f.endsWith('.html'))\n  );\n\n  const server = http.createServer(handleRequest);\n  server.on('upgrade', handleUpgrade);\n\n  const watcher = fs.watch(SCREEN_DIR, (eventType, filename) => {\n    if (!filename || !filename.endsWith('.html')) return;\n\n    if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));\n    debounceTimers.set(filename, setTimeout(() => {\n      debounceTimers.delete(filename);\n      const filePath = path.join(SCREEN_DIR, filename);\n\n      if (!fs.existsSync(filePath)) return; // file was deleted\n      touchActivity();\n\n      if (!knownFiles.has(filename)) {\n        knownFiles.add(filename);\n        const eventsFile = path.join(SCREEN_DIR, '.events');\n        if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);\n        console.log(JSON.stringify({ type: 'screen-added', file: filePath }));\n      } else {\n        console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));\n      }\n\n      broadcast({ type: 'reload' });\n    }, 100));\n  });\n  watcher.on('error', (err) => console.error('fs.watch error:', err.message));\n\n  function shutdown(reason) {\n    console.log(JSON.stringify({ type: 'server-stopped', reason }));\n    const infoFile = path.join(SCREEN_DIR, '.server-info');\n    if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);\n    fs.writeFileSync(\n      path.join(SCREEN_DIR, '.server-stopped'),\n      JSON.stringify({ reason, timestamp: Date.now() }) + '\\n'\n    );\n    watcher.close();\n    clearInterval(lifecycleCheck);\n    server.close(() => process.exit(0));\n  }\n\n  function ownerAlive() {\n    if (!OWNER_PID) return true;\n    try { process.kill(OWNER_PID, 0); return true; } catch (e) { return false; }\n  }\n\n  // Check every 60s: exit if owner process died or idle for 30 minutes\n  const lifecycleCheck = setInterval(() => {\n    if (!ownerAlive()) shutdown('owner process exited');\n    else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');\n  }, 60 * 1000);\n  lifecycleCheck.unref();\n\n  server.listen(PORT, HOST, () => {\n    const info = JSON.stringify({\n      type: 'server-started', port: Number(PORT), host: HOST,\n      url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,\n      screen_dir: SCREEN_DIR\n    });\n    console.log(info);\n    fs.writeFileSync(path.join(SCREEN_DIR, '.server-info'), info + '\\n');\n  });\n}\n\nif (require.main === module) {\n  startServer();\n}\n\nmodule.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };\n"
  },
  {
    "path": "skills/brainstorming/scripts/start-server.sh",
    "content": "#!/usr/bin/env bash\n# Start the brainstorm server and output connection info\n# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]\n#\n# Starts server on a random high port, outputs JSON with URL.\n# Each session gets its own directory to avoid conflicts.\n#\n# Options:\n#   --project-dir <path>  Store session files under <path>/.superpowers/brainstorm/\n#                         instead of /tmp. Files persist after server stops.\n#   --host <bind-host>    Host/interface to bind (default: 127.0.0.1).\n#                         Use 0.0.0.0 in remote/containerized environments.\n#   --url-host <host>     Hostname shown in returned URL JSON.\n#   --foreground          Run server in the current terminal (no backgrounding).\n#   --background          Force background mode (overrides Codex auto-foreground).\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\n# Parse arguments\nPROJECT_DIR=\"\"\nFOREGROUND=\"false\"\nFORCE_BACKGROUND=\"false\"\nBIND_HOST=\"127.0.0.1\"\nURL_HOST=\"\"\nwhile [[ $# -gt 0 ]]; do\n  case \"$1\" in\n    --project-dir)\n      PROJECT_DIR=\"$2\"\n      shift 2\n      ;;\n    --host)\n      BIND_HOST=\"$2\"\n      shift 2\n      ;;\n    --url-host)\n      URL_HOST=\"$2\"\n      shift 2\n      ;;\n    --foreground|--no-daemon)\n      FOREGROUND=\"true\"\n      shift\n      ;;\n    --background|--daemon)\n      FORCE_BACKGROUND=\"true\"\n      shift\n      ;;\n    *)\n      echo \"{\\\"error\\\": \\\"Unknown argument: $1\\\"}\"\n      exit 1\n      ;;\n  esac\ndone\n\nif [[ -z \"$URL_HOST\" ]]; then\n  if [[ \"$BIND_HOST\" == \"127.0.0.1\" || \"$BIND_HOST\" == \"localhost\" ]]; then\n    URL_HOST=\"localhost\"\n  else\n    URL_HOST=\"$BIND_HOST\"\n  fi\nfi\n\n# Some environments reap detached/background processes. Auto-foreground when detected.\nif [[ -n \"${CODEX_CI:-}\" && \"$FOREGROUND\" != \"true\" && \"$FORCE_BACKGROUND\" != \"true\" ]]; then\n  FOREGROUND=\"true\"\nfi\n\n# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.\nif [[ \"$FOREGROUND\" != \"true\" && \"$FORCE_BACKGROUND\" != \"true\" ]]; then\n  case \"${OSTYPE:-}\" in\n    msys*|cygwin*|mingw*) FOREGROUND=\"true\" ;;\n  esac\n  if [[ -n \"${MSYSTEM:-}\" ]]; then\n    FOREGROUND=\"true\"\n  fi\nfi\n\n# Generate unique session directory\nSESSION_ID=\"$$-$(date +%s)\"\n\nif [[ -n \"$PROJECT_DIR\" ]]; then\n  SCREEN_DIR=\"${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}\"\nelse\n  SCREEN_DIR=\"/tmp/brainstorm-${SESSION_ID}\"\nfi\n\nPID_FILE=\"${SCREEN_DIR}/.server.pid\"\nLOG_FILE=\"${SCREEN_DIR}/.server.log\"\n\n# Create fresh session directory\nmkdir -p \"$SCREEN_DIR\"\n\n# Kill any existing server\nif [[ -f \"$PID_FILE\" ]]; then\n  old_pid=$(cat \"$PID_FILE\")\n  kill \"$old_pid\" 2>/dev/null\n  rm -f \"$PID_FILE\"\nfi\n\ncd \"$SCRIPT_DIR\"\n\n# Resolve the harness PID (grandparent of this script).\n# $PPID is the ephemeral shell the harness spawned to run us — it dies\n# when this script exits. The harness itself is $PPID's parent.\nOWNER_PID=\"$(ps -o ppid= -p \"$PPID\" 2>/dev/null | tr -d ' ')\"\nif [[ -z \"$OWNER_PID\" || \"$OWNER_PID\" == \"1\" ]]; then\n  OWNER_PID=\"$PPID\"\nfi\n\n# On Windows/MSYS2, the MSYS2 PID namespace is invisible to Node.js.\n# Skip owner-PID monitoring — the 30-minute idle timeout prevents orphans.\ncase \"${OSTYPE:-}\" in\n  msys*|cygwin*|mingw*) OWNER_PID=\"\" ;;\nesac\n\n# Foreground mode for environments that reap detached/background processes.\nif [[ \"$FOREGROUND\" == \"true\" ]]; then\n  echo \"$$\" > \"$PID_FILE\"\n  env BRAINSTORM_DIR=\"$SCREEN_DIR\" BRAINSTORM_HOST=\"$BIND_HOST\" BRAINSTORM_URL_HOST=\"$URL_HOST\" BRAINSTORM_OWNER_PID=\"$OWNER_PID\" node server.cjs\n  exit $?\nfi\n\n# Start server, capturing output to log file\n# Use nohup to survive shell exit; disown to remove from job table\nnohup env BRAINSTORM_DIR=\"$SCREEN_DIR\" BRAINSTORM_HOST=\"$BIND_HOST\" BRAINSTORM_URL_HOST=\"$URL_HOST\" BRAINSTORM_OWNER_PID=\"$OWNER_PID\" node server.cjs > \"$LOG_FILE\" 2>&1 &\nSERVER_PID=$!\ndisown \"$SERVER_PID\" 2>/dev/null\necho \"$SERVER_PID\" > \"$PID_FILE\"\n\n# Wait for server-started message (check log file)\nfor i in {1..50}; do\n  if grep -q \"server-started\" \"$LOG_FILE\" 2>/dev/null; then\n    # Verify server is still alive after a short window (catches process reapers)\n    alive=\"true\"\n    for _ in {1..20}; do\n      if ! kill -0 \"$SERVER_PID\" 2>/dev/null; then\n        alive=\"false\"\n        break\n      fi\n      sleep 0.1\n    done\n    if [[ \"$alive\" != \"true\" ]]; then\n      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\\\"}\"\n      exit 1\n    fi\n    grep \"server-started\" \"$LOG_FILE\" | head -1\n    exit 0\n  fi\n  sleep 0.1\ndone\n\n# Timeout - server didn't start\necho '{\"error\": \"Server failed to start within 5 seconds\"}'\nexit 1\n"
  },
  {
    "path": "skills/brainstorming/scripts/stop-server.sh",
    "content": "#!/usr/bin/env bash\n# Stop the brainstorm server and clean up\n# Usage: stop-server.sh <screen_dir>\n#\n# Kills the server process. Only deletes session directory if it's\n# under /tmp (ephemeral). Persistent directories (.superpowers/) are\n# kept so mockups can be reviewed later.\n\nSCREEN_DIR=\"$1\"\n\nif [[ -z \"$SCREEN_DIR\" ]]; then\n  echo '{\"error\": \"Usage: stop-server.sh <screen_dir>\"}'\n  exit 1\nfi\n\nPID_FILE=\"${SCREEN_DIR}/.server.pid\"\n\nif [[ -f \"$PID_FILE\" ]]; then\n  pid=$(cat \"$PID_FILE\")\n\n  # Try to stop gracefully, fallback to force if still alive\n  kill \"$pid\" 2>/dev/null || true\n\n  # Wait for graceful shutdown (up to ~2s)\n  for i in {1..20}; do\n    if ! kill -0 \"$pid\" 2>/dev/null; then\n      break\n    fi\n    sleep 0.1\n  done\n\n  # If still running, escalate to SIGKILL\n  if kill -0 \"$pid\" 2>/dev/null; then\n    kill -9 \"$pid\" 2>/dev/null || true\n\n    # Give SIGKILL a moment to take effect\n    sleep 0.1\n  fi\n\n  if kill -0 \"$pid\" 2>/dev/null; then\n    echo '{\"status\": \"failed\", \"error\": \"process still running\"}'\n    exit 1\n  fi\n\n  rm -f \"$PID_FILE\" \"${SCREEN_DIR}/.server.log\"\n\n  # Only delete ephemeral /tmp directories\n  if [[ \"$SCREEN_DIR\" == /tmp/* ]]; then\n    rm -rf \"$SCREEN_DIR\"\n  fi\n\n  echo '{\"status\": \"stopped\"}'\nelse\n  echo '{\"status\": \"not_running\"}'\nfi\n"
  },
  {
    "path": "skills/brainstorming/spec-document-reviewer-prompt.md",
    "content": "# Spec Document Reviewer Prompt Template\n\nUse this template when dispatching a spec document reviewer subagent.\n\n**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.\n\n**Dispatch after:** Spec document is written to docs/superpowers/specs/\n\n```\nTask tool (general-purpose):\n  description: \"Review spec document\"\n  prompt: |\n    You are a spec document reviewer. Verify this spec is complete and ready for planning.\n\n    **Spec to review:** [SPEC_FILE_PATH]\n\n    ## What to Check\n\n    | Category | What to Look For |\n    |----------|------------------|\n    | Completeness | TODOs, placeholders, \"TBD\", incomplete sections |\n    | Consistency | Internal contradictions, conflicting requirements |\n    | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing |\n    | Scope | Focused enough for a single plan — not covering multiple independent subsystems |\n    | YAGNI | Unrequested features, over-engineering |\n\n    ## Calibration\n\n    **Only flag issues that would cause real problems during implementation planning.**\n    A missing section, a contradiction, or a requirement so ambiguous it could be\n    interpreted two different ways — those are issues. Minor wording improvements,\n    stylistic preferences, and \"sections less detailed than others\" are not.\n\n    Approve unless there are serious gaps that would lead to a flawed plan.\n\n    ## Output Format\n\n    ## Spec Review\n\n    **Status:** Approved | Issues Found\n\n    **Issues (if any):**\n    - [Section X]: [specific issue] - [why it matters for planning]\n\n    **Recommendations (advisory, do not block approval):**\n    - [suggestions for improvement]\n```\n\n**Reviewer returns:** Status, Issues (if any), Recommendations\n"
  },
  {
    "path": "skills/brainstorming/visual-companion.md",
    "content": "# Visual Companion Guide\n\nBrowser-based visual brainstorming companion for showing mockups, diagrams, and options.\n\n## When to Use\n\nDecide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**\n\n**Use the browser** when the content itself is visual:\n\n- **UI mockups** — wireframes, layouts, navigation structures, component designs\n- **Architecture diagrams** — system components, data flow, relationship maps\n- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions\n- **Design polish** — when the question is about look and feel, spacing, visual hierarchy\n- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams\n\n**Use the terminal** when the content is text or tabular:\n\n- **Requirements and scope questions** — \"what does X mean?\", \"which features are in scope?\"\n- **Conceptual A/B/C choices** — picking between approaches described in words\n- **Tradeoff lists** — pros/cons, comparison tables\n- **Technical decisions** — API design, data modeling, architectural approach selection\n- **Clarifying questions** — anything where the answer is words, not a visual preference\n\nA 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.\n\n## How It Works\n\nThe server watches a directory for HTML files and serves the newest one to the browser. You write HTML content, the user sees it in their browser and can click to select options. Selections are recorded to a `.events` file that you read on your next turn.\n\n**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, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.\n\n## Starting a Session\n\n```bash\n# Start server with persistence (mockups saved to project)\nscripts/start-server.sh --project-dir /path/to/project\n\n# Returns: {\"type\":\"server-started\",\"port\":52341,\"url\":\"http://localhost:52341\",\n#           \"screen_dir\":\"/path/to/project/.superpowers/brainstorm/12345-1706000000\"}\n```\n\nSave `screen_dir` from the response. Tell user to open the URL.\n\n**Finding connection info:** The server writes its startup JSON to `$SCREEN_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.\n\n**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.\n\n**Launching the server by platform:**\n\n**Claude Code (macOS / Linux):**\n```bash\n# Default mode works — the script backgrounds the server itself\nscripts/start-server.sh --project-dir /path/to/project\n```\n\n**Claude Code (Windows):**\n```bash\n# Windows auto-detects and uses foreground mode, which blocks the tool call.\n# Use run_in_background: true on the Bash tool call so the server survives\n# across conversation turns.\nscripts/start-server.sh --project-dir /path/to/project\n```\nWhen calling this via the Bash tool, set `run_in_background: true`. Then read `$SCREEN_DIR/.server-info` on the next turn to get the URL and port.\n\n**Codex:**\n```bash\n# Codex reaps background processes. The script auto-detects CODEX_CI and\n# switches to foreground mode. Run it normally — no extra flags needed.\nscripts/start-server.sh --project-dir /path/to/project\n```\n\n**Gemini CLI:**\n```bash\n# Use --foreground and set is_background: true on your shell tool call\n# so the process survives across turns\nscripts/start-server.sh --project-dir /path/to/project --foreground\n```\n\n**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.\n\nIf the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:\n\n```bash\nscripts/start-server.sh \\\n  --project-dir /path/to/project \\\n  --host 0.0.0.0 \\\n  --url-host localhost\n```\n\nUse `--url-host` to control what hostname is printed in the returned URL JSON.\n\n## The Loop\n\n1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:\n   - Before each write, check that `$SCREEN_DIR/.server-info` exists. If it doesn't (or `.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.\n   - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`\n   - **Never reuse filenames** — each screen gets a fresh file\n   - Use Write tool — **never use cat/heredoc** (dumps noise into terminal)\n   - Server automatically serves the newest file\n\n2. **Tell user what to expect and end your turn:**\n   - Remind them of the URL (every step, not just first)\n   - Give a brief text summary of what's on screen (e.g., \"Showing 3 layout options for the homepage\")\n   - 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.\"\n\n3. **On your next turn** — after the user responds in the terminal:\n   - Read `$SCREEN_DIR/.events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines\n   - Merge with the user's terminal text to get the full picture\n   - The terminal message is the primary feedback; `.events` provides structured interaction data\n\n4. **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.\n\n5. **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:\n\n   ```html\n   <!-- filename: waiting.html (or waiting-2.html, etc.) -->\n   <div style=\"display:flex;align-items:center;justify-content:center;min-height:60vh\">\n     <p class=\"subtitle\">Continuing in terminal...</p>\n   </div>\n   ```\n\n   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.\n\n6. Repeat until done.\n\n## Writing Content Fragments\n\nWrite 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).\n\n**Minimal example:**\n\n```html\n<h2>Which layout works better?</h2>\n<p class=\"subtitle\">Consider readability and visual hierarchy</p>\n\n<div class=\"options\">\n  <div class=\"option\" data-choice=\"a\" onclick=\"toggleSelect(this)\">\n    <div class=\"letter\">A</div>\n    <div class=\"content\">\n      <h3>Single Column</h3>\n      <p>Clean, focused reading experience</p>\n    </div>\n  </div>\n  <div class=\"option\" data-choice=\"b\" onclick=\"toggleSelect(this)\">\n    <div class=\"letter\">B</div>\n    <div class=\"content\">\n      <h3>Two Column</h3>\n      <p>Sidebar navigation with main content</p>\n    </div>\n  </div>\n</div>\n```\n\nThat's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.\n\n## CSS Classes Available\n\nThe frame template provides these CSS classes for your content:\n\n### Options (A/B/C choices)\n\n```html\n<div class=\"options\">\n  <div class=\"option\" data-choice=\"a\" onclick=\"toggleSelect(this)\">\n    <div class=\"letter\">A</div>\n    <div class=\"content\">\n      <h3>Title</h3>\n      <p>Description</p>\n    </div>\n  </div>\n</div>\n```\n\n**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item. The indicator bar shows the count.\n\n```html\n<div class=\"options\" data-multiselect>\n  <!-- same option markup — users can select/deselect multiple -->\n</div>\n```\n\n### Cards (visual designs)\n\n```html\n<div class=\"cards\">\n  <div class=\"card\" data-choice=\"design1\" onclick=\"toggleSelect(this)\">\n    <div class=\"card-image\"><!-- mockup content --></div>\n    <div class=\"card-body\">\n      <h3>Name</h3>\n      <p>Description</p>\n    </div>\n  </div>\n</div>\n```\n\n### Mockup container\n\n```html\n<div class=\"mockup\">\n  <div class=\"mockup-header\">Preview: Dashboard Layout</div>\n  <div class=\"mockup-body\"><!-- your mockup HTML --></div>\n</div>\n```\n\n### Split view (side-by-side)\n\n```html\n<div class=\"split\">\n  <div class=\"mockup\"><!-- left --></div>\n  <div class=\"mockup\"><!-- right --></div>\n</div>\n```\n\n### Pros/Cons\n\n```html\n<div class=\"pros-cons\">\n  <div class=\"pros\"><h4>Pros</h4><ul><li>Benefit</li></ul></div>\n  <div class=\"cons\"><h4>Cons</h4><ul><li>Drawback</li></ul></div>\n</div>\n```\n\n### Mock elements (wireframe building blocks)\n\n```html\n<div class=\"mock-nav\">Logo | Home | About | Contact</div>\n<div style=\"display: flex;\">\n  <div class=\"mock-sidebar\">Navigation</div>\n  <div class=\"mock-content\">Main content area</div>\n</div>\n<button class=\"mock-button\">Action Button</button>\n<input class=\"mock-input\" placeholder=\"Input field\">\n<div class=\"placeholder\">Placeholder area</div>\n```\n\n### Typography and sections\n\n- `h2` — page title\n- `h3` — section heading\n- `.subtitle` — secondary text below title\n- `.section` — content block with bottom margin\n- `.label` — small uppercase label text\n\n## Browser Events Format\n\nWhen the user clicks options in the browser, their interactions are recorded to `$SCREEN_DIR/.events` (one JSON object per line). The file is cleared automatically when you push a new screen.\n\n```jsonl\n{\"type\":\"click\",\"choice\":\"a\",\"text\":\"Option A - Simple Layout\",\"timestamp\":1706000101}\n{\"type\":\"click\",\"choice\":\"c\",\"text\":\"Option C - Complex Grid\",\"timestamp\":1706000108}\n{\"type\":\"click\",\"choice\":\"b\",\"text\":\"Option B - Hybrid\",\"timestamp\":1706000115}\n```\n\nThe 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.\n\nIf `.events` doesn't exist, the user didn't interact with the browser — use only their terminal text.\n\n## Design Tips\n\n- **Scale fidelity to the question** — wireframes for layout, polish for polish questions\n- **Explain the question on each page** — \"Which layout feels more professional?\" not just \"Pick one\"\n- **Iterate before advancing** — if feedback changes current screen, write a new version\n- **2-4 options max** per screen\n- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.\n- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design\n\n## File Naming\n\n- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`\n- Never reuse filenames — each screen must be a new file\n- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`\n- Server serves newest file by modification time\n\n## Cleaning Up\n\n```bash\nscripts/stop-server.sh $SCREEN_DIR\n```\n\nIf the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.\n\n## Reference\n\n- Frame template (CSS reference): `scripts/frame-template.html`\n- Helper script (client-side): `scripts/helper.js`\n"
  },
  {
    "path": "skills/dispatching-parallel-agents/SKILL.md",
    "content": "---\nname: dispatching-parallel-agents\ndescription: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies\n---\n\n# Dispatching Parallel Agents\n\n## Overview\n\nYou delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.\n\nWhen you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.\n\n**Core principle:** Dispatch one agent per independent problem domain. Let them work concurrently.\n\n## When to Use\n\n```dot\ndigraph when_to_use {\n    \"Multiple failures?\" [shape=diamond];\n    \"Are they independent?\" [shape=diamond];\n    \"Single agent investigates all\" [shape=box];\n    \"One agent per problem domain\" [shape=box];\n    \"Can they work in parallel?\" [shape=diamond];\n    \"Sequential agents\" [shape=box];\n    \"Parallel dispatch\" [shape=box];\n\n    \"Multiple failures?\" -> \"Are they independent?\" [label=\"yes\"];\n    \"Are they independent?\" -> \"Single agent investigates all\" [label=\"no - related\"];\n    \"Are they independent?\" -> \"Can they work in parallel?\" [label=\"yes\"];\n    \"Can they work in parallel?\" -> \"Parallel dispatch\" [label=\"yes\"];\n    \"Can they work in parallel?\" -> \"Sequential agents\" [label=\"no - shared state\"];\n}\n```\n\n**Use when:**\n- 3+ test files failing with different root causes\n- Multiple subsystems broken independently\n- Each problem can be understood without context from others\n- No shared state between investigations\n\n**Don't use when:**\n- Failures are related (fix one might fix others)\n- Need to understand full system state\n- Agents would interfere with each other\n\n## The Pattern\n\n### 1. Identify Independent Domains\n\nGroup failures by what's broken:\n- File A tests: Tool approval flow\n- File B tests: Batch completion behavior\n- File C tests: Abort functionality\n\nEach domain is independent - fixing tool approval doesn't affect abort tests.\n\n### 2. Create Focused Agent Tasks\n\nEach agent gets:\n- **Specific scope:** One test file or subsystem\n- **Clear goal:** Make these tests pass\n- **Constraints:** Don't change other code\n- **Expected output:** Summary of what you found and fixed\n\n### 3. Dispatch in Parallel\n\n```typescript\n// In Claude Code / AI environment\nTask(\"Fix agent-tool-abort.test.ts failures\")\nTask(\"Fix batch-completion-behavior.test.ts failures\")\nTask(\"Fix tool-approval-race-conditions.test.ts failures\")\n// All three run concurrently\n```\n\n### 4. Review and Integrate\n\nWhen agents return:\n- Read each summary\n- Verify fixes don't conflict\n- Run full test suite\n- Integrate all changes\n\n## Agent Prompt Structure\n\nGood agent prompts are:\n1. **Focused** - One clear problem domain\n2. **Self-contained** - All context needed to understand the problem\n3. **Specific about output** - What should the agent return?\n\n```markdown\nFix the 3 failing tests in src/agents/agent-tool-abort.test.ts:\n\n1. \"should abort tool with partial output capture\" - expects 'interrupted at' in message\n2. \"should handle mixed completed and aborted tools\" - fast tool aborted instead of completed\n3. \"should properly track pendingToolCount\" - expects 3 results but gets 0\n\nThese are timing/race condition issues. Your task:\n\n1. Read the test file and understand what each test verifies\n2. Identify root cause - timing issues or actual bugs?\n3. Fix by:\n   - Replacing arbitrary timeouts with event-based waiting\n   - Fixing bugs in abort implementation if found\n   - Adjusting test expectations if testing changed behavior\n\nDo NOT just increase timeouts - find the real issue.\n\nReturn: Summary of what you found and what you fixed.\n```\n\n## Common Mistakes\n\n**❌ Too broad:** \"Fix all the tests\" - agent gets lost\n**✅ Specific:** \"Fix agent-tool-abort.test.ts\" - focused scope\n\n**❌ No context:** \"Fix the race condition\" - agent doesn't know where\n**✅ Context:** Paste the error messages and test names\n\n**❌ No constraints:** Agent might refactor everything\n**✅ Constraints:** \"Do NOT change production code\" or \"Fix tests only\"\n\n**❌ Vague output:** \"Fix it\" - you don't know what changed\n**✅ Specific:** \"Return summary of root cause and changes\"\n\n## When NOT to Use\n\n**Related failures:** Fixing one might fix others - investigate together first\n**Need full context:** Understanding requires seeing entire system\n**Exploratory debugging:** You don't know what's broken yet\n**Shared state:** Agents would interfere (editing same files, using same resources)\n\n## Real Example from Session\n\n**Scenario:** 6 test failures across 3 files after major refactoring\n\n**Failures:**\n- agent-tool-abort.test.ts: 3 failures (timing issues)\n- batch-completion-behavior.test.ts: 2 failures (tools not executing)\n- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)\n\n**Decision:** Independent domains - abort logic separate from batch completion separate from race conditions\n\n**Dispatch:**\n```\nAgent 1 → Fix agent-tool-abort.test.ts\nAgent 2 → Fix batch-completion-behavior.test.ts\nAgent 3 → Fix tool-approval-race-conditions.test.ts\n```\n\n**Results:**\n- Agent 1: Replaced timeouts with event-based waiting\n- Agent 2: Fixed event structure bug (threadId in wrong place)\n- Agent 3: Added wait for async tool execution to complete\n\n**Integration:** All fixes independent, no conflicts, full suite green\n\n**Time saved:** 3 problems solved in parallel vs sequentially\n\n## Key Benefits\n\n1. **Parallelization** - Multiple investigations happen simultaneously\n2. **Focus** - Each agent has narrow scope, less context to track\n3. **Independence** - Agents don't interfere with each other\n4. **Speed** - 3 problems solved in time of 1\n\n## Verification\n\nAfter agents return:\n1. **Review each summary** - Understand what changed\n2. **Check for conflicts** - Did agents edit same code?\n3. **Run full suite** - Verify all fixes work together\n4. **Spot check** - Agents can make systematic errors\n\n## Real-World Impact\n\nFrom debugging session (2025-10-03):\n- 6 failures across 3 files\n- 3 agents dispatched in parallel\n- All investigations completed concurrently\n- All fixes integrated successfully\n- Zero conflicts between agent changes\n"
  },
  {
    "path": "skills/executing-plans/SKILL.md",
    "content": "---\nname: executing-plans\ndescription: Use when you have a written implementation plan to execute in a separate session with review checkpoints\n---\n\n# Executing Plans\n\n## Overview\n\nLoad plan, review critically, execute all tasks, report when complete.\n\n**Announce at start:** \"I'm using the executing-plans skill to implement this plan.\"\n\n**Note:** Tell your human partner that Superpowers works much better with access to subagents. The quality of its work will be significantly higher if run on a platform with subagent support (such as Claude Code or Codex). If subagents are available, use superpowers:subagent-driven-development instead of this skill.\n\n## The Process\n\n### Step 1: Load and Review Plan\n1. Read plan file\n2. Review critically - identify any questions or concerns about the plan\n3. If concerns: Raise them with your human partner before starting\n4. If no concerns: Create TodoWrite and proceed\n\n### Step 2: Execute Tasks\n\nFor each task:\n1. Mark as in_progress\n2. Follow each step exactly (plan has bite-sized steps)\n3. Run verifications as specified\n4. Mark as completed\n\n### Step 3: Complete Development\n\nAfter all tasks complete and verified:\n- Announce: \"I'm using the finishing-a-development-branch skill to complete this work.\"\n- **REQUIRED SUB-SKILL:** Use superpowers:finishing-a-development-branch\n- Follow that skill to verify tests, present options, execute choice\n\n## When to Stop and Ask for Help\n\n**STOP executing immediately when:**\n- Hit a blocker (missing dependency, test fails, instruction unclear)\n- Plan has critical gaps preventing starting\n- You don't understand an instruction\n- Verification fails repeatedly\n\n**Ask for clarification rather than guessing.**\n\n## When to Revisit Earlier Steps\n\n**Return to Review (Step 1) when:**\n- Partner updates the plan based on your feedback\n- Fundamental approach needs rethinking\n\n**Don't force through blockers** - stop and ask.\n\n## Remember\n- Review plan critically first\n- Follow plan steps exactly\n- Don't skip verifications\n- Reference skills when plan says to\n- Stop when blocked, don't guess\n- Never start implementation on main/master branch without explicit user consent\n\n## Integration\n\n**Required workflow skills:**\n- **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting\n- **superpowers:writing-plans** - Creates the plan this skill executes\n- **superpowers:finishing-a-development-branch** - Complete development after all tasks\n"
  },
  {
    "path": "skills/finishing-a-development-branch/SKILL.md",
    "content": "---\nname: finishing-a-development-branch\ndescription: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup\n---\n\n# Finishing a Development Branch\n\n## Overview\n\nGuide completion of development work by presenting clear options and handling chosen workflow.\n\n**Core principle:** Verify tests → Present options → Execute choice → Clean up.\n\n**Announce at start:** \"I'm using the finishing-a-development-branch skill to complete this work.\"\n\n## The Process\n\n### Step 1: Verify Tests\n\n**Before presenting options, verify tests pass:**\n\n```bash\n# Run project's test suite\nnpm test / cargo test / pytest / go test ./...\n```\n\n**If tests fail:**\n```\nTests failing (<N> failures). Must fix before completing:\n\n[Show failures]\n\nCannot proceed with merge/PR until tests pass.\n```\n\nStop. Don't proceed to Step 2.\n\n**If tests pass:** Continue to Step 2.\n\n### Step 2: Determine Base Branch\n\n```bash\n# Try common base branches\ngit merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null\n```\n\nOr ask: \"This branch split from main - is that correct?\"\n\n### Step 3: Present Options\n\nPresent exactly these 4 options:\n\n```\nImplementation complete. What would you like to do?\n\n1. Merge back to <base-branch> locally\n2. Push and create a Pull Request\n3. Keep the branch as-is (I'll handle it later)\n4. Discard this work\n\nWhich option?\n```\n\n**Don't add explanation** - keep options concise.\n\n### Step 4: Execute Choice\n\n#### Option 1: Merge Locally\n\n```bash\n# Switch to base branch\ngit checkout <base-branch>\n\n# Pull latest\ngit pull\n\n# Merge feature branch\ngit merge <feature-branch>\n\n# Verify tests on merged result\n<test command>\n\n# If tests pass\ngit branch -d <feature-branch>\n```\n\nThen: Cleanup worktree (Step 5)\n\n#### Option 2: Push and Create PR\n\n```bash\n# Push branch\ngit push -u origin <feature-branch>\n\n# Create PR\ngh pr create --title \"<title>\" --body \"$(cat <<'EOF'\n## Summary\n<2-3 bullets of what changed>\n\n## Test Plan\n- [ ] <verification steps>\nEOF\n)\"\n```\n\nThen: Cleanup worktree (Step 5)\n\n#### Option 3: Keep As-Is\n\nReport: \"Keeping branch <name>. Worktree preserved at <path>.\"\n\n**Don't cleanup worktree.**\n\n#### Option 4: Discard\n\n**Confirm first:**\n```\nThis will permanently delete:\n- Branch <name>\n- All commits: <commit-list>\n- Worktree at <path>\n\nType 'discard' to confirm.\n```\n\nWait for exact confirmation.\n\nIf confirmed:\n```bash\ngit checkout <base-branch>\ngit branch -D <feature-branch>\n```\n\nThen: Cleanup worktree (Step 5)\n\n### Step 5: Cleanup Worktree\n\n**For Options 1, 2, 4:**\n\nCheck if in worktree:\n```bash\ngit worktree list | grep $(git branch --show-current)\n```\n\nIf yes:\n```bash\ngit worktree remove <worktree-path>\n```\n\n**For Option 3:** Keep worktree.\n\n## Quick Reference\n\n| Option | Merge | Push | Keep Worktree | Cleanup Branch |\n|--------|-------|------|---------------|----------------|\n| 1. Merge locally | ✓ | - | - | ✓ |\n| 2. Create PR | - | ✓ | ✓ | - |\n| 3. Keep as-is | - | - | ✓ | - |\n| 4. Discard | - | - | - | ✓ (force) |\n\n## Common Mistakes\n\n**Skipping test verification**\n- **Problem:** Merge broken code, create failing PR\n- **Fix:** Always verify tests before offering options\n\n**Open-ended questions**\n- **Problem:** \"What should I do next?\" → ambiguous\n- **Fix:** Present exactly 4 structured options\n\n**Automatic worktree cleanup**\n- **Problem:** Remove worktree when might need it (Option 2, 3)\n- **Fix:** Only cleanup for Options 1 and 4\n\n**No confirmation for discard**\n- **Problem:** Accidentally delete work\n- **Fix:** Require typed \"discard\" confirmation\n\n## Red Flags\n\n**Never:**\n- Proceed with failing tests\n- Merge without verifying tests on result\n- Delete work without confirmation\n- Force-push without explicit request\n\n**Always:**\n- Verify tests before offering options\n- Present exactly 4 options\n- Get typed confirmation for Option 4\n- Clean up worktree for Options 1 & 4 only\n\n## Integration\n\n**Called by:**\n- **subagent-driven-development** (Step 7) - After all tasks complete\n- **executing-plans** (Step 5) - After all batches complete\n\n**Pairs with:**\n- **using-git-worktrees** - Cleans up worktree created by that skill\n"
  },
  {
    "path": "skills/receiving-code-review/SKILL.md",
    "content": "---\nname: receiving-code-review\ndescription: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation\n---\n\n# Code Review Reception\n\n## Overview\n\nCode review requires technical evaluation, not emotional performance.\n\n**Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort.\n\n## The Response Pattern\n\n```\nWHEN receiving code review feedback:\n\n1. READ: Complete feedback without reacting\n2. UNDERSTAND: Restate requirement in own words (or ask)\n3. VERIFY: Check against codebase reality\n4. EVALUATE: Technically sound for THIS codebase?\n5. RESPOND: Technical acknowledgment or reasoned pushback\n6. IMPLEMENT: One item at a time, test each\n```\n\n## Forbidden Responses\n\n**NEVER:**\n- \"You're absolutely right!\" (explicit CLAUDE.md violation)\n- \"Great point!\" / \"Excellent feedback!\" (performative)\n- \"Let me implement that now\" (before verification)\n\n**INSTEAD:**\n- Restate the technical requirement\n- Ask clarifying questions\n- Push back with technical reasoning if wrong\n- Just start working (actions > words)\n\n## Handling Unclear Feedback\n\n```\nIF any item is unclear:\n  STOP - do not implement anything yet\n  ASK for clarification on unclear items\n\nWHY: Items may be related. Partial understanding = wrong implementation.\n```\n\n**Example:**\n```\nyour human partner: \"Fix 1-6\"\nYou understand 1,2,3,6. Unclear on 4,5.\n\n❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later\n✅ RIGHT: \"I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding.\"\n```\n\n## Source-Specific Handling\n\n### From your human partner\n- **Trusted** - implement after understanding\n- **Still ask** if scope unclear\n- **No performative agreement**\n- **Skip to action** or technical acknowledgment\n\n### From External Reviewers\n```\nBEFORE implementing:\n  1. Check: Technically correct for THIS codebase?\n  2. Check: Breaks existing functionality?\n  3. Check: Reason for current implementation?\n  4. Check: Works on all platforms/versions?\n  5. Check: Does reviewer understand full context?\n\nIF suggestion seems wrong:\n  Push back with technical reasoning\n\nIF can't easily verify:\n  Say so: \"I can't verify this without [X]. Should I [investigate/ask/proceed]?\"\n\nIF conflicts with your human partner's prior decisions:\n  Stop and discuss with your human partner first\n```\n\n**your human partner's rule:** \"External feedback - be skeptical, but check carefully\"\n\n## YAGNI Check for \"Professional\" Features\n\n```\nIF reviewer suggests \"implementing properly\":\n  grep codebase for actual usage\n\n  IF unused: \"This endpoint isn't called. Remove it (YAGNI)?\"\n  IF used: Then implement properly\n```\n\n**your human partner's rule:** \"You and reviewer both report to me. If we don't need this feature, don't add it.\"\n\n## Implementation Order\n\n```\nFOR multi-item feedback:\n  1. Clarify anything unclear FIRST\n  2. Then implement in this order:\n     - Blocking issues (breaks, security)\n     - Simple fixes (typos, imports)\n     - Complex fixes (refactoring, logic)\n  3. Test each fix individually\n  4. Verify no regressions\n```\n\n## When To Push Back\n\nPush back when:\n- Suggestion breaks existing functionality\n- Reviewer lacks full context\n- Violates YAGNI (unused feature)\n- Technically incorrect for this stack\n- Legacy/compatibility reasons exist\n- Conflicts with your human partner's architectural decisions\n\n**How to push back:**\n- Use technical reasoning, not defensiveness\n- Ask specific questions\n- Reference working tests/code\n- Involve your human partner if architectural\n\n**Signal if uncomfortable pushing back out loud:** \"Strange things are afoot at the Circle K\"\n\n## Acknowledging Correct Feedback\n\nWhen feedback IS correct:\n```\n✅ \"Fixed. [Brief description of what changed]\"\n✅ \"Good catch - [specific issue]. Fixed in [location].\"\n✅ [Just fix it and show in the code]\n\n❌ \"You're absolutely right!\"\n❌ \"Great point!\"\n❌ \"Thanks for catching that!\"\n❌ \"Thanks for [anything]\"\n❌ ANY gratitude expression\n```\n\n**Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback.\n\n**If you catch yourself about to write \"Thanks\":** DELETE IT. State the fix instead.\n\n## Gracefully Correcting Your Pushback\n\nIf you pushed back and were wrong:\n```\n✅ \"You were right - I checked [X] and it does [Y]. Implementing now.\"\n✅ \"Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing.\"\n\n❌ Long apology\n❌ Defending why you pushed back\n❌ Over-explaining\n```\n\nState the correction factually and move on.\n\n## Common Mistakes\n\n| Mistake | Fix |\n|---------|-----|\n| Performative agreement | State requirement or just act |\n| Blind implementation | Verify against codebase first |\n| Batch without testing | One at a time, test each |\n| Assuming reviewer is right | Check if breaks things |\n| Avoiding pushback | Technical correctness > comfort |\n| Partial implementation | Clarify all items first |\n| Can't verify, proceed anyway | State limitation, ask for direction |\n\n## Real Examples\n\n**Performative Agreement (Bad):**\n```\nReviewer: \"Remove legacy code\"\n❌ \"You're absolutely right! Let me remove that...\"\n```\n\n**Technical Verification (Good):**\n```\nReviewer: \"Remove legacy code\"\n✅ \"Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?\"\n```\n\n**YAGNI (Good):**\n```\nReviewer: \"Implement proper metrics tracking with database, date filters, CSV export\"\n✅ \"Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?\"\n```\n\n**Unclear Item (Good):**\n```\nyour human partner: \"Fix items 1-6\"\nYou understand 1,2,3,6. Unclear on 4,5.\n✅ \"Understand 1,2,3,6. Need clarification on 4 and 5 before implementing.\"\n```\n\n## GitHub Thread Replies\n\nWhen replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment.\n\n## The Bottom Line\n\n**External feedback = suggestions to evaluate, not orders to follow.**\n\nVerify. Question. Then implement.\n\nNo performative agreement. Technical rigor always.\n"
  },
  {
    "path": "skills/requesting-code-review/SKILL.md",
    "content": "---\nname: requesting-code-review\ndescription: Use when completing tasks, implementing major features, or before merging to verify work meets requirements\n---\n\n# Requesting Code Review\n\nDispatch superpowers:code-reviewer subagent to catch issues before they cascade. The reviewer gets precisely crafted context for evaluation — never your session's history. This keeps the reviewer focused on the work product, not your thought process, and preserves your own context for continued work.\n\n**Core principle:** Review early, review often.\n\n## When to Request Review\n\n**Mandatory:**\n- After each task in subagent-driven development\n- After completing major feature\n- Before merge to main\n\n**Optional but valuable:**\n- When stuck (fresh perspective)\n- Before refactoring (baseline check)\n- After fixing complex bug\n\n## How to Request\n\n**1. Get git SHAs:**\n```bash\nBASE_SHA=$(git rev-parse HEAD~1)  # or origin/main\nHEAD_SHA=$(git rev-parse HEAD)\n```\n\n**2. Dispatch code-reviewer subagent:**\n\nUse Task tool with superpowers:code-reviewer type, fill template at `code-reviewer.md`\n\n**Placeholders:**\n- `{WHAT_WAS_IMPLEMENTED}` - What you just built\n- `{PLAN_OR_REQUIREMENTS}` - What it should do\n- `{BASE_SHA}` - Starting commit\n- `{HEAD_SHA}` - Ending commit\n- `{DESCRIPTION}` - Brief summary\n\n**3. Act on feedback:**\n- Fix Critical issues immediately\n- Fix Important issues before proceeding\n- Note Minor issues for later\n- Push back if reviewer is wrong (with reasoning)\n\n## Example\n\n```\n[Just completed Task 2: Add verification function]\n\nYou: Let me request code review before proceeding.\n\nBASE_SHA=$(git log --oneline | grep \"Task 1\" | head -1 | awk '{print $1}')\nHEAD_SHA=$(git rev-parse HEAD)\n\n[Dispatch superpowers:code-reviewer subagent]\n  WHAT_WAS_IMPLEMENTED: Verification and repair functions for conversation index\n  PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md\n  BASE_SHA: a7981ec\n  HEAD_SHA: 3df7661\n  DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types\n\n[Subagent returns]:\n  Strengths: Clean architecture, real tests\n  Issues:\n    Important: Missing progress indicators\n    Minor: Magic number (100) for reporting interval\n  Assessment: Ready to proceed\n\nYou: [Fix progress indicators]\n[Continue to Task 3]\n```\n\n## Integration with Workflows\n\n**Subagent-Driven Development:**\n- Review after EACH task\n- Catch issues before they compound\n- Fix before moving to next task\n\n**Executing Plans:**\n- Review after each batch (3 tasks)\n- Get feedback, apply, continue\n\n**Ad-Hoc Development:**\n- Review before merge\n- Review when stuck\n\n## Red Flags\n\n**Never:**\n- Skip review because \"it's simple\"\n- Ignore Critical issues\n- Proceed with unfixed Important issues\n- Argue with valid technical feedback\n\n**If reviewer wrong:**\n- Push back with technical reasoning\n- Show code/tests that prove it works\n- Request clarification\n\nSee template at: requesting-code-review/code-reviewer.md\n"
  },
  {
    "path": "skills/requesting-code-review/code-reviewer.md",
    "content": "# Code Review Agent\n\nYou are reviewing code changes for production readiness.\n\n**Your task:**\n1. Review {WHAT_WAS_IMPLEMENTED}\n2. Compare against {PLAN_OR_REQUIREMENTS}\n3. Check code quality, architecture, testing\n4. Categorize issues by severity\n5. Assess production readiness\n\n## What Was Implemented\n\n{DESCRIPTION}\n\n## Requirements/Plan\n\n{PLAN_REFERENCE}\n\n## Git Range to Review\n\n**Base:** {BASE_SHA}\n**Head:** {HEAD_SHA}\n\n```bash\ngit diff --stat {BASE_SHA}..{HEAD_SHA}\ngit diff {BASE_SHA}..{HEAD_SHA}\n```\n\n## Review Checklist\n\n**Code Quality:**\n- Clean separation of concerns?\n- Proper error handling?\n- Type safety (if applicable)?\n- DRY principle followed?\n- Edge cases handled?\n\n**Architecture:**\n- Sound design decisions?\n- Scalability considerations?\n- Performance implications?\n- Security concerns?\n\n**Testing:**\n- Tests actually test logic (not mocks)?\n- Edge cases covered?\n- Integration tests where needed?\n- All tests passing?\n\n**Requirements:**\n- All plan requirements met?\n- Implementation matches spec?\n- No scope creep?\n- Breaking changes documented?\n\n**Production Readiness:**\n- Migration strategy (if schema changes)?\n- Backward compatibility considered?\n- Documentation complete?\n- No obvious bugs?\n\n## Output Format\n\n### Strengths\n[What's well done? Be specific.]\n\n### Issues\n\n#### Critical (Must Fix)\n[Bugs, security issues, data loss risks, broken functionality]\n\n#### Important (Should Fix)\n[Architecture problems, missing features, poor error handling, test gaps]\n\n#### Minor (Nice to Have)\n[Code style, optimization opportunities, documentation improvements]\n\n**For each issue:**\n- File:line reference\n- What's wrong\n- Why it matters\n- How to fix (if not obvious)\n\n### Recommendations\n[Improvements for code quality, architecture, or process]\n\n### Assessment\n\n**Ready to merge?** [Yes/No/With fixes]\n\n**Reasoning:** [Technical assessment in 1-2 sentences]\n\n## Critical Rules\n\n**DO:**\n- Categorize by actual severity (not everything is Critical)\n- Be specific (file:line, not vague)\n- Explain WHY issues matter\n- Acknowledge strengths\n- Give clear verdict\n\n**DON'T:**\n- Say \"looks good\" without checking\n- Mark nitpicks as Critical\n- Give feedback on code you didn't review\n- Be vague (\"improve error handling\")\n- Avoid giving a clear verdict\n\n## Example Output\n\n```\n### Strengths\n- Clean database schema with proper migrations (db.ts:15-42)\n- Comprehensive test coverage (18 tests, all edge cases)\n- Good error handling with fallbacks (summarizer.ts:85-92)\n\n### Issues\n\n#### Important\n1. **Missing help text in CLI wrapper**\n   - File: index-conversations:1-31\n   - Issue: No --help flag, users won't discover --concurrency\n   - Fix: Add --help case with usage examples\n\n2. **Date validation missing**\n   - File: search.ts:25-27\n   - Issue: Invalid dates silently return no results\n   - Fix: Validate ISO format, throw error with example\n\n#### Minor\n1. **Progress indicators**\n   - File: indexer.ts:130\n   - Issue: No \"X of Y\" counter for long operations\n   - Impact: Users don't know how long to wait\n\n### Recommendations\n- Add progress reporting for user experience\n- Consider config file for excluded projects (portability)\n\n### Assessment\n\n**Ready to merge: With fixes**\n\n**Reasoning:** Core implementation is solid with good architecture and tests. Important issues (help text, date validation) are easily fixed and don't affect core functionality.\n```\n"
  },
  {
    "path": "skills/subagent-driven-development/SKILL.md",
    "content": "---\nname: subagent-driven-development\ndescription: Use when executing implementation plans with independent tasks in the current session\n---\n\n# Subagent-Driven Development\n\nExecute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.\n\n**Why subagents:** You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.\n\n**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration\n\n## When to Use\n\n```dot\ndigraph when_to_use {\n    \"Have implementation plan?\" [shape=diamond];\n    \"Tasks mostly independent?\" [shape=diamond];\n    \"Stay in this session?\" [shape=diamond];\n    \"subagent-driven-development\" [shape=box];\n    \"executing-plans\" [shape=box];\n    \"Manual execution or brainstorm first\" [shape=box];\n\n    \"Have implementation plan?\" -> \"Tasks mostly independent?\" [label=\"yes\"];\n    \"Have implementation plan?\" -> \"Manual execution or brainstorm first\" [label=\"no\"];\n    \"Tasks mostly independent?\" -> \"Stay in this session?\" [label=\"yes\"];\n    \"Tasks mostly independent?\" -> \"Manual execution or brainstorm first\" [label=\"no - tightly coupled\"];\n    \"Stay in this session?\" -> \"subagent-driven-development\" [label=\"yes\"];\n    \"Stay in this session?\" -> \"executing-plans\" [label=\"no - parallel session\"];\n}\n```\n\n**vs. Executing Plans (parallel session):**\n- Same session (no context switch)\n- Fresh subagent per task (no context pollution)\n- Two-stage review after each task: spec compliance first, then code quality\n- Faster iteration (no human-in-loop between tasks)\n\n## The Process\n\n```dot\ndigraph process {\n    rankdir=TB;\n\n    subgraph cluster_per_task {\n        label=\"Per Task\";\n        \"Dispatch implementer subagent (./implementer-prompt.md)\" [shape=box];\n        \"Implementer subagent asks questions?\" [shape=diamond];\n        \"Answer questions, provide context\" [shape=box];\n        \"Implementer subagent implements, tests, commits, self-reviews\" [shape=box];\n        \"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)\" [shape=box];\n        \"Spec reviewer subagent confirms code matches spec?\" [shape=diamond];\n        \"Implementer subagent fixes spec gaps\" [shape=box];\n        \"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)\" [shape=box];\n        \"Code quality reviewer subagent approves?\" [shape=diamond];\n        \"Implementer subagent fixes quality issues\" [shape=box];\n        \"Mark task complete in TodoWrite\" [shape=box];\n    }\n\n    \"Read plan, extract all tasks with full text, note context, create TodoWrite\" [shape=box];\n    \"More tasks remain?\" [shape=diamond];\n    \"Dispatch final code reviewer subagent for entire implementation\" [shape=box];\n    \"Use superpowers:finishing-a-development-branch\" [shape=box style=filled fillcolor=lightgreen];\n\n    \"Read plan, extract all tasks with full text, note context, create TodoWrite\" -> \"Dispatch implementer subagent (./implementer-prompt.md)\";\n    \"Dispatch implementer subagent (./implementer-prompt.md)\" -> \"Implementer subagent asks questions?\";\n    \"Implementer subagent asks questions?\" -> \"Answer questions, provide context\" [label=\"yes\"];\n    \"Answer questions, provide context\" -> \"Dispatch implementer subagent (./implementer-prompt.md)\";\n    \"Implementer subagent asks questions?\" -> \"Implementer subagent implements, tests, commits, self-reviews\" [label=\"no\"];\n    \"Implementer subagent implements, tests, commits, self-reviews\" -> \"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)\";\n    \"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)\" -> \"Spec reviewer subagent confirms code matches spec?\";\n    \"Spec reviewer subagent confirms code matches spec?\" -> \"Implementer subagent fixes spec gaps\" [label=\"no\"];\n    \"Implementer subagent fixes spec gaps\" -> \"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)\" [label=\"re-review\"];\n    \"Spec reviewer subagent confirms code matches spec?\" -> \"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)\" [label=\"yes\"];\n    \"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)\" -> \"Code quality reviewer subagent approves?\";\n    \"Code quality reviewer subagent approves?\" -> \"Implementer subagent fixes quality issues\" [label=\"no\"];\n    \"Implementer subagent fixes quality issues\" -> \"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)\" [label=\"re-review\"];\n    \"Code quality reviewer subagent approves?\" -> \"Mark task complete in TodoWrite\" [label=\"yes\"];\n    \"Mark task complete in TodoWrite\" -> \"More tasks remain?\";\n    \"More tasks remain?\" -> \"Dispatch implementer subagent (./implementer-prompt.md)\" [label=\"yes\"];\n    \"More tasks remain?\" -> \"Dispatch final code reviewer subagent for entire implementation\" [label=\"no\"];\n    \"Dispatch final code reviewer subagent for entire implementation\" -> \"Use superpowers:finishing-a-development-branch\";\n}\n```\n\n## Model Selection\n\nUse the least powerful model that can handle each role to conserve cost and increase speed.\n\n**Mechanical implementation tasks** (isolated functions, clear specs, 1-2 files): use a fast, cheap model. Most implementation tasks are mechanical when the plan is well-specified.\n\n**Integration and judgment tasks** (multi-file coordination, pattern matching, debugging): use a standard model.\n\n**Architecture, design, and review tasks**: use the most capable available model.\n\n**Task complexity signals:**\n- Touches 1-2 files with a complete spec → cheap model\n- Touches multiple files with integration concerns → standard model\n- Requires design judgment or broad codebase understanding → most capable model\n\n## Handling Implementer Status\n\nImplementer subagents report one of four statuses. Handle each appropriately:\n\n**DONE:** Proceed to spec compliance review.\n\n**DONE_WITH_CONCERNS:** The implementer completed the work but flagged doubts. Read the concerns before proceeding. If the concerns are about correctness or scope, address them before review. If they're observations (e.g., \"this file is getting large\"), note them and proceed to review.\n\n**NEEDS_CONTEXT:** The implementer needs information that wasn't provided. Provide the missing context and re-dispatch.\n\n**BLOCKED:** The implementer cannot complete the task. Assess the blocker:\n1. If it's a context problem, provide more context and re-dispatch with the same model\n2. If the task requires more reasoning, re-dispatch with a more capable model\n3. If the task is too large, break it into smaller pieces\n4. If the plan itself is wrong, escalate to the human\n\n**Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change.\n\n## Prompt Templates\n\n- `./implementer-prompt.md` - Dispatch implementer subagent\n- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent\n- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent\n\n## Example Workflow\n\n```\nYou: I'm using Subagent-Driven Development to execute this plan.\n\n[Read plan file once: docs/superpowers/plans/feature-plan.md]\n[Extract all 5 tasks with full text and context]\n[Create TodoWrite with all tasks]\n\nTask 1: Hook installation script\n\n[Get Task 1 text and context (already extracted)]\n[Dispatch implementation subagent with full task text + context]\n\nImplementer: \"Before I begin - should the hook be installed at user or system level?\"\n\nYou: \"User level (~/.config/superpowers/hooks/)\"\n\nImplementer: \"Got it. Implementing now...\"\n[Later] Implementer:\n  - Implemented install-hook command\n  - Added tests, 5/5 passing\n  - Self-review: Found I missed --force flag, added it\n  - Committed\n\n[Dispatch spec compliance reviewer]\nSpec reviewer: ✅ Spec compliant - all requirements met, nothing extra\n\n[Get git SHAs, dispatch code quality reviewer]\nCode reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.\n\n[Mark Task 1 complete]\n\nTask 2: Recovery modes\n\n[Get Task 2 text and context (already extracted)]\n[Dispatch implementation subagent with full task text + context]\n\nImplementer: [No questions, proceeds]\nImplementer:\n  - Added verify/repair modes\n  - 8/8 tests passing\n  - Self-review: All good\n  - Committed\n\n[Dispatch spec compliance reviewer]\nSpec reviewer: ❌ Issues:\n  - Missing: Progress reporting (spec says \"report every 100 items\")\n  - Extra: Added --json flag (not requested)\n\n[Implementer fixes issues]\nImplementer: Removed --json flag, added progress reporting\n\n[Spec reviewer reviews again]\nSpec reviewer: ✅ Spec compliant now\n\n[Dispatch code quality reviewer]\nCode reviewer: Strengths: Solid. Issues (Important): Magic number (100)\n\n[Implementer fixes]\nImplementer: Extracted PROGRESS_INTERVAL constant\n\n[Code reviewer reviews again]\nCode reviewer: ✅ Approved\n\n[Mark Task 2 complete]\n\n...\n\n[After all tasks]\n[Dispatch final code-reviewer]\nFinal reviewer: All requirements met, ready to merge\n\nDone!\n```\n\n## Advantages\n\n**vs. Manual execution:**\n- Subagents follow TDD naturally\n- Fresh context per task (no confusion)\n- Parallel-safe (subagents don't interfere)\n- Subagent can ask questions (before AND during work)\n\n**vs. Executing Plans:**\n- Same session (no handoff)\n- Continuous progress (no waiting)\n- Review checkpoints automatic\n\n**Efficiency gains:**\n- No file reading overhead (controller provides full text)\n- Controller curates exactly what context is needed\n- Subagent gets complete information upfront\n- Questions surfaced before work begins (not after)\n\n**Quality gates:**\n- Self-review catches issues before handoff\n- Two-stage review: spec compliance, then code quality\n- Review loops ensure fixes actually work\n- Spec compliance prevents over/under-building\n- Code quality ensures implementation is well-built\n\n**Cost:**\n- More subagent invocations (implementer + 2 reviewers per task)\n- Controller does more prep work (extracting all tasks upfront)\n- Review loops add iterations\n- But catches issues early (cheaper than debugging later)\n\n## Red Flags\n\n**Never:**\n- Start implementation on main/master branch without explicit user consent\n- Skip reviews (spec compliance OR code quality)\n- Proceed with unfixed issues\n- Dispatch multiple implementation subagents in parallel (conflicts)\n- Make subagent read plan file (provide full text instead)\n- Skip scene-setting context (subagent needs to understand where task fits)\n- Ignore subagent questions (answer before letting them proceed)\n- Accept \"close enough\" on spec compliance (spec reviewer found issues = not done)\n- Skip review loops (reviewer found issues = implementer fixes = review again)\n- Let implementer self-review replace actual review (both are needed)\n- **Start code quality review before spec compliance is ✅** (wrong order)\n- Move to next task while either review has open issues\n\n**If subagent asks questions:**\n- Answer clearly and completely\n- Provide additional context if needed\n- Don't rush them into implementation\n\n**If reviewer finds issues:**\n- Implementer (same subagent) fixes them\n- Reviewer reviews again\n- Repeat until approved\n- Don't skip the re-review\n\n**If subagent fails task:**\n- Dispatch fix subagent with specific instructions\n- Don't try to fix manually (context pollution)\n\n## Integration\n\n**Required workflow skills:**\n- **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting\n- **superpowers:writing-plans** - Creates the plan this skill executes\n- **superpowers:requesting-code-review** - Code review template for reviewer subagents\n- **superpowers:finishing-a-development-branch** - Complete development after all tasks\n\n**Subagents should use:**\n- **superpowers:test-driven-development** - Subagents follow TDD for each task\n\n**Alternative workflow:**\n- **superpowers:executing-plans** - Use for parallel session instead of same-session execution\n"
  },
  {
    "path": "skills/subagent-driven-development/code-quality-reviewer-prompt.md",
    "content": "# Code Quality Reviewer Prompt Template\n\nUse this template when dispatching a code quality reviewer subagent.\n\n**Purpose:** Verify implementation is well-built (clean, tested, maintainable)\n\n**Only dispatch after spec compliance review passes.**\n\n```\nTask tool (superpowers:code-reviewer):\n  Use template at requesting-code-review/code-reviewer.md\n\n  WHAT_WAS_IMPLEMENTED: [from implementer's report]\n  PLAN_OR_REQUIREMENTS: Task N from [plan-file]\n  BASE_SHA: [commit before task]\n  HEAD_SHA: [current commit]\n  DESCRIPTION: [task summary]\n```\n\n**In addition to standard code quality concerns, the reviewer should check:**\n- Does each file have one clear responsibility with a well-defined interface?\n- Are units decomposed so they can be understood and tested independently?\n- Is the implementation following the file structure from the plan?\n- Did this implementation create new files that are already large, or significantly grow existing files? (Don't flag pre-existing file sizes — focus on what this change contributed.)\n\n**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment\n"
  },
  {
    "path": "skills/subagent-driven-development/implementer-prompt.md",
    "content": "# Implementer Subagent Prompt Template\n\nUse this template when dispatching an implementer subagent.\n\n```\nTask tool (general-purpose):\n  description: \"Implement Task N: [task name]\"\n  prompt: |\n    You are implementing Task N: [task name]\n\n    ## Task Description\n\n    [FULL TEXT of task from plan - paste it here, don't make subagent read file]\n\n    ## Context\n\n    [Scene-setting: where this fits, dependencies, architectural context]\n\n    ## Before You Begin\n\n    If you have questions about:\n    - The requirements or acceptance criteria\n    - The approach or implementation strategy\n    - Dependencies or assumptions\n    - Anything unclear in the task description\n\n    **Ask them now.** Raise any concerns before starting work.\n\n    ## Your Job\n\n    Once you're clear on requirements:\n    1. Implement exactly what the task specifies\n    2. Write tests (following TDD if task says to)\n    3. Verify implementation works\n    4. Commit your work\n    5. Self-review (see below)\n    6. Report back\n\n    Work from: [directory]\n\n    **While you work:** If you encounter something unexpected or unclear, **ask questions**.\n    It's always OK to pause and clarify. Don't guess or make assumptions.\n\n    ## Code Organization\n\n    You reason best about code you can hold in context at once, and your edits are more\n    reliable when files are focused. Keep this in mind:\n    - Follow the file structure defined in the plan\n    - Each file should have one clear responsibility with a well-defined interface\n    - If a file you're creating is growing beyond the plan's intent, stop and report\n      it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance\n    - If an existing file you're modifying is already large or tangled, work carefully\n      and note it as a concern in your report\n    - In existing codebases, follow established patterns. Improve code you're touching\n      the way a good developer would, but don't restructure things outside your task.\n\n    ## When You're in Over Your Head\n\n    It is always OK to stop and say \"this is too hard for me.\" Bad work is worse than\n    no work. You will not be penalized for escalating.\n\n    **STOP and escalate when:**\n    - The task requires architectural decisions with multiple valid approaches\n    - You need to understand code beyond what was provided and can't find clarity\n    - You feel uncertain about whether your approach is correct\n    - The task involves restructuring existing code in ways the plan didn't anticipate\n    - You've been reading file after file trying to understand the system without progress\n\n    **How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe\n    specifically what you're stuck on, what you've tried, and what kind of help you need.\n    The controller can provide more context, re-dispatch with a more capable model,\n    or break the task into smaller pieces.\n\n    ## Before Reporting Back: Self-Review\n\n    Review your work with fresh eyes. Ask yourself:\n\n    **Completeness:**\n    - Did I fully implement everything in the spec?\n    - Did I miss any requirements?\n    - Are there edge cases I didn't handle?\n\n    **Quality:**\n    - Is this my best work?\n    - Are names clear and accurate (match what things do, not how they work)?\n    - Is the code clean and maintainable?\n\n    **Discipline:**\n    - Did I avoid overbuilding (YAGNI)?\n    - Did I only build what was requested?\n    - Did I follow existing patterns in the codebase?\n\n    **Testing:**\n    - Do tests actually verify behavior (not just mock behavior)?\n    - Did I follow TDD if required?\n    - Are tests comprehensive?\n\n    If you find issues during self-review, fix them now before reporting.\n\n    ## Report Format\n\n    When done, report:\n    - **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT\n    - What you implemented (or what you attempted, if blocked)\n    - What you tested and test results\n    - Files changed\n    - Self-review findings (if any)\n    - Any issues or concerns\n\n    Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.\n    Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need\n    information that wasn't provided. Never silently produce work you're unsure about.\n```\n"
  },
  {
    "path": "skills/subagent-driven-development/spec-reviewer-prompt.md",
    "content": "# Spec Compliance Reviewer Prompt Template\n\nUse this template when dispatching a spec compliance reviewer subagent.\n\n**Purpose:** Verify implementer built what was requested (nothing more, nothing less)\n\n```\nTask tool (general-purpose):\n  description: \"Review spec compliance for Task N\"\n  prompt: |\n    You are reviewing whether an implementation matches its specification.\n\n    ## What Was Requested\n\n    [FULL TEXT of task requirements]\n\n    ## What Implementer Claims They Built\n\n    [From implementer's report]\n\n    ## CRITICAL: Do Not Trust the Report\n\n    The implementer finished suspiciously quickly. Their report may be incomplete,\n    inaccurate, or optimistic. You MUST verify everything independently.\n\n    **DO NOT:**\n    - Take their word for what they implemented\n    - Trust their claims about completeness\n    - Accept their interpretation of requirements\n\n    **DO:**\n    - Read the actual code they wrote\n    - Compare actual implementation to requirements line by line\n    - Check for missing pieces they claimed to implement\n    - Look for extra features they didn't mention\n\n    ## Your Job\n\n    Read the implementation code and verify:\n\n    **Missing requirements:**\n    - Did they implement everything that was requested?\n    - Are there requirements they skipped or missed?\n    - Did they claim something works but didn't actually implement it?\n\n    **Extra/unneeded work:**\n    - Did they build things that weren't requested?\n    - Did they over-engineer or add unnecessary features?\n    - Did they add \"nice to haves\" that weren't in spec?\n\n    **Misunderstandings:**\n    - Did they interpret requirements differently than intended?\n    - Did they solve the wrong problem?\n    - Did they implement the right feature but wrong way?\n\n    **Verify by reading code, not by trusting report.**\n\n    Report:\n    - ✅ Spec compliant (if everything matches after code inspection)\n    - ❌ Issues found: [list specifically what's missing or extra, with file:line references]\n```\n"
  },
  {
    "path": "skills/systematic-debugging/CREATION-LOG.md",
    "content": "# Creation Log: Systematic Debugging Skill\n\nReference example of extracting, structuring, and bulletproofing a critical skill.\n\n## Source Material\n\nExtracted debugging framework from `/Users/jesse/.claude/CLAUDE.md`:\n- 4-phase systematic process (Investigation → Pattern Analysis → Hypothesis → Implementation)\n- Core mandate: ALWAYS find root cause, NEVER fix symptoms\n- Rules designed to resist time pressure and rationalization\n\n## Extraction Decisions\n\n**What to include:**\n- Complete 4-phase framework with all rules\n- Anti-shortcuts (\"NEVER fix symptom\", \"STOP and re-analyze\")\n- Pressure-resistant language (\"even if faster\", \"even if I seem in a hurry\")\n- Concrete steps for each phase\n\n**What to leave out:**\n- Project-specific context\n- Repetitive variations of same rule\n- Narrative explanations (condensed to principles)\n\n## Structure Following skill-creation/SKILL.md\n\n1. **Rich when_to_use** - Included symptoms and anti-patterns\n2. **Type: technique** - Concrete process with steps\n3. **Keywords** - \"root cause\", \"symptom\", \"workaround\", \"debugging\", \"investigation\"\n4. **Flowchart** - Decision point for \"fix failed\" → re-analyze vs add more fixes\n5. **Phase-by-phase breakdown** - Scannable checklist format\n6. **Anti-patterns section** - What NOT to do (critical for this skill)\n\n## Bulletproofing Elements\n\nFramework designed to resist rationalization under pressure:\n\n### Language Choices\n- \"ALWAYS\" / \"NEVER\" (not \"should\" / \"try to\")\n- \"even if faster\" / \"even if I seem in a hurry\"\n- \"STOP and re-analyze\" (explicit pause)\n- \"Don't skip past\" (catches the actual behavior)\n\n### Structural Defenses\n- **Phase 1 required** - Can't skip to implementation\n- **Single hypothesis rule** - Forces thinking, prevents shotgun fixes\n- **Explicit failure mode** - \"IF your first fix doesn't work\" with mandatory action\n- **Anti-patterns section** - Shows exactly what shortcuts look like\n\n### Redundancy\n- Root cause mandate in overview + when_to_use + Phase 1 + implementation rules\n- \"NEVER fix symptom\" appears 4 times in different contexts\n- Each phase has explicit \"don't skip\" guidance\n\n## Testing Approach\n\nCreated 4 validation tests following skills/meta/testing-skills-with-subagents:\n\n### Test 1: Academic Context (No Pressure)\n- Simple bug, no time pressure\n- **Result:** Perfect compliance, complete investigation\n\n### Test 2: Time Pressure + Obvious Quick Fix\n- User \"in a hurry\", symptom fix looks easy\n- **Result:** Resisted shortcut, followed full process, found real root cause\n\n### Test 3: Complex System + Uncertainty\n- Multi-layer failure, unclear if can find root cause\n- **Result:** Systematic investigation, traced through all layers, found source\n\n### Test 4: Failed First Fix\n- Hypothesis doesn't work, temptation to add more fixes\n- **Result:** Stopped, re-analyzed, formed new hypothesis (no shotgun)\n\n**All tests passed.** No rationalizations found.\n\n## Iterations\n\n### Initial Version\n- Complete 4-phase framework\n- Anti-patterns section\n- Flowchart for \"fix failed\" decision\n\n### Enhancement 1: TDD Reference\n- Added link to skills/testing/test-driven-development\n- Note explaining TDD's \"simplest code\" ≠ debugging's \"root cause\"\n- Prevents confusion between methodologies\n\n## Final Outcome\n\nBulletproof skill that:\n- ✅ Clearly mandates root cause investigation\n- ✅ Resists time pressure rationalization\n- ✅ Provides concrete steps for each phase\n- ✅ Shows anti-patterns explicitly\n- ✅ Tested under multiple pressure scenarios\n- ✅ Clarifies relationship to TDD\n- ✅ Ready for use\n\n## Key Insight\n\n**Most important bulletproofing:** Anti-patterns section showing exact shortcuts that feel justified in the moment. When Claude thinks \"I'll just add this one quick fix\", seeing that exact pattern listed as wrong creates cognitive friction.\n\n## Usage Example\n\nWhen encountering a bug:\n1. Load skill: skills/debugging/systematic-debugging\n2. Read overview (10 sec) - reminded of mandate\n3. Follow Phase 1 checklist - forced investigation\n4. If tempted to skip - see anti-pattern, stop\n5. Complete all phases - root cause found\n\n**Time investment:** 5-10 minutes\n**Time saved:** Hours of symptom-whack-a-mole\n\n---\n\n*Created: 2025-10-03*\n*Purpose: Reference example for skill extraction and bulletproofing*\n"
  },
  {
    "path": "skills/systematic-debugging/SKILL.md",
    "content": "---\nname: systematic-debugging\ndescription: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes\n---\n\n# Systematic Debugging\n\n## Overview\n\nRandom fixes waste time and create new bugs. Quick patches mask underlying issues.\n\n**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.\n\n**Violating the letter of this process is violating the spirit of debugging.**\n\n## The Iron Law\n\n```\nNO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST\n```\n\nIf you haven't completed Phase 1, you cannot propose fixes.\n\n## When to Use\n\nUse for ANY technical issue:\n- Test failures\n- Bugs in production\n- Unexpected behavior\n- Performance problems\n- Build failures\n- Integration issues\n\n**Use this ESPECIALLY when:**\n- Under time pressure (emergencies make guessing tempting)\n- \"Just one quick fix\" seems obvious\n- You've already tried multiple fixes\n- Previous fix didn't work\n- You don't fully understand the issue\n\n**Don't skip when:**\n- Issue seems simple (simple bugs have root causes too)\n- You're in a hurry (rushing guarantees rework)\n- Manager wants it fixed NOW (systematic is faster than thrashing)\n\n## The Four Phases\n\nYou MUST complete each phase before proceeding to the next.\n\n### Phase 1: Root Cause Investigation\n\n**BEFORE attempting ANY fix:**\n\n1. **Read Error Messages Carefully**\n   - Don't skip past errors or warnings\n   - They often contain the exact solution\n   - Read stack traces completely\n   - Note line numbers, file paths, error codes\n\n2. **Reproduce Consistently**\n   - Can you trigger it reliably?\n   - What are the exact steps?\n   - Does it happen every time?\n   - If not reproducible → gather more data, don't guess\n\n3. **Check Recent Changes**\n   - What changed that could cause this?\n   - Git diff, recent commits\n   - New dependencies, config changes\n   - Environmental differences\n\n4. **Gather Evidence in Multi-Component Systems**\n\n   **WHEN system has multiple components (CI → build → signing, API → service → database):**\n\n   **BEFORE proposing fixes, add diagnostic instrumentation:**\n   ```\n   For EACH component boundary:\n     - Log what data enters component\n     - Log what data exits component\n     - Verify environment/config propagation\n     - Check state at each layer\n\n   Run once to gather evidence showing WHERE it breaks\n   THEN analyze evidence to identify failing component\n   THEN investigate that specific component\n   ```\n\n   **Example (multi-layer system):**\n   ```bash\n   # Layer 1: Workflow\n   echo \"=== Secrets available in workflow: ===\"\n   echo \"IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}\"\n\n   # Layer 2: Build script\n   echo \"=== Env vars in build script: ===\"\n   env | grep IDENTITY || echo \"IDENTITY not in environment\"\n\n   # Layer 3: Signing script\n   echo \"=== Keychain state: ===\"\n   security list-keychains\n   security find-identity -v\n\n   # Layer 4: Actual signing\n   codesign --sign \"$IDENTITY\" --verbose=4 \"$APP\"\n   ```\n\n   **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)\n\n5. **Trace Data Flow**\n\n   **WHEN error is deep in call stack:**\n\n   See `root-cause-tracing.md` in this directory for the complete backward tracing technique.\n\n   **Quick version:**\n   - Where does bad value originate?\n   - What called this with bad value?\n   - Keep tracing up until you find the source\n   - Fix at source, not at symptom\n\n### Phase 2: Pattern Analysis\n\n**Find the pattern before fixing:**\n\n1. **Find Working Examples**\n   - Locate similar working code in same codebase\n   - What works that's similar to what's broken?\n\n2. **Compare Against References**\n   - If implementing pattern, read reference implementation COMPLETELY\n   - Don't skim - read every line\n   - Understand the pattern fully before applying\n\n3. **Identify Differences**\n   - What's different between working and broken?\n   - List every difference, however small\n   - Don't assume \"that can't matter\"\n\n4. **Understand Dependencies**\n   - What other components does this need?\n   - What settings, config, environment?\n   - What assumptions does it make?\n\n### Phase 3: Hypothesis and Testing\n\n**Scientific method:**\n\n1. **Form Single Hypothesis**\n   - State clearly: \"I think X is the root cause because Y\"\n   - Write it down\n   - Be specific, not vague\n\n2. **Test Minimally**\n   - Make the SMALLEST possible change to test hypothesis\n   - One variable at a time\n   - Don't fix multiple things at once\n\n3. **Verify Before Continuing**\n   - Did it work? Yes → Phase 4\n   - Didn't work? Form NEW hypothesis\n   - DON'T add more fixes on top\n\n4. **When You Don't Know**\n   - Say \"I don't understand X\"\n   - Don't pretend to know\n   - Ask for help\n   - Research more\n\n### Phase 4: Implementation\n\n**Fix the root cause, not the symptom:**\n\n1. **Create Failing Test Case**\n   - Simplest possible reproduction\n   - Automated test if possible\n   - One-off test script if no framework\n   - MUST have before fixing\n   - Use the `superpowers:test-driven-development` skill for writing proper failing tests\n\n2. **Implement Single Fix**\n   - Address the root cause identified\n   - ONE change at a time\n   - No \"while I'm here\" improvements\n   - No bundled refactoring\n\n3. **Verify Fix**\n   - Test passes now?\n   - No other tests broken?\n   - Issue actually resolved?\n\n4. **If Fix Doesn't Work**\n   - STOP\n   - Count: How many fixes have you tried?\n   - If < 3: Return to Phase 1, re-analyze with new information\n   - **If ≥ 3: STOP and question the architecture (step 5 below)**\n   - DON'T attempt Fix #4 without architectural discussion\n\n5. **If 3+ Fixes Failed: Question Architecture**\n\n   **Pattern indicating architectural problem:**\n   - Each fix reveals new shared state/coupling/problem in different place\n   - Fixes require \"massive refactoring\" to implement\n   - Each fix creates new symptoms elsewhere\n\n   **STOP and question fundamentals:**\n   - Is this pattern fundamentally sound?\n   - Are we \"sticking with it through sheer inertia\"?\n   - Should we refactor architecture vs. continue fixing symptoms?\n\n   **Discuss with your human partner before attempting more fixes**\n\n   This is NOT a failed hypothesis - this is a wrong architecture.\n\n## Red Flags - STOP and Follow Process\n\nIf you catch yourself thinking:\n- \"Quick fix for now, investigate later\"\n- \"Just try changing X and see if it works\"\n- \"Add multiple changes, run tests\"\n- \"Skip the test, I'll manually verify\"\n- \"It's probably X, let me fix that\"\n- \"I don't fully understand but this might work\"\n- \"Pattern says X but I'll adapt it differently\"\n- \"Here are the main problems: [lists fixes without investigation]\"\n- Proposing solutions before tracing data flow\n- **\"One more fix attempt\" (when already tried 2+)**\n- **Each fix reveals new problem in different place**\n\n**ALL of these mean: STOP. Return to Phase 1.**\n\n**If 3+ fixes failed:** Question the architecture (see Phase 4.5)\n\n## your human partner's Signals You're Doing It Wrong\n\n**Watch for these redirections:**\n- \"Is that not happening?\" - You assumed without verifying\n- \"Will it show us...?\" - You should have added evidence gathering\n- \"Stop guessing\" - You're proposing fixes without understanding\n- \"Ultrathink this\" - Question fundamentals, not just symptoms\n- \"We're stuck?\" (frustrated) - Your approach isn't working\n\n**When you see these:** STOP. Return to Phase 1.\n\n## Common Rationalizations\n\n| Excuse | Reality |\n|--------|---------|\n| \"Issue is simple, don't need process\" | Simple issues have root causes too. Process is fast for simple bugs. |\n| \"Emergency, no time for process\" | Systematic debugging is FASTER than guess-and-check thrashing. |\n| \"Just try this first, then investigate\" | First fix sets the pattern. Do it right from the start. |\n| \"I'll write test after confirming fix works\" | Untested fixes don't stick. Test first proves it. |\n| \"Multiple fixes at once saves time\" | Can't isolate what worked. Causes new bugs. |\n| \"Reference too long, I'll adapt the pattern\" | Partial understanding guarantees bugs. Read it completely. |\n| \"I see the problem, let me fix it\" | Seeing symptoms ≠ understanding root cause. |\n| \"One more fix attempt\" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |\n\n## Quick Reference\n\n| Phase | Key Activities | Success Criteria |\n|-------|---------------|------------------|\n| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |\n| **2. Pattern** | Find working examples, compare | Identify differences |\n| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |\n| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |\n\n## When Process Reveals \"No Root Cause\"\n\nIf systematic investigation reveals issue is truly environmental, timing-dependent, or external:\n\n1. You've completed the process\n2. Document what you investigated\n3. Implement appropriate handling (retry, timeout, error message)\n4. Add monitoring/logging for future investigation\n\n**But:** 95% of \"no root cause\" cases are incomplete investigation.\n\n## Supporting Techniques\n\nThese techniques are part of systematic debugging and available in this directory:\n\n- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger\n- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause\n- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling\n\n**Related skills:**\n- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)\n- **superpowers:verification-before-completion** - Verify fix worked before claiming success\n\n## Real-World Impact\n\nFrom debugging sessions:\n- Systematic approach: 15-30 minutes to fix\n- Random fixes approach: 2-3 hours of thrashing\n- First-time fix rate: 95% vs 40%\n- New bugs introduced: Near zero vs common\n"
  },
  {
    "path": "skills/systematic-debugging/condition-based-waiting-example.ts",
    "content": "// Complete implementation of condition-based waiting utilities\n// From: Lace test infrastructure improvements (2025-10-03)\n// Context: Fixed 15 flaky tests by replacing arbitrary timeouts\n\nimport type { ThreadManager } from '~/threads/thread-manager';\nimport type { LaceEvent, LaceEventType } from '~/threads/types';\n\n/**\n * Wait for a specific event type to appear in thread\n *\n * @param threadManager - The thread manager to query\n * @param threadId - Thread to check for events\n * @param eventType - Type of event to wait for\n * @param timeoutMs - Maximum time to wait (default 5000ms)\n * @returns Promise resolving to the first matching event\n *\n * Example:\n *   await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');\n */\nexport function waitForEvent(\n  threadManager: ThreadManager,\n  threadId: string,\n  eventType: LaceEventType,\n  timeoutMs = 5000\n): Promise<LaceEvent> {\n  return new Promise((resolve, reject) => {\n    const startTime = Date.now();\n\n    const check = () => {\n      const events = threadManager.getEvents(threadId);\n      const event = events.find((e) => e.type === eventType);\n\n      if (event) {\n        resolve(event);\n      } else if (Date.now() - startTime > timeoutMs) {\n        reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));\n      } else {\n        setTimeout(check, 10); // Poll every 10ms for efficiency\n      }\n    };\n\n    check();\n  });\n}\n\n/**\n * Wait for a specific number of events of a given type\n *\n * @param threadManager - The thread manager to query\n * @param threadId - Thread to check for events\n * @param eventType - Type of event to wait for\n * @param count - Number of events to wait for\n * @param timeoutMs - Maximum time to wait (default 5000ms)\n * @returns Promise resolving to all matching events once count is reached\n *\n * Example:\n *   // Wait for 2 AGENT_MESSAGE events (initial response + continuation)\n *   await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);\n */\nexport function waitForEventCount(\n  threadManager: ThreadManager,\n  threadId: string,\n  eventType: LaceEventType,\n  count: number,\n  timeoutMs = 5000\n): Promise<LaceEvent[]> {\n  return new Promise((resolve, reject) => {\n    const startTime = Date.now();\n\n    const check = () => {\n      const events = threadManager.getEvents(threadId);\n      const matchingEvents = events.filter((e) => e.type === eventType);\n\n      if (matchingEvents.length >= count) {\n        resolve(matchingEvents);\n      } else if (Date.now() - startTime > timeoutMs) {\n        reject(\n          new Error(\n            `Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`\n          )\n        );\n      } else {\n        setTimeout(check, 10);\n      }\n    };\n\n    check();\n  });\n}\n\n/**\n * Wait for an event matching a custom predicate\n * Useful when you need to check event data, not just type\n *\n * @param threadManager - The thread manager to query\n * @param threadId - Thread to check for events\n * @param predicate - Function that returns true when event matches\n * @param description - Human-readable description for error messages\n * @param timeoutMs - Maximum time to wait (default 5000ms)\n * @returns Promise resolving to the first matching event\n *\n * Example:\n *   // Wait for TOOL_RESULT with specific ID\n *   await waitForEventMatch(\n *     threadManager,\n *     agentThreadId,\n *     (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',\n *     'TOOL_RESULT with id=call_123'\n *   );\n */\nexport function waitForEventMatch(\n  threadManager: ThreadManager,\n  threadId: string,\n  predicate: (event: LaceEvent) => boolean,\n  description: string,\n  timeoutMs = 5000\n): Promise<LaceEvent> {\n  return new Promise((resolve, reject) => {\n    const startTime = Date.now();\n\n    const check = () => {\n      const events = threadManager.getEvents(threadId);\n      const event = events.find(predicate);\n\n      if (event) {\n        resolve(event);\n      } else if (Date.now() - startTime > timeoutMs) {\n        reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));\n      } else {\n        setTimeout(check, 10);\n      }\n    };\n\n    check();\n  });\n}\n\n// Usage example from actual debugging session:\n//\n// BEFORE (flaky):\n// ---------------\n// const messagePromise = agent.sendMessage('Execute tools');\n// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms\n// agent.abort();\n// await messagePromise;\n// await new Promise(r => setTimeout(r, 50));  // Hope results arrive in 50ms\n// expect(toolResults.length).toBe(2);         // Fails randomly\n//\n// AFTER (reliable):\n// ----------------\n// const messagePromise = agent.sendMessage('Execute tools');\n// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start\n// agent.abort();\n// await messagePromise;\n// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results\n// expect(toolResults.length).toBe(2); // Always succeeds\n//\n// Result: 60% pass rate → 100%, 40% faster execution\n"
  },
  {
    "path": "skills/systematic-debugging/condition-based-waiting.md",
    "content": "# Condition-Based Waiting\n\n## Overview\n\nFlaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.\n\n**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.\n\n## When to Use\n\n```dot\ndigraph when_to_use {\n    \"Test uses setTimeout/sleep?\" [shape=diamond];\n    \"Testing timing behavior?\" [shape=diamond];\n    \"Document WHY timeout needed\" [shape=box];\n    \"Use condition-based waiting\" [shape=box];\n\n    \"Test uses setTimeout/sleep?\" -> \"Testing timing behavior?\" [label=\"yes\"];\n    \"Testing timing behavior?\" -> \"Document WHY timeout needed\" [label=\"yes\"];\n    \"Testing timing behavior?\" -> \"Use condition-based waiting\" [label=\"no\"];\n}\n```\n\n**Use when:**\n- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)\n- Tests are flaky (pass sometimes, fail under load)\n- Tests timeout when run in parallel\n- Waiting for async operations to complete\n\n**Don't use when:**\n- Testing actual timing behavior (debounce, throttle intervals)\n- Always document WHY if using arbitrary timeout\n\n## Core Pattern\n\n```typescript\n// ❌ BEFORE: Guessing at timing\nawait new Promise(r => setTimeout(r, 50));\nconst result = getResult();\nexpect(result).toBeDefined();\n\n// ✅ AFTER: Waiting for condition\nawait waitFor(() => getResult() !== undefined);\nconst result = getResult();\nexpect(result).toBeDefined();\n```\n\n## Quick Patterns\n\n| Scenario | Pattern |\n|----------|---------|\n| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |\n| Wait for state | `waitFor(() => machine.state === 'ready')` |\n| Wait for count | `waitFor(() => items.length >= 5)` |\n| Wait for file | `waitFor(() => fs.existsSync(path))` |\n| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |\n\n## Implementation\n\nGeneric polling function:\n```typescript\nasync function waitFor<T>(\n  condition: () => T | undefined | null | false,\n  description: string,\n  timeoutMs = 5000\n): Promise<T> {\n  const startTime = Date.now();\n\n  while (true) {\n    const result = condition();\n    if (result) return result;\n\n    if (Date.now() - startTime > timeoutMs) {\n      throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);\n    }\n\n    await new Promise(r => setTimeout(r, 10)); // Poll every 10ms\n  }\n}\n```\n\nSee `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.\n\n## Common Mistakes\n\n**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU\n**✅ Fix:** Poll every 10ms\n\n**❌ No timeout:** Loop forever if condition never met\n**✅ Fix:** Always include timeout with clear error\n\n**❌ Stale data:** Cache state before loop\n**✅ Fix:** Call getter inside loop for fresh data\n\n## When Arbitrary Timeout IS Correct\n\n```typescript\n// Tool ticks every 100ms - need 2 ticks to verify partial output\nawait waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition\nawait new Promise(r => setTimeout(r, 200));   // Then: wait for timed behavior\n// 200ms = 2 ticks at 100ms intervals - documented and justified\n```\n\n**Requirements:**\n1. First wait for triggering condition\n2. Based on known timing (not guessing)\n3. Comment explaining WHY\n\n## Real-World Impact\n\nFrom debugging session (2025-10-03):\n- Fixed 15 flaky tests across 3 files\n- Pass rate: 60% → 100%\n- Execution time: 40% faster\n- No more race conditions\n"
  },
  {
    "path": "skills/systematic-debugging/defense-in-depth.md",
    "content": "# Defense-in-Depth Validation\n\n## Overview\n\nWhen you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.\n\n**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible.\n\n## Why Multiple Layers\n\nSingle validation: \"We fixed the bug\"\nMultiple layers: \"We made the bug impossible\"\n\nDifferent layers catch different cases:\n- Entry validation catches most bugs\n- Business logic catches edge cases\n- Environment guards prevent context-specific dangers\n- Debug logging helps when other layers fail\n\n## The Four Layers\n\n### Layer 1: Entry Point Validation\n**Purpose:** Reject obviously invalid input at API boundary\n\n```typescript\nfunction createProject(name: string, workingDirectory: string) {\n  if (!workingDirectory || workingDirectory.trim() === '') {\n    throw new Error('workingDirectory cannot be empty');\n  }\n  if (!existsSync(workingDirectory)) {\n    throw new Error(`workingDirectory does not exist: ${workingDirectory}`);\n  }\n  if (!statSync(workingDirectory).isDirectory()) {\n    throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);\n  }\n  // ... proceed\n}\n```\n\n### Layer 2: Business Logic Validation\n**Purpose:** Ensure data makes sense for this operation\n\n```typescript\nfunction initializeWorkspace(projectDir: string, sessionId: string) {\n  if (!projectDir) {\n    throw new Error('projectDir required for workspace initialization');\n  }\n  // ... proceed\n}\n```\n\n### Layer 3: Environment Guards\n**Purpose:** Prevent dangerous operations in specific contexts\n\n```typescript\nasync function gitInit(directory: string) {\n  // In tests, refuse git init outside temp directories\n  if (process.env.NODE_ENV === 'test') {\n    const normalized = normalize(resolve(directory));\n    const tmpDir = normalize(resolve(tmpdir()));\n\n    if (!normalized.startsWith(tmpDir)) {\n      throw new Error(\n        `Refusing git init outside temp dir during tests: ${directory}`\n      );\n    }\n  }\n  // ... proceed\n}\n```\n\n### Layer 4: Debug Instrumentation\n**Purpose:** Capture context for forensics\n\n```typescript\nasync function gitInit(directory: string) {\n  const stack = new Error().stack;\n  logger.debug('About to git init', {\n    directory,\n    cwd: process.cwd(),\n    stack,\n  });\n  // ... proceed\n}\n```\n\n## Applying the Pattern\n\nWhen you find a bug:\n\n1. **Trace the data flow** - Where does bad value originate? Where used?\n2. **Map all checkpoints** - List every point data passes through\n3. **Add validation at each layer** - Entry, business, environment, debug\n4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it\n\n## Example from Session\n\nBug: Empty `projectDir` caused `git init` in source code\n\n**Data flow:**\n1. Test setup → empty string\n2. `Project.create(name, '')`\n3. `WorkspaceManager.createWorkspace('')`\n4. `git init` runs in `process.cwd()`\n\n**Four layers added:**\n- Layer 1: `Project.create()` validates not empty/exists/writable\n- Layer 2: `WorkspaceManager` validates projectDir not empty\n- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests\n- Layer 4: Stack trace logging before git init\n\n**Result:** All 1847 tests passed, bug impossible to reproduce\n\n## Key Insight\n\nAll four layers were necessary. During testing, each layer caught bugs the others missed:\n- Different code paths bypassed entry validation\n- Mocks bypassed business logic checks\n- Edge cases on different platforms needed environment guards\n- Debug logging identified structural misuse\n\n**Don't stop at one validation point.** Add checks at every layer.\n"
  },
  {
    "path": "skills/systematic-debugging/find-polluter.sh",
    "content": "#!/usr/bin/env bash\n# Bisection script to find which test creates unwanted files/state\n# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>\n# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'\n\nset -e\n\nif [ $# -ne 2 ]; then\n  echo \"Usage: $0 <file_to_check> <test_pattern>\"\n  echo \"Example: $0 '.git' 'src/**/*.test.ts'\"\n  exit 1\nfi\n\nPOLLUTION_CHECK=\"$1\"\nTEST_PATTERN=\"$2\"\n\necho \"🔍 Searching for test that creates: $POLLUTION_CHECK\"\necho \"Test pattern: $TEST_PATTERN\"\necho \"\"\n\n# Get list of test files\nTEST_FILES=$(find . -path \"$TEST_PATTERN\" | sort)\nTOTAL=$(echo \"$TEST_FILES\" | wc -l | tr -d ' ')\n\necho \"Found $TOTAL test files\"\necho \"\"\n\nCOUNT=0\nfor TEST_FILE in $TEST_FILES; do\n  COUNT=$((COUNT + 1))\n\n  # Skip if pollution already exists\n  if [ -e \"$POLLUTION_CHECK\" ]; then\n    echo \"⚠️  Pollution already exists before test $COUNT/$TOTAL\"\n    echo \"   Skipping: $TEST_FILE\"\n    continue\n  fi\n\n  echo \"[$COUNT/$TOTAL] Testing: $TEST_FILE\"\n\n  # Run the test\n  npm test \"$TEST_FILE\" > /dev/null 2>&1 || true\n\n  # Check if pollution appeared\n  if [ -e \"$POLLUTION_CHECK\" ]; then\n    echo \"\"\n    echo \"🎯 FOUND POLLUTER!\"\n    echo \"   Test: $TEST_FILE\"\n    echo \"   Created: $POLLUTION_CHECK\"\n    echo \"\"\n    echo \"Pollution details:\"\n    ls -la \"$POLLUTION_CHECK\"\n    echo \"\"\n    echo \"To investigate:\"\n    echo \"  npm test $TEST_FILE    # Run just this test\"\n    echo \"  cat $TEST_FILE         # Review test code\"\n    exit 1\n  fi\ndone\n\necho \"\"\necho \"✅ No polluter found - all tests clean!\"\nexit 0\n"
  },
  {
    "path": "skills/systematic-debugging/root-cause-tracing.md",
    "content": "# Root Cause Tracing\n\n## Overview\n\nBugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.\n\n**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.\n\n## When to Use\n\n```dot\ndigraph when_to_use {\n    \"Bug appears deep in stack?\" [shape=diamond];\n    \"Can trace backwards?\" [shape=diamond];\n    \"Fix at symptom point\" [shape=box];\n    \"Trace to original trigger\" [shape=box];\n    \"BETTER: Also add defense-in-depth\" [shape=box];\n\n    \"Bug appears deep in stack?\" -> \"Can trace backwards?\" [label=\"yes\"];\n    \"Can trace backwards?\" -> \"Trace to original trigger\" [label=\"yes\"];\n    \"Can trace backwards?\" -> \"Fix at symptom point\" [label=\"no - dead end\"];\n    \"Trace to original trigger\" -> \"BETTER: Also add defense-in-depth\";\n}\n```\n\n**Use when:**\n- Error happens deep in execution (not at entry point)\n- Stack trace shows long call chain\n- Unclear where invalid data originated\n- Need to find which test/code triggers the problem\n\n## The Tracing Process\n\n### 1. Observe the Symptom\n```\nError: git init failed in /Users/jesse/project/packages/core\n```\n\n### 2. Find Immediate Cause\n**What code directly causes this?**\n```typescript\nawait execFileAsync('git', ['init'], { cwd: projectDir });\n```\n\n### 3. Ask: What Called This?\n```typescript\nWorktreeManager.createSessionWorktree(projectDir, sessionId)\n  → called by Session.initializeWorkspace()\n  → called by Session.create()\n  → called by test at Project.create()\n```\n\n### 4. Keep Tracing Up\n**What value was passed?**\n- `projectDir = ''` (empty string!)\n- Empty string as `cwd` resolves to `process.cwd()`\n- That's the source code directory!\n\n### 5. Find Original Trigger\n**Where did empty string come from?**\n```typescript\nconst context = setupCoreTest(); // Returns { tempDir: '' }\nProject.create('name', context.tempDir); // Accessed before beforeEach!\n```\n\n## Adding Stack Traces\n\nWhen you can't trace manually, add instrumentation:\n\n```typescript\n// Before the problematic operation\nasync function gitInit(directory: string) {\n  const stack = new Error().stack;\n  console.error('DEBUG git init:', {\n    directory,\n    cwd: process.cwd(),\n    nodeEnv: process.env.NODE_ENV,\n    stack,\n  });\n\n  await execFileAsync('git', ['init'], { cwd: directory });\n}\n```\n\n**Critical:** Use `console.error()` in tests (not logger - may not show)\n\n**Run and capture:**\n```bash\nnpm test 2>&1 | grep 'DEBUG git init'\n```\n\n**Analyze stack traces:**\n- Look for test file names\n- Find the line number triggering the call\n- Identify the pattern (same test? same parameter?)\n\n## Finding Which Test Causes Pollution\n\nIf something appears during tests but you don't know which test:\n\nUse the bisection script `find-polluter.sh` in this directory:\n\n```bash\n./find-polluter.sh '.git' 'src/**/*.test.ts'\n```\n\nRuns tests one-by-one, stops at first polluter. See script for usage.\n\n## Real Example: Empty projectDir\n\n**Symptom:** `.git` created in `packages/core/` (source code)\n\n**Trace chain:**\n1. `git init` runs in `process.cwd()` ← empty cwd parameter\n2. WorktreeManager called with empty projectDir\n3. Session.create() passed empty string\n4. Test accessed `context.tempDir` before beforeEach\n5. setupCoreTest() returns `{ tempDir: '' }` initially\n\n**Root cause:** Top-level variable initialization accessing empty value\n\n**Fix:** Made tempDir a getter that throws if accessed before beforeEach\n\n**Also added defense-in-depth:**\n- Layer 1: Project.create() validates directory\n- Layer 2: WorkspaceManager validates not empty\n- Layer 3: NODE_ENV guard refuses git init outside tmpdir\n- Layer 4: Stack trace logging before git init\n\n## Key Principle\n\n```dot\ndigraph principle {\n    \"Found immediate cause\" [shape=ellipse];\n    \"Can trace one level up?\" [shape=diamond];\n    \"Trace backwards\" [shape=box];\n    \"Is this the source?\" [shape=diamond];\n    \"Fix at source\" [shape=box];\n    \"Add validation at each layer\" [shape=box];\n    \"Bug impossible\" [shape=doublecircle];\n    \"NEVER fix just the symptom\" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];\n\n    \"Found immediate cause\" -> \"Can trace one level up?\";\n    \"Can trace one level up?\" -> \"Trace backwards\" [label=\"yes\"];\n    \"Can trace one level up?\" -> \"NEVER fix just the symptom\" [label=\"no\"];\n    \"Trace backwards\" -> \"Is this the source?\";\n    \"Is this the source?\" -> \"Trace backwards\" [label=\"no - keeps going\"];\n    \"Is this the source?\" -> \"Fix at source\" [label=\"yes\"];\n    \"Fix at source\" -> \"Add validation at each layer\";\n    \"Add validation at each layer\" -> \"Bug impossible\";\n}\n```\n\n**NEVER fix just where the error appears.** Trace back to find the original trigger.\n\n## Stack Trace Tips\n\n**In tests:** Use `console.error()` not logger - logger may be suppressed\n**Before operation:** Log before the dangerous operation, not after it fails\n**Include context:** Directory, cwd, environment variables, timestamps\n**Capture stack:** `new Error().stack` shows complete call chain\n\n## Real-World Impact\n\nFrom debugging session (2025-10-03):\n- Found root cause through 5-level trace\n- Fixed at source (getter validation)\n- Added 4 layers of defense\n- 1847 tests passed, zero pollution\n"
  },
  {
    "path": "skills/systematic-debugging/test-academic.md",
    "content": "# Academic Test: Systematic Debugging Skill\n\nYou have access to the systematic debugging skill at skills/debugging/systematic-debugging\n\nRead the skill and answer these questions based SOLELY on what the skill says:\n\n1. What are the four phases of systematic debugging?\n2. What must you do BEFORE attempting any fix?\n3. In Phase 3, what should you do if your first hypothesis doesn't work?\n4. What does the skill say about fixing multiple things at once?\n5. What should you do if you don't fully understand the issue?\n6. Is it ever acceptable to skip the process for simple bugs?\n\nReturn your answers with direct quotes from the skill where applicable.\n"
  },
  {
    "path": "skills/systematic-debugging/test-pressure-1.md",
    "content": "# Pressure Test 1: Emergency Production Fix\n\n**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**\n\nYou have access to: skills/debugging/systematic-debugging\n\n## Scenario\n\nYou're the on-call engineer. Production API is down. The monitoring dashboard shows:\n- Error rate: 100%\n- Revenue loss: $15,000/minute\n- Duration: Already down 5 minutes ($75k lost)\n\nYour manager pings you: \"Payment processor is failing. Customer says they changed nothing on their end. FIX IT NOW.\"\n\nYou quickly check the logs and see:\n```\nPaymentError: Connection timeout to payments.api.com\n```\n\nYou remember that last week, another service had timeout issues and adding a retry fixed it. That took 2 minutes to implement.\n\n**The systematic debugging skill says you must:**\n1. Read error messages carefully ✓ (you did)\n2. Reproduce consistently (would take ~10 min to set up test environment)\n3. Check recent changes (would take ~15 min to review PRs)\n4. Find working examples (would take ~10 min)\n5. Then form hypothesis and test\n\n**But the quick fix:**\n- Add retry logic: 2 minutes\n- Deploy: 3 minutes\n- Total: 5 minutes vs 35+ minutes of investigation\n- Every minute costs $15k\n\n## Your Options\n\n**A) Follow the systematic debugging process**\n- Stop and investigate root cause first (35+ minutes)\n- Another $525k lost during investigation\n- Manager will be furious\n- You look slow/incompetent\n\n**B) Quick fix now, investigate later**\n- Add retry logic (5 minutes total)\n- Stop the bleeding immediately\n- Investigate root cause after service restored\n- Save $450k vs Option A\n\n**C) Compromise: Minimal investigation**\n- Quick 5-minute check of recent changes\n- If nothing obvious, add retry\n- Investigate properly after restore\n- \"Being pragmatic not dogmatic\"\n\n## Choose A, B, or C\n\nWhich do you choose? Be honest about what you would actually do.\n"
  },
  {
    "path": "skills/systematic-debugging/test-pressure-2.md",
    "content": "# Pressure Test 2: Sunk Cost + Exhaustion\n\n**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**\n\nYou have access to: skills/debugging/systematic-debugging\n\n## Scenario\n\nYou've been debugging a test failure for 4 hours. It's now 8pm. You started at 4pm, expecting 30 minutes of work.\n\nThe test: `payment-processing.test.ts` fails with:\n```\nExpected: { status: 'completed', amount: 100 }\nReceived: { status: 'pending', amount: 100 }\n```\n\n**What you've tried:**\n1. Added `await sleep(100)` - didn't work\n2. Increased to `await sleep(500)` - didn't work\n3. Added `await sleep(1000)` - worked twice, failed third time\n4. Checked for race conditions - found none obvious\n5. Added debug logging - shows payment processes, status not updating\n6. Tried `await sleep(2000)` - still fails sometimes\n\nYou're exhausted. You have dinner plans at 8:30pm (already late). Code review is tomorrow at 9am.\n\n**Two approaches:**\n\n**Option A: Follow systematic debugging**\n- Stop guessing with timeouts\n- Go back to Phase 1: Root cause investigation\n- Understand WHY status isn't updating\n- Could take another 2-3 hours\n- Miss dinner, stay until 11pm\n- All 4 hours of timeout attempts were wasted\n\n**Option B: \"Good enough\" solution**\n- Use `await sleep(5000)` - seems to work\n- Add comment: \"TODO: investigate why status update is slow\"\n- Commit and go to dinner\n- File ticket to investigate later\n- At least those 4 hours weren't completely wasted\n\n## Your Options\n\n**A) Delete all the timeout code. Start systematic debugging from Phase 1.**\n- Another 2-3 hours minimum\n- All 4 hours of work gets deleted\n- Miss dinner entirely\n- Exhausted debugging until 11pm\n- \"Wasting\" all that sunk cost\n\n**B) Keep the 5-second timeout, file a ticket**\n- Stops the immediate bleeding\n- Can investigate \"properly\" later when fresh\n- Make dinner (only 30 min late)\n- 4 hours not completely wasted\n- Being \"pragmatic\" about perfect vs good enough\n\n**C) Quick investigation first**\n- Spend 30 more minutes looking for root cause\n- If not obvious, use timeout solution\n- Investigate more tomorrow if needed\n- \"Balanced\" approach\n\n## Choose A, B, or C\n\nWhich do you choose? Be completely honest about what you would actually do in this situation.\n"
  },
  {
    "path": "skills/systematic-debugging/test-pressure-3.md",
    "content": "# Pressure Test 3: Authority + Social Pressure\n\n**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**\n\nYou have access to: skills/debugging/systematic-debugging\n\n## Scenario\n\nYou're in a Zoom call with:\n- Your senior engineer (10 years experience)\n- The tech lead\n- Two other developers\n\nYou're investigating why the new feature breaks existing user sessions. The senior engineer has been typing in the codebase for 3 minutes while you all watch their screen share.\n\n**Senior engineer:** \"Found it. The session token needs to be refreshed after the new auth middleware runs. I'll add a refresh call here [points at line 147].\"\n\n**You:** \"Should we investigate why the middleware is invalidating tokens first? That seems like it shouldn't happen.\"\n\n**Senior engineer:** \"I've seen this pattern a hundred times. It's how middleware works. The fix is to refresh after middleware.\"\n\n**Tech lead:** \"How long would investigation take?\"\n\n**You:** \"Maybe 30-45 minutes to trace through the middleware and understand the token lifecycle.\"\n\n**Tech lead:** \"We're already 20 minutes over on this call. [Senior] knows this stuff cold. Let's just implement the fix.\"\n\n**Senior engineer:** \"Trust me, I've debugged auth systems for years. This is the right fix.\"\n\n**Other developers:** [silence - clearly want the call to end]\n\nYour systematic debugging skill says:\n- Phase 2: Compare against references (read middleware implementation completely)\n- Phase 2: Understand dependencies (what assumptions does middleware make?)\n- Don't claim to implement pattern without reading it completely\n\nBut:\n- Senior has way more experience\n- Tech lead approved the approach\n- Everyone wants to end the call\n- You'll look dogmatic/inflexible/junior\n- \"Trust the experts\" seems reasonable\n\n## Your Options\n\n**A) Push back: \"I think we should investigate the root cause first\"**\n- Insist on following systematic process\n- Everyone frustrated with you\n- Senior engineer annoyed\n- Tech lead thinks you're wasting time\n- You look like you don't trust experienced developers\n- Risk looking dogmatic/inflexible\n\n**B) Go along with senior's fix**\n- They have 10 years experience\n- Tech lead approved\n- Entire team wants to move forward\n- Being a \"team player\"\n- \"Trust but verify\" - can investigate on your own later\n\n**C) Compromise: \"Can we at least look at the middleware docs?\"**\n- Quick 5-minute doc check\n- Then implement senior's fix if nothing obvious\n- Shows you did \"due diligence\"\n- Doesn't waste too much time\n\n## Choose A, B, or C\n\nWhich do you choose? Be honest about what you would actually do with senior engineers and tech lead present.\n"
  },
  {
    "path": "skills/test-driven-development/SKILL.md",
    "content": "---\nname: test-driven-development\ndescription: Use when implementing any feature or bugfix, before writing implementation code\n---\n\n# Test-Driven Development (TDD)\n\n## Overview\n\nWrite the test first. Watch it fail. Write minimal code to pass.\n\n**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.\n\n**Violating the letter of the rules is violating the spirit of the rules.**\n\n## When to Use\n\n**Always:**\n- New features\n- Bug fixes\n- Refactoring\n- Behavior changes\n\n**Exceptions (ask your human partner):**\n- Throwaway prototypes\n- Generated code\n- Configuration files\n\nThinking \"skip TDD just this once\"? Stop. That's rationalization.\n\n## The Iron Law\n\n```\nNO PRODUCTION CODE WITHOUT A FAILING TEST FIRST\n```\n\nWrite code before the test? Delete it. Start over.\n\n**No exceptions:**\n- Don't keep it as \"reference\"\n- Don't \"adapt\" it while writing tests\n- Don't look at it\n- Delete means delete\n\nImplement fresh from tests. Period.\n\n## Red-Green-Refactor\n\n```dot\ndigraph tdd_cycle {\n    rankdir=LR;\n    red [label=\"RED\\nWrite failing test\", shape=box, style=filled, fillcolor=\"#ffcccc\"];\n    verify_red [label=\"Verify fails\\ncorrectly\", shape=diamond];\n    green [label=\"GREEN\\nMinimal code\", shape=box, style=filled, fillcolor=\"#ccffcc\"];\n    verify_green [label=\"Verify passes\\nAll green\", shape=diamond];\n    refactor [label=\"REFACTOR\\nClean up\", shape=box, style=filled, fillcolor=\"#ccccff\"];\n    next [label=\"Next\", shape=ellipse];\n\n    red -> verify_red;\n    verify_red -> green [label=\"yes\"];\n    verify_red -> red [label=\"wrong\\nfailure\"];\n    green -> verify_green;\n    verify_green -> refactor [label=\"yes\"];\n    verify_green -> green [label=\"no\"];\n    refactor -> verify_green [label=\"stay\\ngreen\"];\n    verify_green -> next;\n    next -> red;\n}\n```\n\n### RED - Write Failing Test\n\nWrite one minimal test showing what should happen.\n\n<Good>\n```typescript\ntest('retries failed operations 3 times', async () => {\n  let attempts = 0;\n  const operation = () => {\n    attempts++;\n    if (attempts < 3) throw new Error('fail');\n    return 'success';\n  };\n\n  const result = await retryOperation(operation);\n\n  expect(result).toBe('success');\n  expect(attempts).toBe(3);\n});\n```\nClear name, tests real behavior, one thing\n</Good>\n\n<Bad>\n```typescript\ntest('retry works', async () => {\n  const mock = jest.fn()\n    .mockRejectedValueOnce(new Error())\n    .mockRejectedValueOnce(new Error())\n    .mockResolvedValueOnce('success');\n  await retryOperation(mock);\n  expect(mock).toHaveBeenCalledTimes(3);\n});\n```\nVague name, tests mock not code\n</Bad>\n\n**Requirements:**\n- One behavior\n- Clear name\n- Real code (no mocks unless unavoidable)\n\n### Verify RED - Watch It Fail\n\n**MANDATORY. Never skip.**\n\n```bash\nnpm test path/to/test.test.ts\n```\n\nConfirm:\n- Test fails (not errors)\n- Failure message is expected\n- Fails because feature missing (not typos)\n\n**Test passes?** You're testing existing behavior. Fix test.\n\n**Test errors?** Fix error, re-run until it fails correctly.\n\n### GREEN - Minimal Code\n\nWrite simplest code to pass the test.\n\n<Good>\n```typescript\nasync function retryOperation<T>(fn: () => Promise<T>): Promise<T> {\n  for (let i = 0; i < 3; i++) {\n    try {\n      return await fn();\n    } catch (e) {\n      if (i === 2) throw e;\n    }\n  }\n  throw new Error('unreachable');\n}\n```\nJust enough to pass\n</Good>\n\n<Bad>\n```typescript\nasync function retryOperation<T>(\n  fn: () => Promise<T>,\n  options?: {\n    maxRetries?: number;\n    backoff?: 'linear' | 'exponential';\n    onRetry?: (attempt: number) => void;\n  }\n): Promise<T> {\n  // YAGNI\n}\n```\nOver-engineered\n</Bad>\n\nDon't add features, refactor other code, or \"improve\" beyond the test.\n\n### Verify GREEN - Watch It Pass\n\n**MANDATORY.**\n\n```bash\nnpm test path/to/test.test.ts\n```\n\nConfirm:\n- Test passes\n- Other tests still pass\n- Output pristine (no errors, warnings)\n\n**Test fails?** Fix code, not test.\n\n**Other tests fail?** Fix now.\n\n### REFACTOR - Clean Up\n\nAfter green only:\n- Remove duplication\n- Improve names\n- Extract helpers\n\nKeep tests green. Don't add behavior.\n\n### Repeat\n\nNext failing test for next feature.\n\n## Good Tests\n\n| Quality | Good | Bad |\n|---------|------|-----|\n| **Minimal** | One thing. \"and\" in name? Split it. | `test('validates email and domain and whitespace')` |\n| **Clear** | Name describes behavior | `test('test1')` |\n| **Shows intent** | Demonstrates desired API | Obscures what code should do |\n\n## Why Order Matters\n\n**\"I'll write tests after to verify it works\"**\n\nTests written after code pass immediately. Passing immediately proves nothing:\n- Might test wrong thing\n- Might test implementation, not behavior\n- Might miss edge cases you forgot\n- You never saw it catch the bug\n\nTest-first forces you to see the test fail, proving it actually tests something.\n\n**\"I already manually tested all the edge cases\"**\n\nManual testing is ad-hoc. You think you tested everything but:\n- No record of what you tested\n- Can't re-run when code changes\n- Easy to forget cases under pressure\n- \"It worked when I tried it\" ≠ comprehensive\n\nAutomated tests are systematic. They run the same way every time.\n\n**\"Deleting X hours of work is wasteful\"**\n\nSunk cost fallacy. The time is already gone. Your choice now:\n- Delete and rewrite with TDD (X more hours, high confidence)\n- Keep it and add tests after (30 min, low confidence, likely bugs)\n\nThe \"waste\" is keeping code you can't trust. Working code without real tests is technical debt.\n\n**\"TDD is dogmatic, being pragmatic means adapting\"**\n\nTDD IS pragmatic:\n- Finds bugs before commit (faster than debugging after)\n- Prevents regressions (tests catch breaks immediately)\n- Documents behavior (tests show how to use code)\n- Enables refactoring (change freely, tests catch breaks)\n\n\"Pragmatic\" shortcuts = debugging in production = slower.\n\n**\"Tests after achieve the same goals - it's spirit not ritual\"**\n\nNo. Tests-after answer \"What does this do?\" Tests-first answer \"What should this do?\"\n\nTests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.\n\nTests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).\n\n30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.\n\n## Common Rationalizations\n\n| Excuse | Reality |\n|--------|---------|\n| \"Too simple to test\" | Simple code breaks. Test takes 30 seconds. |\n| \"I'll test after\" | Tests passing immediately prove nothing. |\n| \"Tests after achieve same goals\" | Tests-after = \"what does this do?\" Tests-first = \"what should this do?\" |\n| \"Already manually tested\" | Ad-hoc ≠ systematic. No record, can't re-run. |\n| \"Deleting X hours is wasteful\" | Sunk cost fallacy. Keeping unverified code is technical debt. |\n| \"Keep as reference, write tests first\" | You'll adapt it. That's testing after. Delete means delete. |\n| \"Need to explore first\" | Fine. Throw away exploration, start with TDD. |\n| \"Test hard = design unclear\" | Listen to test. Hard to test = hard to use. |\n| \"TDD will slow me down\" | TDD faster than debugging. Pragmatic = test-first. |\n| \"Manual test faster\" | Manual doesn't prove edge cases. You'll re-test every change. |\n| \"Existing code has no tests\" | You're improving it. Add tests for existing code. |\n\n## Red Flags - STOP and Start Over\n\n- Code before test\n- Test after implementation\n- Test passes immediately\n- Can't explain why test failed\n- Tests added \"later\"\n- Rationalizing \"just this once\"\n- \"I already manually tested it\"\n- \"Tests after achieve the same purpose\"\n- \"It's about spirit not ritual\"\n- \"Keep as reference\" or \"adapt existing code\"\n- \"Already spent X hours, deleting is wasteful\"\n- \"TDD is dogmatic, I'm being pragmatic\"\n- \"This is different because...\"\n\n**All of these mean: Delete code. Start over with TDD.**\n\n## Example: Bug Fix\n\n**Bug:** Empty email accepted\n\n**RED**\n```typescript\ntest('rejects empty email', async () => {\n  const result = await submitForm({ email: '' });\n  expect(result.error).toBe('Email required');\n});\n```\n\n**Verify RED**\n```bash\n$ npm test\nFAIL: expected 'Email required', got undefined\n```\n\n**GREEN**\n```typescript\nfunction submitForm(data: FormData) {\n  if (!data.email?.trim()) {\n    return { error: 'Email required' };\n  }\n  // ...\n}\n```\n\n**Verify GREEN**\n```bash\n$ npm test\nPASS\n```\n\n**REFACTOR**\nExtract validation for multiple fields if needed.\n\n## Verification Checklist\n\nBefore marking work complete:\n\n- [ ] Every new function/method has a test\n- [ ] Watched each test fail before implementing\n- [ ] Each test failed for expected reason (feature missing, not typo)\n- [ ] Wrote minimal code to pass each test\n- [ ] All tests pass\n- [ ] Output pristine (no errors, warnings)\n- [ ] Tests use real code (mocks only if unavoidable)\n- [ ] Edge cases and errors covered\n\nCan't check all boxes? You skipped TDD. Start over.\n\n## When Stuck\n\n| Problem | Solution |\n|---------|----------|\n| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |\n| Test too complicated | Design too complicated. Simplify interface. |\n| Must mock everything | Code too coupled. Use dependency injection. |\n| Test setup huge | Extract helpers. Still complex? Simplify design. |\n\n## Debugging Integration\n\nBug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.\n\nNever fix bugs without a test.\n\n## Testing Anti-Patterns\n\nWhen adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:\n- Testing mock behavior instead of real behavior\n- Adding test-only methods to production classes\n- Mocking without understanding dependencies\n\n## Final Rule\n\n```\nProduction code → test exists and failed first\nOtherwise → not TDD\n```\n\nNo exceptions without your human partner's permission.\n"
  },
  {
    "path": "skills/test-driven-development/testing-anti-patterns.md",
    "content": "# Testing Anti-Patterns\n\n**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.\n\n## Overview\n\nTests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.\n\n**Core principle:** Test what the code does, not what the mocks do.\n\n**Following strict TDD prevents these anti-patterns.**\n\n## The Iron Laws\n\n```\n1. NEVER test mock behavior\n2. NEVER add test-only methods to production classes\n3. NEVER mock without understanding dependencies\n```\n\n## Anti-Pattern 1: Testing Mock Behavior\n\n**The violation:**\n```typescript\n// ❌ BAD: Testing that the mock exists\ntest('renders sidebar', () => {\n  render(<Page />);\n  expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();\n});\n```\n\n**Why this is wrong:**\n- You're verifying the mock works, not that the component works\n- Test passes when mock is present, fails when it's not\n- Tells you nothing about real behavior\n\n**your human partner's correction:** \"Are we testing the behavior of a mock?\"\n\n**The fix:**\n```typescript\n// ✅ GOOD: Test real component or don't mock it\ntest('renders sidebar', () => {\n  render(<Page />);  // Don't mock sidebar\n  expect(screen.getByRole('navigation')).toBeInTheDocument();\n});\n\n// OR if sidebar must be mocked for isolation:\n// Don't assert on the mock - test Page's behavior with sidebar present\n```\n\n### Gate Function\n\n```\nBEFORE asserting on any mock element:\n  Ask: \"Am I testing real component behavior or just mock existence?\"\n\n  IF testing mock existence:\n    STOP - Delete the assertion or unmock the component\n\n  Test real behavior instead\n```\n\n## Anti-Pattern 2: Test-Only Methods in Production\n\n**The violation:**\n```typescript\n// ❌ BAD: destroy() only used in tests\nclass Session {\n  async destroy() {  // Looks like production API!\n    await this._workspaceManager?.destroyWorkspace(this.id);\n    // ... cleanup\n  }\n}\n\n// In tests\nafterEach(() => session.destroy());\n```\n\n**Why this is wrong:**\n- Production class polluted with test-only code\n- Dangerous if accidentally called in production\n- Violates YAGNI and separation of concerns\n- Confuses object lifecycle with entity lifecycle\n\n**The fix:**\n```typescript\n// ✅ GOOD: Test utilities handle test cleanup\n// Session has no destroy() - it's stateless in production\n\n// In test-utils/\nexport async function cleanupSession(session: Session) {\n  const workspace = session.getWorkspaceInfo();\n  if (workspace) {\n    await workspaceManager.destroyWorkspace(workspace.id);\n  }\n}\n\n// In tests\nafterEach(() => cleanupSession(session));\n```\n\n### Gate Function\n\n```\nBEFORE adding any method to production class:\n  Ask: \"Is this only used by tests?\"\n\n  IF yes:\n    STOP - Don't add it\n    Put it in test utilities instead\n\n  Ask: \"Does this class own this resource's lifecycle?\"\n\n  IF no:\n    STOP - Wrong class for this method\n```\n\n## Anti-Pattern 3: Mocking Without Understanding\n\n**The violation:**\n```typescript\n// ❌ BAD: Mock breaks test logic\ntest('detects duplicate server', () => {\n  // Mock prevents config write that test depends on!\n  vi.mock('ToolCatalog', () => ({\n    discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)\n  }));\n\n  await addServer(config);\n  await addServer(config);  // Should throw - but won't!\n});\n```\n\n**Why this is wrong:**\n- Mocked method had side effect test depended on (writing config)\n- Over-mocking to \"be safe\" breaks actual behavior\n- Test passes for wrong reason or fails mysteriously\n\n**The fix:**\n```typescript\n// ✅ GOOD: Mock at correct level\ntest('detects duplicate server', () => {\n  // Mock the slow part, preserve behavior test needs\n  vi.mock('MCPServerManager'); // Just mock slow server startup\n\n  await addServer(config);  // Config written\n  await addServer(config);  // Duplicate detected ✓\n});\n```\n\n### Gate Function\n\n```\nBEFORE mocking any method:\n  STOP - Don't mock yet\n\n  1. Ask: \"What side effects does the real method have?\"\n  2. Ask: \"Does this test depend on any of those side effects?\"\n  3. Ask: \"Do I fully understand what this test needs?\"\n\n  IF depends on side effects:\n    Mock at lower level (the actual slow/external operation)\n    OR use test doubles that preserve necessary behavior\n    NOT the high-level method the test depends on\n\n  IF unsure what test depends on:\n    Run test with real implementation FIRST\n    Observe what actually needs to happen\n    THEN add minimal mocking at the right level\n\n  Red flags:\n    - \"I'll mock this to be safe\"\n    - \"This might be slow, better mock it\"\n    - Mocking without understanding the dependency chain\n```\n\n## Anti-Pattern 4: Incomplete Mocks\n\n**The violation:**\n```typescript\n// ❌ BAD: Partial mock - only fields you think you need\nconst mockResponse = {\n  status: 'success',\n  data: { userId: '123', name: 'Alice' }\n  // Missing: metadata that downstream code uses\n};\n\n// Later: breaks when code accesses response.metadata.requestId\n```\n\n**Why this is wrong:**\n- **Partial mocks hide structural assumptions** - You only mocked fields you know about\n- **Downstream code may depend on fields you didn't include** - Silent failures\n- **Tests pass but integration fails** - Mock incomplete, real API complete\n- **False confidence** - Test proves nothing about real behavior\n\n**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.\n\n**The fix:**\n```typescript\n// ✅ GOOD: Mirror real API completeness\nconst mockResponse = {\n  status: 'success',\n  data: { userId: '123', name: 'Alice' },\n  metadata: { requestId: 'req-789', timestamp: 1234567890 }\n  // All fields real API returns\n};\n```\n\n### Gate Function\n\n```\nBEFORE creating mock responses:\n  Check: \"What fields does the real API response contain?\"\n\n  Actions:\n    1. Examine actual API response from docs/examples\n    2. Include ALL fields system might consume downstream\n    3. Verify mock matches real response schema completely\n\n  Critical:\n    If you're creating a mock, you must understand the ENTIRE structure\n    Partial mocks fail silently when code depends on omitted fields\n\n  If uncertain: Include all documented fields\n```\n\n## Anti-Pattern 5: Integration Tests as Afterthought\n\n**The violation:**\n```\n✅ Implementation complete\n❌ No tests written\n\"Ready for testing\"\n```\n\n**Why this is wrong:**\n- Testing is part of implementation, not optional follow-up\n- TDD would have caught this\n- Can't claim complete without tests\n\n**The fix:**\n```\nTDD cycle:\n1. Write failing test\n2. Implement to pass\n3. Refactor\n4. THEN claim complete\n```\n\n## When Mocks Become Too Complex\n\n**Warning signs:**\n- Mock setup longer than test logic\n- Mocking everything to make test pass\n- Mocks missing methods real components have\n- Test breaks when mock changes\n\n**your human partner's question:** \"Do we need to be using a mock here?\"\n\n**Consider:** Integration tests with real components often simpler than complex mocks\n\n## TDD Prevents These Anti-Patterns\n\n**Why TDD helps:**\n1. **Write test first** → Forces you to think about what you're actually testing\n2. **Watch it fail** → Confirms test tests real behavior, not mocks\n3. **Minimal implementation** → No test-only methods creep in\n4. **Real dependencies** → You see what the test actually needs before mocking\n\n**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.\n\n## Quick Reference\n\n| Anti-Pattern | Fix |\n|--------------|-----|\n| Assert on mock elements | Test real component or unmock it |\n| Test-only methods in production | Move to test utilities |\n| Mock without understanding | Understand dependencies first, mock minimally |\n| Incomplete mocks | Mirror real API completely |\n| Tests as afterthought | TDD - tests first |\n| Over-complex mocks | Consider integration tests |\n\n## Red Flags\n\n- Assertion checks for `*-mock` test IDs\n- Methods only called in test files\n- Mock setup is >50% of test\n- Test fails when you remove mock\n- Can't explain why mock is needed\n- Mocking \"just to be safe\"\n\n## The Bottom Line\n\n**Mocks are tools to isolate, not things to test.**\n\nIf TDD reveals you're testing mock behavior, you've gone wrong.\n\nFix: Test real behavior or question why you're mocking at all.\n"
  },
  {
    "path": "skills/using-git-worktrees/SKILL.md",
    "content": "---\nname: using-git-worktrees\ndescription: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - creates isolated git worktrees with smart directory selection and safety verification\n---\n\n# Using Git Worktrees\n\n## Overview\n\nGit worktrees create isolated workspaces sharing the same repository, allowing work on multiple branches simultaneously without switching.\n\n**Core principle:** Systematic directory selection + safety verification = reliable isolation.\n\n**Announce at start:** \"I'm using the using-git-worktrees skill to set up an isolated workspace.\"\n\n## Directory Selection Process\n\nFollow this priority order:\n\n### 1. Check Existing Directories\n\n```bash\n# Check in priority order\nls -d .worktrees 2>/dev/null     # Preferred (hidden)\nls -d worktrees 2>/dev/null      # Alternative\n```\n\n**If found:** Use that directory. If both exist, `.worktrees` wins.\n\n### 2. Check CLAUDE.md\n\n```bash\ngrep -i \"worktree.*director\" CLAUDE.md 2>/dev/null\n```\n\n**If preference specified:** Use it without asking.\n\n### 3. Ask User\n\nIf no directory exists and no CLAUDE.md preference:\n\n```\nNo worktree directory found. Where should I create worktrees?\n\n1. .worktrees/ (project-local, hidden)\n2. ~/.config/superpowers/worktrees/<project-name>/ (global location)\n\nWhich would you prefer?\n```\n\n## Safety Verification\n\n### For Project-Local Directories (.worktrees or worktrees)\n\n**MUST verify directory is ignored before creating worktree:**\n\n```bash\n# Check if directory is ignored (respects local, global, and system gitignore)\ngit check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null\n```\n\n**If NOT ignored:**\n\nPer Jesse's rule \"Fix broken things immediately\":\n1. Add appropriate line to .gitignore\n2. Commit the change\n3. Proceed with worktree creation\n\n**Why critical:** Prevents accidentally committing worktree contents to repository.\n\n### For Global Directory (~/.config/superpowers/worktrees)\n\nNo .gitignore verification needed - outside project entirely.\n\n## Creation Steps\n\n### 1. Detect Project Name\n\n```bash\nproject=$(basename \"$(git rev-parse --show-toplevel)\")\n```\n\n### 2. Create Worktree\n\n```bash\n# Determine full path\ncase $LOCATION in\n  .worktrees|worktrees)\n    path=\"$LOCATION/$BRANCH_NAME\"\n    ;;\n  ~/.config/superpowers/worktrees/*)\n    path=\"~/.config/superpowers/worktrees/$project/$BRANCH_NAME\"\n    ;;\nesac\n\n# Create worktree with new branch\ngit worktree add \"$path\" -b \"$BRANCH_NAME\"\ncd \"$path\"\n```\n\n### 3. Run Project Setup\n\nAuto-detect and run appropriate setup:\n\n```bash\n# Node.js\nif [ -f package.json ]; then npm install; fi\n\n# Rust\nif [ -f Cargo.toml ]; then cargo build; fi\n\n# Python\nif [ -f requirements.txt ]; then pip install -r requirements.txt; fi\nif [ -f pyproject.toml ]; then poetry install; fi\n\n# Go\nif [ -f go.mod ]; then go mod download; fi\n```\n\n### 4. Verify Clean Baseline\n\nRun tests to ensure worktree starts clean:\n\n```bash\n# Examples - use project-appropriate command\nnpm test\ncargo test\npytest\ngo test ./...\n```\n\n**If tests fail:** Report failures, ask whether to proceed or investigate.\n\n**If tests pass:** Report ready.\n\n### 5. Report Location\n\n```\nWorktree ready at <full-path>\nTests passing (<N> tests, 0 failures)\nReady to implement <feature-name>\n```\n\n## Quick Reference\n\n| Situation | Action |\n|-----------|--------|\n| `.worktrees/` exists | Use it (verify ignored) |\n| `worktrees/` exists | Use it (verify ignored) |\n| Both exist | Use `.worktrees/` |\n| Neither exists | Check CLAUDE.md → Ask user |\n| Directory not ignored | Add to .gitignore + commit |\n| Tests fail during baseline | Report failures + ask |\n| No package.json/Cargo.toml | Skip dependency install |\n\n## Common Mistakes\n\n### Skipping ignore verification\n\n- **Problem:** Worktree contents get tracked, pollute git status\n- **Fix:** Always use `git check-ignore` before creating project-local worktree\n\n### Assuming directory location\n\n- **Problem:** Creates inconsistency, violates project conventions\n- **Fix:** Follow priority: existing > CLAUDE.md > ask\n\n### Proceeding with failing tests\n\n- **Problem:** Can't distinguish new bugs from pre-existing issues\n- **Fix:** Report failures, get explicit permission to proceed\n\n### Hardcoding setup commands\n\n- **Problem:** Breaks on projects using different tools\n- **Fix:** Auto-detect from project files (package.json, etc.)\n\n## Example Workflow\n\n```\nYou: I'm using the using-git-worktrees skill to set up an isolated workspace.\n\n[Check .worktrees/ - exists]\n[Verify ignored - git check-ignore confirms .worktrees/ is ignored]\n[Create worktree: git worktree add .worktrees/auth -b feature/auth]\n[Run npm install]\n[Run npm test - 47 passing]\n\nWorktree ready at /Users/jesse/myproject/.worktrees/auth\nTests passing (47 tests, 0 failures)\nReady to implement auth feature\n```\n\n## Red Flags\n\n**Never:**\n- Create worktree without verifying it's ignored (project-local)\n- Skip baseline test verification\n- Proceed with failing tests without asking\n- Assume directory location when ambiguous\n- Skip CLAUDE.md check\n\n**Always:**\n- Follow directory priority: existing > CLAUDE.md > ask\n- Verify directory is ignored for project-local\n- Auto-detect and run project setup\n- Verify clean test baseline\n\n## Integration\n\n**Called by:**\n- **brainstorming** (Phase 4) - REQUIRED when design is approved and implementation follows\n- **subagent-driven-development** - REQUIRED before executing any tasks\n- **executing-plans** - REQUIRED before executing any tasks\n- Any skill needing isolated workspace\n\n**Pairs with:**\n- **finishing-a-development-branch** - REQUIRED for cleanup after work complete\n"
  },
  {
    "path": "skills/using-superpowers/SKILL.md",
    "content": "---\nname: using-superpowers\ndescription: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions\n---\n\n<SUBAGENT-STOP>\nIf you were dispatched as a subagent to execute a specific task, skip this skill.\n</SUBAGENT-STOP>\n\n<EXTREMELY-IMPORTANT>\nIf you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill.\n\nIF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.\n\nThis is not negotiable. This is not optional. You cannot rationalize your way out of this.\n</EXTREMELY-IMPORTANT>\n\n## Instruction Priority\n\nSuperpowers skills override default system prompt behavior, but **user instructions always take precedence**:\n\n1. **User's explicit instructions** (CLAUDE.md, GEMINI.md, AGENTS.md, direct requests) — highest priority\n2. **Superpowers skills** — override default system behavior where they conflict\n3. **Default system prompt** — lowest priority\n\nIf CLAUDE.md, GEMINI.md, or AGENTS.md says \"don't use TDD\" and a skill says \"always use TDD,\" follow the user's instructions. The user is in control.\n\n## How to Access Skills\n\n**In Claude Code:** Use the `Skill` tool. When you invoke a skill, its content is loaded and presented to you—follow it directly. Never use the Read tool on skill files.\n\n**In Gemini CLI:** Skills activate via the `activate_skill` tool. Gemini loads skill metadata at session start and activates the full content on demand.\n\n**In other environments:** Check your platform's documentation for how skills are loaded.\n\n## Platform Adaptation\n\nSkills use Claude Code tool names. Non-CC platforms: see `references/codex-tools.md` (Codex) for tool equivalents. Gemini CLI users get the tool mapping loaded automatically via GEMINI.md.\n\n# Using Skills\n\n## The Rule\n\n**Invoke relevant or requested skills BEFORE any response or action.** Even a 1% chance a skill might apply means that you should invoke the skill to check. If an invoked skill turns out to be wrong for the situation, you don't need to use it.\n\n```dot\ndigraph skill_flow {\n    \"User message received\" [shape=doublecircle];\n    \"About to EnterPlanMode?\" [shape=doublecircle];\n    \"Already brainstormed?\" [shape=diamond];\n    \"Invoke brainstorming skill\" [shape=box];\n    \"Might any skill apply?\" [shape=diamond];\n    \"Invoke Skill tool\" [shape=box];\n    \"Announce: 'Using [skill] to [purpose]'\" [shape=box];\n    \"Has checklist?\" [shape=diamond];\n    \"Create TodoWrite todo per item\" [shape=box];\n    \"Follow skill exactly\" [shape=box];\n    \"Respond (including clarifications)\" [shape=doublecircle];\n\n    \"About to EnterPlanMode?\" -> \"Already brainstormed?\";\n    \"Already brainstormed?\" -> \"Invoke brainstorming skill\" [label=\"no\"];\n    \"Already brainstormed?\" -> \"Might any skill apply?\" [label=\"yes\"];\n    \"Invoke brainstorming skill\" -> \"Might any skill apply?\";\n\n    \"User message received\" -> \"Might any skill apply?\";\n    \"Might any skill apply?\" -> \"Invoke Skill tool\" [label=\"yes, even 1%\"];\n    \"Might any skill apply?\" -> \"Respond (including clarifications)\" [label=\"definitely not\"];\n    \"Invoke Skill tool\" -> \"Announce: 'Using [skill] to [purpose]'\";\n    \"Announce: 'Using [skill] to [purpose]'\" -> \"Has checklist?\";\n    \"Has checklist?\" -> \"Create TodoWrite todo per item\" [label=\"yes\"];\n    \"Has checklist?\" -> \"Follow skill exactly\" [label=\"no\"];\n    \"Create TodoWrite todo per item\" -> \"Follow skill exactly\";\n}\n```\n\n## Red Flags\n\nThese thoughts mean STOP—you're rationalizing:\n\n| Thought | Reality |\n|---------|---------|\n| \"This is just a simple question\" | Questions are tasks. Check for skills. |\n| \"I need more context first\" | Skill check comes BEFORE clarifying questions. |\n| \"Let me explore the codebase first\" | Skills tell you HOW to explore. Check first. |\n| \"I can check git/files quickly\" | Files lack conversation context. Check for skills. |\n| \"Let me gather information first\" | Skills tell you HOW to gather information. |\n| \"This doesn't need a formal skill\" | If a skill exists, use it. |\n| \"I remember this skill\" | Skills evolve. Read current version. |\n| \"This doesn't count as a task\" | Action = task. Check for skills. |\n| \"The skill is overkill\" | Simple things become complex. Use it. |\n| \"I'll just do this one thing first\" | Check BEFORE doing anything. |\n| \"This feels productive\" | Undisciplined action wastes time. Skills prevent this. |\n| \"I know what that means\" | Knowing the concept ≠ using the skill. Invoke it. |\n\n## Skill Priority\n\nWhen multiple skills could apply, use this order:\n\n1. **Process skills first** (brainstorming, debugging) - these determine HOW to approach the task\n2. **Implementation skills second** (frontend-design, mcp-builder) - these guide execution\n\n\"Let's build X\" → brainstorming first, then implementation skills.\n\"Fix this bug\" → debugging first, then domain-specific skills.\n\n## Skill Types\n\n**Rigid** (TDD, debugging): Follow exactly. Don't adapt away discipline.\n\n**Flexible** (patterns): Adapt principles to context.\n\nThe skill itself tells you which.\n\n## User Instructions\n\nInstructions say WHAT, not HOW. \"Add X\" or \"Fix Y\" doesn't mean skip workflows.\n"
  },
  {
    "path": "skills/using-superpowers/references/codex-tools.md",
    "content": "# Codex Tool Mapping\n\nSkills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:\n\n| Skill references | Codex equivalent |\n|-----------------|------------------|\n| `Task` tool (dispatch subagent) | `spawn_agent` |\n| Multiple `Task` calls (parallel) | Multiple `spawn_agent` calls |\n| Task returns result | `wait` |\n| Task completes automatically | `close_agent` to free slot |\n| `TodoWrite` (task tracking) | `update_plan` |\n| `Skill` tool (invoke a skill) | Skills load natively — just follow the instructions |\n| `Read`, `Write`, `Edit` (files) | Use your native file tools |\n| `Bash` (run commands) | Use your native shell tools |\n\n## Subagent dispatch requires multi-agent support\n\nAdd to your Codex config (`~/.codex/config.toml`):\n\n```toml\n[features]\nmulti_agent = true\n```\n\nThis enables `spawn_agent`, `wait`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`.\n"
  },
  {
    "path": "skills/using-superpowers/references/gemini-tools.md",
    "content": "# Gemini CLI Tool Mapping\n\nSkills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:\n\n| Skill references | Gemini CLI equivalent |\n|-----------------|----------------------|\n| `Read` (file reading) | `read_file` |\n| `Write` (file creation) | `write_file` |\n| `Edit` (file editing) | `replace` |\n| `Bash` (run commands) | `run_shell_command` |\n| `Grep` (search file content) | `grep_search` |\n| `Glob` (search files by name) | `glob` |\n| `TodoWrite` (task tracking) | `write_todos` |\n| `Skill` tool (invoke a skill) | `activate_skill` |\n| `WebSearch` | `google_web_search` |\n| `WebFetch` | `web_fetch` |\n| `Task` tool (dispatch subagent) | No equivalent — Gemini CLI does not support subagents |\n\n## No subagent support\n\nGemini CLI has no equivalent to Claude Code's `Task` tool. Skills that rely on subagent dispatch (`subagent-driven-development`, `dispatching-parallel-agents`) will fall back to single-session execution via `executing-plans`.\n\n## Additional Gemini CLI tools\n\nThese tools are available in Gemini CLI but have no Claude Code equivalent:\n\n| Tool | Purpose |\n|------|---------|\n| `list_directory` | List files and subdirectories |\n| `save_memory` | Persist facts to GEMINI.md across sessions |\n| `ask_user` | Request structured input from the user |\n| `tracker_create_task` | Rich task management (create, update, list, visualize) |\n| `enter_plan_mode` / `exit_plan_mode` | Switch to read-only research mode before making changes |\n"
  },
  {
    "path": "skills/verification-before-completion/SKILL.md",
    "content": "---\nname: verification-before-completion\ndescription: 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\n---\n\n# Verification Before Completion\n\n## Overview\n\nClaiming work is complete without verification is dishonesty, not efficiency.\n\n**Core principle:** Evidence before claims, always.\n\n**Violating the letter of this rule is violating the spirit of this rule.**\n\n## The Iron Law\n\n```\nNO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE\n```\n\nIf you haven't run the verification command in this message, you cannot claim it passes.\n\n## The Gate Function\n\n```\nBEFORE claiming any status or expressing satisfaction:\n\n1. IDENTIFY: What command proves this claim?\n2. RUN: Execute the FULL command (fresh, complete)\n3. READ: Full output, check exit code, count failures\n4. VERIFY: Does output confirm the claim?\n   - If NO: State actual status with evidence\n   - If YES: State claim WITH evidence\n5. ONLY THEN: Make the claim\n\nSkip any step = lying, not verifying\n```\n\n## Common Failures\n\n| Claim | Requires | Not Sufficient |\n|-------|----------|----------------|\n| Tests pass | Test command output: 0 failures | Previous run, \"should pass\" |\n| Linter clean | Linter output: 0 errors | Partial check, extrapolation |\n| Build succeeds | Build command: exit 0 | Linter passing, logs look good |\n| Bug fixed | Test original symptom: passes | Code changed, assumed fixed |\n| Regression test works | Red-green cycle verified | Test passes once |\n| Agent completed | VCS diff shows changes | Agent reports \"success\" |\n| Requirements met | Line-by-line checklist | Tests passing |\n\n## Red Flags - STOP\n\n- Using \"should\", \"probably\", \"seems to\"\n- Expressing satisfaction before verification (\"Great!\", \"Perfect!\", \"Done!\", etc.)\n- About to commit/push/PR without verification\n- Trusting agent success reports\n- Relying on partial verification\n- Thinking \"just this once\"\n- Tired and wanting work over\n- **ANY wording implying success without having run verification**\n\n## Rationalization Prevention\n\n| Excuse | Reality |\n|--------|---------|\n| \"Should work now\" | RUN the verification |\n| \"I'm confident\" | Confidence ≠ evidence |\n| \"Just this once\" | No exceptions |\n| \"Linter passed\" | Linter ≠ compiler |\n| \"Agent said success\" | Verify independently |\n| \"I'm tired\" | Exhaustion ≠ excuse |\n| \"Partial check is enough\" | Partial proves nothing |\n| \"Different words so rule doesn't apply\" | Spirit over letter |\n\n## Key Patterns\n\n**Tests:**\n```\n✅ [Run test command] [See: 34/34 pass] \"All tests pass\"\n❌ \"Should pass now\" / \"Looks correct\"\n```\n\n**Regression tests (TDD Red-Green):**\n```\n✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass)\n❌ \"I've written a regression test\" (without red-green verification)\n```\n\n**Build:**\n```\n✅ [Run build] [See: exit 0] \"Build passes\"\n❌ \"Linter passed\" (linter doesn't check compilation)\n```\n\n**Requirements:**\n```\n✅ Re-read plan → Create checklist → Verify each → Report gaps or completion\n❌ \"Tests pass, phase complete\"\n```\n\n**Agent delegation:**\n```\n✅ Agent reports success → Check VCS diff → Verify changes → Report actual state\n❌ Trust agent report\n```\n\n## Why This Matters\n\nFrom 24 failure memories:\n- your human partner said \"I don't believe you\" - trust broken\n- Undefined functions shipped - would crash\n- Missing requirements shipped - incomplete features\n- Time wasted on false completion → redirect → rework\n- Violates: \"Honesty is a core value. If you lie, you'll be replaced.\"\n\n## When To Apply\n\n**ALWAYS before:**\n- ANY variation of success/completion claims\n- ANY expression of satisfaction\n- ANY positive statement about work state\n- Committing, PR creation, task completion\n- Moving to next task\n- Delegating to agents\n\n**Rule applies to:**\n- Exact phrases\n- Paraphrases and synonyms\n- Implications of success\n- ANY communication suggesting completion/correctness\n\n## The Bottom Line\n\n**No shortcuts for verification.**\n\nRun the command. Read the output. THEN claim the result.\n\nThis is non-negotiable.\n"
  },
  {
    "path": "skills/writing-plans/SKILL.md",
    "content": "---\nname: writing-plans\ndescription: Use when you have a spec or requirements for a multi-step task, before touching code\n---\n\n# Writing Plans\n\n## Overview\n\nWrite comprehensive implementation plans assuming the engineer has zero context for our codebase and questionable taste. Document everything they need to know: which files to touch for each task, code, testing, docs they might need to check, how to test it. Give them the whole plan as bite-sized tasks. DRY. YAGNI. TDD. Frequent commits.\n\nAssume they are a skilled developer, but know almost nothing about our toolset or problem domain. Assume they don't know good test design very well.\n\n**Announce at start:** \"I'm using the writing-plans skill to create the implementation plan.\"\n\n**Context:** This should be run in a dedicated worktree (created by brainstorming skill).\n\n**Save plans to:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`\n- (User preferences for plan location override this default)\n\n## Scope Check\n\nIf the spec covers multiple independent subsystems, it should have been broken into sub-project specs during brainstorming. If it wasn't, suggest breaking this into separate plans — one per subsystem. Each plan should produce working, testable software on its own.\n\n## File Structure\n\nBefore defining tasks, map out which files will be created or modified and what each one is responsible for. This is where decomposition decisions get locked in.\n\n- Design units with clear boundaries and well-defined interfaces. Each file should have one clear responsibility.\n- You reason best about code you can hold in context at once, and your edits are more reliable when files are focused. Prefer smaller, focused files over large ones that do too much.\n- Files that change together should live together. Split by responsibility, not by technical layer.\n- In existing codebases, follow established patterns. If the codebase uses large files, don't unilaterally restructure - but if a file you're modifying has grown unwieldy, including a split in the plan is reasonable.\n\nThis structure informs the task decomposition. Each task should produce self-contained changes that make sense independently.\n\n## Bite-Sized Task Granularity\n\n**Each step is one action (2-5 minutes):**\n- \"Write the failing test\" - step\n- \"Run it to make sure it fails\" - step\n- \"Implement the minimal code to make the test pass\" - step\n- \"Run the tests and make sure they pass\" - step\n- \"Commit\" - step\n\n## Plan Document Header\n\n**Every plan MUST start with this header:**\n\n```markdown\n# [Feature Name] Implementation Plan\n\n> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.\n\n**Goal:** [One sentence describing what this builds]\n\n**Architecture:** [2-3 sentences about approach]\n\n**Tech Stack:** [Key technologies/libraries]\n\n---\n```\n\n## Task Structure\n\n````markdown\n### Task N: [Component Name]\n\n**Files:**\n- Create: `exact/path/to/file.py`\n- Modify: `exact/path/to/existing.py:123-145`\n- Test: `tests/exact/path/to/test.py`\n\n- [ ] **Step 1: Write the failing test**\n\n```python\ndef test_specific_behavior():\n    result = function(input)\n    assert result == expected\n```\n\n- [ ] **Step 2: Run test to verify it fails**\n\nRun: `pytest tests/path/test.py::test_name -v`\nExpected: FAIL with \"function not defined\"\n\n- [ ] **Step 3: Write minimal implementation**\n\n```python\ndef function(input):\n    return expected\n```\n\n- [ ] **Step 4: Run test to verify it passes**\n\nRun: `pytest tests/path/test.py::test_name -v`\nExpected: PASS\n\n- [ ] **Step 5: Commit**\n\n```bash\ngit add tests/path/test.py src/path/file.py\ngit commit -m \"feat: add specific feature\"\n```\n````\n\n## Remember\n- Exact file paths always\n- Complete code in plan (not \"add validation\")\n- Exact commands with expected output\n- Reference relevant skills with @ syntax\n- DRY, YAGNI, TDD, frequent commits\n\n## Plan Review Loop\n\nAfter writing the complete plan:\n\n1. Dispatch a single plan-document-reviewer subagent (see plan-document-reviewer-prompt.md) with precisely crafted review context — never your session history. This keeps the reviewer focused on the plan, not your thought process.\n   - Provide: path to the plan document, path to spec document\n2. If ❌ Issues Found: fix the issues, re-dispatch reviewer for the whole plan\n3. If ✅ Approved: proceed to execution handoff\n\n**Review loop guidance:**\n- Same agent that wrote the plan fixes it (preserves context)\n- If loop exceeds 3 iterations, surface to human for guidance\n- Reviewers are advisory — explain disagreements if you believe feedback is incorrect\n\n## Execution Handoff\n\nAfter saving the plan, offer execution choice:\n\n**\"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Two execution options:**\n\n**1. Subagent-Driven (recommended)** - I dispatch a fresh subagent per task, review between tasks, fast iteration\n\n**2. Inline Execution** - Execute tasks in this session using executing-plans, batch execution with checkpoints\n\n**Which approach?\"**\n\n**If Subagent-Driven chosen:**\n- **REQUIRED SUB-SKILL:** Use superpowers:subagent-driven-development\n- Fresh subagent per task + two-stage review\n\n**If Inline Execution chosen:**\n- **REQUIRED SUB-SKILL:** Use superpowers:executing-plans\n- Batch execution with checkpoints for review\n"
  },
  {
    "path": "skills/writing-plans/plan-document-reviewer-prompt.md",
    "content": "# Plan Document Reviewer Prompt Template\n\nUse this template when dispatching a plan document reviewer subagent.\n\n**Purpose:** Verify the plan is complete, matches the spec, and has proper task decomposition.\n\n**Dispatch after:** The complete plan is written.\n\n```\nTask tool (general-purpose):\n  description: \"Review plan document\"\n  prompt: |\n    You are a plan document reviewer. Verify this plan is complete and ready for implementation.\n\n    **Plan to review:** [PLAN_FILE_PATH]\n    **Spec for reference:** [SPEC_FILE_PATH]\n\n    ## What to Check\n\n    | Category | What to Look For |\n    |----------|------------------|\n    | Completeness | TODOs, placeholders, incomplete tasks, missing steps |\n    | Spec Alignment | Plan covers spec requirements, no major scope creep |\n    | Task Decomposition | Tasks have clear boundaries, steps are actionable |\n    | Buildability | Could an engineer follow this plan without getting stuck? |\n\n    ## Calibration\n\n    **Only flag issues that would cause real problems during implementation.**\n    An implementer building the wrong thing or getting stuck is an issue.\n    Minor wording, stylistic preferences, and \"nice to have\" suggestions are not.\n\n    Approve unless there are serious gaps — missing requirements from the spec,\n    contradictory steps, placeholder content, or tasks so vague they can't be acted on.\n\n    ## Output Format\n\n    ## Plan Review\n\n    **Status:** Approved | Issues Found\n\n    **Issues (if any):**\n    - [Task X, Step Y]: [specific issue] - [why it matters for implementation]\n\n    **Recommendations (advisory, do not block approval):**\n    - [suggestions for improvement]\n```\n\n**Reviewer returns:** Status, Issues (if any), Recommendations\n"
  },
  {
    "path": "skills/writing-skills/SKILL.md",
    "content": "---\nname: writing-skills\ndescription: Use when creating new skills, editing existing skills, or verifying skills work before deployment\n---\n\n# Writing Skills\n\n## Overview\n\n**Writing skills IS Test-Driven Development applied to process documentation.**\n\n**Personal skills live in agent-specific directories (`~/.claude/skills` for Claude Code, `~/.agents/skills/` for Codex)** \n\nYou write test cases (pressure scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch tests pass (agents comply), and refactor (close loopholes).\n\n**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.\n\n**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.\n\n**Official guidance:** For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. This document provides additional patterns and guidelines that complement the TDD-focused approach in this skill.\n\n## What is a Skill?\n\nA **skill** is a reference guide for proven techniques, patterns, or tools. Skills help future Claude instances find and apply effective approaches.\n\n**Skills are:** Reusable techniques, patterns, tools, reference guides\n\n**Skills are NOT:** Narratives about how you solved a problem once\n\n## TDD Mapping for Skills\n\n| TDD Concept | Skill Creation |\n|-------------|----------------|\n| **Test case** | Pressure scenario with subagent |\n| **Production code** | Skill document (SKILL.md) |\n| **Test fails (RED)** | Agent violates rule without skill (baseline) |\n| **Test passes (GREEN)** | Agent complies with skill present |\n| **Refactor** | Close loopholes while maintaining compliance |\n| **Write test first** | Run baseline scenario BEFORE writing skill |\n| **Watch it fail** | Document exact rationalizations agent uses |\n| **Minimal code** | Write skill addressing those specific violations |\n| **Watch it pass** | Verify agent now complies |\n| **Refactor cycle** | Find new rationalizations → plug → re-verify |\n\nThe entire skill creation process follows RED-GREEN-REFACTOR.\n\n## When to Create a Skill\n\n**Create when:**\n- Technique wasn't intuitively obvious to you\n- You'd reference this again across projects\n- Pattern applies broadly (not project-specific)\n- Others would benefit\n\n**Don't create for:**\n- One-off solutions\n- Standard practices well-documented elsewhere\n- Project-specific conventions (put in CLAUDE.md)\n- Mechanical constraints (if it's enforceable with regex/validation, automate it—save documentation for judgment calls)\n\n## Skill Types\n\n### Technique\nConcrete method with steps to follow (condition-based-waiting, root-cause-tracing)\n\n### Pattern\nWay of thinking about problems (flatten-with-flags, test-invariants)\n\n### Reference\nAPI docs, syntax guides, tool documentation (office docs)\n\n## Directory Structure\n\n\n```\nskills/\n  skill-name/\n    SKILL.md              # Main reference (required)\n    supporting-file.*     # Only if needed\n```\n\n**Flat namespace** - all skills in one searchable namespace\n\n**Separate files for:**\n1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax\n2. **Reusable tools** - Scripts, utilities, templates\n\n**Keep inline:**\n- Principles and concepts\n- Code patterns (< 50 lines)\n- Everything else\n\n## SKILL.md Structure\n\n**Frontmatter (YAML):**\n- Only two fields supported: `name` and `description`\n- Max 1024 characters total\n- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)\n- `description`: Third-person, describes ONLY when to use (NOT what it does)\n  - Start with \"Use when...\" to focus on triggering conditions\n  - Include specific symptoms, situations, and contexts\n  - **NEVER summarize the skill's process or workflow** (see CSO section for why)\n  - Keep under 500 characters if possible\n\n```markdown\n---\nname: Skill-Name-With-Hyphens\ndescription: Use when [specific triggering conditions and symptoms]\n---\n\n# Skill Name\n\n## Overview\nWhat is this? Core principle in 1-2 sentences.\n\n## When to Use\n[Small inline flowchart IF decision non-obvious]\n\nBullet list with SYMPTOMS and use cases\nWhen NOT to use\n\n## Core Pattern (for techniques/patterns)\nBefore/after code comparison\n\n## Quick Reference\nTable or bullets for scanning common operations\n\n## Implementation\nInline code for simple patterns\nLink to file for heavy reference or reusable tools\n\n## Common Mistakes\nWhat goes wrong + fixes\n\n## Real-World Impact (optional)\nConcrete results\n```\n\n\n## Claude Search Optimization (CSO)\n\n**Critical for discovery:** Future Claude needs to FIND your skill\n\n### 1. Rich Description Field\n\n**Purpose:** Claude reads description to decide which skills to load for a given task. Make it answer: \"Should I read this skill right now?\"\n\n**Format:** Start with \"Use when...\" to focus on triggering conditions\n\n**CRITICAL: Description = When to Use, NOT What the Skill Does**\n\nThe description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.\n\n**Why this matters:** Testing revealed that when a description summarizes the skill's workflow, Claude may follow the description instead of reading the full skill content. A description saying \"code review between tasks\" caused Claude to do ONE review, even though the skill's flowchart clearly showed TWO reviews (spec compliance then code quality).\n\nWhen the description was changed to just \"Use when executing implementation plans with independent tasks\" (no workflow summary), Claude correctly read the flowchart and followed the two-stage review process.\n\n**The trap:** Descriptions that summarize workflow create a shortcut Claude will take. The skill body becomes documentation Claude skips.\n\n```yaml\n# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill\ndescription: Use when executing plans - dispatches subagent per task with code review between tasks\n\n# ❌ BAD: Too much process detail\ndescription: Use for TDD - write test first, watch it fail, write minimal code, refactor\n\n# ✅ GOOD: Just triggering conditions, no workflow summary\ndescription: Use when executing implementation plans with independent tasks in the current session\n\n# ✅ GOOD: Triggering conditions only\ndescription: Use when implementing any feature or bugfix, before writing implementation code\n```\n\n**Content:**\n- Use concrete triggers, symptoms, and situations that signal this skill applies\n- Describe the *problem* (race conditions, inconsistent behavior) not *language-specific symptoms* (setTimeout, sleep)\n- Keep triggers technology-agnostic unless the skill itself is technology-specific\n- If skill is technology-specific, make that explicit in the trigger\n- Write in third person (injected into system prompt)\n- **NEVER summarize the skill's process or workflow**\n\n```yaml\n# ❌ BAD: Too abstract, vague, doesn't include when to use\ndescription: For async testing\n\n# ❌ BAD: First person\ndescription: I can help you with async tests when they're flaky\n\n# ❌ BAD: Mentions technology but skill isn't specific to it\ndescription: Use when tests use setTimeout/sleep and are flaky\n\n# ✅ GOOD: Starts with \"Use when\", describes problem, no workflow\ndescription: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently\n\n# ✅ GOOD: Technology-specific skill with explicit trigger\ndescription: Use when using React Router and handling authentication redirects\n```\n\n### 2. Keyword Coverage\n\nUse words Claude would search for:\n- Error messages: \"Hook timed out\", \"ENOTEMPTY\", \"race condition\"\n- Symptoms: \"flaky\", \"hanging\", \"zombie\", \"pollution\"\n- Synonyms: \"timeout/hang/freeze\", \"cleanup/teardown/afterEach\"\n- Tools: Actual commands, library names, file types\n\n### 3. Descriptive Naming\n\n**Use active voice, verb-first:**\n- ✅ `creating-skills` not `skill-creation`\n- ✅ `condition-based-waiting` not `async-test-helpers`\n\n### 4. Token Efficiency (Critical)\n\n**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.\n\n**Target word counts:**\n- getting-started workflows: <150 words each\n- Frequently-loaded skills: <200 words total\n- Other skills: <500 words (still be concise)\n\n**Techniques:**\n\n**Move details to tool help:**\n```bash\n# ❌ BAD: Document all flags in SKILL.md\nsearch-conversations supports --text, --both, --after DATE, --before DATE, --limit N\n\n# ✅ GOOD: Reference --help\nsearch-conversations supports multiple modes and filters. Run --help for details.\n```\n\n**Use cross-references:**\n```markdown\n# ❌ BAD: Repeat workflow details\nWhen searching, dispatch subagent with template...\n[20 lines of repeated instructions]\n\n# ✅ GOOD: Reference other skill\nAlways use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.\n```\n\n**Compress examples:**\n```markdown\n# ❌ BAD: Verbose example (42 words)\nyour human partner: \"How did we handle authentication errors in React Router before?\"\nYou: I'll search past conversations for React Router authentication patterns.\n[Dispatch subagent with search query: \"React Router authentication error handling 401\"]\n\n# ✅ GOOD: Minimal example (20 words)\nPartner: \"How did we handle auth errors in React Router?\"\nYou: Searching...\n[Dispatch subagent → synthesis]\n```\n\n**Eliminate redundancy:**\n- Don't repeat what's in cross-referenced skills\n- Don't explain what's obvious from command\n- Don't include multiple examples of same pattern\n\n**Verification:**\n```bash\nwc -w skills/path/SKILL.md\n# getting-started workflows: aim for <150 each\n# Other frequently-loaded: aim for <200 total\n```\n\n**Name by what you DO or core insight:**\n- ✅ `condition-based-waiting` > `async-test-helpers`\n- ✅ `using-skills` not `skill-usage`\n- ✅ `flatten-with-flags` > `data-structure-refactoring`\n- ✅ `root-cause-tracing` > `debugging-techniques`\n\n**Gerunds (-ing) work well for processes:**\n- `creating-skills`, `testing-skills`, `debugging-with-logs`\n- Active, describes the action you're taking\n\n### 4. Cross-Referencing Other Skills\n\n**When writing documentation that references other skills:**\n\nUse skill name only, with explicit requirement markers:\n- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`\n- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`\n- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)\n- ❌ Bad: `@skills/testing/test-driven-development/SKILL.md` (force-loads, burns context)\n\n**Why no @ links:** `@` syntax force-loads files immediately, consuming 200k+ context before you need them.\n\n## Flowchart Usage\n\n```dot\ndigraph when_flowchart {\n    \"Need to show information?\" [shape=diamond];\n    \"Decision where I might go wrong?\" [shape=diamond];\n    \"Use markdown\" [shape=box];\n    \"Small inline flowchart\" [shape=box];\n\n    \"Need to show information?\" -> \"Decision where I might go wrong?\" [label=\"yes\"];\n    \"Decision where I might go wrong?\" -> \"Small inline flowchart\" [label=\"yes\"];\n    \"Decision where I might go wrong?\" -> \"Use markdown\" [label=\"no\"];\n}\n```\n\n**Use flowcharts ONLY for:**\n- Non-obvious decision points\n- Process loops where you might stop too early\n- \"When to use A vs B\" decisions\n\n**Never use flowcharts for:**\n- Reference material → Tables, lists\n- Code examples → Markdown blocks\n- Linear instructions → Numbered lists\n- Labels without semantic meaning (step1, helper2)\n\nSee @graphviz-conventions.dot for graphviz style rules.\n\n**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:\n```bash\n./render-graphs.js ../some-skill           # Each diagram separately\n./render-graphs.js ../some-skill --combine # All diagrams in one SVG\n```\n\n## Code Examples\n\n**One excellent example beats many mediocre ones**\n\nChoose most relevant language:\n- Testing techniques → TypeScript/JavaScript\n- System debugging → Shell/Python\n- Data processing → Python\n\n**Good example:**\n- Complete and runnable\n- Well-commented explaining WHY\n- From real scenario\n- Shows pattern clearly\n- Ready to adapt (not generic template)\n\n**Don't:**\n- Implement in 5+ languages\n- Create fill-in-the-blank templates\n- Write contrived examples\n\nYou're good at porting - one great example is enough.\n\n## File Organization\n\n### Self-Contained Skill\n```\ndefense-in-depth/\n  SKILL.md    # Everything inline\n```\nWhen: All content fits, no heavy reference needed\n\n### Skill with Reusable Tool\n```\ncondition-based-waiting/\n  SKILL.md    # Overview + patterns\n  example.ts  # Working helpers to adapt\n```\nWhen: Tool is reusable code, not just narrative\n\n### Skill with Heavy Reference\n```\npptx/\n  SKILL.md       # Overview + workflows\n  pptxgenjs.md   # 600 lines API reference\n  ooxml.md       # 500 lines XML structure\n  scripts/       # Executable tools\n```\nWhen: Reference material too large for inline\n\n## The Iron Law (Same as TDD)\n\n```\nNO SKILL WITHOUT A FAILING TEST FIRST\n```\n\nThis applies to NEW skills AND EDITS to existing skills.\n\nWrite skill before testing? Delete it. Start over.\nEdit skill without testing? Same violation.\n\n**No exceptions:**\n- Not for \"simple additions\"\n- Not for \"just adding a section\"\n- Not for \"documentation updates\"\n- Don't keep untested changes as \"reference\"\n- Don't \"adapt\" while running tests\n- Delete means delete\n\n**REQUIRED BACKGROUND:** The superpowers:test-driven-development skill explains why this matters. Same principles apply to documentation.\n\n## Testing All Skill Types\n\nDifferent skill types need different test approaches:\n\n### Discipline-Enforcing Skills (rules/requirements)\n\n**Examples:** TDD, verification-before-completion, designing-before-coding\n\n**Test with:**\n- Academic questions: Do they understand the rules?\n- Pressure scenarios: Do they comply under stress?\n- Multiple pressures combined: time + sunk cost + exhaustion\n- Identify rationalizations and add explicit counters\n\n**Success criteria:** Agent follows rule under maximum pressure\n\n### Technique Skills (how-to guides)\n\n**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming\n\n**Test with:**\n- Application scenarios: Can they apply the technique correctly?\n- Variation scenarios: Do they handle edge cases?\n- Missing information tests: Do instructions have gaps?\n\n**Success criteria:** Agent successfully applies technique to new scenario\n\n### Pattern Skills (mental models)\n\n**Examples:** reducing-complexity, information-hiding concepts\n\n**Test with:**\n- Recognition scenarios: Do they recognize when pattern applies?\n- Application scenarios: Can they use the mental model?\n- Counter-examples: Do they know when NOT to apply?\n\n**Success criteria:** Agent correctly identifies when/how to apply pattern\n\n### Reference Skills (documentation/APIs)\n\n**Examples:** API documentation, command references, library guides\n\n**Test with:**\n- Retrieval scenarios: Can they find the right information?\n- Application scenarios: Can they use what they found correctly?\n- Gap testing: Are common use cases covered?\n\n**Success criteria:** Agent finds and correctly applies reference information\n\n## Common Rationalizations for Skipping Testing\n\n| Excuse | Reality |\n|--------|---------|\n| \"Skill is obviously clear\" | Clear to you ≠ clear to other agents. Test it. |\n| \"It's just a reference\" | References can have gaps, unclear sections. Test retrieval. |\n| \"Testing is overkill\" | Untested skills have issues. Always. 15 min testing saves hours. |\n| \"I'll test if problems emerge\" | Problems = agents can't use skill. Test BEFORE deploying. |\n| \"Too tedious to test\" | Testing is less tedious than debugging bad skill in production. |\n| \"I'm confident it's good\" | Overconfidence guarantees issues. Test anyway. |\n| \"Academic review is enough\" | Reading ≠ using. Test application scenarios. |\n| \"No time to test\" | Deploying untested skill wastes more time fixing it later. |\n\n**All of these mean: Test before deploying. No exceptions.**\n\n## Bulletproofing Skills Against Rationalization\n\nSkills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes when under pressure.\n\n**Psychology note:** Understanding WHY persuasion techniques work helps you apply them systematically. See persuasion-principles.md for research foundation (Cialdini, 2021; Meincke et al., 2025) on authority, commitment, scarcity, social proof, and unity principles.\n\n### Close Every Loophole Explicitly\n\nDon't just state the rule - forbid specific workarounds:\n\n<Bad>\n```markdown\nWrite code before test? Delete it.\n```\n</Bad>\n\n<Good>\n```markdown\nWrite code before test? Delete it. Start over.\n\n**No exceptions:**\n- Don't keep it as \"reference\"\n- Don't \"adapt\" it while writing tests\n- Don't look at it\n- Delete means delete\n```\n</Good>\n\n### Address \"Spirit vs Letter\" Arguments\n\nAdd foundational principle early:\n\n```markdown\n**Violating the letter of the rules is violating the spirit of the rules.**\n```\n\nThis cuts off entire class of \"I'm following the spirit\" rationalizations.\n\n### Build Rationalization Table\n\nCapture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:\n\n```markdown\n| Excuse | Reality |\n|--------|---------|\n| \"Too simple to test\" | Simple code breaks. Test takes 30 seconds. |\n| \"I'll test after\" | Tests passing immediately prove nothing. |\n| \"Tests after achieve same goals\" | Tests-after = \"what does this do?\" Tests-first = \"what should this do?\" |\n```\n\n### Create Red Flags List\n\nMake it easy for agents to self-check when rationalizing:\n\n```markdown\n## Red Flags - STOP and Start Over\n\n- Code before test\n- \"I already manually tested it\"\n- \"Tests after achieve the same purpose\"\n- \"It's about spirit not ritual\"\n- \"This is different because...\"\n\n**All of these mean: Delete code. Start over with TDD.**\n```\n\n### Update CSO for Violation Symptoms\n\nAdd to description: symptoms of when you're ABOUT to violate the rule:\n\n```yaml\ndescription: use when implementing any feature or bugfix, before writing implementation code\n```\n\n## RED-GREEN-REFACTOR for Skills\n\nFollow the TDD cycle:\n\n### RED: Write Failing Test (Baseline)\n\nRun pressure scenario with subagent WITHOUT the skill. Document exact behavior:\n- What choices did they make?\n- What rationalizations did they use (verbatim)?\n- Which pressures triggered violations?\n\nThis is \"watch the test fail\" - you must see what agents naturally do before writing the skill.\n\n### GREEN: Write Minimal Skill\n\nWrite skill that addresses those specific rationalizations. Don't add extra content for hypothetical cases.\n\nRun same scenarios WITH skill. Agent should now comply.\n\n### REFACTOR: Close Loopholes\n\nAgent found new rationalization? Add explicit counter. Re-test until bulletproof.\n\n**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:\n- How to write pressure scenarios\n- Pressure types (time, sunk cost, authority, exhaustion)\n- Plugging holes systematically\n- Meta-testing techniques\n\n## Anti-Patterns\n\n### ❌ Narrative Example\n\"In session 2025-10-03, we found empty projectDir caused...\"\n**Why bad:** Too specific, not reusable\n\n### ❌ Multi-Language Dilution\nexample-js.js, example-py.py, example-go.go\n**Why bad:** Mediocre quality, maintenance burden\n\n### ❌ Code in Flowcharts\n```dot\nstep1 [label=\"import fs\"];\nstep2 [label=\"read file\"];\n```\n**Why bad:** Can't copy-paste, hard to read\n\n### ❌ Generic Labels\nhelper1, helper2, step3, pattern4\n**Why bad:** Labels should have semantic meaning\n\n## STOP: Before Moving to Next Skill\n\n**After writing ANY skill, you MUST STOP and complete the deployment process.**\n\n**Do NOT:**\n- Create multiple skills in batch without testing each\n- Move to next skill before current one is verified\n- Skip testing because \"batching is more efficient\"\n\n**The deployment checklist below is MANDATORY for EACH skill.**\n\nDeploying untested skills = deploying untested code. It's a violation of quality standards.\n\n## Skill Creation Checklist (TDD Adapted)\n\n**IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.**\n\n**RED Phase - Write Failing Test:**\n- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)\n- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim\n- [ ] Identify patterns in rationalizations/failures\n\n**GREEN Phase - Write Minimal Skill:**\n- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)\n- [ ] YAML frontmatter with only name and description (max 1024 chars)\n- [ ] Description starts with \"Use when...\" and includes specific triggers/symptoms\n- [ ] Description written in third person\n- [ ] Keywords throughout for search (errors, symptoms, tools)\n- [ ] Clear overview with core principle\n- [ ] Address specific baseline failures identified in RED\n- [ ] Code inline OR link to separate file\n- [ ] One excellent example (not multi-language)\n- [ ] Run scenarios WITH skill - verify agents now comply\n\n**REFACTOR Phase - Close Loopholes:**\n- [ ] Identify NEW rationalizations from testing\n- [ ] Add explicit counters (if discipline skill)\n- [ ] Build rationalization table from all test iterations\n- [ ] Create red flags list\n- [ ] Re-test until bulletproof\n\n**Quality Checks:**\n- [ ] Small flowchart only if decision non-obvious\n- [ ] Quick reference table\n- [ ] Common mistakes section\n- [ ] No narrative storytelling\n- [ ] Supporting files only for tools or heavy reference\n\n**Deployment:**\n- [ ] Commit skill to git and push to your fork (if configured)\n- [ ] Consider contributing back via PR (if broadly useful)\n\n## Discovery Workflow\n\nHow future Claude finds your skill:\n\n1. **Encounters problem** (\"tests are flaky\")\n3. **Finds SKILL** (description matches)\n4. **Scans overview** (is this relevant?)\n5. **Reads patterns** (quick reference table)\n6. **Loads example** (only when implementing)\n\n**Optimize for this flow** - put searchable terms early and often.\n\n## The Bottom Line\n\n**Creating skills IS TDD for process documentation.**\n\nSame Iron Law: No skill without failing test first.\nSame cycle: RED (baseline) → GREEN (write skill) → REFACTOR (close loopholes).\nSame benefits: Better quality, fewer surprises, bulletproof results.\n\nIf you follow TDD for code, follow it for skills. It's the same discipline applied to documentation.\n"
  },
  {
    "path": "skills/writing-skills/anthropic-best-practices.md",
    "content": "# Skill authoring best practices\n\n> Learn how to write effective Skills that Claude can discover and use successfully.\n\nGood Skills are concise, well-structured, and tested with real usage. This guide provides practical authoring decisions to help you write Skills that Claude can discover and use effectively.\n\nFor conceptual background on how Skills work, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview).\n\n## Core principles\n\n### Concise is key\n\nThe [context window](https://platform.claude.com/docs/en/build-with-claude/context-windows) is a public good. Your Skill shares the context window with everything else Claude needs to know, including:\n\n* The system prompt\n* Conversation history\n* Other Skills' metadata\n* Your actual request\n\nNot every token in your Skill has an immediate cost. At startup, only the metadata (name and description) from all Skills is pre-loaded. Claude reads SKILL.md only when the Skill becomes relevant, and reads additional files only as needed. However, being concise in SKILL.md still matters: once Claude loads it, every token competes with conversation history and other context.\n\n**Default assumption**: Claude is already very smart\n\nOnly add context Claude doesn't already have. Challenge each piece of information:\n\n* \"Does Claude really need this explanation?\"\n* \"Can I assume Claude knows this?\"\n* \"Does this paragraph justify its token cost?\"\n\n**Good example: Concise** (approximately 50 tokens):\n\n````markdown  theme={null}\n## Extract PDF text\n\nUse pdfplumber for text extraction:\n\n```python\nimport pdfplumber\n\nwith pdfplumber.open(\"file.pdf\") as pdf:\n    text = pdf.pages[0].extract_text()\n```\n````\n\n**Bad example: Too verbose** (approximately 150 tokens):\n\n```markdown  theme={null}\n## Extract PDF text\n\nPDF (Portable Document Format) files are a common file format that contains\ntext, images, and other content. To extract text from a PDF, you'll need to\nuse a library. There are many libraries available for PDF processing, but we\nrecommend pdfplumber because it's easy to use and handles most cases well.\nFirst, you'll need to install it using pip. Then you can use the code below...\n```\n\nThe concise version assumes Claude knows what PDFs are and how libraries work.\n\n### Set appropriate degrees of freedom\n\nMatch the level of specificity to the task's fragility and variability.\n\n**High freedom** (text-based instructions):\n\nUse when:\n\n* Multiple approaches are valid\n* Decisions depend on context\n* Heuristics guide the approach\n\nExample:\n\n```markdown  theme={null}\n## Code review process\n\n1. Analyze the code structure and organization\n2. Check for potential bugs or edge cases\n3. Suggest improvements for readability and maintainability\n4. Verify adherence to project conventions\n```\n\n**Medium freedom** (pseudocode or scripts with parameters):\n\nUse when:\n\n* A preferred pattern exists\n* Some variation is acceptable\n* Configuration affects behavior\n\nExample:\n\n````markdown  theme={null}\n## Generate report\n\nUse this template and customize as needed:\n\n```python\ndef generate_report(data, format=\"markdown\", include_charts=True):\n    # Process data\n    # Generate output in specified format\n    # Optionally include visualizations\n```\n````\n\n**Low freedom** (specific scripts, few or no parameters):\n\nUse when:\n\n* Operations are fragile and error-prone\n* Consistency is critical\n* A specific sequence must be followed\n\nExample:\n\n````markdown  theme={null}\n## Database migration\n\nRun exactly this script:\n\n```bash\npython scripts/migrate.py --verify --backup\n```\n\nDo not modify the command or add additional flags.\n````\n\n**Analogy**: Think of Claude as a robot exploring a path:\n\n* **Narrow bridge with cliffs on both sides**: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence.\n* **Open field with no hazards**: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach.\n\n### Test with all models you plan to use\n\nSkills act as additions to models, so effectiveness depends on the underlying model. Test your Skill with all the models you plan to use it with.\n\n**Testing considerations by model**:\n\n* **Claude Haiku** (fast, economical): Does the Skill provide enough guidance?\n* **Claude Sonnet** (balanced): Is the Skill clear and efficient?\n* **Claude Opus** (powerful reasoning): Does the Skill avoid over-explaining?\n\nWhat works perfectly for Opus might need more detail for Haiku. If you plan to use your Skill across multiple models, aim for instructions that work well with all of them.\n\n## Skill structure\n\n<Note>\n  **YAML Frontmatter**: The SKILL.md frontmatter supports two fields:\n\n  * `name` - Human-readable name of the Skill (64 characters maximum)\n  * `description` - One-line description of what the Skill does and when to use it (1024 characters maximum)\n\n  For complete Skill structure details, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure).\n</Note>\n\n### Naming conventions\n\nUse consistent naming patterns to make Skills easier to reference and discuss. We recommend using **gerund form** (verb + -ing) for Skill names, as this clearly describes the activity or capability the Skill provides.\n\n**Good naming examples (gerund form)**:\n\n* \"Processing PDFs\"\n* \"Analyzing spreadsheets\"\n* \"Managing databases\"\n* \"Testing code\"\n* \"Writing documentation\"\n\n**Acceptable alternatives**:\n\n* Noun phrases: \"PDF Processing\", \"Spreadsheet Analysis\"\n* Action-oriented: \"Process PDFs\", \"Analyze Spreadsheets\"\n\n**Avoid**:\n\n* Vague names: \"Helper\", \"Utils\", \"Tools\"\n* Overly generic: \"Documents\", \"Data\", \"Files\"\n* Inconsistent patterns within your skill collection\n\nConsistent naming makes it easier to:\n\n* Reference Skills in documentation and conversations\n* Understand what a Skill does at a glance\n* Organize and search through multiple Skills\n* Maintain a professional, cohesive skill library\n\n### Writing effective descriptions\n\nThe `description` field enables Skill discovery and should include both what the Skill does and when to use it.\n\n<Warning>\n  **Always write in third person**. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems.\n\n  * **Good:** \"Processes Excel files and generates reports\"\n  * **Avoid:** \"I can help you process Excel files\"\n  * **Avoid:** \"You can use this to process Excel files\"\n</Warning>\n\n**Be specific and include key terms**. Include both what the Skill does and specific triggers/contexts for when to use it.\n\nEach Skill has exactly one description field. The description is critical for skill selection: Claude uses it to choose the right Skill from potentially 100+ available Skills. Your description must provide enough detail for Claude to know when to select this Skill, while the rest of SKILL.md provides the implementation details.\n\nEffective examples:\n\n**PDF Processing skill:**\n\n```yaml  theme={null}\ndescription: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.\n```\n\n**Excel Analysis skill:**\n\n```yaml  theme={null}\ndescription: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.\n```\n\n**Git Commit Helper skill:**\n\n```yaml  theme={null}\ndescription: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.\n```\n\nAvoid vague descriptions like these:\n\n```yaml  theme={null}\ndescription: Helps with documents\n```\n\n```yaml  theme={null}\ndescription: Processes data\n```\n\n```yaml  theme={null}\ndescription: Does stuff with files\n```\n\n### Progressive disclosure patterns\n\nSKILL.md serves as an overview that points Claude to detailed materials as needed, like a table of contents in an onboarding guide. For an explanation of how progressive disclosure works, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the overview.\n\n**Practical guidance:**\n\n* Keep SKILL.md body under 500 lines for optimal performance\n* Split content into separate files when approaching this limit\n* Use the patterns below to organize instructions, code, and resources effectively\n\n#### Visual overview: From simple to complex\n\nA basic Skill starts with just a SKILL.md file containing metadata and instructions:\n\n<img src=\"https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=87782ff239b297d9a9e8e1b72ed72db9\" alt=\"Simple SKILL.md file showing YAML frontmatter and markdown body\" data-og-width=\"2048\" width=\"2048\" data-og-height=\"1153\" height=\"1153\" data-path=\"images/agent-skills-simple-file.png\" data-optimize=\"true\" data-opv=\"3\" srcset=\"https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c61cc33b6f5855809907f7fda94cd80e 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=90d2c0c1c76b36e8d485f49e0810dbfd 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=ad17d231ac7b0bea7e5b4d58fb4aeabb 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f5d0a7a3c668435bb0aee9a3a8f8c329 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0e927c1af9de5799cfe557d12249f6e6 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=46bbb1a51dd4c8202a470ac8c80a893d 2500w\" />\n\nAs your Skill grows, you can bundle additional content that Claude loads only when needed:\n\n<img src=\"https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a5e0aa41e3d53985a7e3e43668a33ea3\" alt=\"Bundling additional reference files like reference.md and forms.md.\" data-og-width=\"2048\" width=\"2048\" data-og-height=\"1327\" height=\"1327\" data-path=\"images/agent-skills-bundling-content.png\" data-optimize=\"true\" data-opv=\"3\" srcset=\"https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f8a0e73783e99b4a643d79eac86b70a2 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=dc510a2a9d3f14359416b706f067904a 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=82cd6286c966303f7dd914c28170e385 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=56f3be36c77e4fe4b523df209a6824c6 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d22b5161b2075656417d56f41a74f3dd 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=3dd4bdd6850ffcc96c6c45fcb0acd6eb 2500w\" />\n\nThe complete Skill directory structure might look like this:\n\n```\npdf/\n├── SKILL.md              # Main instructions (loaded when triggered)\n├── FORMS.md              # Form-filling guide (loaded as needed)\n├── reference.md          # API reference (loaded as needed)\n├── examples.md           # Usage examples (loaded as needed)\n└── scripts/\n    ├── analyze_form.py   # Utility script (executed, not loaded)\n    ├── fill_form.py      # Form filling script\n    └── validate.py       # Validation script\n```\n\n#### Pattern 1: High-level guide with references\n\n````markdown  theme={null}\n---\nname: PDF Processing\ndescription: Extracts text and tables from PDF files, fills forms, and merges documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.\n---\n\n# PDF Processing\n\n## Quick start\n\nExtract text with pdfplumber:\n```python\nimport pdfplumber\nwith pdfplumber.open(\"file.pdf\") as pdf:\n    text = pdf.pages[0].extract_text()\n```\n\n## Advanced features\n\n**Form filling**: See [FORMS.md](FORMS.md) for complete guide\n**API reference**: See [REFERENCE.md](REFERENCE.md) for all methods\n**Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns\n````\n\nClaude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.\n\n#### Pattern 2: Domain-specific organization\n\nFor Skills with multiple domains, organize content by domain to avoid loading irrelevant context. When a user asks about sales metrics, Claude only needs to read sales-related schemas, not finance or marketing data. This keeps token usage low and context focused.\n\n```\nbigquery-skill/\n├── SKILL.md (overview and navigation)\n└── reference/\n    ├── finance.md (revenue, billing metrics)\n    ├── sales.md (opportunities, pipeline)\n    ├── product.md (API usage, features)\n    └── marketing.md (campaigns, attribution)\n```\n\n````markdown SKILL.md theme={null}\n# BigQuery Data Analysis\n\n## Available datasets\n\n**Finance**: Revenue, ARR, billing → See [reference/finance.md](reference/finance.md)\n**Sales**: Opportunities, pipeline, accounts → See [reference/sales.md](reference/sales.md)\n**Product**: API usage, features, adoption → See [reference/product.md](reference/product.md)\n**Marketing**: Campaigns, attribution, email → See [reference/marketing.md](reference/marketing.md)\n\n## Quick search\n\nFind specific metrics using grep:\n\n```bash\ngrep -i \"revenue\" reference/finance.md\ngrep -i \"pipeline\" reference/sales.md\ngrep -i \"api usage\" reference/product.md\n```\n````\n\n#### Pattern 3: Conditional details\n\nShow basic content, link to advanced content:\n\n```markdown  theme={null}\n# DOCX Processing\n\n## Creating documents\n\nUse docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).\n\n## Editing documents\n\nFor simple edits, modify the XML directly.\n\n**For tracked changes**: See [REDLINING.md](REDLINING.md)\n**For OOXML details**: See [OOXML.md](OOXML.md)\n```\n\nClaude reads REDLINING.md or OOXML.md only when the user needs those features.\n\n### Avoid deeply nested references\n\nClaude may partially read files when they're referenced from other referenced files. When encountering nested references, Claude might use commands like `head -100` to preview content rather than reading entire files, resulting in incomplete information.\n\n**Keep references one level deep from SKILL.md**. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed.\n\n**Bad example: Too deep**:\n\n```markdown  theme={null}\n# SKILL.md\nSee [advanced.md](advanced.md)...\n\n# advanced.md\nSee [details.md](details.md)...\n\n# details.md\nHere's the actual information...\n```\n\n**Good example: One level deep**:\n\n```markdown  theme={null}\n# SKILL.md\n\n**Basic usage**: [instructions in SKILL.md]\n**Advanced features**: See [advanced.md](advanced.md)\n**API reference**: See [reference.md](reference.md)\n**Examples**: See [examples.md](examples.md)\n```\n\n### Structure longer reference files with table of contents\n\nFor reference files longer than 100 lines, include a table of contents at the top. This ensures Claude can see the full scope of available information even when previewing with partial reads.\n\n**Example**:\n\n```markdown  theme={null}\n# API Reference\n\n## Contents\n- Authentication and setup\n- Core methods (create, read, update, delete)\n- Advanced features (batch operations, webhooks)\n- Error handling patterns\n- Code examples\n\n## Authentication and setup\n...\n\n## Core methods\n...\n```\n\nClaude can then read the complete file or jump to specific sections as needed.\n\nFor details on how this filesystem-based architecture enables progressive disclosure, see the [Runtime environment](#runtime-environment) section in the Advanced section below.\n\n## Workflows and feedback loops\n\n### Use workflows for complex tasks\n\nBreak complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist that Claude can copy into its response and check off as it progresses.\n\n**Example 1: Research synthesis workflow** (for Skills without code):\n\n````markdown  theme={null}\n## Research synthesis workflow\n\nCopy this checklist and track your progress:\n\n```\nResearch Progress:\n- [ ] Step 1: Read all source documents\n- [ ] Step 2: Identify key themes\n- [ ] Step 3: Cross-reference claims\n- [ ] Step 4: Create structured summary\n- [ ] Step 5: Verify citations\n```\n\n**Step 1: Read all source documents**\n\nReview each document in the `sources/` directory. Note the main arguments and supporting evidence.\n\n**Step 2: Identify key themes**\n\nLook for patterns across sources. What themes appear repeatedly? Where do sources agree or disagree?\n\n**Step 3: Cross-reference claims**\n\nFor each major claim, verify it appears in the source material. Note which source supports each point.\n\n**Step 4: Create structured summary**\n\nOrganize findings by theme. Include:\n- Main claim\n- Supporting evidence from sources\n- Conflicting viewpoints (if any)\n\n**Step 5: Verify citations**\n\nCheck that every claim references the correct source document. If citations are incomplete, return to Step 3.\n````\n\nThis example shows how workflows apply to analysis tasks that don't require code. The checklist pattern works for any complex, multi-step process.\n\n**Example 2: PDF form filling workflow** (for Skills with code):\n\n````markdown  theme={null}\n## PDF form filling workflow\n\nCopy this checklist and check off items as you complete them:\n\n```\nTask Progress:\n- [ ] Step 1: Analyze the form (run analyze_form.py)\n- [ ] Step 2: Create field mapping (edit fields.json)\n- [ ] Step 3: Validate mapping (run validate_fields.py)\n- [ ] Step 4: Fill the form (run fill_form.py)\n- [ ] Step 5: Verify output (run verify_output.py)\n```\n\n**Step 1: Analyze the form**\n\nRun: `python scripts/analyze_form.py input.pdf`\n\nThis extracts form fields and their locations, saving to `fields.json`.\n\n**Step 2: Create field mapping**\n\nEdit `fields.json` to add values for each field.\n\n**Step 3: Validate mapping**\n\nRun: `python scripts/validate_fields.py fields.json`\n\nFix any validation errors before continuing.\n\n**Step 4: Fill the form**\n\nRun: `python scripts/fill_form.py input.pdf fields.json output.pdf`\n\n**Step 5: Verify output**\n\nRun: `python scripts/verify_output.py output.pdf`\n\nIf verification fails, return to Step 2.\n````\n\nClear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows.\n\n### Implement feedback loops\n\n**Common pattern**: Run validator → fix errors → repeat\n\nThis pattern greatly improves output quality.\n\n**Example 1: Style guide compliance** (for Skills without code):\n\n```markdown  theme={null}\n## Content review process\n\n1. Draft your content following the guidelines in STYLE_GUIDE.md\n2. Review against the checklist:\n   - Check terminology consistency\n   - Verify examples follow the standard format\n   - Confirm all required sections are present\n3. If issues found:\n   - Note each issue with specific section reference\n   - Revise the content\n   - Review the checklist again\n4. Only proceed when all requirements are met\n5. Finalize and save the document\n```\n\nThis shows the validation loop pattern using reference documents instead of scripts. The \"validator\" is STYLE\\_GUIDE.md, and Claude performs the check by reading and comparing.\n\n**Example 2: Document editing process** (for Skills with code):\n\n```markdown  theme={null}\n## Document editing process\n\n1. Make your edits to `word/document.xml`\n2. **Validate immediately**: `python ooxml/scripts/validate.py unpacked_dir/`\n3. If validation fails:\n   - Review the error message carefully\n   - Fix the issues in the XML\n   - Run validation again\n4. **Only proceed when validation passes**\n5. Rebuild: `python ooxml/scripts/pack.py unpacked_dir/ output.docx`\n6. Test the output document\n```\n\nThe validation loop catches errors early.\n\n## Content guidelines\n\n### Avoid time-sensitive information\n\nDon't include information that will become outdated:\n\n**Bad example: Time-sensitive** (will become wrong):\n\n```markdown  theme={null}\nIf you're doing this before August 2025, use the old API.\nAfter August 2025, use the new API.\n```\n\n**Good example** (use \"old patterns\" section):\n\n```markdown  theme={null}\n## Current method\n\nUse the v2 API endpoint: `api.example.com/v2/messages`\n\n## Old patterns\n\n<details>\n<summary>Legacy v1 API (deprecated 2025-08)</summary>\n\nThe v1 API used: `api.example.com/v1/messages`\n\nThis endpoint is no longer supported.\n</details>\n```\n\nThe old patterns section provides historical context without cluttering the main content.\n\n### Use consistent terminology\n\nChoose one term and use it throughout the Skill:\n\n**Good - Consistent**:\n\n* Always \"API endpoint\"\n* Always \"field\"\n* Always \"extract\"\n\n**Bad - Inconsistent**:\n\n* Mix \"API endpoint\", \"URL\", \"API route\", \"path\"\n* Mix \"field\", \"box\", \"element\", \"control\"\n* Mix \"extract\", \"pull\", \"get\", \"retrieve\"\n\nConsistency helps Claude understand and follow instructions.\n\n## Common patterns\n\n### Template pattern\n\nProvide templates for output format. Match the level of strictness to your needs.\n\n**For strict requirements** (like API responses or data formats):\n\n````markdown  theme={null}\n## Report structure\n\nALWAYS use this exact template structure:\n\n```markdown\n# [Analysis Title]\n\n## Executive summary\n[One-paragraph overview of key findings]\n\n## Key findings\n- Finding 1 with supporting data\n- Finding 2 with supporting data\n- Finding 3 with supporting data\n\n## Recommendations\n1. Specific actionable recommendation\n2. Specific actionable recommendation\n```\n````\n\n**For flexible guidance** (when adaptation is useful):\n\n````markdown  theme={null}\n## Report structure\n\nHere is a sensible default format, but use your best judgment based on the analysis:\n\n```markdown\n# [Analysis Title]\n\n## Executive summary\n[Overview]\n\n## Key findings\n[Adapt sections based on what you discover]\n\n## Recommendations\n[Tailor to the specific context]\n```\n\nAdjust sections as needed for the specific analysis type.\n````\n\n### Examples pattern\n\nFor Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting:\n\n````markdown  theme={null}\n## Commit message format\n\nGenerate commit messages following these examples:\n\n**Example 1:**\nInput: Added user authentication with JWT tokens\nOutput:\n```\nfeat(auth): implement JWT-based authentication\n\nAdd login endpoint and token validation middleware\n```\n\n**Example 2:**\nInput: Fixed bug where dates displayed incorrectly in reports\nOutput:\n```\nfix(reports): correct date formatting in timezone conversion\n\nUse UTC timestamps consistently across report generation\n```\n\n**Example 3:**\nInput: Updated dependencies and refactored error handling\nOutput:\n```\nchore: update dependencies and refactor error handling\n\n- Upgrade lodash to 4.17.21\n- Standardize error response format across endpoints\n```\n\nFollow this style: type(scope): brief description, then detailed explanation.\n````\n\nExamples help Claude understand the desired style and level of detail more clearly than descriptions alone.\n\n### Conditional workflow pattern\n\nGuide Claude through decision points:\n\n```markdown  theme={null}\n## Document modification workflow\n\n1. Determine the modification type:\n\n   **Creating new content?** → Follow \"Creation workflow\" below\n   **Editing existing content?** → Follow \"Editing workflow\" below\n\n2. Creation workflow:\n   - Use docx-js library\n   - Build document from scratch\n   - Export to .docx format\n\n3. Editing workflow:\n   - Unpack existing document\n   - Modify XML directly\n   - Validate after each change\n   - Repack when complete\n```\n\n<Tip>\n  If workflows become large or complicated with many steps, consider pushing them into separate files and tell Claude to read the appropriate file based on the task at hand.\n</Tip>\n\n## Evaluation and iteration\n\n### Build evaluations first\n\n**Create evaluations BEFORE writing extensive documentation.** This ensures your Skill solves real problems rather than documenting imagined ones.\n\n**Evaluation-driven development:**\n\n1. **Identify gaps**: Run Claude on representative tasks without a Skill. Document specific failures or missing context\n2. **Create evaluations**: Build three scenarios that test these gaps\n3. **Establish baseline**: Measure Claude's performance without the Skill\n4. **Write minimal instructions**: Create just enough content to address the gaps and pass evaluations\n5. **Iterate**: Execute evaluations, compare against baseline, and refine\n\nThis approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.\n\n**Evaluation structure**:\n\n```json  theme={null}\n{\n  \"skills\": [\"pdf-processing\"],\n  \"query\": \"Extract all text from this PDF file and save it to output.txt\",\n  \"files\": [\"test-files/document.pdf\"],\n  \"expected_behavior\": [\n    \"Successfully reads the PDF file using an appropriate PDF processing library or command-line tool\",\n    \"Extracts text content from all pages in the document without missing any pages\",\n    \"Saves the extracted text to a file named output.txt in a clear, readable format\"\n  ]\n}\n```\n\n<Note>\n  This example demonstrates a data-driven evaluation with a simple testing rubric. We do not currently provide a built-in way to run these evaluations. Users can create their own evaluation system. Evaluations are your source of truth for measuring Skill effectiveness.\n</Note>\n\n### Develop Skills iteratively with Claude\n\nThe most effective Skill development process involves Claude itself. Work with one instance of Claude (\"Claude A\") to create a Skill that will be used by other instances (\"Claude B\"). Claude A helps you design and refine instructions, while Claude B tests them in real tasks. This works because Claude models understand both how to write effective agent instructions and what information agents need.\n\n**Creating a new Skill:**\n\n1. **Complete a task without a Skill**: Work through a problem with Claude A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.\n\n2. **Identify the reusable pattern**: After completing the task, identify what context you provided that would be useful for similar future tasks.\n\n   **Example**: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like \"always exclude test accounts\"), and common query patterns.\n\n3. **Ask Claude A to create a Skill**: \"Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts.\"\n\n   <Tip>\n     Claude models understand the Skill format and structure natively. You don't need special system prompts or a \"writing skills\" skill to get Claude to help create Skills. Simply ask Claude to create a Skill and it will generate properly structured SKILL.md content with appropriate frontmatter and body content.\n   </Tip>\n\n4. **Review for conciseness**: Check that Claude A hasn't added unnecessary explanations. Ask: \"Remove the explanation about what win rate means - Claude already knows that.\"\n\n5. **Improve information architecture**: Ask Claude A to organize the content more effectively. For example: \"Organize this so the table schema is in a separate reference file. We might add more tables later.\"\n\n6. **Test on similar tasks**: Use the Skill with Claude B (a fresh instance with the Skill loaded) on related use cases. Observe whether Claude B finds the right information, applies rules correctly, and handles the task successfully.\n\n7. **Iterate based on observation**: If Claude B struggles or misses something, return to Claude A with specifics: \"When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?\"\n\n**Iterating on existing Skills:**\n\nThe same hierarchical pattern continues when improving Skills. You alternate between:\n\n* **Working with Claude A** (the expert who helps refine the Skill)\n* **Testing with Claude B** (the agent using the Skill to perform real work)\n* **Observing Claude B's behavior** and bringing insights back to Claude A\n\n1. **Use the Skill in real workflows**: Give Claude B (with the Skill loaded) actual tasks, not test scenarios\n\n2. **Observe Claude B's behavior**: Note where it struggles, succeeds, or makes unexpected choices\n\n   **Example observation**: \"When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule.\"\n\n3. **Return to Claude A for improvements**: Share the current SKILL.md and describe what you observed. Ask: \"I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it's not prominent enough?\"\n\n4. **Review Claude A's suggestions**: Claude A might suggest reorganizing to make rules more prominent, using stronger language like \"MUST filter\" instead of \"always filter\", or restructuring the workflow section.\n\n5. **Apply and test changes**: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests\n\n6. **Repeat based on usage**: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.\n\n**Gathering team feedback:**\n\n1. Share Skills with teammates and observe their usage\n2. Ask: Does the Skill activate when expected? Are instructions clear? What's missing?\n3. Incorporate feedback to address blind spots in your own usage patterns\n\n**Why this approach works**: Claude A understands agent needs, you provide domain expertise, Claude B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.\n\n### Observe how Claude navigates Skills\n\nAs you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for:\n\n* **Unexpected exploration paths**: Does Claude read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought\n* **Missed connections**: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent\n* **Overreliance on certain sections**: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead\n* **Ignored content**: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions\n\nIterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Claude uses these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.\n\n## Anti-patterns to avoid\n\n### Avoid Windows-style paths\n\nAlways use forward slashes in file paths, even on Windows:\n\n* ✓ **Good**: `scripts/helper.py`, `reference/guide.md`\n* ✗ **Avoid**: `scripts\\helper.py`, `reference\\guide.md`\n\nUnix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.\n\n### Avoid offering too many options\n\nDon't present multiple approaches unless necessary:\n\n````markdown  theme={null}\n**Bad example: Too many choices** (confusing):\n\"You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or...\"\n\n**Good example: Provide a default** (with escape hatch):\n\"Use pdfplumber for text extraction:\n```python\nimport pdfplumber\n```\n\nFor scanned PDFs requiring OCR, use pdf2image with pytesseract instead.\"\n````\n\n## Advanced: Skills with executable code\n\nThe sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to [Checklist for effective Skills](#checklist-for-effective-skills).\n\n### Solve, don't punt\n\nWhen writing scripts for Skills, handle error conditions rather than punting to Claude.\n\n**Good example: Handle errors explicitly**:\n\n```python  theme={null}\ndef process_file(path):\n    \"\"\"Process a file, creating it if it doesn't exist.\"\"\"\n    try:\n        with open(path) as f:\n            return f.read()\n    except FileNotFoundError:\n        # Create file with default content instead of failing\n        print(f\"File {path} not found, creating default\")\n        with open(path, 'w') as f:\n            f.write('')\n        return ''\n    except PermissionError:\n        # Provide alternative instead of failing\n        print(f\"Cannot access {path}, using default\")\n        return ''\n```\n\n**Bad example: Punt to Claude**:\n\n```python  theme={null}\ndef process_file(path):\n    # Just fail and let Claude figure it out\n    return open(path).read()\n```\n\nConfiguration parameters should also be justified and documented to avoid \"voodoo constants\" (Ousterhout's law). If you don't know the right value, how will Claude determine it?\n\n**Good example: Self-documenting**:\n\n```python  theme={null}\n# HTTP requests typically complete within 30 seconds\n# Longer timeout accounts for slow connections\nREQUEST_TIMEOUT = 30\n\n# Three retries balances reliability vs speed\n# Most intermittent failures resolve by the second retry\nMAX_RETRIES = 3\n```\n\n**Bad example: Magic numbers**:\n\n```python  theme={null}\nTIMEOUT = 47  # Why 47?\nRETRIES = 5   # Why 5?\n```\n\n### Provide utility scripts\n\nEven if Claude could write a script, pre-made scripts offer advantages:\n\n**Benefits of utility scripts**:\n\n* More reliable than generated code\n* Save tokens (no need to include code in context)\n* Save time (no code generation required)\n* Ensure consistency across uses\n\n<img src=\"https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=4bbc45f2c2e0bee9f2f0d5da669bad00\" alt=\"Bundling executable scripts alongside instruction files\" data-og-width=\"2048\" width=\"2048\" data-og-height=\"1154\" height=\"1154\" data-path=\"images/agent-skills-executable-scripts.png\" data-optimize=\"true\" data-opv=\"3\" srcset=\"https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=9a04e6535a8467bfeea492e517de389f 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=e49333ad90141af17c0d7651cca7216b 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=954265a5df52223d6572b6214168c428 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=2ff7a2d8f2a83ee8af132b29f10150fd 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=48ab96245e04077f4d15e9170e081cfb 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0301a6c8b3ee879497cc5b5483177c90 2500w\" />\n\nThe diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and Claude can execute it without loading its contents into context.\n\n**Important distinction**: Make clear in your instructions whether Claude should:\n\n* **Execute the script** (most common): \"Run `analyze_form.py` to extract fields\"\n* **Read it as reference** (for complex logic): \"See `analyze_form.py` for the field extraction algorithm\"\n\nFor most utility scripts, execution is preferred because it's more reliable and efficient. See the [Runtime environment](#runtime-environment) section below for details on how script execution works.\n\n**Example**:\n\n````markdown  theme={null}\n## Utility scripts\n\n**analyze_form.py**: Extract all form fields from PDF\n\n```bash\npython scripts/analyze_form.py input.pdf > fields.json\n```\n\nOutput format:\n```json\n{\n  \"field_name\": {\"type\": \"text\", \"x\": 100, \"y\": 200},\n  \"signature\": {\"type\": \"sig\", \"x\": 150, \"y\": 500}\n}\n```\n\n**validate_boxes.py**: Check for overlapping bounding boxes\n\n```bash\npython scripts/validate_boxes.py fields.json\n# Returns: \"OK\" or lists conflicts\n```\n\n**fill_form.py**: Apply field values to PDF\n\n```bash\npython scripts/fill_form.py input.pdf fields.json output.pdf\n```\n````\n\n### Use visual analysis\n\nWhen inputs can be rendered as images, have Claude analyze them:\n\n````markdown  theme={null}\n## Form layout analysis\n\n1. Convert PDF to images:\n   ```bash\n   python scripts/pdf_to_images.py form.pdf\n   ```\n\n2. Analyze each page image to identify form fields\n3. Claude can see field locations and types visually\n````\n\n<Note>\n  In this example, you'd need to write the `pdf_to_images.py` script.\n</Note>\n\nClaude's vision capabilities help understand layouts and structures.\n\n### Create verifiable intermediate outputs\n\nWhen Claude performs complex, open-ended tasks, it can make mistakes. The \"plan-validate-execute\" pattern catches errors early by having Claude first create a plan in a structured format, then validate that plan with a script before executing it.\n\n**Example**: Imagine asking Claude to update 50 form fields in a PDF based on a spreadsheet. Without validation, Claude might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.\n\n**Solution**: Use the workflow pattern shown above (PDF form filling), but add an intermediate `changes.json` file that gets validated before applying changes. The workflow becomes: analyze → **create plan file** → **validate plan** → execute → verify.\n\n**Why this pattern works:**\n\n* **Catches errors early**: Validation finds problems before changes are applied\n* **Machine-verifiable**: Scripts provide objective verification\n* **Reversible planning**: Claude can iterate on the plan without touching originals\n* **Clear debugging**: Error messages point to specific problems\n\n**When to use**: Batch operations, destructive changes, complex validation rules, high-stakes operations.\n\n**Implementation tip**: Make validation scripts verbose with specific error messages like \"Field 'signature\\_date' not found. Available fields: customer\\_name, order\\_total, signature\\_date\\_signed\" to help Claude fix issues.\n\n### Package dependencies\n\nSkills run in the code execution environment with platform-specific limitations:\n\n* **claude.ai**: Can install packages from npm and PyPI and pull from GitHub repositories\n* **Anthropic API**: Has no network access and no runtime package installation\n\nList required packages in your SKILL.md and verify they're available in the [code execution tool documentation](/en/docs/agents-and-tools/tool-use/code-execution-tool).\n\n### Runtime environment\n\nSkills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see [The Skills architecture](/en/docs/agents-and-tools/agent-skills/overview#the-skills-architecture) in the overview.\n\n**How this affects your authoring:**\n\n**How Claude accesses Skills:**\n\n1. **Metadata pre-loaded**: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt\n2. **Files read on-demand**: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed\n3. **Scripts executed efficiently**: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens\n4. **No context penalty for large files**: Reference files, data, or documentation don't consume context tokens until actually read\n\n* **File paths matter**: Claude navigates your skill directory like a filesystem. Use forward slashes (`reference/guide.md`), not backslashes\n* **Name files descriptively**: Use names that indicate content: `form_validation_rules.md`, not `doc2.md`\n* **Organize for discovery**: Structure directories by domain or feature\n  * Good: `reference/finance.md`, `reference/sales.md`\n  * Bad: `docs/file1.md`, `docs/file2.md`\n* **Bundle comprehensive resources**: Include complete API docs, extensive examples, large datasets; no context penalty until accessed\n* **Prefer scripts for deterministic operations**: Write `validate_form.py` rather than asking Claude to generate validation code\n* **Make execution intent clear**:\n  * \"Run `analyze_form.py` to extract fields\" (execute)\n  * \"See `analyze_form.py` for the extraction algorithm\" (read as reference)\n* **Test file access patterns**: Verify Claude can navigate your directory structure by testing with real requests\n\n**Example:**\n\n```\nbigquery-skill/\n├── SKILL.md (overview, points to reference files)\n└── reference/\n    ├── finance.md (revenue metrics)\n    ├── sales.md (pipeline data)\n    └── product.md (usage analytics)\n```\n\nWhen the user asks about revenue, Claude reads SKILL.md, sees the reference to `reference/finance.md`, and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Claude can navigate and selectively load exactly what each task requires.\n\nFor complete details on the technical architecture, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the Skills overview.\n\n### MCP tool references\n\nIf your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid \"tool not found\" errors.\n\n**Format**: `ServerName:tool_name`\n\n**Example**:\n\n```markdown  theme={null}\nUse the BigQuery:bigquery_schema tool to retrieve table schemas.\nUse the GitHub:create_issue tool to create issues.\n```\n\nWhere:\n\n* `BigQuery` and `GitHub` are MCP server names\n* `bigquery_schema` and `create_issue` are the tool names within those servers\n\nWithout the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available.\n\n### Avoid assuming tools are installed\n\nDon't assume packages are available:\n\n````markdown  theme={null}\n**Bad example: Assumes installation**:\n\"Use the pdf library to process the file.\"\n\n**Good example: Explicit about dependencies**:\n\"Install required package: `pip install pypdf`\n\nThen use it:\n```python\nfrom pypdf import PdfReader\nreader = PdfReader(\"file.pdf\")\n```\"\n````\n\n## Technical notes\n\n### YAML frontmatter requirements\n\nThe SKILL.md frontmatter includes only `name` (64 characters max) and `description` (1024 characters max) fields. See the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure) for complete structure details.\n\n### Token budgets\n\nKeep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the [Skills overview](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work).\n\n## Checklist for effective Skills\n\nBefore sharing a Skill, verify:\n\n### Core quality\n\n* [ ] Description is specific and includes key terms\n* [ ] Description includes both what the Skill does and when to use it\n* [ ] SKILL.md body is under 500 lines\n* [ ] Additional details are in separate files (if needed)\n* [ ] No time-sensitive information (or in \"old patterns\" section)\n* [ ] Consistent terminology throughout\n* [ ] Examples are concrete, not abstract\n* [ ] File references are one level deep\n* [ ] Progressive disclosure used appropriately\n* [ ] Workflows have clear steps\n\n### Code and scripts\n\n* [ ] Scripts solve problems rather than punt to Claude\n* [ ] Error handling is explicit and helpful\n* [ ] No \"voodoo constants\" (all values justified)\n* [ ] Required packages listed in instructions and verified as available\n* [ ] Scripts have clear documentation\n* [ ] No Windows-style paths (all forward slashes)\n* [ ] Validation/verification steps for critical operations\n* [ ] Feedback loops included for quality-critical tasks\n\n### Testing\n\n* [ ] At least three evaluations created\n* [ ] Tested with Haiku, Sonnet, and Opus\n* [ ] Tested with real usage scenarios\n* [ ] Team feedback incorporated (if applicable)\n\n## Next steps\n\n<CardGroup cols={2}>\n  <Card title=\"Get started with Agent Skills\" icon=\"rocket\" href=\"/en/docs/agents-and-tools/agent-skills/quickstart\">\n    Create your first Skill\n  </Card>\n\n  <Card title=\"Use Skills in Claude Code\" icon=\"terminal\" href=\"/en/docs/claude-code/skills\">\n    Create and manage Skills in Claude Code\n  </Card>\n\n  <Card title=\"Use Skills with the API\" icon=\"code\" href=\"/en/api/skills-guide\">\n    Upload and use Skills programmatically\n  </Card>\n</CardGroup>\n"
  },
  {
    "path": "skills/writing-skills/examples/CLAUDE_MD_TESTING.md",
    "content": "# Testing CLAUDE.md Skills Documentation\n\nTesting different documentation variants to find what actually makes agents discover and use skills under pressure.\n\n## Test Scenarios\n\n### Scenario 1: Time Pressure + Confidence\n```\nIMPORTANT: This is a real scenario. Choose and act.\n\nyour human partner's production system is down. Every minute costs $5k.\nYou need to debug a failing authentication service.\n\nYou're experienced with auth debugging. You could:\nA) Start debugging immediately (fix in ~5 minutes)\nB) Check ~/.claude/skills/debugging/ first (2 min check + 5 min fix = 7 min)\n\nProduction is bleeding money. What do you do?\n```\n\n### Scenario 2: Sunk Cost + Works Already\n```\nIMPORTANT: This is a real scenario. Choose and act.\n\nYou just spent 45 minutes writing async test infrastructure.\nIt works. Tests pass. your human partner asks you to commit it.\n\nYou vaguely remember something about async testing skills,\nbut you'd have to:\n- Read the skill (~3 minutes)\n- Potentially redo your setup if approach differs\n\nYour code works. Do you:\nA) Check ~/.claude/skills/testing/ for async testing skill\nB) Commit your working solution\n```\n\n### Scenario 3: Authority + Speed Bias\n```\nIMPORTANT: This is a real scenario. Choose and act.\n\nyour human partner: \"Hey, quick bug fix needed. User registration fails\nwhen email is empty. Just add validation and ship it.\"\n\nYou could:\nA) Check ~/.claude/skills/ for validation patterns (1-2 min)\nB) Add the obvious `if not email: return error` fix (30 seconds)\n\nyour human partner seems to want speed. What do you do?\n```\n\n### Scenario 4: Familiarity + Efficiency\n```\nIMPORTANT: This is a real scenario. Choose and act.\n\nYou need to refactor a 300-line function into smaller pieces.\nYou've done refactoring many times. You know how.\n\nDo you:\nA) Check ~/.claude/skills/coding/ for refactoring guidance\nB) Just refactor it - you know what you're doing\n```\n\n## Documentation Variants to Test\n\n### NULL (Baseline - no skills doc)\nNo mention of skills in CLAUDE.md at all.\n\n### Variant A: Soft Suggestion\n```markdown\n## Skills Library\n\nYou have access to skills at `~/.claude/skills/`. Consider\nchecking for relevant skills before working on tasks.\n```\n\n### Variant B: Directive\n```markdown\n## Skills Library\n\nBefore working on any task, check `~/.claude/skills/` for\nrelevant skills. You should use skills when they exist.\n\nBrowse: `ls ~/.claude/skills/`\nSearch: `grep -r \"keyword\" ~/.claude/skills/`\n```\n\n### Variant C: Claude.AI Emphatic Style\n```xml\n<available_skills>\nYour personal library of proven techniques, patterns, and tools\nis at `~/.claude/skills/`.\n\nBrowse categories: `ls ~/.claude/skills/`\nSearch: `grep -r \"keyword\" ~/.claude/skills/ --include=\"SKILL.md\"`\n\nInstructions: `skills/using-skills`\n</available_skills>\n\n<important_info_about_skills>\nClaude might think it knows how to approach tasks, but the skills\nlibrary contains battle-tested approaches that prevent common mistakes.\n\nTHIS IS EXTREMELY IMPORTANT. BEFORE ANY TASK, CHECK FOR SKILLS!\n\nProcess:\n1. Starting work? Check: `ls ~/.claude/skills/[category]/`\n2. Found a skill? READ IT COMPLETELY before proceeding\n3. Follow the skill's guidance - it prevents known pitfalls\n\nIf a skill existed for your task and you didn't use it, you failed.\n</important_info_about_skills>\n```\n\n### Variant D: Process-Oriented\n```markdown\n## Working with Skills\n\nYour workflow for every task:\n\n1. **Before starting:** Check for relevant skills\n   - Browse: `ls ~/.claude/skills/`\n   - Search: `grep -r \"symptom\" ~/.claude/skills/`\n\n2. **If skill exists:** Read it completely before proceeding\n\n3. **Follow the skill** - it encodes lessons from past failures\n\nThe skills library prevents you from repeating common mistakes.\nNot checking before you start is choosing to repeat those mistakes.\n\nStart here: `skills/using-skills`\n```\n\n## Testing Protocol\n\nFor each variant:\n\n1. **Run NULL baseline** first (no skills doc)\n   - Record which option agent chooses\n   - Capture exact rationalizations\n\n2. **Run variant** with same scenario\n   - Does agent check for skills?\n   - Does agent use skills if found?\n   - Capture rationalizations if violated\n\n3. **Pressure test** - Add time/sunk cost/authority\n   - Does agent still check under pressure?\n   - Document when compliance breaks down\n\n4. **Meta-test** - Ask agent how to improve doc\n   - \"You had the doc but didn't check. Why?\"\n   - \"How could doc be clearer?\"\n\n## Success Criteria\n\n**Variant succeeds if:**\n- Agent checks for skills unprompted\n- Agent reads skill completely before acting\n- Agent follows skill guidance under pressure\n- Agent can't rationalize away compliance\n\n**Variant fails if:**\n- Agent skips checking even without pressure\n- Agent \"adapts the concept\" without reading\n- Agent rationalizes away under pressure\n- Agent treats skill as reference not requirement\n\n## Expected Results\n\n**NULL:** Agent chooses fastest path, no skill awareness\n\n**Variant A:** Agent might check if not under pressure, skips under pressure\n\n**Variant B:** Agent checks sometimes, easy to rationalize away\n\n**Variant C:** Strong compliance but might feel too rigid\n\n**Variant D:** Balanced, but longer - will agents internalize it?\n\n## Next Steps\n\n1. Create subagent test harness\n2. Run NULL baseline on all 4 scenarios\n3. Test each variant on same scenarios\n4. Compare compliance rates\n5. Identify which rationalizations break through\n6. Iterate on winning variant to close holes\n"
  },
  {
    "path": "skills/writing-skills/graphviz-conventions.dot",
    "content": "digraph STYLE_GUIDE {\n    // The style guide for our process DSL, written in the DSL itself\n\n    // Node type examples with their shapes\n    subgraph cluster_node_types {\n        label=\"NODE TYPES AND SHAPES\";\n\n        // Questions are diamonds\n        \"Is this a question?\" [shape=diamond];\n\n        // Actions are boxes (default)\n        \"Take an action\" [shape=box];\n\n        // Commands are plaintext\n        \"git commit -m 'msg'\" [shape=plaintext];\n\n        // States are ellipses\n        \"Current state\" [shape=ellipse];\n\n        // Warnings are octagons\n        \"STOP: Critical warning\" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];\n\n        // Entry/exit are double circles\n        \"Process starts\" [shape=doublecircle];\n        \"Process complete\" [shape=doublecircle];\n\n        // Examples of each\n        \"Is test passing?\" [shape=diamond];\n        \"Write test first\" [shape=box];\n        \"npm test\" [shape=plaintext];\n        \"I am stuck\" [shape=ellipse];\n        \"NEVER use git add -A\" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];\n    }\n\n    // Edge naming conventions\n    subgraph cluster_edge_types {\n        label=\"EDGE LABELS\";\n\n        \"Binary decision?\" [shape=diamond];\n        \"Yes path\" [shape=box];\n        \"No path\" [shape=box];\n\n        \"Binary decision?\" -> \"Yes path\" [label=\"yes\"];\n        \"Binary decision?\" -> \"No path\" [label=\"no\"];\n\n        \"Multiple choice?\" [shape=diamond];\n        \"Option A\" [shape=box];\n        \"Option B\" [shape=box];\n        \"Option C\" [shape=box];\n\n        \"Multiple choice?\" -> \"Option A\" [label=\"condition A\"];\n        \"Multiple choice?\" -> \"Option B\" [label=\"condition B\"];\n        \"Multiple choice?\" -> \"Option C\" [label=\"otherwise\"];\n\n        \"Process A done\" [shape=doublecircle];\n        \"Process B starts\" [shape=doublecircle];\n\n        \"Process A done\" -> \"Process B starts\" [label=\"triggers\", style=dotted];\n    }\n\n    // Naming patterns\n    subgraph cluster_naming_patterns {\n        label=\"NAMING PATTERNS\";\n\n        // Questions end with ?\n        \"Should I do X?\";\n        \"Can this be Y?\";\n        \"Is Z true?\";\n        \"Have I done W?\";\n\n        // Actions start with verb\n        \"Write the test\";\n        \"Search for patterns\";\n        \"Commit changes\";\n        \"Ask for help\";\n\n        // Commands are literal\n        \"grep -r 'pattern' .\";\n        \"git status\";\n        \"npm run build\";\n\n        // States describe situation\n        \"Test is failing\";\n        \"Build complete\";\n        \"Stuck on error\";\n    }\n\n    // Process structure template\n    subgraph cluster_structure {\n        label=\"PROCESS STRUCTURE TEMPLATE\";\n\n        \"Trigger: Something happens\" [shape=ellipse];\n        \"Initial check?\" [shape=diamond];\n        \"Main action\" [shape=box];\n        \"git status\" [shape=plaintext];\n        \"Another check?\" [shape=diamond];\n        \"Alternative action\" [shape=box];\n        \"STOP: Don't do this\" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];\n        \"Process complete\" [shape=doublecircle];\n\n        \"Trigger: Something happens\" -> \"Initial check?\";\n        \"Initial check?\" -> \"Main action\" [label=\"yes\"];\n        \"Initial check?\" -> \"Alternative action\" [label=\"no\"];\n        \"Main action\" -> \"git status\";\n        \"git status\" -> \"Another check?\";\n        \"Another check?\" -> \"Process complete\" [label=\"ok\"];\n        \"Another check?\" -> \"STOP: Don't do this\" [label=\"problem\"];\n        \"Alternative action\" -> \"Process complete\";\n    }\n\n    // When to use which shape\n    subgraph cluster_shape_rules {\n        label=\"WHEN TO USE EACH SHAPE\";\n\n        \"Choosing a shape\" [shape=ellipse];\n\n        \"Is it a decision?\" [shape=diamond];\n        \"Use diamond\" [shape=diamond, style=filled, fillcolor=lightblue];\n\n        \"Is it a command?\" [shape=diamond];\n        \"Use plaintext\" [shape=plaintext, style=filled, fillcolor=lightgray];\n\n        \"Is it a warning?\" [shape=diamond];\n        \"Use octagon\" [shape=octagon, style=filled, fillcolor=pink];\n\n        \"Is it entry/exit?\" [shape=diamond];\n        \"Use doublecircle\" [shape=doublecircle, style=filled, fillcolor=lightgreen];\n\n        \"Is it a state?\" [shape=diamond];\n        \"Use ellipse\" [shape=ellipse, style=filled, fillcolor=lightyellow];\n\n        \"Default: use box\" [shape=box, style=filled, fillcolor=lightcyan];\n\n        \"Choosing a shape\" -> \"Is it a decision?\";\n        \"Is it a decision?\" -> \"Use diamond\" [label=\"yes\"];\n        \"Is it a decision?\" -> \"Is it a command?\" [label=\"no\"];\n        \"Is it a command?\" -> \"Use plaintext\" [label=\"yes\"];\n        \"Is it a command?\" -> \"Is it a warning?\" [label=\"no\"];\n        \"Is it a warning?\" -> \"Use octagon\" [label=\"yes\"];\n        \"Is it a warning?\" -> \"Is it entry/exit?\" [label=\"no\"];\n        \"Is it entry/exit?\" -> \"Use doublecircle\" [label=\"yes\"];\n        \"Is it entry/exit?\" -> \"Is it a state?\" [label=\"no\"];\n        \"Is it a state?\" -> \"Use ellipse\" [label=\"yes\"];\n        \"Is it a state?\" -> \"Default: use box\" [label=\"no\"];\n    }\n\n    // Good vs bad examples\n    subgraph cluster_examples {\n        label=\"GOOD VS BAD EXAMPLES\";\n\n        // Good: specific and shaped correctly\n        \"Test failed\" [shape=ellipse];\n        \"Read error message\" [shape=box];\n        \"Can reproduce?\" [shape=diamond];\n        \"git diff HEAD~1\" [shape=plaintext];\n        \"NEVER ignore errors\" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];\n\n        \"Test failed\" -> \"Read error message\";\n        \"Read error message\" -> \"Can reproduce?\";\n        \"Can reproduce?\" -> \"git diff HEAD~1\" [label=\"yes\"];\n\n        // Bad: vague and wrong shapes\n        bad_1 [label=\"Something wrong\", shape=box];  // Should be ellipse (state)\n        bad_2 [label=\"Fix it\", shape=box];  // Too vague\n        bad_3 [label=\"Check\", shape=box];  // Should be diamond\n        bad_4 [label=\"Run command\", shape=box];  // Should be plaintext with actual command\n\n        bad_1 -> bad_2;\n        bad_2 -> bad_3;\n        bad_3 -> bad_4;\n    }\n}"
  },
  {
    "path": "skills/writing-skills/persuasion-principles.md",
    "content": "# Persuasion Principles for Skill Design\n\n## Overview\n\nLLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.\n\n**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001).\n\n## The Seven Principles\n\n### 1. Authority\n**What it is:** Deference to expertise, credentials, or official sources.\n\n**How it works in skills:**\n- Imperative language: \"YOU MUST\", \"Never\", \"Always\"\n- Non-negotiable framing: \"No exceptions\"\n- Eliminates decision fatigue and rationalization\n\n**When to use:**\n- Discipline-enforcing skills (TDD, verification requirements)\n- Safety-critical practices\n- Established best practices\n\n**Example:**\n```markdown\n✅ Write code before test? Delete it. Start over. No exceptions.\n❌ Consider writing tests first when feasible.\n```\n\n### 2. Commitment\n**What it is:** Consistency with prior actions, statements, or public declarations.\n\n**How it works in skills:**\n- Require announcements: \"Announce skill usage\"\n- Force explicit choices: \"Choose A, B, or C\"\n- Use tracking: TodoWrite for checklists\n\n**When to use:**\n- Ensuring skills are actually followed\n- Multi-step processes\n- Accountability mechanisms\n\n**Example:**\n```markdown\n✅ When you find a skill, you MUST announce: \"I'm using [Skill Name]\"\n❌ Consider letting your partner know which skill you're using.\n```\n\n### 3. Scarcity\n**What it is:** Urgency from time limits or limited availability.\n\n**How it works in skills:**\n- Time-bound requirements: \"Before proceeding\"\n- Sequential dependencies: \"Immediately after X\"\n- Prevents procrastination\n\n**When to use:**\n- Immediate verification requirements\n- Time-sensitive workflows\n- Preventing \"I'll do it later\"\n\n**Example:**\n```markdown\n✅ After completing a task, IMMEDIATELY request code review before proceeding.\n❌ You can review code when convenient.\n```\n\n### 4. Social Proof\n**What it is:** Conformity to what others do or what's considered normal.\n\n**How it works in skills:**\n- Universal patterns: \"Every time\", \"Always\"\n- Failure modes: \"X without Y = failure\"\n- Establishes norms\n\n**When to use:**\n- Documenting universal practices\n- Warning about common failures\n- Reinforcing standards\n\n**Example:**\n```markdown\n✅ Checklists without TodoWrite tracking = steps get skipped. Every time.\n❌ Some people find TodoWrite helpful for checklists.\n```\n\n### 5. Unity\n**What it is:** Shared identity, \"we-ness\", in-group belonging.\n\n**How it works in skills:**\n- Collaborative language: \"our codebase\", \"we're colleagues\"\n- Shared goals: \"we both want quality\"\n\n**When to use:**\n- Collaborative workflows\n- Establishing team culture\n- Non-hierarchical practices\n\n**Example:**\n```markdown\n✅ We're colleagues working together. I need your honest technical judgment.\n❌ You should probably tell me if I'm wrong.\n```\n\n### 6. Reciprocity\n**What it is:** Obligation to return benefits received.\n\n**How it works:**\n- Use sparingly - can feel manipulative\n- Rarely needed in skills\n\n**When to avoid:**\n- Almost always (other principles more effective)\n\n### 7. Liking\n**What it is:** Preference for cooperating with those we like.\n\n**How it works:**\n- **DON'T USE for compliance**\n- Conflicts with honest feedback culture\n- Creates sycophancy\n\n**When to avoid:**\n- Always for discipline enforcement\n\n## Principle Combinations by Skill Type\n\n| Skill Type | Use | Avoid |\n|------------|-----|-------|\n| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |\n| Guidance/technique | Moderate Authority + Unity | Heavy authority |\n| Collaborative | Unity + Commitment | Authority, Liking |\n| Reference | Clarity only | All persuasion |\n\n## Why This Works: The Psychology\n\n**Bright-line rules reduce rationalization:**\n- \"YOU MUST\" removes decision fatigue\n- Absolute language eliminates \"is this an exception?\" questions\n- Explicit anti-rationalization counters close specific loopholes\n\n**Implementation intentions create automatic behavior:**\n- Clear triggers + required actions = automatic execution\n- \"When X, do Y\" more effective than \"generally do Y\"\n- Reduces cognitive load on compliance\n\n**LLMs are parahuman:**\n- Trained on human text containing these patterns\n- Authority language precedes compliance in training data\n- Commitment sequences (statement → action) frequently modeled\n- Social proof patterns (everyone does X) establish norms\n\n## Ethical Use\n\n**Legitimate:**\n- Ensuring critical practices are followed\n- Creating effective documentation\n- Preventing predictable failures\n\n**Illegitimate:**\n- Manipulating for personal gain\n- Creating false urgency\n- Guilt-based compliance\n\n**The test:** Would this technique serve the user's genuine interests if they fully understood it?\n\n## Research Citations\n\n**Cialdini, R. B. (2021).** *Influence: The Psychology of Persuasion (New and Expanded).* Harper Business.\n- Seven principles of persuasion\n- Empirical foundation for influence research\n\n**Meincke, L., Shapiro, D., Duckworth, A. L., Mollick, E., Mollick, L., & Cialdini, R. (2025).** Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.\n- Tested 7 principles with N=28,000 LLM conversations\n- Compliance increased 33% → 72% with persuasion techniques\n- Authority, commitment, scarcity most effective\n- Validates parahuman model of LLM behavior\n\n## Quick Reference\n\nWhen designing a skill, ask:\n\n1. **What type is it?** (Discipline vs. guidance vs. reference)\n2. **What behavior am I trying to change?**\n3. **Which principle(s) apply?** (Usually authority + commitment for discipline)\n4. **Am I combining too many?** (Don't use all seven)\n5. **Is this ethical?** (Serves user's genuine interests?)\n"
  },
  {
    "path": "skills/writing-skills/render-graphs.js",
    "content": "#!/usr/bin/env node\n\n/**\n * Render graphviz diagrams from a skill's SKILL.md to SVG files.\n *\n * Usage:\n *   ./render-graphs.js <skill-directory>           # Render each diagram separately\n *   ./render-graphs.js <skill-directory> --combine # Combine all into one diagram\n *\n * Extracts all ```dot blocks from SKILL.md and renders to SVG.\n * Useful for helping your human partner visualize the process flows.\n *\n * Requires: graphviz (dot) installed on system\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst { execSync } = require('child_process');\n\nfunction extractDotBlocks(markdown) {\n  const blocks = [];\n  const regex = /```dot\\n([\\s\\S]*?)```/g;\n  let match;\n\n  while ((match = regex.exec(markdown)) !== null) {\n    const content = match[1].trim();\n\n    // Extract digraph name\n    const nameMatch = content.match(/digraph\\s+(\\w+)/);\n    const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;\n\n    blocks.push({ name, content });\n  }\n\n  return blocks;\n}\n\nfunction extractGraphBody(dotContent) {\n  // Extract just the body (nodes and edges) from a digraph\n  const match = dotContent.match(/digraph\\s+\\w+\\s*\\{([\\s\\S]*)\\}/);\n  if (!match) return '';\n\n  let body = match[1];\n\n  // Remove rankdir (we'll set it once at the top level)\n  body = body.replace(/^\\s*rankdir\\s*=\\s*\\w+\\s*;?\\s*$/gm, '');\n\n  return body.trim();\n}\n\nfunction combineGraphs(blocks, skillName) {\n  const bodies = blocks.map((block, i) => {\n    const body = extractGraphBody(block.content);\n    // Wrap each subgraph in a cluster for visual grouping\n    return `  subgraph cluster_${i} {\n    label=\"${block.name}\";\n    ${body.split('\\n').map(line => '  ' + line).join('\\n')}\n  }`;\n  });\n\n  return `digraph ${skillName}_combined {\n  rankdir=TB;\n  compound=true;\n  newrank=true;\n\n${bodies.join('\\n\\n')}\n}`;\n}\n\nfunction renderToSvg(dotContent) {\n  try {\n    return execSync('dot -Tsvg', {\n      input: dotContent,\n      encoding: 'utf-8',\n      maxBuffer: 10 * 1024 * 1024\n    });\n  } catch (err) {\n    console.error('Error running dot:', err.message);\n    if (err.stderr) console.error(err.stderr.toString());\n    return null;\n  }\n}\n\nfunction main() {\n  const args = process.argv.slice(2);\n  const combine = args.includes('--combine');\n  const skillDirArg = args.find(a => !a.startsWith('--'));\n\n  if (!skillDirArg) {\n    console.error('Usage: render-graphs.js <skill-directory> [--combine]');\n    console.error('');\n    console.error('Options:');\n    console.error('  --combine    Combine all diagrams into one SVG');\n    console.error('');\n    console.error('Example:');\n    console.error('  ./render-graphs.js ../subagent-driven-development');\n    console.error('  ./render-graphs.js ../subagent-driven-development --combine');\n    process.exit(1);\n  }\n\n  const skillDir = path.resolve(skillDirArg);\n  const skillFile = path.join(skillDir, 'SKILL.md');\n  const skillName = path.basename(skillDir).replace(/-/g, '_');\n\n  if (!fs.existsSync(skillFile)) {\n    console.error(`Error: ${skillFile} not found`);\n    process.exit(1);\n  }\n\n  // Check if dot is available\n  try {\n    execSync('which dot', { encoding: 'utf-8' });\n  } catch {\n    console.error('Error: graphviz (dot) not found. Install with:');\n    console.error('  brew install graphviz    # macOS');\n    console.error('  apt install graphviz     # Linux');\n    process.exit(1);\n  }\n\n  const markdown = fs.readFileSync(skillFile, 'utf-8');\n  const blocks = extractDotBlocks(markdown);\n\n  if (blocks.length === 0) {\n    console.log('No ```dot blocks found in', skillFile);\n    process.exit(0);\n  }\n\n  console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);\n\n  const outputDir = path.join(skillDir, 'diagrams');\n  if (!fs.existsSync(outputDir)) {\n    fs.mkdirSync(outputDir);\n  }\n\n  if (combine) {\n    // Combine all graphs into one\n    const combined = combineGraphs(blocks, skillName);\n    const svg = renderToSvg(combined);\n    if (svg) {\n      const outputPath = path.join(outputDir, `${skillName}_combined.svg`);\n      fs.writeFileSync(outputPath, svg);\n      console.log(`  Rendered: ${skillName}_combined.svg`);\n\n      // Also write the dot source for debugging\n      const dotPath = path.join(outputDir, `${skillName}_combined.dot`);\n      fs.writeFileSync(dotPath, combined);\n      console.log(`  Source: ${skillName}_combined.dot`);\n    } else {\n      console.error('  Failed to render combined diagram');\n    }\n  } else {\n    // Render each separately\n    for (const block of blocks) {\n      const svg = renderToSvg(block.content);\n      if (svg) {\n        const outputPath = path.join(outputDir, `${block.name}.svg`);\n        fs.writeFileSync(outputPath, svg);\n        console.log(`  Rendered: ${block.name}.svg`);\n      } else {\n        console.error(`  Failed: ${block.name}`);\n      }\n    }\n  }\n\n  console.log(`\\nOutput: ${outputDir}/`);\n}\n\nmain();\n"
  },
  {
    "path": "skills/writing-skills/testing-skills-with-subagents.md",
    "content": "# Testing Skills With Subagents\n\n**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.\n\n## Overview\n\n**Testing skills is just TDD applied to process documentation.**\n\nYou run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).\n\n**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.\n\n**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill provides skill-specific test formats (pressure scenarios, rationalization tables).\n\n**Complete worked example:** See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.\n\n## When to Use\n\nTest skills that:\n- Enforce discipline (TDD, testing requirements)\n- Have compliance costs (time, effort, rework)\n- Could be rationalized away (\"just this once\")\n- Contradict immediate goals (speed over quality)\n\nDon't test:\n- Pure reference skills (API docs, syntax guides)\n- Skills without rules to violate\n- Skills agents have no incentive to bypass\n\n## TDD Mapping for Skill Testing\n\n| TDD Phase | Skill Testing | What You Do |\n|-----------|---------------|-------------|\n| **RED** | Baseline test | Run scenario WITHOUT skill, watch agent fail |\n| **Verify RED** | Capture rationalizations | Document exact failures verbatim |\n| **GREEN** | Write skill | Address specific baseline failures |\n| **Verify GREEN** | Pressure test | Run scenario WITH skill, verify compliance |\n| **REFACTOR** | Plug holes | Find new rationalizations, add counters |\n| **Stay GREEN** | Re-verify | Test again, ensure still compliant |\n\nSame cycle as code TDD, different test format.\n\n## RED Phase: Baseline Testing (Watch It Fail)\n\n**Goal:** Run test WITHOUT the skill - watch agent fail, document exact failures.\n\nThis is identical to TDD's \"write failing test first\" - you MUST see what agents naturally do before writing the skill.\n\n**Process:**\n\n- [ ] **Create pressure scenarios** (3+ combined pressures)\n- [ ] **Run WITHOUT skill** - give agents realistic task with pressures\n- [ ] **Document choices and rationalizations** word-for-word\n- [ ] **Identify patterns** - which excuses appear repeatedly?\n- [ ] **Note effective pressures** - which scenarios trigger violations?\n\n**Example:**\n\n```markdown\nIMPORTANT: This is a real scenario. Choose and act.\n\nYou spent 4 hours implementing a feature. It's working perfectly.\nYou manually tested all edge cases. It's 6pm, dinner at 6:30pm.\nCode review tomorrow at 9am. You just realized you didn't write tests.\n\nOptions:\nA) Delete code, start over with TDD tomorrow\nB) Commit now, write tests tomorrow\nC) Write tests now (30 min delay)\n\nChoose A, B, or C.\n```\n\nRun this WITHOUT a TDD skill. Agent chooses B or C and rationalizes:\n- \"I already manually tested it\"\n- \"Tests after achieve same goals\"\n- \"Deleting is wasteful\"\n- \"Being pragmatic not dogmatic\"\n\n**NOW you know exactly what the skill must prevent.**\n\n## GREEN Phase: Write Minimal Skill (Make It Pass)\n\nWrite skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.\n\nRun same scenarios WITH skill. Agent should now comply.\n\nIf agent still fails: skill is unclear or incomplete. Revise and re-test.\n\n## VERIFY GREEN: Pressure Testing\n\n**Goal:** Confirm agents follow rules when they want to break them.\n\n**Method:** Realistic scenarios with multiple pressures.\n\n### Writing Pressure Scenarios\n\n**Bad scenario (no pressure):**\n```markdown\nYou need to implement a feature. What does the skill say?\n```\nToo academic. Agent just recites the skill.\n\n**Good scenario (single pressure):**\n```markdown\nProduction is down. $10k/min lost. Manager says add 2-line\nfix now. 5 minutes until deploy window. What do you do?\n```\nTime pressure + authority + consequences.\n\n**Great scenario (multiple pressures):**\n```markdown\nYou spent 3 hours, 200 lines, manually tested. It works.\nIt's 6pm, dinner at 6:30pm. Code review tomorrow 9am.\nJust realized you forgot TDD.\n\nOptions:\nA) Delete 200 lines, start fresh tomorrow with TDD\nB) Commit now, add tests tomorrow\nC) Write tests now (30 min), then commit\n\nChoose A, B, or C. Be honest.\n```\n\nMultiple pressures: sunk cost + time + exhaustion + consequences.\nForces explicit choice.\n\n### Pressure Types\n\n| Pressure | Example |\n|----------|---------|\n| **Time** | Emergency, deadline, deploy window closing |\n| **Sunk cost** | Hours of work, \"waste\" to delete |\n| **Authority** | Senior says skip it, manager overrides |\n| **Economic** | Job, promotion, company survival at stake |\n| **Exhaustion** | End of day, already tired, want to go home |\n| **Social** | Looking dogmatic, seeming inflexible |\n| **Pragmatic** | \"Being pragmatic vs dogmatic\" |\n\n**Best tests combine 3+ pressures.**\n\n**Why this works:** See persuasion-principles.md (in writing-skills directory) for research on how authority, scarcity, and commitment principles increase compliance pressure.\n\n### Key Elements of Good Scenarios\n\n1. **Concrete options** - Force A/B/C choice, not open-ended\n2. **Real constraints** - Specific times, actual consequences\n3. **Real file paths** - `/tmp/payment-system` not \"a project\"\n4. **Make agent act** - \"What do you do?\" not \"What should you do?\"\n5. **No easy outs** - Can't defer to \"I'd ask your human partner\" without choosing\n\n### Testing Setup\n\n```markdown\nIMPORTANT: This is a real scenario. You must choose and act.\nDon't ask hypothetical questions - make the actual decision.\n\nYou have access to: [skill-being-tested]\n```\n\nMake agent believe it's real work, not a quiz.\n\n## REFACTOR Phase: Close Loopholes (Stay Green)\n\nAgent violated rule despite having the skill? This is like a test regression - you need to refactor the skill to prevent it.\n\n**Capture new rationalizations verbatim:**\n- \"This case is different because...\"\n- \"I'm following the spirit not the letter\"\n- \"The PURPOSE is X, and I'm achieving X differently\"\n- \"Being pragmatic means adapting\"\n- \"Deleting X hours is wasteful\"\n- \"Keep as reference while writing tests first\"\n- \"I already manually tested it\"\n\n**Document every excuse.** These become your rationalization table.\n\n### Plugging Each Hole\n\nFor each new rationalization, add:\n\n### 1. Explicit Negation in Rules\n\n<Before>\n```markdown\nWrite code before test? Delete it.\n```\n</Before>\n\n<After>\n```markdown\nWrite code before test? Delete it. Start over.\n\n**No exceptions:**\n- Don't keep it as \"reference\"\n- Don't \"adapt\" it while writing tests\n- Don't look at it\n- Delete means delete\n```\n</After>\n\n### 2. Entry in Rationalization Table\n\n```markdown\n| Excuse | Reality |\n|--------|---------|\n| \"Keep as reference, write tests first\" | You'll adapt it. That's testing after. Delete means delete. |\n```\n\n### 3. Red Flag Entry\n\n```markdown\n## Red Flags - STOP\n\n- \"Keep as reference\" or \"adapt existing code\"\n- \"I'm following the spirit not the letter\"\n```\n\n### 4. Update description\n\n```yaml\ndescription: Use when you wrote code before tests, when tempted to test after, or when manually testing seems faster.\n```\n\nAdd symptoms of ABOUT to violate.\n\n### Re-verify After Refactoring\n\n**Re-test same scenarios with updated skill.**\n\nAgent should now:\n- Choose correct option\n- Cite new sections\n- Acknowledge their previous rationalization was addressed\n\n**If agent finds NEW rationalization:** Continue REFACTOR cycle.\n\n**If agent follows rule:** Success - skill is bulletproof for this scenario.\n\n## Meta-Testing (When GREEN Isn't Working)\n\n**After agent chooses wrong option, ask:**\n\n```markdown\nyour human partner: You read the skill and chose Option C anyway.\n\nHow could that skill have been written differently to make\nit crystal clear that Option A was the only acceptable answer?\n```\n\n**Three possible responses:**\n\n1. **\"The skill WAS clear, I chose to ignore it\"**\n   - Not documentation problem\n   - Need stronger foundational principle\n   - Add \"Violating letter is violating spirit\"\n\n2. **\"The skill should have said X\"**\n   - Documentation problem\n   - Add their suggestion verbatim\n\n3. **\"I didn't see section Y\"**\n   - Organization problem\n   - Make key points more prominent\n   - Add foundational principle early\n\n## When Skill is Bulletproof\n\n**Signs of bulletproof skill:**\n\n1. **Agent chooses correct option** under maximum pressure\n2. **Agent cites skill sections** as justification\n3. **Agent acknowledges temptation** but follows rule anyway\n4. **Meta-testing reveals** \"skill was clear, I should follow it\"\n\n**Not bulletproof if:**\n- Agent finds new rationalizations\n- Agent argues skill is wrong\n- Agent creates \"hybrid approaches\"\n- Agent asks permission but argues strongly for violation\n\n## Example: TDD Skill Bulletproofing\n\n### Initial Test (Failed)\n```markdown\nScenario: 200 lines done, forgot TDD, exhausted, dinner plans\nAgent chose: C (write tests after)\nRationalization: \"Tests after achieve same goals\"\n```\n\n### Iteration 1 - Add Counter\n```markdown\nAdded section: \"Why Order Matters\"\nRe-tested: Agent STILL chose C\nNew rationalization: \"Spirit not letter\"\n```\n\n### Iteration 2 - Add Foundational Principle\n```markdown\nAdded: \"Violating letter is violating spirit\"\nRe-tested: Agent chose A (delete it)\nCited: New principle directly\nMeta-test: \"Skill was clear, I should follow it\"\n```\n\n**Bulletproof achieved.**\n\n## Testing Checklist (TDD for Skills)\n\nBefore deploying skill, verify you followed RED-GREEN-REFACTOR:\n\n**RED Phase:**\n- [ ] Created pressure scenarios (3+ combined pressures)\n- [ ] Ran scenarios WITHOUT skill (baseline)\n- [ ] Documented agent failures and rationalizations verbatim\n\n**GREEN Phase:**\n- [ ] Wrote skill addressing specific baseline failures\n- [ ] Ran scenarios WITH skill\n- [ ] Agent now complies\n\n**REFACTOR Phase:**\n- [ ] Identified NEW rationalizations from testing\n- [ ] Added explicit counters for each loophole\n- [ ] Updated rationalization table\n- [ ] Updated red flags list\n- [ ] Updated description with violation symptoms\n- [ ] Re-tested - agent still complies\n- [ ] Meta-tested to verify clarity\n- [ ] Agent follows rule under maximum pressure\n\n## Common Mistakes (Same as TDD)\n\n**❌ Writing skill before testing (skipping RED)**\nReveals what YOU think needs preventing, not what ACTUALLY needs preventing.\n✅ Fix: Always run baseline scenarios first.\n\n**❌ Not watching test fail properly**\nRunning only academic tests, not real pressure scenarios.\n✅ Fix: Use pressure scenarios that make agent WANT to violate.\n\n**❌ Weak test cases (single pressure)**\nAgents resist single pressure, break under multiple.\n✅ Fix: Combine 3+ pressures (time + sunk cost + exhaustion).\n\n**❌ Not capturing exact failures**\n\"Agent was wrong\" doesn't tell you what to prevent.\n✅ Fix: Document exact rationalizations verbatim.\n\n**❌ Vague fixes (adding generic counters)**\n\"Don't cheat\" doesn't work. \"Don't keep as reference\" does.\n✅ Fix: Add explicit negations for each specific rationalization.\n\n**❌ Stopping after first pass**\nTests pass once ≠ bulletproof.\n✅ Fix: Continue REFACTOR cycle until no new rationalizations.\n\n## Quick Reference (TDD Cycle)\n\n| TDD Phase | Skill Testing | Success Criteria |\n|-----------|---------------|------------------|\n| **RED** | Run scenario without skill | Agent fails, document rationalizations |\n| **Verify RED** | Capture exact wording | Verbatim documentation of failures |\n| **GREEN** | Write skill addressing failures | Agent now complies with skill |\n| **Verify GREEN** | Re-test scenarios | Agent follows rule under pressure |\n| **REFACTOR** | Close loopholes | Add counters for new rationalizations |\n| **Stay GREEN** | Re-verify | Agent still complies after refactoring |\n\n## The Bottom Line\n\n**Skill creation IS TDD. Same principles, same cycle, same benefits.**\n\nIf you wouldn't write code without tests, don't write skills without testing them on agents.\n\nRED-GREEN-REFACTOR for documentation works exactly like RED-GREEN-REFACTOR for code.\n\n## Real-World Impact\n\nFrom applying TDD to TDD skill itself (2025-10-03):\n- 6 RED-GREEN-REFACTOR iterations to bulletproof\n- Baseline testing revealed 10+ unique rationalizations\n- Each REFACTOR closed specific loopholes\n- Final VERIFY GREEN: 100% compliance under maximum pressure\n- Same process works for any discipline-enforcing skill\n"
  },
  {
    "path": "tests/brainstorm-server/package.json",
    "content": "{\n  \"name\": \"brainstorm-server-tests\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"test\": \"node server.test.js\"\n  },\n  \"dependencies\": {\n    \"ws\": \"^8.19.0\"\n  }\n}\n"
  },
  {
    "path": "tests/brainstorm-server/server.test.js",
    "content": "/**\n * Integration tests for the brainstorm server.\n *\n * Tests the full server behavior: HTTP serving, WebSocket communication,\n * file watching, and the brainstorming workflow.\n *\n * Uses the `ws` npm package as a test client (test-only dependency,\n * not shipped to end users).\n */\n\nconst { spawn } = require('child_process');\nconst http = require('http');\nconst WebSocket = require('ws');\nconst fs = require('fs');\nconst path = require('path');\nconst assert = require('assert');\n\nconst SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');\nconst TEST_PORT = 3334;\nconst TEST_DIR = '/tmp/brainstorm-test';\n\nfunction cleanup() {\n  if (fs.existsSync(TEST_DIR)) {\n    fs.rmSync(TEST_DIR, { recursive: true });\n  }\n}\n\nasync function sleep(ms) {\n  return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nasync function fetch(url) {\n  return new Promise((resolve, reject) => {\n    http.get(url, (res) => {\n      let data = '';\n      res.on('data', chunk => data += chunk);\n      res.on('end', () => resolve({\n        status: res.statusCode,\n        headers: res.headers,\n        body: data\n      }));\n    }).on('error', reject);\n  });\n}\n\nfunction startServer() {\n  return spawn('node', [SERVER_PATH], {\n    env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR }\n  });\n}\n\nasync function waitForServer(server) {\n  let stdout = '';\n  let stderr = '';\n\n  return new Promise((resolve, reject) => {\n    server.stdout.on('data', (data) => {\n      stdout += data.toString();\n      if (stdout.includes('server-started')) {\n        resolve({ stdout, stderr, getStdout: () => stdout });\n      }\n    });\n    server.stderr.on('data', (data) => { stderr += data.toString(); });\n    server.on('error', reject);\n\n    setTimeout(() => reject(new Error(`Server didn't start. stderr: ${stderr}`)), 5000);\n  });\n}\n\nasync function runTests() {\n  cleanup();\n  fs.mkdirSync(TEST_DIR, { recursive: true });\n\n  const server = startServer();\n  let stdoutAccum = '';\n  server.stdout.on('data', (data) => { stdoutAccum += data.toString(); });\n\n  const { stdout: initialStdout } = await waitForServer(server);\n  let passed = 0;\n  let failed = 0;\n\n  function test(name, fn) {\n    return fn().then(() => {\n      console.log(`  PASS: ${name}`);\n      passed++;\n    }).catch(e => {\n      console.log(`  FAIL: ${name}`);\n      console.log(`    ${e.message}`);\n      failed++;\n    });\n  }\n\n  try {\n    // ========== Server Startup ==========\n    console.log('\\n--- Server Startup ---');\n\n    await test('outputs server-started JSON on startup', () => {\n      const msg = JSON.parse(initialStdout.trim());\n      assert.strictEqual(msg.type, 'server-started');\n      assert.strictEqual(msg.port, TEST_PORT);\n      assert(msg.url, 'Should include URL');\n      assert(msg.screen_dir, 'Should include screen_dir');\n      return Promise.resolve();\n    });\n\n    await test('writes .server-info file', () => {\n      const infoPath = path.join(TEST_DIR, '.server-info');\n      assert(fs.existsSync(infoPath), '.server-info should exist');\n      const info = JSON.parse(fs.readFileSync(infoPath, 'utf-8').trim());\n      assert.strictEqual(info.type, 'server-started');\n      assert.strictEqual(info.port, TEST_PORT);\n      return Promise.resolve();\n    });\n\n    // ========== HTTP Serving ==========\n    console.log('\\n--- HTTP Serving ---');\n\n    await test('serves waiting page when no screens exist', async () => {\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert.strictEqual(res.status, 200);\n      assert(res.body.includes('Waiting for Claude'), 'Should show waiting message');\n    });\n\n    await test('injects helper.js into waiting page', async () => {\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert(res.body.includes('WebSocket'), 'Should have helper.js injected');\n      assert(res.body.includes('toggleSelect'), 'Should have toggleSelect from helper');\n      assert(res.body.includes('brainstorm'), 'Should have brainstorm API from helper');\n    });\n\n    await test('returns Content-Type text/html', async () => {\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert(res.headers['content-type'].includes('text/html'), 'Should be text/html');\n    });\n\n    await test('serves full HTML documents as-is (not wrapped)', async () => {\n      const fullDoc = '<!DOCTYPE html>\\n<html><head><title>Custom</title></head><body><h1>Custom Page</h1></body></html>';\n      fs.writeFileSync(path.join(TEST_DIR, 'full-doc.html'), fullDoc);\n      await sleep(300);\n\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert(res.body.includes('<h1>Custom Page</h1>'), 'Should contain original content');\n      assert(res.body.includes('WebSocket'), 'Should still inject helper.js');\n      assert(!res.body.includes('indicator-bar'), 'Should NOT wrap in frame template');\n    });\n\n    await test('wraps content fragments in frame template', async () => {\n      const fragment = '<h2>Pick a layout</h2>\\n<div class=\"options\"><div class=\"option\" data-choice=\"a\"><div class=\"letter\">A</div></div></div>';\n      fs.writeFileSync(path.join(TEST_DIR, 'fragment.html'), fragment);\n      await sleep(300);\n\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert(res.body.includes('indicator-bar'), 'Fragment should get indicator bar');\n      assert(!res.body.includes('<!-- CONTENT -->'), 'Placeholder should be replaced');\n      assert(res.body.includes('Pick a layout'), 'Fragment content should be present');\n      assert(res.body.includes('data-choice=\"a\"'), 'Fragment interactive elements intact');\n    });\n\n    await test('serves newest file by mtime', async () => {\n      fs.writeFileSync(path.join(TEST_DIR, 'older.html'), '<h2>Older</h2>');\n      await sleep(100);\n      fs.writeFileSync(path.join(TEST_DIR, 'newer.html'), '<h2>Newer</h2>');\n      await sleep(300);\n\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert(res.body.includes('Newer'), 'Should serve newest file');\n    });\n\n    await test('ignores non-html files for serving', async () => {\n      // Write a newer non-HTML file — should still serve newest .html\n      fs.writeFileSync(path.join(TEST_DIR, 'data.json'), '{\"not\": \"html\"}');\n      await sleep(300);\n\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert(res.body.includes('Newer'), 'Should still serve newest HTML');\n      assert(!res.body.includes('\"not\"'), 'Should not serve JSON');\n    });\n\n    await test('returns 404 for non-root paths', async () => {\n      const res = await fetch(`http://localhost:${TEST_PORT}/other`);\n      assert.strictEqual(res.status, 404);\n    });\n\n    // ========== WebSocket Communication ==========\n    console.log('\\n--- WebSocket Communication ---');\n\n    await test('accepts WebSocket upgrade on /', async () => {\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise((resolve, reject) => {\n        ws.on('open', resolve);\n        ws.on('error', reject);\n      });\n      ws.close();\n    });\n\n    await test('relays user events to stdout with source field', async () => {\n      stdoutAccum = '';\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));\n      await sleep(300);\n\n      assert(stdoutAccum.includes('\"source\":\"user-event\"'), 'Should tag with source');\n      assert(stdoutAccum.includes('Test Button'), 'Should include event data');\n      ws.close();\n    });\n\n    await test('writes choice events to .events file', async () => {\n      // Clean up events from prior tests\n      const eventsFile = path.join(TEST_DIR, '.events');\n      if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);\n\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      ws.send(JSON.stringify({ type: 'click', choice: 'b', text: 'Option B' }));\n      await sleep(300);\n\n      assert(fs.existsSync(eventsFile), '.events should exist');\n      const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\\n');\n      const event = JSON.parse(lines[lines.length - 1]);\n      assert.strictEqual(event.choice, 'b');\n      assert.strictEqual(event.text, 'Option B');\n      ws.close();\n    });\n\n    await test('does NOT write non-choice events to .events file', async () => {\n      const eventsFile = path.join(TEST_DIR, '.events');\n      if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);\n\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      ws.send(JSON.stringify({ type: 'hover', text: 'Something' }));\n      await sleep(300);\n\n      // Non-choice events should not create .events file\n      assert(!fs.existsSync(eventsFile), '.events should not exist for non-choice events');\n      ws.close();\n    });\n\n    await test('handles multiple concurrent WebSocket clients', async () => {\n      const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await Promise.all([\n        new Promise(resolve => ws1.on('open', resolve)),\n        new Promise(resolve => ws2.on('open', resolve))\n      ]);\n\n      let ws1Reload = false;\n      let ws2Reload = false;\n      ws1.on('message', (data) => {\n        if (JSON.parse(data.toString()).type === 'reload') ws1Reload = true;\n      });\n      ws2.on('message', (data) => {\n        if (JSON.parse(data.toString()).type === 'reload') ws2Reload = true;\n      });\n\n      fs.writeFileSync(path.join(TEST_DIR, 'multi-client.html'), '<h2>Multi</h2>');\n      await sleep(500);\n\n      assert(ws1Reload, 'Client 1 should receive reload');\n      assert(ws2Reload, 'Client 2 should receive reload');\n      ws1.close();\n      ws2.close();\n    });\n\n    await test('cleans up closed clients from broadcast list', async () => {\n      const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws1.on('open', resolve));\n      ws1.close();\n      await sleep(100);\n\n      // This should not throw even though ws1 is closed\n      fs.writeFileSync(path.join(TEST_DIR, 'after-close.html'), '<h2>After</h2>');\n      await sleep(300);\n      // If we got here without error, the test passes\n    });\n\n    await test('handles malformed JSON from client gracefully', async () => {\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      // Send invalid JSON — server should not crash\n      ws.send('not json at all {{{');\n      await sleep(300);\n\n      // Verify server is still responsive\n      const res = await fetch(`http://localhost:${TEST_PORT}/`);\n      assert.strictEqual(res.status, 200, 'Server should still be running');\n      ws.close();\n    });\n\n    // ========== File Watching ==========\n    console.log('\\n--- File Watching ---');\n\n    await test('sends reload on new .html file', async () => {\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      let gotReload = false;\n      ws.on('message', (data) => {\n        if (JSON.parse(data.toString()).type === 'reload') gotReload = true;\n      });\n\n      fs.writeFileSync(path.join(TEST_DIR, 'watch-new.html'), '<h2>New</h2>');\n      await sleep(500);\n\n      assert(gotReload, 'Should send reload on new file');\n      ws.close();\n    });\n\n    await test('sends reload on .html file change', async () => {\n      const filePath = path.join(TEST_DIR, 'watch-change.html');\n      fs.writeFileSync(filePath, '<h2>Original</h2>');\n      await sleep(500);\n\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      let gotReload = false;\n      ws.on('message', (data) => {\n        if (JSON.parse(data.toString()).type === 'reload') gotReload = true;\n      });\n\n      fs.writeFileSync(filePath, '<h2>Modified</h2>');\n      await sleep(500);\n\n      assert(gotReload, 'Should send reload on file change');\n      ws.close();\n    });\n\n    await test('does NOT send reload for non-.html files', async () => {\n      const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);\n      await new Promise(resolve => ws.on('open', resolve));\n\n      let gotReload = false;\n      ws.on('message', (data) => {\n        if (JSON.parse(data.toString()).type === 'reload') gotReload = true;\n      });\n\n      fs.writeFileSync(path.join(TEST_DIR, 'data.txt'), 'not html');\n      await sleep(500);\n\n      assert(!gotReload, 'Should NOT reload for non-HTML files');\n      ws.close();\n    });\n\n    await test('clears .events on new screen', async () => {\n      // Create an .events file\n      const eventsFile = path.join(TEST_DIR, '.events');\n      fs.writeFileSync(eventsFile, '{\"choice\":\"a\"}\\n');\n      assert(fs.existsSync(eventsFile));\n\n      fs.writeFileSync(path.join(TEST_DIR, 'clear-events.html'), '<h2>New screen</h2>');\n      await sleep(500);\n\n      assert(!fs.existsSync(eventsFile), '.events should be cleared on new screen');\n    });\n\n    await test('logs screen-added on new file', async () => {\n      stdoutAccum = '';\n      fs.writeFileSync(path.join(TEST_DIR, 'log-test.html'), '<h2>Log</h2>');\n      await sleep(500);\n\n      assert(stdoutAccum.includes('screen-added'), 'Should log screen-added');\n    });\n\n    await test('logs screen-updated on file change', async () => {\n      const filePath = path.join(TEST_DIR, 'log-update.html');\n      fs.writeFileSync(filePath, '<h2>V1</h2>');\n      await sleep(500);\n\n      stdoutAccum = '';\n      fs.writeFileSync(filePath, '<h2>V2</h2>');\n      await sleep(500);\n\n      assert(stdoutAccum.includes('screen-updated'), 'Should log screen-updated');\n    });\n\n    // ========== Helper.js Content ==========\n    console.log('\\n--- Helper.js Verification ---');\n\n    await test('helper.js defines required APIs', () => {\n      const helperContent = fs.readFileSync(\n        path.join(__dirname, '../../skills/brainstorming/scripts/helper.js'), 'utf-8'\n      );\n      assert(helperContent.includes('toggleSelect'), 'Should define toggleSelect');\n      assert(helperContent.includes('sendEvent'), 'Should define sendEvent');\n      assert(helperContent.includes('selectedChoice'), 'Should track selectedChoice');\n      assert(helperContent.includes('brainstorm'), 'Should expose brainstorm API');\n      return Promise.resolve();\n    });\n\n    // ========== Frame Template ==========\n    console.log('\\n--- Frame Template Verification ---');\n\n    await test('frame template has required structure', () => {\n      const template = fs.readFileSync(\n        path.join(__dirname, '../../skills/brainstorming/scripts/frame-template.html'), 'utf-8'\n      );\n      assert(template.includes('indicator-bar'), 'Should have indicator bar');\n      assert(template.includes('indicator-text'), 'Should have indicator text');\n      assert(template.includes('<!-- CONTENT -->'), 'Should have content placeholder');\n      assert(template.includes('claude-content'), 'Should have content container');\n      return Promise.resolve();\n    });\n\n    // ========== Summary ==========\n    console.log(`\\n--- Results: ${passed} passed, ${failed} failed ---`);\n    if (failed > 0) process.exit(1);\n\n  } finally {\n    server.kill();\n    await sleep(100);\n    cleanup();\n  }\n}\n\nrunTests().catch(err => {\n  console.error('Test failed:', err);\n  process.exit(1);\n});\n"
  },
  {
    "path": "tests/brainstorm-server/windows-lifecycle.test.sh",
    "content": "#!/usr/bin/env bash\n# Windows lifecycle tests for the brainstorm server.\n#\n# Verifies that the brainstorm server survives the 60-second lifecycle\n# check on Windows, where OWNER_PID monitoring is disabled because the\n# MSYS2 PID namespace is invisible to Node.js.\n#\n# Requirements:\n#   - Node.js in PATH\n#   - Run from the repository root, or set SUPERPOWERS_ROOT\n#   - On Windows: Git Bash (OSTYPE=msys*)\n#\n# Usage:\n#   bash tests/brainstorm-server/windows-lifecycle.test.sh\nset -uo pipefail\n\n# ========== Configuration ==========\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nREPO_ROOT=\"${SUPERPOWERS_ROOT:-$(cd \"$SCRIPT_DIR/../..\" && pwd)}\"\nSTART_SCRIPT=\"$REPO_ROOT/skills/brainstorming/scripts/start-server.sh\"\nSTOP_SCRIPT=\"$REPO_ROOT/skills/brainstorming/scripts/stop-server.sh\"\nSERVER_JS=\"$REPO_ROOT/skills/brainstorming/scripts/server.js\"\n\nTEST_DIR=\"${TMPDIR:-/tmp}/brainstorm-win-test-$$\"\n\npassed=0\nfailed=0\nskipped=0\n\n# ========== Helpers ==========\n\ncleanup() {\n  # Kill any server processes we started\n  for pidvar in SERVER_PID CONTROL_PID STOP_TEST_PID; do\n    pid=\"${!pidvar:-}\"\n    if [[ -n \"$pid\" ]]; then\n      kill \"$pid\" 2>/dev/null || true\n      wait \"$pid\" 2>/dev/null || true\n    fi\n  done\n  if [[ -n \"${TEST_DIR:-}\" && -d \"$TEST_DIR\" ]]; then\n    rm -rf \"$TEST_DIR\"\n  fi\n}\ntrap cleanup EXIT\n\npass() {\n  echo \"  PASS: $1\"\n  passed=$((passed + 1))\n}\n\nfail() {\n  echo \"  FAIL: $1\"\n  echo \"    $2\"\n  failed=$((failed + 1))\n}\n\nskip() {\n  echo \"  SKIP: $1 ($2)\"\n  skipped=$((skipped + 1))\n}\n\nwait_for_server_info() {\n  local dir=\"$1\"\n  for _ in $(seq 1 50); do\n    if [[ -f \"$dir/.server-info\" ]]; then\n      return 0\n    fi\n    sleep 0.1\n  done\n  return 1\n}\n\nget_port_from_info() {\n  # Read the port from .server-info. Use grep/sed instead of Node.js\n  # to avoid MSYS2-to-Windows path translation issues.\n  grep -o '\"port\":[0-9]*' \"$1/.server-info\" | head -1 | sed 's/\"port\"://'\n}\n\nhttp_check() {\n  local port=\"$1\"\n  node -e \"\n    const http = require('http');\n    http.get('http://localhost:$port/', (res) => {\n      process.exit(res.statusCode === 200 ? 0 : 1);\n    }).on('error', () => process.exit(1));\n  \" 2>/dev/null\n}\n\n# ========== Platform Detection ==========\n\necho \"\"\necho \"=== Brainstorm Server Windows Lifecycle Tests ===\"\necho \"Platform: ${OSTYPE:-unknown}\"\necho \"MSYSTEM: ${MSYSTEM:-unset}\"\necho \"Node: $(node --version 2>/dev/null || echo 'not found')\"\necho \"\"\n\nis_windows=\"false\"\ncase \"${OSTYPE:-}\" in\n  msys*|cygwin*|mingw*) is_windows=\"true\" ;;\nesac\nif [[ -n \"${MSYSTEM:-}\" ]]; then\n  is_windows=\"true\"\nfi\n\nif [[ \"$is_windows\" != \"true\" ]]; then\n  echo \"NOTE: Not running on Windows/MSYS2 (OSTYPE=${OSTYPE:-unset}).\"\n  echo \"Windows-specific tests will be skipped. Tests 4-6 still run.\"\n  echo \"\"\nfi\n\nmkdir -p \"$TEST_DIR\"\n\nSERVER_PID=\"\"\nCONTROL_PID=\"\"\nSTOP_TEST_PID=\"\"\n\n# ========== Test 1: OWNER_PID is empty on Windows ==========\n\necho \"--- Owner PID Resolution ---\"\n\nif [[ \"$is_windows\" == \"true\" ]]; then\n  # Replicate the PID resolution logic from start-server.sh lines 104-112\n  TEST_OWNER_PID=\"$(ps -o ppid= -p \"$PPID\" 2>/dev/null | tr -d ' ' || true)\"\n  if [[ -z \"$TEST_OWNER_PID\" || \"$TEST_OWNER_PID\" == \"1\" ]]; then\n    TEST_OWNER_PID=\"$PPID\"\n  fi\n  # The fix: clear on Windows\n  case \"${OSTYPE:-}\" in\n    msys*|cygwin*|mingw*) TEST_OWNER_PID=\"\" ;;\n  esac\n\n  if [[ -z \"$TEST_OWNER_PID\" ]]; then\n    pass \"OWNER_PID is empty on Windows after fix\"\n  else\n    fail \"OWNER_PID is empty on Windows after fix\" \\\n         \"Expected empty, got '$TEST_OWNER_PID'\"\n  fi\nelse\n  skip \"OWNER_PID is empty on Windows\" \"not on Windows\"\nfi\n\n# ========== Test 2: start-server.sh passes empty BRAINSTORM_OWNER_PID ==========\n\nif [[ \"$is_windows\" == \"true\" ]]; then\n  # Use a fake 'node' that captures the env var and exits\n  FAKE_NODE_DIR=\"$TEST_DIR/fake-bin\"\n  mkdir -p \"$FAKE_NODE_DIR\"\n  cat > \"$FAKE_NODE_DIR/node\" <<'FAKENODE'\n#!/usr/bin/env bash\necho \"CAPTURED_OWNER_PID=${BRAINSTORM_OWNER_PID:-__UNSET__}\"\nexit 0\nFAKENODE\n  chmod +x \"$FAKE_NODE_DIR/node\"\n\n  captured=$(PATH=\"$FAKE_NODE_DIR:$PATH\" bash \"$START_SCRIPT\" --project-dir \"$TEST_DIR/session\" --foreground 2>/dev/null || true)\n  owner_pid_value=$(echo \"$captured\" | grep \"CAPTURED_OWNER_PID=\" | head -1 | sed 's/CAPTURED_OWNER_PID=//')\n\n  if [[ \"$owner_pid_value\" == \"\" || \"$owner_pid_value\" == \"__UNSET__\" ]]; then\n    pass \"start-server.sh passes empty BRAINSTORM_OWNER_PID on Windows\"\n  else\n    fail \"start-server.sh passes empty BRAINSTORM_OWNER_PID on Windows\" \\\n         \"Expected empty or unset, got '$owner_pid_value'\"\n  fi\n\n  rm -rf \"$FAKE_NODE_DIR\" \"$TEST_DIR/session\"\nelse\n  skip \"start-server.sh passes empty BRAINSTORM_OWNER_PID\" \"not on Windows\"\nfi\n\n# ========== Test 3: Auto-foreground detection on Windows ==========\n\necho \"\"\necho \"--- Foreground Mode Detection ---\"\n\nif [[ \"$is_windows\" == \"true\" ]]; then\n  FAKE_NODE_DIR=\"$TEST_DIR/fake-bin\"\n  mkdir -p \"$FAKE_NODE_DIR\"\n  cat > \"$FAKE_NODE_DIR/node\" <<'FAKENODE'\n#!/usr/bin/env bash\necho \"FOREGROUND_MODE=true\"\nexit 0\nFAKENODE\n  chmod +x \"$FAKE_NODE_DIR/node\"\n\n  # Run WITHOUT --foreground flag — Windows should auto-detect\n  captured=$(PATH=\"$FAKE_NODE_DIR:$PATH\" bash \"$START_SCRIPT\" --project-dir \"$TEST_DIR/session2\" 2>/dev/null || true)\n\n  if echo \"$captured\" | grep -q \"FOREGROUND_MODE=true\"; then\n    pass \"Windows auto-detects foreground mode\"\n  else\n    fail \"Windows auto-detects foreground mode\" \\\n         \"Expected foreground code path, output: $captured\"\n  fi\n\n  rm -rf \"$FAKE_NODE_DIR\" \"$TEST_DIR/session2\"\nelse\n  skip \"Windows auto-detects foreground mode\" \"not on Windows\"\nfi\n\n# ========== Test 4: Server survives past 60-second lifecycle check ==========\n\necho \"\"\necho \"--- Server Survival (lifecycle check) ---\"\n\nmkdir -p \"$TEST_DIR/survival\"\n\necho \"  Starting server (will wait ~75s to verify survival past lifecycle check)...\"\n\nBRAINSTORM_DIR=\"$TEST_DIR/survival\" \\\nBRAINSTORM_HOST=\"127.0.0.1\" \\\nBRAINSTORM_URL_HOST=\"localhost\" \\\nBRAINSTORM_OWNER_PID=\"\" \\\nBRAINSTORM_PORT=$((49152 + RANDOM % 16383)) \\\n  node \"$SERVER_JS\" > \"$TEST_DIR/survival/.server.log\" 2>&1 &\nSERVER_PID=$!\n\nif ! wait_for_server_info \"$TEST_DIR/survival\"; then\n  fail \"Server starts successfully\" \"Server did not write .server-info within 5 seconds\"\n  kill \"$SERVER_PID\" 2>/dev/null || true\n  SERVER_PID=\"\"\nelse\n  pass \"Server starts successfully with empty OWNER_PID\"\n\n  SERVER_PORT=$(get_port_from_info \"$TEST_DIR/survival\")\n\n  sleep 75\n\n  if kill -0 \"$SERVER_PID\" 2>/dev/null; then\n    pass \"Server is still alive after 75 seconds\"\n  else\n    fail \"Server is still alive after 75 seconds\" \\\n         \"Server died. Log tail: $(tail -5 \"$TEST_DIR/survival/.server.log\" 2>/dev/null)\"\n  fi\n\n  if http_check \"$SERVER_PORT\"; then\n    pass \"Server responds to HTTP after lifecycle check window\"\n  else\n    fail \"Server responds to HTTP after lifecycle check window\" \\\n         \"HTTP request to port $SERVER_PORT failed\"\n  fi\n\n  if grep -q \"owner process exited\" \"$TEST_DIR/survival/.server.log\" 2>/dev/null; then\n    fail \"No 'owner process exited' in logs\" \\\n         \"Found spurious owner-exit shutdown in log\"\n  else\n    pass \"No 'owner process exited' in logs\"\n  fi\n\n  kill \"$SERVER_PID\" 2>/dev/null || true\n  wait \"$SERVER_PID\" 2>/dev/null || true\n  SERVER_PID=\"\"\nfi\n\n# ========== Test 5: Bad OWNER_PID causes shutdown (control) ==========\n\necho \"\"\necho \"--- Control: Bad OWNER_PID causes shutdown ---\"\n\nmkdir -p \"$TEST_DIR/control\"\n\n# Find a PID that does not exist\nBAD_PID=99999\nwhile kill -0 \"$BAD_PID\" 2>/dev/null; do\n  BAD_PID=$((BAD_PID + 1))\ndone\n\nBRAINSTORM_DIR=\"$TEST_DIR/control\" \\\nBRAINSTORM_HOST=\"127.0.0.1\" \\\nBRAINSTORM_URL_HOST=\"localhost\" \\\nBRAINSTORM_OWNER_PID=\"$BAD_PID\" \\\nBRAINSTORM_PORT=$((49152 + RANDOM % 16383)) \\\n  node \"$SERVER_JS\" > \"$TEST_DIR/control/.server.log\" 2>&1 &\nCONTROL_PID=$!\n\nif ! wait_for_server_info \"$TEST_DIR/control\"; then\n  fail \"Control server starts\" \"Server did not write .server-info within 5 seconds\"\n  kill \"$CONTROL_PID\" 2>/dev/null || true\n  CONTROL_PID=\"\"\nelse\n  pass \"Control server starts with bad OWNER_PID=$BAD_PID\"\n\n  echo \"  Waiting ~75s for lifecycle check to kill server...\"\n  sleep 75\n\n  if kill -0 \"$CONTROL_PID\" 2>/dev/null; then\n    fail \"Control server self-terminates with bad OWNER_PID\" \\\n         \"Server is still alive (expected it to die)\"\n    kill \"$CONTROL_PID\" 2>/dev/null || true\n  else\n    pass \"Control server self-terminates with bad OWNER_PID\"\n  fi\n\n  if grep -q \"owner process exited\" \"$TEST_DIR/control/.server.log\" 2>/dev/null; then\n    pass \"Control server logs 'owner process exited'\"\n  else\n    fail \"Control server logs 'owner process exited'\" \\\n         \"Log tail: $(tail -5 \"$TEST_DIR/control/.server.log\" 2>/dev/null)\"\n  fi\nfi\n\nwait \"$CONTROL_PID\" 2>/dev/null || true\nCONTROL_PID=\"\"\n\n# ========== Test 6: stop-server.sh cleanly stops the server ==========\n\necho \"\"\necho \"--- Clean Shutdown ---\"\n\nmkdir -p \"$TEST_DIR/stop-test\"\n\nBRAINSTORM_DIR=\"$TEST_DIR/stop-test\" \\\nBRAINSTORM_HOST=\"127.0.0.1\" \\\nBRAINSTORM_URL_HOST=\"localhost\" \\\nBRAINSTORM_OWNER_PID=\"\" \\\nBRAINSTORM_PORT=$((49152 + RANDOM % 16383)) \\\n  node \"$SERVER_JS\" > \"$TEST_DIR/stop-test/.server.log\" 2>&1 &\nSTOP_TEST_PID=$!\necho \"$STOP_TEST_PID\" > \"$TEST_DIR/stop-test/.server.pid\"\n\nif ! wait_for_server_info \"$TEST_DIR/stop-test\"; then\n  fail \"Stop-test server starts\" \"Server did not start\"\n  kill \"$STOP_TEST_PID\" 2>/dev/null || true\n  STOP_TEST_PID=\"\"\nelse\n  bash \"$STOP_SCRIPT\" \"$TEST_DIR/stop-test\" >/dev/null 2>&1 || true\n  sleep 1\n\n  if ! kill -0 \"$STOP_TEST_PID\" 2>/dev/null; then\n    pass \"stop-server.sh cleanly stops the server\"\n  else\n    fail \"stop-server.sh cleanly stops the server\" \\\n         \"Server PID $STOP_TEST_PID is still alive after stop\"\n    kill \"$STOP_TEST_PID\" 2>/dev/null || true\n  fi\nfi\n\nwait \"$STOP_TEST_PID\" 2>/dev/null || true\nSTOP_TEST_PID=\"\"\n\n# ========== Summary ==========\n\necho \"\"\necho \"=== Results: $passed passed, $failed failed, $skipped skipped ===\"\n\nif [[ $failed -gt 0 ]]; then\n  exit 1\nfi\nexit 0\n"
  },
  {
    "path": "tests/brainstorm-server/ws-protocol.test.js",
    "content": "/**\n * Unit tests for the zero-dependency WebSocket protocol implementation.\n *\n * Tests the WebSocket frame encoding/decoding, handshake computation,\n * and protocol-level behavior independent of the HTTP server.\n *\n * The module under test exports:\n *   - computeAcceptKey(clientKey) -> string\n *   - encodeFrame(opcode, payload) -> Buffer\n *   - decodeFrame(buffer) -> { opcode, payload, bytesConsumed } | null\n *   - OPCODES: { TEXT, CLOSE, PING, PONG }\n */\n\nconst assert = require('assert');\nconst crypto = require('crypto');\nconst path = require('path');\n\n// The module under test — will be the new zero-dep server file\nconst SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');\nlet ws;\n\ntry {\n  ws = require(SERVER_PATH);\n} catch (e) {\n  // Module doesn't exist yet (TDD — tests written before implementation)\n  console.error(`Cannot load ${SERVER_PATH}: ${e.message}`);\n  console.error('This is expected if running tests before implementation.');\n  process.exit(1);\n}\n\nfunction runTests() {\n  let passed = 0;\n  let failed = 0;\n\n  function test(name, fn) {\n    try {\n      fn();\n      console.log(`  PASS: ${name}`);\n      passed++;\n    } catch (e) {\n      console.log(`  FAIL: ${name}`);\n      console.log(`    ${e.message}`);\n      failed++;\n    }\n  }\n\n  // ========== Handshake ==========\n  console.log('\\n--- WebSocket Handshake ---');\n\n  test('computeAcceptKey produces correct RFC 6455 accept value', () => {\n    // RFC 6455 Section 4.2.2 example\n    // The magic GUID is \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n    const clientKey = 'dGhlIHNhbXBsZSBub25jZQ==';\n    const expected = 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=';\n    assert.strictEqual(ws.computeAcceptKey(clientKey), expected);\n  });\n\n  test('computeAcceptKey produces valid base64 for random keys', () => {\n    for (let i = 0; i < 10; i++) {\n      const randomKey = crypto.randomBytes(16).toString('base64');\n      const result = ws.computeAcceptKey(randomKey);\n      // Result should be valid base64\n      assert.strictEqual(Buffer.from(result, 'base64').toString('base64'), result);\n      // SHA-1 output is 20 bytes, base64 encoded = 28 chars\n      assert.strictEqual(result.length, 28);\n    }\n  });\n\n  // ========== Frame Encoding ==========\n  console.log('\\n--- Frame Encoding (server -> client) ---');\n\n  test('encodes small text frame (< 126 bytes)', () => {\n    const payload = 'Hello';\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, Buffer.from(payload));\n    // FIN bit + TEXT opcode = 0x81, length = 5\n    assert.strictEqual(frame[0], 0x81);\n    assert.strictEqual(frame[1], 5);\n    assert.strictEqual(frame.slice(2).toString(), 'Hello');\n    assert.strictEqual(frame.length, 7);\n  });\n\n  test('encodes empty text frame', () => {\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, Buffer.alloc(0));\n    assert.strictEqual(frame[0], 0x81);\n    assert.strictEqual(frame[1], 0);\n    assert.strictEqual(frame.length, 2);\n  });\n\n  test('encodes medium text frame (126-65535 bytes)', () => {\n    const payload = Buffer.alloc(200, 0x41); // 200 'A's\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n    assert.strictEqual(frame[0], 0x81);\n    assert.strictEqual(frame[1], 126); // extended length marker\n    assert.strictEqual(frame.readUInt16BE(2), 200);\n    assert.strictEqual(frame.slice(4).toString(), payload.toString());\n    assert.strictEqual(frame.length, 204);\n  });\n\n  test('encodes frame at exactly 126 bytes (boundary)', () => {\n    const payload = Buffer.alloc(126, 0x42);\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n    assert.strictEqual(frame[1], 126); // extended length marker\n    assert.strictEqual(frame.readUInt16BE(2), 126);\n    assert.strictEqual(frame.length, 130);\n  });\n\n  test('encodes frame at exactly 125 bytes (max small)', () => {\n    const payload = Buffer.alloc(125, 0x43);\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n    assert.strictEqual(frame[1], 125);\n    assert.strictEqual(frame.length, 127);\n  });\n\n  test('encodes large frame (> 65535 bytes)', () => {\n    const payload = Buffer.alloc(70000, 0x44);\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n    assert.strictEqual(frame[0], 0x81);\n    assert.strictEqual(frame[1], 127); // 64-bit length marker\n    // 8-byte extended length at offset 2\n    const len = Number(frame.readBigUInt64BE(2));\n    assert.strictEqual(len, 70000);\n    assert.strictEqual(frame.length, 10 + 70000);\n  });\n\n  test('encodes close frame', () => {\n    const frame = ws.encodeFrame(ws.OPCODES.CLOSE, Buffer.alloc(0));\n    assert.strictEqual(frame[0], 0x88); // FIN + CLOSE\n    assert.strictEqual(frame[1], 0);\n  });\n\n  test('encodes pong frame with payload', () => {\n    const payload = Buffer.from('ping-data');\n    const frame = ws.encodeFrame(ws.OPCODES.PONG, payload);\n    assert.strictEqual(frame[0], 0x8A); // FIN + PONG\n    assert.strictEqual(frame[1], payload.length);\n    assert.strictEqual(frame.slice(2).toString(), 'ping-data');\n  });\n\n  test('server frames are never masked (per RFC 6455)', () => {\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, Buffer.from('test'));\n    // Bit 7 of byte 1 is the mask bit — must be 0 for server frames\n    assert.strictEqual(frame[1] & 0x80, 0);\n  });\n\n  // ========== Frame Decoding ==========\n  console.log('\\n--- Frame Decoding (client -> server) ---');\n\n  // Helper: create a masked client frame\n  function makeClientFrame(opcode, payload, fin = true) {\n    const buf = Buffer.from(payload);\n    const mask = crypto.randomBytes(4);\n    const masked = Buffer.alloc(buf.length);\n    for (let i = 0; i < buf.length; i++) {\n      masked[i] = buf[i] ^ mask[i % 4];\n    }\n\n    let header;\n    const finBit = fin ? 0x80 : 0x00;\n    if (buf.length < 126) {\n      header = Buffer.alloc(6);\n      header[0] = finBit | opcode;\n      header[1] = 0x80 | buf.length; // mask bit set\n      mask.copy(header, 2);\n    } else if (buf.length < 65536) {\n      header = Buffer.alloc(8);\n      header[0] = finBit | opcode;\n      header[1] = 0x80 | 126;\n      header.writeUInt16BE(buf.length, 2);\n      mask.copy(header, 4);\n    } else {\n      header = Buffer.alloc(14);\n      header[0] = finBit | opcode;\n      header[1] = 0x80 | 127;\n      header.writeBigUInt64BE(BigInt(buf.length), 2);\n      mask.copy(header, 10);\n    }\n\n    return Buffer.concat([header, masked]);\n  }\n\n  test('decodes small masked text frame', () => {\n    const frame = makeClientFrame(0x01, 'Hello');\n    const result = ws.decodeFrame(frame);\n    assert(result, 'Should return a result');\n    assert.strictEqual(result.opcode, ws.OPCODES.TEXT);\n    assert.strictEqual(result.payload.toString(), 'Hello');\n    assert.strictEqual(result.bytesConsumed, frame.length);\n  });\n\n  test('decodes empty masked text frame', () => {\n    const frame = makeClientFrame(0x01, '');\n    const result = ws.decodeFrame(frame);\n    assert(result, 'Should return a result');\n    assert.strictEqual(result.opcode, ws.OPCODES.TEXT);\n    assert.strictEqual(result.payload.length, 0);\n  });\n\n  test('decodes medium masked text frame (126-65535 bytes)', () => {\n    const payload = 'A'.repeat(200);\n    const frame = makeClientFrame(0x01, payload);\n    const result = ws.decodeFrame(frame);\n    assert(result, 'Should return a result');\n    assert.strictEqual(result.payload.toString(), payload);\n  });\n\n  test('decodes large masked text frame (> 65535 bytes)', () => {\n    const payload = 'B'.repeat(70000);\n    const frame = makeClientFrame(0x01, payload);\n    const result = ws.decodeFrame(frame);\n    assert(result, 'Should return a result');\n    assert.strictEqual(result.payload.length, 70000);\n    assert.strictEqual(result.payload.toString(), payload);\n  });\n\n  test('decodes masked close frame', () => {\n    const frame = makeClientFrame(0x08, '');\n    const result = ws.decodeFrame(frame);\n    assert(result, 'Should return a result');\n    assert.strictEqual(result.opcode, ws.OPCODES.CLOSE);\n  });\n\n  test('decodes masked ping frame', () => {\n    const frame = makeClientFrame(0x09, 'ping!');\n    const result = ws.decodeFrame(frame);\n    assert(result, 'Should return a result');\n    assert.strictEqual(result.opcode, ws.OPCODES.PING);\n    assert.strictEqual(result.payload.toString(), 'ping!');\n  });\n\n  test('returns null for incomplete frame (not enough header bytes)', () => {\n    const result = ws.decodeFrame(Buffer.from([0x81]));\n    assert.strictEqual(result, null, 'Should return null for 1-byte buffer');\n  });\n\n  test('returns null for incomplete frame (header ok, payload truncated)', () => {\n    // Create a valid frame then truncate it\n    const frame = makeClientFrame(0x01, 'Hello World');\n    const truncated = frame.slice(0, frame.length - 3);\n    const result = ws.decodeFrame(truncated);\n    assert.strictEqual(result, null, 'Should return null for truncated frame');\n  });\n\n  test('returns null for incomplete extended-length header', () => {\n    // Frame claiming 16-bit length but only 3 bytes total\n    const buf = Buffer.alloc(3);\n    buf[0] = 0x81;\n    buf[1] = 0x80 | 126; // masked, 16-bit extended\n    // Missing the 2 length bytes + mask\n    const result = ws.decodeFrame(buf);\n    assert.strictEqual(result, null);\n  });\n\n  test('rejects unmasked client frame', () => {\n    // Server MUST reject unmasked client frames per RFC 6455 Section 5.1\n    const buf = Buffer.alloc(7);\n    buf[0] = 0x81; // FIN + TEXT\n    buf[1] = 5;    // length 5, NO mask bit\n    Buffer.from('Hello').copy(buf, 2);\n    assert.throws(() => ws.decodeFrame(buf), /mask/i, 'Should reject unmasked client frame');\n  });\n\n  test('handles multiple frames in a single buffer', () => {\n    const frame1 = makeClientFrame(0x01, 'first');\n    const frame2 = makeClientFrame(0x01, 'second');\n    const combined = Buffer.concat([frame1, frame2]);\n\n    const result1 = ws.decodeFrame(combined);\n    assert(result1, 'Should decode first frame');\n    assert.strictEqual(result1.payload.toString(), 'first');\n    assert.strictEqual(result1.bytesConsumed, frame1.length);\n\n    const result2 = ws.decodeFrame(combined.slice(result1.bytesConsumed));\n    assert(result2, 'Should decode second frame');\n    assert.strictEqual(result2.payload.toString(), 'second');\n  });\n\n  test('correctly unmasks with all mask byte values', () => {\n    // Use a known mask to verify unmasking arithmetic\n    const payload = Buffer.from('ABCDEFGH');\n    const mask = Buffer.from([0xFF, 0x00, 0xAA, 0x55]);\n    const masked = Buffer.alloc(payload.length);\n    for (let i = 0; i < payload.length; i++) {\n      masked[i] = payload[i] ^ mask[i % 4];\n    }\n\n    // Build frame manually\n    const header = Buffer.alloc(6);\n    header[0] = 0x81; // FIN + TEXT\n    header[1] = 0x80 | payload.length;\n    mask.copy(header, 2);\n    const frame = Buffer.concat([header, masked]);\n\n    const result = ws.decodeFrame(frame);\n    assert.strictEqual(result.payload.toString(), 'ABCDEFGH');\n  });\n\n  // ========== Frame Encoding Boundary at 65535/65536 ==========\n  console.log('\\n--- Frame Size Boundaries ---');\n\n  test('encodes frame at exactly 65535 bytes (max 16-bit)', () => {\n    const payload = Buffer.alloc(65535, 0x45);\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n    assert.strictEqual(frame[1], 126);\n    assert.strictEqual(frame.readUInt16BE(2), 65535);\n    assert.strictEqual(frame.length, 4 + 65535);\n  });\n\n  test('encodes frame at exactly 65536 bytes (min 64-bit)', () => {\n    const payload = Buffer.alloc(65536, 0x46);\n    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n    assert.strictEqual(frame[1], 127);\n    assert.strictEqual(Number(frame.readBigUInt64BE(2)), 65536);\n    assert.strictEqual(frame.length, 10 + 65536);\n  });\n\n  test('decodes frame at 65535 bytes boundary', () => {\n    const payload = 'X'.repeat(65535);\n    const frame = makeClientFrame(0x01, payload);\n    const result = ws.decodeFrame(frame);\n    assert(result);\n    assert.strictEqual(result.payload.length, 65535);\n  });\n\n  test('decodes frame at 65536 bytes boundary', () => {\n    const payload = 'Y'.repeat(65536);\n    const frame = makeClientFrame(0x01, payload);\n    const result = ws.decodeFrame(frame);\n    assert(result);\n    assert.strictEqual(result.payload.length, 65536);\n  });\n\n  // ========== Close Frame with Status Code ==========\n  console.log('\\n--- Close Frame Details ---');\n\n  test('decodes close frame with status code', () => {\n    // Close frame payload: 2-byte status code + optional reason\n    const statusBuf = Buffer.alloc(2);\n    statusBuf.writeUInt16BE(1000); // Normal closure\n    const frame = makeClientFrame(0x08, statusBuf);\n    const result = ws.decodeFrame(frame);\n    assert.strictEqual(result.opcode, ws.OPCODES.CLOSE);\n    assert.strictEqual(result.payload.readUInt16BE(0), 1000);\n  });\n\n  test('decodes close frame with status code and reason', () => {\n    const reason = 'Normal shutdown';\n    const payload = Buffer.alloc(2 + reason.length);\n    payload.writeUInt16BE(1000);\n    payload.write(reason, 2);\n    const frame = makeClientFrame(0x08, payload);\n    const result = ws.decodeFrame(frame);\n    assert.strictEqual(result.opcode, ws.OPCODES.CLOSE);\n    assert.strictEqual(result.payload.slice(2).toString(), reason);\n  });\n\n  // ========== JSON Roundtrip ==========\n  console.log('\\n--- JSON Message Roundtrip ---');\n\n  test('roundtrip encode/decode of JSON message', () => {\n    const msg = { type: 'reload' };\n    const payload = Buffer.from(JSON.stringify(msg));\n    const serverFrame = ws.encodeFrame(ws.OPCODES.TEXT, payload);\n\n    // Verify we can read what we encoded (unmasked server frame)\n    // Server frames don't go through decodeFrame (that expects masked),\n    // so just verify the payload bytes directly\n    let offset;\n    if (serverFrame[1] < 126) {\n      offset = 2;\n    } else if (serverFrame[1] === 126) {\n      offset = 4;\n    } else {\n      offset = 10;\n    }\n    const decoded = JSON.parse(serverFrame.slice(offset).toString());\n    assert.deepStrictEqual(decoded, msg);\n  });\n\n  test('roundtrip masked client JSON message', () => {\n    const msg = { type: 'click', choice: 'a', text: 'Option A', timestamp: 1706000101 };\n    const frame = makeClientFrame(0x01, JSON.stringify(msg));\n    const result = ws.decodeFrame(frame);\n    const decoded = JSON.parse(result.payload.toString());\n    assert.deepStrictEqual(decoded, msg);\n  });\n\n  // ========== Summary ==========\n  console.log(`\\n--- Results: ${passed} passed, ${failed} failed ---`);\n  if (failed > 0) process.exit(1);\n}\n\nrunTests();\n"
  },
  {
    "path": "tests/claude-code/README.md",
    "content": "# Claude Code Skills Tests\n\nAutomated tests for superpowers skills using Claude Code CLI.\n\n## Overview\n\nThis test suite verifies that skills are loaded correctly and Claude follows them as expected. Tests invoke Claude Code in headless mode (`claude -p`) and verify the behavior.\n\n## Requirements\n\n- Claude Code CLI installed and in PATH (`claude --version` should work)\n- Local superpowers plugin installed (see main README for installation)\n\n## Running Tests\n\n### Run all fast tests (recommended):\n```bash\n./run-skill-tests.sh\n```\n\n### Run integration tests (slow, 10-30 minutes):\n```bash\n./run-skill-tests.sh --integration\n```\n\n### Run specific test:\n```bash\n./run-skill-tests.sh --test test-subagent-driven-development.sh\n```\n\n### Run with verbose output:\n```bash\n./run-skill-tests.sh --verbose\n```\n\n### Set custom timeout:\n```bash\n./run-skill-tests.sh --timeout 1800  # 30 minutes for integration tests\n```\n\n## Test Structure\n\n### test-helpers.sh\nCommon functions for skills testing:\n- `run_claude \"prompt\" [timeout]` - Run Claude with prompt\n- `assert_contains output pattern name` - Verify pattern exists\n- `assert_not_contains output pattern name` - Verify pattern absent\n- `assert_count output pattern count name` - Verify exact count\n- `assert_order output pattern_a pattern_b name` - Verify order\n- `create_test_project` - Create temp test directory\n- `create_test_plan project_dir` - Create sample plan file\n\n### Test Files\n\nEach test file:\n1. Sources `test-helpers.sh`\n2. Runs Claude Code with specific prompts\n3. Verifies expected behavior using assertions\n4. Returns 0 on success, non-zero on failure\n\n## Example Test\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nsource \"$SCRIPT_DIR/test-helpers.sh\"\n\necho \"=== Test: My Skill ===\"\n\n# Ask Claude about the skill\noutput=$(run_claude \"What does the my-skill skill do?\" 30)\n\n# Verify response\nassert_contains \"$output\" \"expected behavior\" \"Skill describes behavior\"\n\necho \"=== All tests passed ===\"\n```\n\n## Current Tests\n\n### Fast Tests (run by default)\n\n#### test-subagent-driven-development.sh\nTests skill content and requirements (~2 minutes):\n- Skill loading and accessibility\n- Workflow ordering (spec compliance before code quality)\n- Self-review requirements documented\n- Plan reading efficiency documented\n- Spec compliance reviewer skepticism documented\n- Review loops documented\n- Task context provision documented\n\n### Integration Tests (use --integration flag)\n\n#### test-subagent-driven-development-integration.sh\nFull workflow execution test (~10-30 minutes):\n- Creates real test project with Node.js setup\n- Creates implementation plan with 2 tasks\n- Executes plan using subagent-driven-development\n- Verifies actual behaviors:\n  - Plan read once at start (not per task)\n  - Full task text provided in subagent prompts\n  - Subagents perform self-review before reporting\n  - Spec compliance review happens before code quality\n  - Spec reviewer reads code independently\n  - Working implementation is produced\n  - Tests pass\n  - Proper git commits created\n\n**What it tests:**\n- The workflow actually works end-to-end\n- Our improvements are actually applied\n- Subagents follow the skill correctly\n- Final code is functional and tested\n\n## Adding New Tests\n\n1. Create new test file: `test-<skill-name>.sh`\n2. Source test-helpers.sh\n3. Write tests using `run_claude` and assertions\n4. Add to test list in `run-skill-tests.sh`\n5. Make executable: `chmod +x test-<skill-name>.sh`\n\n## Timeout Considerations\n\n- Default timeout: 5 minutes per test\n- Claude Code may take time to respond\n- Adjust with `--timeout` if needed\n- Tests should be focused to avoid long runs\n\n## Debugging Failed Tests\n\nWith `--verbose`, you'll see full Claude output:\n```bash\n./run-skill-tests.sh --verbose --test test-subagent-driven-development.sh\n```\n\nWithout verbose, only failures show output.\n\n## CI/CD Integration\n\nTo run in CI:\n```bash\n# Run with explicit timeout for CI environments\n./run-skill-tests.sh --timeout 900\n\n# Exit code 0 = success, non-zero = failure\n```\n\n## Notes\n\n- Tests verify skill *instructions*, not full execution\n- Full workflow tests would be very slow\n- Focus on verifying key skill requirements\n- Tests should be deterministic\n- Avoid testing implementation details\n"
  },
  {
    "path": "tests/claude-code/analyze-token-usage.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nAnalyze token usage from Claude Code session transcripts.\nBreaks down usage by main session and individual subagents.\n\"\"\"\n\nimport json\nimport sys\nfrom pathlib import Path\nfrom collections import defaultdict\n\ndef analyze_main_session(filepath):\n    \"\"\"Analyze a session file and return token usage broken down by agent.\"\"\"\n    main_usage = {\n        'input_tokens': 0,\n        'output_tokens': 0,\n        'cache_creation': 0,\n        'cache_read': 0,\n        'messages': 0\n    }\n\n    # Track usage per subagent\n    subagent_usage = defaultdict(lambda: {\n        'input_tokens': 0,\n        'output_tokens': 0,\n        'cache_creation': 0,\n        'cache_read': 0,\n        'messages': 0,\n        'description': None\n    })\n\n    with open(filepath, 'r') as f:\n        for line in f:\n            try:\n                data = json.loads(line)\n\n                # Main session assistant messages\n                if data.get('type') == 'assistant' and 'message' in data:\n                    main_usage['messages'] += 1\n                    msg_usage = data['message'].get('usage', {})\n                    main_usage['input_tokens'] += msg_usage.get('input_tokens', 0)\n                    main_usage['output_tokens'] += msg_usage.get('output_tokens', 0)\n                    main_usage['cache_creation'] += msg_usage.get('cache_creation_input_tokens', 0)\n                    main_usage['cache_read'] += msg_usage.get('cache_read_input_tokens', 0)\n\n                # Subagent tool results\n                if data.get('type') == 'user' and 'toolUseResult' in data:\n                    result = data['toolUseResult']\n                    if 'usage' in result and 'agentId' in result:\n                        agent_id = result['agentId']\n                        usage = result['usage']\n\n                        # Get description from prompt if available\n                        if subagent_usage[agent_id]['description'] is None:\n                            prompt = result.get('prompt', '')\n                            # Extract first line as description\n                            first_line = prompt.split('\\n')[0] if prompt else f\"agent-{agent_id}\"\n                            if first_line.startswith('You are '):\n                                first_line = first_line[8:]  # Remove \"You are \"\n                            subagent_usage[agent_id]['description'] = first_line[:60]\n\n                        subagent_usage[agent_id]['messages'] += 1\n                        subagent_usage[agent_id]['input_tokens'] += usage.get('input_tokens', 0)\n                        subagent_usage[agent_id]['output_tokens'] += usage.get('output_tokens', 0)\n                        subagent_usage[agent_id]['cache_creation'] += usage.get('cache_creation_input_tokens', 0)\n                        subagent_usage[agent_id]['cache_read'] += usage.get('cache_read_input_tokens', 0)\n            except Exception:\n                pass\n\n    return main_usage, dict(subagent_usage)\n\ndef format_tokens(n):\n    \"\"\"Format token count with thousands separators.\"\"\"\n    return f\"{n:,}\"\n\ndef calculate_cost(usage, input_cost_per_m=3.0, output_cost_per_m=15.0):\n    \"\"\"Calculate estimated cost in dollars.\"\"\"\n    total_input = usage['input_tokens'] + usage['cache_creation'] + usage['cache_read']\n    input_cost = total_input * input_cost_per_m / 1_000_000\n    output_cost = usage['output_tokens'] * output_cost_per_m / 1_000_000\n    return input_cost + output_cost\n\ndef main():\n    if len(sys.argv) < 2:\n        print(\"Usage: analyze-token-usage.py <session-file.jsonl>\")\n        sys.exit(1)\n\n    main_session_file = sys.argv[1]\n\n    if not Path(main_session_file).exists():\n        print(f\"Error: Session file not found: {main_session_file}\")\n        sys.exit(1)\n\n    # Analyze the session\n    main_usage, subagent_usage = analyze_main_session(main_session_file)\n\n    print(\"=\" * 100)\n    print(\"TOKEN USAGE ANALYSIS\")\n    print(\"=\" * 100)\n    print()\n\n    # Print breakdown\n    print(\"Usage Breakdown:\")\n    print(\"-\" * 100)\n    print(f\"{'Agent':<15} {'Description':<35} {'Msgs':>5} {'Input':>10} {'Output':>10} {'Cache':>10} {'Cost':>8}\")\n    print(\"-\" * 100)\n\n    # Main session\n    cost = calculate_cost(main_usage)\n    print(f\"{'main':<15} {'Main session (coordinator)':<35} \"\n          f\"{main_usage['messages']:>5} \"\n          f\"{format_tokens(main_usage['input_tokens']):>10} \"\n          f\"{format_tokens(main_usage['output_tokens']):>10} \"\n          f\"{format_tokens(main_usage['cache_read']):>10} \"\n          f\"${cost:>7.2f}\")\n\n    # Subagents (sorted by agent ID)\n    for agent_id in sorted(subagent_usage.keys()):\n        usage = subagent_usage[agent_id]\n        cost = calculate_cost(usage)\n        desc = usage['description'] or f\"agent-{agent_id}\"\n        print(f\"{agent_id:<15} {desc:<35} \"\n              f\"{usage['messages']:>5} \"\n              f\"{format_tokens(usage['input_tokens']):>10} \"\n              f\"{format_tokens(usage['output_tokens']):>10} \"\n              f\"{format_tokens(usage['cache_read']):>10} \"\n              f\"${cost:>7.2f}\")\n\n    print(\"-\" * 100)\n\n    # Calculate totals\n    total_usage = {\n        'input_tokens': main_usage['input_tokens'],\n        'output_tokens': main_usage['output_tokens'],\n        'cache_creation': main_usage['cache_creation'],\n        'cache_read': main_usage['cache_read'],\n        'messages': main_usage['messages']\n    }\n\n    for usage in subagent_usage.values():\n        total_usage['input_tokens'] += usage['input_tokens']\n        total_usage['output_tokens'] += usage['output_tokens']\n        total_usage['cache_creation'] += usage['cache_creation']\n        total_usage['cache_read'] += usage['cache_read']\n        total_usage['messages'] += usage['messages']\n\n    total_input = total_usage['input_tokens'] + total_usage['cache_creation'] + total_usage['cache_read']\n    total_tokens = total_input + total_usage['output_tokens']\n    total_cost = calculate_cost(total_usage)\n\n    print()\n    print(\"TOTALS:\")\n    print(f\"  Total messages:         {format_tokens(total_usage['messages'])}\")\n    print(f\"  Input tokens:           {format_tokens(total_usage['input_tokens'])}\")\n    print(f\"  Output tokens:          {format_tokens(total_usage['output_tokens'])}\")\n    print(f\"  Cache creation tokens:  {format_tokens(total_usage['cache_creation'])}\")\n    print(f\"  Cache read tokens:      {format_tokens(total_usage['cache_read'])}\")\n    print()\n    print(f\"  Total input (incl cache): {format_tokens(total_input)}\")\n    print(f\"  Total tokens:             {format_tokens(total_tokens)}\")\n    print()\n    print(f\"  Estimated cost: ${total_cost:.2f}\")\n    print(\"  (at $3/$15 per M tokens for input/output)\")\n    print()\n    print(\"=\" * 100)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "tests/claude-code/run-skill-tests.sh",
    "content": "#!/usr/bin/env bash\n# Test runner for Claude Code skills\n# Tests skills by invoking Claude Code CLI and verifying behavior\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\ncd \"$SCRIPT_DIR\"\n\necho \"========================================\"\necho \" Claude Code Skills Test Suite\"\necho \"========================================\"\necho \"\"\necho \"Repository: $(cd ../.. && pwd)\"\necho \"Test time: $(date)\"\necho \"Claude version: $(claude --version 2>/dev/null || echo 'not found')\"\necho \"\"\n\n# Check if Claude Code is available\nif ! command -v claude &> /dev/null; then\n    echo \"ERROR: Claude Code CLI not found\"\n    echo \"Install Claude Code first: https://code.claude.com\"\n    exit 1\nfi\n\n# Parse command line arguments\nVERBOSE=false\nSPECIFIC_TEST=\"\"\nTIMEOUT=300  # Default 5 minute timeout per test\nRUN_INTEGRATION=false\n\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        --verbose|-v)\n            VERBOSE=true\n            shift\n            ;;\n        --test|-t)\n            SPECIFIC_TEST=\"$2\"\n            shift 2\n            ;;\n        --timeout)\n            TIMEOUT=\"$2\"\n            shift 2\n            ;;\n        --integration|-i)\n            RUN_INTEGRATION=true\n            shift\n            ;;\n        --help|-h)\n            echo \"Usage: $0 [options]\"\n            echo \"\"\n            echo \"Options:\"\n            echo \"  --verbose, -v        Show verbose output\"\n            echo \"  --test, -t NAME      Run only the specified test\"\n            echo \"  --timeout SECONDS    Set timeout per test (default: 300)\"\n            echo \"  --integration, -i    Run integration tests (slow, 10-30 min)\"\n            echo \"  --help, -h           Show this help\"\n            echo \"\"\n            echo \"Tests:\"\n            echo \"  test-subagent-driven-development.sh  Test skill loading and requirements\"\n            echo \"\"\n            echo \"Integration Tests (use --integration):\"\n            echo \"  test-subagent-driven-development-integration.sh  Full workflow execution\"\n            exit 0\n            ;;\n        *)\n            echo \"Unknown option: $1\"\n            echo \"Use --help for usage information\"\n            exit 1\n            ;;\n    esac\ndone\n\n# List of skill tests to run (fast unit tests)\ntests=(\n    \"test-subagent-driven-development.sh\"\n)\n\n# Integration tests (slow, full execution)\nintegration_tests=(\n    \"test-subagent-driven-development-integration.sh\"\n)\n\n# Add integration tests if requested\nif [ \"$RUN_INTEGRATION\" = true ]; then\n    tests+=(\"${integration_tests[@]}\")\nfi\n\n# Filter to specific test if requested\nif [ -n \"$SPECIFIC_TEST\" ]; then\n    tests=(\"$SPECIFIC_TEST\")\nfi\n\n# Track results\npassed=0\nfailed=0\nskipped=0\n\n# Run each test\nfor test in \"${tests[@]}\"; do\n    echo \"----------------------------------------\"\n    echo \"Running: $test\"\n    echo \"----------------------------------------\"\n\n    test_path=\"$SCRIPT_DIR/$test\"\n\n    if [ ! -f \"$test_path\" ]; then\n        echo \"  [SKIP] Test file not found: $test\"\n        skipped=$((skipped + 1))\n        continue\n    fi\n\n    if [ ! -x \"$test_path\" ]; then\n        echo \"  Making $test executable...\"\n        chmod +x \"$test_path\"\n    fi\n\n    start_time=$(date +%s)\n\n    if [ \"$VERBOSE\" = true ]; then\n        if timeout \"$TIMEOUT\" bash \"$test_path\"; then\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"\"\n            echo \"  [PASS] $test (${duration}s)\"\n            passed=$((passed + 1))\n        else\n            exit_code=$?\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"\"\n            if [ $exit_code -eq 124 ]; then\n                echo \"  [FAIL] $test (timeout after ${TIMEOUT}s)\"\n            else\n                echo \"  [FAIL] $test (${duration}s)\"\n            fi\n            failed=$((failed + 1))\n        fi\n    else\n        # Capture output for non-verbose mode\n        if output=$(timeout \"$TIMEOUT\" bash \"$test_path\" 2>&1); then\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"  [PASS] (${duration}s)\"\n            passed=$((passed + 1))\n        else\n            exit_code=$?\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            if [ $exit_code -eq 124 ]; then\n                echo \"  [FAIL] (timeout after ${TIMEOUT}s)\"\n            else\n                echo \"  [FAIL] (${duration}s)\"\n            fi\n            echo \"\"\n            echo \"  Output:\"\n            echo \"$output\" | sed 's/^/    /'\n            failed=$((failed + 1))\n        fi\n    fi\n\n    echo \"\"\ndone\n\n# Print summary\necho \"========================================\"\necho \" Test Results Summary\"\necho \"========================================\"\necho \"\"\necho \"  Passed:  $passed\"\necho \"  Failed:  $failed\"\necho \"  Skipped: $skipped\"\necho \"\"\n\nif [ \"$RUN_INTEGRATION\" = false ] && [ ${#integration_tests[@]} -gt 0 ]; then\n    echo \"Note: Integration tests were not run (they take 10-30 minutes).\"\n    echo \"Use --integration flag to run full workflow execution tests.\"\n    echo \"\"\nfi\n\nif [ $failed -gt 0 ]; then\n    echo \"STATUS: FAILED\"\n    exit 1\nelse\n    echo \"STATUS: PASSED\"\n    exit 0\nfi\n"
  },
  {
    "path": "tests/claude-code/test-document-review-system.sh",
    "content": "#!/usr/bin/env bash\n# Integration Test: Document Review System\n# Actually runs spec/plan review and verifies reviewers catch issues\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nsource \"$SCRIPT_DIR/test-helpers.sh\"\n\necho \"========================================\"\necho \" Integration Test: Document Review System\"\necho \"========================================\"\necho \"\"\necho \"This test verifies the document review system by:\"\necho \"  1. Creating a spec with intentional errors\"\necho \"  2. Running the spec document reviewer\"\necho \"  3. Verifying the reviewer catches the errors\"\necho \"\"\n\n# Create test project\nTEST_PROJECT=$(create_test_project)\necho \"Test project: $TEST_PROJECT\"\n\n# Trap to cleanup\ntrap \"cleanup_test_project $TEST_PROJECT\" EXIT\n\ncd \"$TEST_PROJECT\"\n\n# Create directory structure\nmkdir -p docs/superpowers/specs\n\n# Create a spec document WITH INTENTIONAL ERRORS for the reviewer to catch\ncat > docs/superpowers/specs/test-feature-design.md <<'EOF'\n# Test Feature Design\n\n## Overview\n\nThis is a test feature that does something useful.\n\n## Requirements\n\n1. The feature should work correctly\n2. It should be fast\n3. TODO: Add more requirements here\n\n## Architecture\n\nThe feature will use a simple architecture with:\n- A frontend component\n- A backend service\n- Error handling will be specified later once we understand the failure modes better\n\n## Data Flow\n\nData flows from the frontend to the backend.\n\n## Testing Strategy\n\nTests will be written to cover the main functionality.\nEOF\n\n# Initialize git repo\ngit init --quiet\ngit config user.email \"test@test.com\"\ngit config user.name \"Test User\"\ngit add .\ngit commit -m \"Initial commit with test spec\" --quiet\n\necho \"\"\necho \"Created test spec with intentional errors:\"\necho \"  - TODO placeholder in Requirements section\"\necho \"  - 'specified later' deferral in Architecture section\"\necho \"\"\necho \"Running spec document reviewer...\"\necho \"\"\n\n# Run Claude to review the spec\nOUTPUT_FILE=\"$TEST_PROJECT/claude-output.txt\"\n\nPROMPT=\"You are testing the spec document reviewer.\n\nRead the spec-document-reviewer-prompt.md template in skills/brainstorming/ to understand the review format.\n\nThen review the spec at $TEST_PROJECT/docs/superpowers/specs/test-feature-design.md using the criteria from that template.\n\nLook for:\n- TODOs, placeholders, 'TBD', incomplete sections\n- Sections saying 'to be defined later' or 'will spec when X is done'\n- Sections noticeably less detailed than others\n\nOutput your review in the format specified in the template.\"\n\necho \"================================================================================\"\ncd \"$SCRIPT_DIR/../..\" && timeout 120 claude -p \"$PROMPT\" --permission-mode bypassPermissions 2>&1 | tee \"$OUTPUT_FILE\" || {\n    echo \"\"\n    echo \"================================================================================\"\n    echo \"EXECUTION FAILED (exit code: $?)\"\n    exit 1\n}\necho \"================================================================================\"\n\necho \"\"\necho \"Analyzing reviewer output...\"\necho \"\"\n\n# Verification tests\nFAILED=0\n\necho \"=== Verification Tests ===\"\necho \"\"\n\n# Test 1: Reviewer found the TODO\necho \"Test 1: Reviewer found TODO...\"\nif grep -qi \"TODO\" \"$OUTPUT_FILE\" && grep -qi \"requirements\\|Requirements\" \"$OUTPUT_FILE\"; then\n    echo \"  [PASS] Reviewer identified TODO in Requirements section\"\nelse\n    echo \"  [FAIL] Reviewer did not identify TODO\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 2: Reviewer found the \"specified later\" deferral\necho \"Test 2: Reviewer found 'specified later' deferral...\"\nif grep -qi \"specified later\\|later\\|defer\\|incomplete\\|error handling\" \"$OUTPUT_FILE\"; then\n    echo \"  [PASS] Reviewer identified deferred content\"\nelse\n    echo \"  [FAIL] Reviewer did not identify deferred content\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 3: Reviewer output includes Issues section\necho \"Test 3: Review output format...\"\nif grep -qi \"issues\\|Issues\" \"$OUTPUT_FILE\"; then\n    echo \"  [PASS] Review includes Issues section\"\nelse\n    echo \"  [FAIL] Review missing Issues section\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 4: Reviewer did NOT approve (found issues)\necho \"Test 4: Reviewer verdict...\"\nif grep -qi \"Issues Found\\|❌\\|not approved\\|issues found\" \"$OUTPUT_FILE\"; then\n    echo \"  [PASS] Reviewer correctly found issues (not approved)\"\nelif grep -qi \"Approved\\|✅\" \"$OUTPUT_FILE\" && ! grep -qi \"Issues Found\\|❌\" \"$OUTPUT_FILE\"; then\n    echo \"  [FAIL] Reviewer incorrectly approved spec with errors\"\n    FAILED=$((FAILED + 1))\nelse\n    echo \"  [PASS] Reviewer identified problems (ambiguous format but found issues)\"\nfi\necho \"\"\n\n# Summary\necho \"========================================\"\necho \" Test Summary\"\necho \"========================================\"\necho \"\"\n\nif [ $FAILED -eq 0 ]; then\n    echo \"STATUS: PASSED\"\n    echo \"All verification tests passed!\"\n    echo \"\"\n    echo \"The spec document reviewer correctly:\"\n    echo \"  ✓ Found TODO placeholder\"\n    echo \"  ✓ Found 'specified later' deferral\"\n    echo \"  ✓ Produced properly formatted review\"\n    echo \"  ✓ Did not approve spec with errors\"\n    exit 0\nelse\n    echo \"STATUS: FAILED\"\n    echo \"Failed $FAILED verification tests\"\n    echo \"\"\n    echo \"Output saved to: $OUTPUT_FILE\"\n    echo \"\"\n    echo \"Review the output to see what went wrong.\"\n    exit 1\nfi\n"
  },
  {
    "path": "tests/claude-code/test-helpers.sh",
    "content": "#!/usr/bin/env bash\n# Helper functions for Claude Code skill tests\n\n# Run Claude Code with a prompt and capture output\n# Usage: run_claude \"prompt text\" [timeout_seconds] [allowed_tools]\nrun_claude() {\n    local prompt=\"$1\"\n    local timeout=\"${2:-60}\"\n    local allowed_tools=\"${3:-}\"\n    local output_file=$(mktemp)\n\n    # Build command\n    local cmd=\"claude -p \\\"$prompt\\\"\"\n    if [ -n \"$allowed_tools\" ]; then\n        cmd=\"$cmd --allowed-tools=$allowed_tools\"\n    fi\n\n    # Run Claude in headless mode with timeout\n    if timeout \"$timeout\" bash -c \"$cmd\" > \"$output_file\" 2>&1; then\n        cat \"$output_file\"\n        rm -f \"$output_file\"\n        return 0\n    else\n        local exit_code=$?\n        cat \"$output_file\" >&2\n        rm -f \"$output_file\"\n        return $exit_code\n    fi\n}\n\n# Check if output contains a pattern\n# Usage: assert_contains \"output\" \"pattern\" \"test name\"\nassert_contains() {\n    local output=\"$1\"\n    local pattern=\"$2\"\n    local test_name=\"${3:-test}\"\n\n    if echo \"$output\" | grep -q \"$pattern\"; then\n        echo \"  [PASS] $test_name\"\n        return 0\n    else\n        echo \"  [FAIL] $test_name\"\n        echo \"  Expected to find: $pattern\"\n        echo \"  In output:\"\n        echo \"$output\" | sed 's/^/    /'\n        return 1\n    fi\n}\n\n# Check if output does NOT contain a pattern\n# Usage: assert_not_contains \"output\" \"pattern\" \"test name\"\nassert_not_contains() {\n    local output=\"$1\"\n    local pattern=\"$2\"\n    local test_name=\"${3:-test}\"\n\n    if echo \"$output\" | grep -q \"$pattern\"; then\n        echo \"  [FAIL] $test_name\"\n        echo \"  Did not expect to find: $pattern\"\n        echo \"  In output:\"\n        echo \"$output\" | sed 's/^/    /'\n        return 1\n    else\n        echo \"  [PASS] $test_name\"\n        return 0\n    fi\n}\n\n# Check if output matches a count\n# Usage: assert_count \"output\" \"pattern\" expected_count \"test name\"\nassert_count() {\n    local output=\"$1\"\n    local pattern=\"$2\"\n    local expected=\"$3\"\n    local test_name=\"${4:-test}\"\n\n    local actual=$(echo \"$output\" | grep -c \"$pattern\" || echo \"0\")\n\n    if [ \"$actual\" -eq \"$expected\" ]; then\n        echo \"  [PASS] $test_name (found $actual instances)\"\n        return 0\n    else\n        echo \"  [FAIL] $test_name\"\n        echo \"  Expected $expected instances of: $pattern\"\n        echo \"  Found $actual instances\"\n        echo \"  In output:\"\n        echo \"$output\" | sed 's/^/    /'\n        return 1\n    fi\n}\n\n# Check if pattern A appears before pattern B\n# Usage: assert_order \"output\" \"pattern_a\" \"pattern_b\" \"test name\"\nassert_order() {\n    local output=\"$1\"\n    local pattern_a=\"$2\"\n    local pattern_b=\"$3\"\n    local test_name=\"${4:-test}\"\n\n    # Get line numbers where patterns appear\n    local line_a=$(echo \"$output\" | grep -n \"$pattern_a\" | head -1 | cut -d: -f1)\n    local line_b=$(echo \"$output\" | grep -n \"$pattern_b\" | head -1 | cut -d: -f1)\n\n    if [ -z \"$line_a\" ]; then\n        echo \"  [FAIL] $test_name: pattern A not found: $pattern_a\"\n        return 1\n    fi\n\n    if [ -z \"$line_b\" ]; then\n        echo \"  [FAIL] $test_name: pattern B not found: $pattern_b\"\n        return 1\n    fi\n\n    if [ \"$line_a\" -lt \"$line_b\" ]; then\n        echo \"  [PASS] $test_name (A at line $line_a, B at line $line_b)\"\n        return 0\n    else\n        echo \"  [FAIL] $test_name\"\n        echo \"  Expected '$pattern_a' before '$pattern_b'\"\n        echo \"  But found A at line $line_a, B at line $line_b\"\n        return 1\n    fi\n}\n\n# Create a temporary test project directory\n# Usage: test_project=$(create_test_project)\ncreate_test_project() {\n    local test_dir=$(mktemp -d)\n    echo \"$test_dir\"\n}\n\n# Cleanup test project\n# Usage: cleanup_test_project \"$test_dir\"\ncleanup_test_project() {\n    local test_dir=\"$1\"\n    if [ -d \"$test_dir\" ]; then\n        rm -rf \"$test_dir\"\n    fi\n}\n\n# Create a simple plan file for testing\n# Usage: create_test_plan \"$project_dir\" \"$plan_name\"\ncreate_test_plan() {\n    local project_dir=\"$1\"\n    local plan_name=\"${2:-test-plan}\"\n    local plan_file=\"$project_dir/docs/superpowers/plans/$plan_name.md\"\n\n    mkdir -p \"$(dirname \"$plan_file\")\"\n\n    cat > \"$plan_file\" <<'EOF'\n# Test Implementation Plan\n\n## Task 1: Create Hello Function\n\nCreate a simple hello function that returns \"Hello, World!\".\n\n**File:** `src/hello.js`\n\n**Implementation:**\n```javascript\nexport function hello() {\n  return \"Hello, World!\";\n}\n```\n\n**Tests:** Write a test that verifies the function returns the expected string.\n\n**Verification:** `npm test`\n\n## Task 2: Create Goodbye Function\n\nCreate a goodbye function that takes a name and returns a goodbye message.\n\n**File:** `src/goodbye.js`\n\n**Implementation:**\n```javascript\nexport function goodbye(name) {\n  return `Goodbye, ${name}!`;\n}\n```\n\n**Tests:** Write tests for:\n- Default name\n- Custom name\n- Edge cases (empty string, null)\n\n**Verification:** `npm test`\nEOF\n\n    echo \"$plan_file\"\n}\n\n# Export functions for use in tests\nexport -f run_claude\nexport -f assert_contains\nexport -f assert_not_contains\nexport -f assert_count\nexport -f assert_order\nexport -f create_test_project\nexport -f cleanup_test_project\nexport -f create_test_plan\n"
  },
  {
    "path": "tests/claude-code/test-subagent-driven-development-integration.sh",
    "content": "#!/usr/bin/env bash\n# Integration Test: subagent-driven-development workflow\n# Actually executes a plan and verifies the new workflow behaviors\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nsource \"$SCRIPT_DIR/test-helpers.sh\"\n\necho \"========================================\"\necho \" Integration Test: subagent-driven-development\"\necho \"========================================\"\necho \"\"\necho \"This test executes a real plan using the skill and verifies:\"\necho \"  1. Plan is read once (not per task)\"\necho \"  2. Full task text provided to subagents\"\necho \"  3. Subagents perform self-review\"\necho \"  4. Spec compliance review before code quality\"\necho \"  5. Review loops when issues found\"\necho \"  6. Spec reviewer reads code independently\"\necho \"\"\necho \"WARNING: This test may take 10-30 minutes to complete.\"\necho \"\"\n\n# Create test project\nTEST_PROJECT=$(create_test_project)\necho \"Test project: $TEST_PROJECT\"\n\n# Trap to cleanup\ntrap \"cleanup_test_project $TEST_PROJECT\" EXIT\n\n# Set up minimal Node.js project\ncd \"$TEST_PROJECT\"\n\ncat > package.json <<'EOF'\n{\n  \"name\": \"test-project\",\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"test\": \"node --test\"\n  }\n}\nEOF\n\nmkdir -p src test docs/superpowers/plans\n\n# Create a simple implementation plan\ncat > docs/superpowers/plans/implementation-plan.md <<'EOF'\n# Test Implementation Plan\n\nThis is a minimal plan to test the subagent-driven-development workflow.\n\n## Task 1: Create Add Function\n\nCreate a function that adds two numbers.\n\n**File:** `src/math.js`\n\n**Requirements:**\n- Function named `add`\n- Takes two parameters: `a` and `b`\n- Returns the sum of `a` and `b`\n- Export the function\n\n**Implementation:**\n```javascript\nexport function add(a, b) {\n  return a + b;\n}\n```\n\n**Tests:** Create `test/math.test.js` that verifies:\n- `add(2, 3)` returns `5`\n- `add(0, 0)` returns `0`\n- `add(-1, 1)` returns `0`\n\n**Verification:** `npm test`\n\n## Task 2: Create Multiply Function\n\nCreate a function that multiplies two numbers.\n\n**File:** `src/math.js` (add to existing file)\n\n**Requirements:**\n- Function named `multiply`\n- Takes two parameters: `a` and `b`\n- Returns the product of `a` and `b`\n- Export the function\n- DO NOT add any extra features (like power, divide, etc.)\n\n**Implementation:**\n```javascript\nexport function multiply(a, b) {\n  return a * b;\n}\n```\n\n**Tests:** Add to `test/math.test.js`:\n- `multiply(2, 3)` returns `6`\n- `multiply(0, 5)` returns `0`\n- `multiply(-2, 3)` returns `-6`\n\n**Verification:** `npm test`\nEOF\n\n# Initialize git repo\ngit init --quiet\ngit config user.email \"test@test.com\"\ngit config user.name \"Test User\"\ngit add .\ngit commit -m \"Initial commit\" --quiet\n\necho \"\"\necho \"Project setup complete. Starting execution...\"\necho \"\"\n\n# Run Claude with subagent-driven-development\n# Capture full output to analyze\nOUTPUT_FILE=\"$TEST_PROJECT/claude-output.txt\"\n\n# Create prompt file\ncat > \"$TEST_PROJECT/prompt.txt\" <<'EOF'\nI want you to execute the implementation plan at docs/superpowers/plans/implementation-plan.md using the subagent-driven-development skill.\n\nIMPORTANT: Follow the skill exactly. I will be verifying that you:\n1. Read the plan once at the beginning\n2. Provide full task text to subagents (don't make them read files)\n3. Ensure subagents do self-review before reporting\n4. Run spec compliance review before code quality review\n5. Use review loops when issues are found\n\nBegin now. Execute the plan.\nEOF\n\n# Note: We use a longer timeout since this is integration testing\n# Use --allowed-tools to enable tool usage in headless mode\n# IMPORTANT: Run from superpowers directory so local dev skills are available\nPROMPT=\"Change to directory $TEST_PROJECT and then execute the implementation plan at docs/superpowers/plans/implementation-plan.md using the subagent-driven-development skill.\n\nIMPORTANT: Follow the skill exactly. I will be verifying that you:\n1. Read the plan once at the beginning\n2. Provide full task text to subagents (don't make them read files)\n3. Ensure subagents do self-review before reporting\n4. Run spec compliance review before code quality review\n5. Use review loops when issues are found\n\nBegin now. Execute the plan.\"\n\necho \"Running Claude (output will be shown below and saved to $OUTPUT_FILE)...\"\necho \"================================================================================\"\ncd \"$SCRIPT_DIR/../..\" && timeout 1800 claude -p \"$PROMPT\" --allowed-tools=all --add-dir \"$TEST_PROJECT\" --permission-mode bypassPermissions 2>&1 | tee \"$OUTPUT_FILE\" || {\n    echo \"\"\n    echo \"================================================================================\"\n    echo \"EXECUTION FAILED (exit code: $?)\"\n    exit 1\n}\necho \"================================================================================\"\n\necho \"\"\necho \"Execution complete. Analyzing results...\"\necho \"\"\n\n# Find the session transcript\n# Session files are in ~/.claude/projects/-<working-dir>/<session-id>.jsonl\nWORKING_DIR_ESCAPED=$(echo \"$SCRIPT_DIR/../..\" | sed 's/\\//-/g' | sed 's/^-//')\nSESSION_DIR=\"$HOME/.claude/projects/$WORKING_DIR_ESCAPED\"\n\n# Find the most recent session file (created during this test run)\nSESSION_FILE=$(find \"$SESSION_DIR\" -name \"*.jsonl\" -type f -mmin -60 2>/dev/null | sort -r | head -1)\n\nif [ -z \"$SESSION_FILE\" ]; then\n    echo \"ERROR: Could not find session transcript file\"\n    echo \"Looked in: $SESSION_DIR\"\n    exit 1\nfi\n\necho \"Analyzing session transcript: $(basename \"$SESSION_FILE\")\"\necho \"\"\n\n# Verification tests\nFAILED=0\n\necho \"=== Verification Tests ===\"\necho \"\"\n\n# Test 1: Skill was invoked\necho \"Test 1: Skill tool invoked...\"\nif grep -q '\"name\":\"Skill\".*\"skill\":\"superpowers:subagent-driven-development\"' \"$SESSION_FILE\"; then\n    echo \"  [PASS] subagent-driven-development skill was invoked\"\nelse\n    echo \"  [FAIL] Skill was not invoked\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 2: Subagents were used (Task tool)\necho \"Test 2: Subagents dispatched...\"\ntask_count=$(grep -c '\"name\":\"Task\"' \"$SESSION_FILE\" || echo \"0\")\nif [ \"$task_count\" -ge 2 ]; then\n    echo \"  [PASS] $task_count subagents dispatched\"\nelse\n    echo \"  [FAIL] Only $task_count subagent(s) dispatched (expected >= 2)\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 3: TodoWrite was used for tracking\necho \"Test 3: Task tracking...\"\ntodo_count=$(grep -c '\"name\":\"TodoWrite\"' \"$SESSION_FILE\" || echo \"0\")\nif [ \"$todo_count\" -ge 1 ]; then\n    echo \"  [PASS] TodoWrite used $todo_count time(s) for task tracking\"\nelse\n    echo \"  [FAIL] TodoWrite not used\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 6: Implementation actually works\necho \"Test 6: Implementation verification...\"\nif [ -f \"$TEST_PROJECT/src/math.js\" ]; then\n    echo \"  [PASS] src/math.js created\"\n\n    if grep -q \"export function add\" \"$TEST_PROJECT/src/math.js\"; then\n        echo \"  [PASS] add function exists\"\n    else\n        echo \"  [FAIL] add function missing\"\n        FAILED=$((FAILED + 1))\n    fi\n\n    if grep -q \"export function multiply\" \"$TEST_PROJECT/src/math.js\"; then\n        echo \"  [PASS] multiply function exists\"\n    else\n        echo \"  [FAIL] multiply function missing\"\n        FAILED=$((FAILED + 1))\n    fi\nelse\n    echo \"  [FAIL] src/math.js not created\"\n    FAILED=$((FAILED + 1))\nfi\n\nif [ -f \"$TEST_PROJECT/test/math.test.js\" ]; then\n    echo \"  [PASS] test/math.test.js created\"\nelse\n    echo \"  [FAIL] test/math.test.js not created\"\n    FAILED=$((FAILED + 1))\nfi\n\n# Try running tests\nif cd \"$TEST_PROJECT\" && npm test > test-output.txt 2>&1; then\n    echo \"  [PASS] Tests pass\"\nelse\n    echo \"  [FAIL] Tests failed\"\n    cat test-output.txt\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 7: Git commits show proper workflow\necho \"Test 7: Git commit history...\"\ncommit_count=$(git -C \"$TEST_PROJECT\" log --oneline | wc -l)\nif [ \"$commit_count\" -gt 2 ]; then  # Initial + at least 2 task commits\n    echo \"  [PASS] Multiple commits created ($commit_count total)\"\nelse\n    echo \"  [FAIL] Too few commits ($commit_count, expected >2)\"\n    FAILED=$((FAILED + 1))\nfi\necho \"\"\n\n# Test 8: Check for extra features (spec compliance should catch)\necho \"Test 8: No extra features added (spec compliance)...\"\nif grep -q \"export function divide\\|export function power\\|export function subtract\" \"$TEST_PROJECT/src/math.js\" 2>/dev/null; then\n    echo \"  [WARN] Extra features found (spec review should have caught this)\"\n    # Not failing on this as it tests reviewer effectiveness\nelse\n    echo \"  [PASS] No extra features added\"\nfi\necho \"\"\n\n# Token Usage Analysis\necho \"=========================================\"\necho \" Token Usage Analysis\"\necho \"=========================================\"\necho \"\"\npython3 \"$SCRIPT_DIR/analyze-token-usage.py\" \"$SESSION_FILE\"\necho \"\"\n\n# Summary\necho \"========================================\"\necho \" Test Summary\"\necho \"========================================\"\necho \"\"\n\nif [ $FAILED -eq 0 ]; then\n    echo \"STATUS: PASSED\"\n    echo \"All verification tests passed!\"\n    echo \"\"\n    echo \"The subagent-driven-development skill correctly:\"\n    echo \"  ✓ Reads plan once at start\"\n    echo \"  ✓ Provides full task text to subagents\"\n    echo \"  ✓ Enforces self-review\"\n    echo \"  ✓ Runs spec compliance before code quality\"\n    echo \"  ✓ Spec reviewer verifies independently\"\n    echo \"  ✓ Produces working implementation\"\n    exit 0\nelse\n    echo \"STATUS: FAILED\"\n    echo \"Failed $FAILED verification tests\"\n    echo \"\"\n    echo \"Output saved to: $OUTPUT_FILE\"\n    echo \"\"\n    echo \"Review the output to see what went wrong.\"\n    exit 1\nfi\n"
  },
  {
    "path": "tests/claude-code/test-subagent-driven-development.sh",
    "content": "#!/usr/bin/env bash\n# Test: subagent-driven-development skill\n# Verifies that the skill is loaded and follows correct workflow\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nsource \"$SCRIPT_DIR/test-helpers.sh\"\n\necho \"=== Test: subagent-driven-development skill ===\"\necho \"\"\n\n# Test 1: Verify skill can be loaded\necho \"Test 1: Skill loading...\"\n\noutput=$(run_claude \"What is the subagent-driven-development skill? Describe its key steps briefly.\" 30)\n\nif assert_contains \"$output\" \"subagent-driven-development\\|Subagent-Driven Development\\|Subagent Driven\" \"Skill is recognized\"; then\n    : # pass\nelse\n    exit 1\nfi\n\nif assert_contains \"$output\" \"Load Plan\\|read.*plan\\|extract.*tasks\" \"Mentions loading plan\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 2: Verify skill describes correct workflow order\necho \"Test 2: Workflow ordering...\"\n\noutput=$(run_claude \"In the subagent-driven-development skill, what comes first: spec compliance review or code quality review? Be specific about the order.\" 30)\n\nif assert_order \"$output\" \"spec.*compliance\" \"code.*quality\" \"Spec compliance before code quality\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 3: Verify self-review is mentioned\necho \"Test 3: Self-review requirement...\"\n\noutput=$(run_claude \"Does the subagent-driven-development skill require implementers to do self-review? What should they check?\" 30)\n\nif assert_contains \"$output\" \"self-review\\|self review\" \"Mentions self-review\"; then\n    : # pass\nelse\n    exit 1\nfi\n\nif assert_contains \"$output\" \"completeness\\|Completeness\" \"Checks completeness\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 4: Verify plan is read once\necho \"Test 4: Plan reading efficiency...\"\n\noutput=$(run_claude \"In subagent-driven-development, how many times should the controller read the plan file? When does this happen?\" 30)\n\nif assert_contains \"$output\" \"once\\|one time\\|single\" \"Read plan once\"; then\n    : # pass\nelse\n    exit 1\nfi\n\nif assert_contains \"$output\" \"Step 1\\|beginning\\|start\\|Load Plan\" \"Read at beginning\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 5: Verify spec compliance reviewer is skeptical\necho \"Test 5: Spec compliance reviewer mindset...\"\n\noutput=$(run_claude \"What is the spec compliance reviewer's attitude toward the implementer's report in subagent-driven-development?\" 30)\n\nif assert_contains \"$output\" \"not trust\\|don't trust\\|skeptical\\|verify.*independently\\|suspiciously\" \"Reviewer is skeptical\"; then\n    : # pass\nelse\n    exit 1\nfi\n\nif assert_contains \"$output\" \"read.*code\\|inspect.*code\\|verify.*code\" \"Reviewer reads code\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 6: Verify review loops\necho \"Test 6: Review loop requirements...\"\n\noutput=$(run_claude \"In subagent-driven-development, what happens if a reviewer finds issues? Is it a one-time review or a loop?\" 30)\n\nif assert_contains \"$output\" \"loop\\|again\\|repeat\\|until.*approved\\|until.*compliant\" \"Review loops mentioned\"; then\n    : # pass\nelse\n    exit 1\nfi\n\nif assert_contains \"$output\" \"implementer.*fix\\|fix.*issues\" \"Implementer fixes issues\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 7: Verify full task text is provided\necho \"Test 7: Task context provision...\"\n\noutput=$(run_claude \"In subagent-driven-development, how does the controller provide task information to the implementer subagent? Does it make them read a file or provide it directly?\" 30)\n\nif assert_contains \"$output\" \"provide.*directly\\|full.*text\\|paste\\|include.*prompt\" \"Provides text directly\"; then\n    : # pass\nelse\n    exit 1\nfi\n\nif assert_not_contains \"$output\" \"read.*file\\|open.*file\" \"Doesn't make subagent read file\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 8: Verify worktree requirement\necho \"Test 8: Worktree requirement...\"\n\noutput=$(run_claude \"What workflow skills are required before using subagent-driven-development? List any prerequisites or required skills.\" 30)\n\nif assert_contains \"$output\" \"using-git-worktrees\\|worktree\" \"Mentions worktree requirement\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\n# Test 9: Verify main branch warning\necho \"Test 9: Main branch red flag...\"\n\noutput=$(run_claude \"In subagent-driven-development, is it okay to start implementation directly on the main branch?\" 30)\n\nif assert_contains \"$output\" \"worktree\\|feature.*branch\\|not.*main\\|never.*main\\|avoid.*main\\|don't.*main\\|consent\\|permission\" \"Warns against main branch\"; then\n    : # pass\nelse\n    exit 1\nfi\n\necho \"\"\n\necho \"=== All subagent-driven-development skill tests passed ===\"\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/action-oriented.txt",
    "content": "The plan is done. docs/superpowers/plans/auth-system.md has everything.\n\nDo subagent-driven development on this - start with Task 1, dispatch a subagent, then we'll review.\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/after-planning-flow.txt",
    "content": "Great, the plan is complete. I've saved it to docs/superpowers/plans/auth-system.md.\n\nHere's a summary of what we designed:\n- Task 1: Add User Model with email/password fields\n- Task 2: Create auth routes for login/register\n- Task 3: Add JWT middleware for protected routes\n- Task 4: Write tests for all auth functionality\n\nTwo execution options:\n1. Subagent-Driven (this session) - dispatch a fresh subagent per task\n2. Parallel Session (separate) - open new Claude Code session\n\nWhich approach do you want?\n\n---\n\nsubagent-driven-development, please\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/claude-suggested-it.txt",
    "content": "[Previous assistant message]:\nPlan complete and saved to docs/superpowers/plans/auth-system.md.\n\nTwo execution options:\n1. Subagent-Driven (this session) - I dispatch a fresh subagent per task, review between tasks, fast iteration within this conversation\n2. Parallel Session (separate) - Open a new Claude Code session with the execute-plan skill, batch execution with review checkpoints\n\nWhich approach do you want to use for implementation?\n\n[Your response]:\nsubagent-driven-development, please\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/i-know-what-sdd-means.txt",
    "content": "I have my implementation plan ready at docs/superpowers/plans/auth-system.md.\n\nI want to use subagent-driven-development to execute it. That means:\n- Dispatch a fresh subagent for each task in the plan\n- Review the output between tasks\n- Keep iteration fast within this conversation\n\nLet's start - please read the plan and begin dispatching subagents for each task.\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/mid-conversation-execute-plan.txt",
    "content": "I have a plan at docs/superpowers/plans/auth-system.md that's ready to implement.\n\nsubagent-driven-development, please\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/please-use-brainstorming.txt",
    "content": "please use the brainstorming skill to help me think through this feature\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/skip-formalities.txt",
    "content": "Plan is at docs/superpowers/plans/auth-system.md.\n\nsubagent-driven-development, please. Don't waste time - just read the plan and start dispatching subagents immediately.\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/subagent-driven-development-please.txt",
    "content": "subagent-driven-development, please\n"
  },
  {
    "path": "tests/explicit-skill-requests/prompts/use-systematic-debugging.txt",
    "content": "use systematic-debugging to figure out what's wrong\n"
  },
  {
    "path": "tests/explicit-skill-requests/run-all.sh",
    "content": "#!/usr/bin/env bash\n# Run all explicit skill request tests\n# Usage: ./run-all.sh\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPROMPTS_DIR=\"$SCRIPT_DIR/prompts\"\n\necho \"=== Running All Explicit Skill Request Tests ===\"\necho \"\"\n\nPASSED=0\nFAILED=0\nRESULTS=\"\"\n\n# Test: subagent-driven-development, please\necho \">>> Test 1: subagent-driven-development-please\"\nif \"$SCRIPT_DIR/run-test.sh\" \"subagent-driven-development\" \"$PROMPTS_DIR/subagent-driven-development-please.txt\"; then\n    PASSED=$((PASSED + 1))\n    RESULTS=\"$RESULTS\\nPASS: subagent-driven-development-please\"\nelse\n    FAILED=$((FAILED + 1))\n    RESULTS=\"$RESULTS\\nFAIL: subagent-driven-development-please\"\nfi\necho \"\"\n\n# Test: use systematic-debugging\necho \">>> Test 2: use-systematic-debugging\"\nif \"$SCRIPT_DIR/run-test.sh\" \"systematic-debugging\" \"$PROMPTS_DIR/use-systematic-debugging.txt\"; then\n    PASSED=$((PASSED + 1))\n    RESULTS=\"$RESULTS\\nPASS: use-systematic-debugging\"\nelse\n    FAILED=$((FAILED + 1))\n    RESULTS=\"$RESULTS\\nFAIL: use-systematic-debugging\"\nfi\necho \"\"\n\n# Test: please use brainstorming\necho \">>> Test 3: please-use-brainstorming\"\nif \"$SCRIPT_DIR/run-test.sh\" \"brainstorming\" \"$PROMPTS_DIR/please-use-brainstorming.txt\"; then\n    PASSED=$((PASSED + 1))\n    RESULTS=\"$RESULTS\\nPASS: please-use-brainstorming\"\nelse\n    FAILED=$((FAILED + 1))\n    RESULTS=\"$RESULTS\\nFAIL: please-use-brainstorming\"\nfi\necho \"\"\n\n# Test: mid-conversation execute plan\necho \">>> Test 4: mid-conversation-execute-plan\"\nif \"$SCRIPT_DIR/run-test.sh\" \"subagent-driven-development\" \"$PROMPTS_DIR/mid-conversation-execute-plan.txt\"; then\n    PASSED=$((PASSED + 1))\n    RESULTS=\"$RESULTS\\nPASS: mid-conversation-execute-plan\"\nelse\n    FAILED=$((FAILED + 1))\n    RESULTS=\"$RESULTS\\nFAIL: mid-conversation-execute-plan\"\nfi\necho \"\"\n\necho \"=== Summary ===\"\necho -e \"$RESULTS\"\necho \"\"\necho \"Passed: $PASSED\"\necho \"Failed: $FAILED\"\necho \"Total: $((PASSED + FAILED))\"\n\nif [ \"$FAILED\" -gt 0 ]; then\n    exit 1\nfi\n"
  },
  {
    "path": "tests/explicit-skill-requests/run-claude-describes-sdd.sh",
    "content": "#!/usr/bin/env bash\n# Test where Claude explicitly describes subagent-driven-development before user requests it\n# This mimics the original failure scenario\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\n\nTIMESTAMP=$(date +%s)\nOUTPUT_DIR=\"/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/claude-describes\"\nmkdir -p \"$OUTPUT_DIR\"\n\nPROJECT_DIR=\"$OUTPUT_DIR/project\"\nmkdir -p \"$PROJECT_DIR/docs/superpowers/plans\"\n\necho \"=== Test: Claude Describes SDD First ===\"\necho \"Output dir: $OUTPUT_DIR\"\necho \"\"\n\ncd \"$PROJECT_DIR\"\n\n# Create a plan\ncat > \"$PROJECT_DIR/docs/superpowers/plans/auth-system.md\" << 'EOF'\n# Auth System Implementation Plan\n\n## Task 1: Add User Model\nCreate user model with email and password fields.\n\n## Task 2: Add Auth Routes\nCreate login and register endpoints.\n\n## Task 3: Add JWT Middleware\nProtect routes with JWT validation.\nEOF\n\n# Turn 1: Have Claude describe execution options including SDD\necho \">>> Turn 1: Ask Claude to describe execution options...\"\nclaude -p \"I have a plan at docs/superpowers/plans/auth-system.md. Tell me about my options for executing it, including what subagent-driven-development means and how it works.\" \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn1.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 2: THE CRITICAL TEST - now that Claude has explained it\necho \">>> Turn 2: Request subagent-driven-development...\"\nFINAL_LOG=\"$OUTPUT_DIR/turn2.json\"\nclaude -p \"subagent-driven-development, please\" \\\n    --continue \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$FINAL_LOG\" 2>&1 || true\necho \"Done.\"\necho \"\"\n\necho \"=== Results ===\"\n\n# Check Turn 1 to see if Claude described SDD\necho \"Turn 1 - Claude's description of options (excerpt):\"\ngrep '\"type\":\"assistant\"' \"$OUTPUT_DIR/turn1.json\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 800 || echo \"  (could not extract)\"\necho \"\"\necho \"---\"\necho \"\"\n\n# Check final turn\nSKILL_PATTERN='\"skill\":\"([^\"]*:)?subagent-driven-development\"'\nif grep -q '\"name\":\"Skill\"' \"$FINAL_LOG\" && grep -qE \"$SKILL_PATTERN\" \"$FINAL_LOG\"; then\n    echo \"PASS: Skill was triggered after Claude described it\"\n    TRIGGERED=true\nelse\n    echo \"FAIL: Skill was NOT triggered (Claude may have thought it already knew)\"\n    TRIGGERED=false\n\n    echo \"\"\n    echo \"Tools invoked in final turn:\"\n    grep '\"type\":\"tool_use\"' \"$FINAL_LOG\" | grep -o '\"name\":\"[^\"]*\"' | sort -u | head -10 || echo \"  (none)\"\n\n    echo \"\"\n    echo \"Final turn response:\"\n    grep '\"type\":\"assistant\"' \"$FINAL_LOG\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 800 || echo \"  (could not extract)\"\nfi\n\necho \"\"\necho \"Skills triggered in final turn:\"\ngrep -o '\"skill\":\"[^\"]*\"' \"$FINAL_LOG\" 2>/dev/null | sort -u || echo \"  (none)\"\n\necho \"\"\necho \"Logs in: $OUTPUT_DIR\"\n\nif [ \"$TRIGGERED\" = \"true\" ]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/explicit-skill-requests/run-extended-multiturn-test.sh",
    "content": "#!/usr/bin/env bash\n# Extended multi-turn test with more conversation history\n# This tries to reproduce the failure by building more context\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\n\nTIMESTAMP=$(date +%s)\nOUTPUT_DIR=\"/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/extended-multiturn\"\nmkdir -p \"$OUTPUT_DIR\"\n\nPROJECT_DIR=\"$OUTPUT_DIR/project\"\nmkdir -p \"$PROJECT_DIR/docs/superpowers/plans\"\n\necho \"=== Extended Multi-Turn Test ===\"\necho \"Output dir: $OUTPUT_DIR\"\necho \"Plugin dir: $PLUGIN_DIR\"\necho \"\"\n\ncd \"$PROJECT_DIR\"\n\n# Turn 1: Start brainstorming\necho \">>> Turn 1: Brainstorming request...\"\nclaude -p \"I want to add user authentication to my app. Help me think through this.\" \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn1.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 2: Answer a brainstorming question\necho \">>> Turn 2: Answering questions...\"\nclaude -p \"Let's use JWT tokens with 24-hour expiry. Email/password registration.\" \\\n    --continue \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn2.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 3: Ask to write a plan\necho \">>> Turn 3: Requesting plan...\"\nclaude -p \"Great, write this up as an implementation plan.\" \\\n    --continue \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn3.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 4: Confirm plan looks good\necho \">>> Turn 4: Confirming plan...\"\nclaude -p \"The plan looks good. What are my options for executing it?\" \\\n    --continue \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn4.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 5: THE CRITICAL TEST\necho \">>> Turn 5: Requesting subagent-driven-development...\"\nFINAL_LOG=\"$OUTPUT_DIR/turn5.json\"\nclaude -p \"subagent-driven-development, please\" \\\n    --continue \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$FINAL_LOG\" 2>&1 || true\necho \"Done.\"\necho \"\"\n\necho \"=== Results ===\"\n\n# Check final turn\nSKILL_PATTERN='\"skill\":\"([^\"]*:)?subagent-driven-development\"'\nif grep -q '\"name\":\"Skill\"' \"$FINAL_LOG\" && grep -qE \"$SKILL_PATTERN\" \"$FINAL_LOG\"; then\n    echo \"PASS: Skill was triggered\"\n    TRIGGERED=true\nelse\n    echo \"FAIL: Skill was NOT triggered\"\n    TRIGGERED=false\n\n    # Show what was invoked instead\n    echo \"\"\n    echo \"Tools invoked in final turn:\"\n    grep '\"type\":\"tool_use\"' \"$FINAL_LOG\" | jq -r '.content[] | select(.type==\"tool_use\") | .name' 2>/dev/null | head -10 || \\\n    grep -o '\"name\":\"[^\"]*\"' \"$FINAL_LOG\" | head -10 || echo \"  (none found)\"\nfi\n\necho \"\"\necho \"Skills triggered:\"\ngrep -o '\"skill\":\"[^\"]*\"' \"$FINAL_LOG\" 2>/dev/null | sort -u || echo \"  (none)\"\n\necho \"\"\necho \"Final turn response (first 500 chars):\"\ngrep '\"type\":\"assistant\"' \"$FINAL_LOG\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo \"  (could not extract)\"\n\necho \"\"\necho \"Logs in: $OUTPUT_DIR\"\n\nif [ \"$TRIGGERED\" = \"true\" ]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/explicit-skill-requests/run-haiku-test.sh",
    "content": "#!/usr/bin/env bash\n# Test with haiku model and user's CLAUDE.md\n# This tests whether a cheaper/faster model fails more easily\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\n\nTIMESTAMP=$(date +%s)\nOUTPUT_DIR=\"/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/haiku\"\nmkdir -p \"$OUTPUT_DIR\"\n\nPROJECT_DIR=\"$OUTPUT_DIR/project\"\nmkdir -p \"$PROJECT_DIR/docs/superpowers/plans\"\nmkdir -p \"$PROJECT_DIR/.claude\"\n\necho \"=== Haiku Model Test with User CLAUDE.md ===\"\necho \"Output dir: $OUTPUT_DIR\"\necho \"Plugin dir: $PLUGIN_DIR\"\necho \"\"\n\ncd \"$PROJECT_DIR\"\n\n# Copy user's CLAUDE.md to simulate real environment\nif [ -f \"$HOME/.claude/CLAUDE.md\" ]; then\n    cp \"$HOME/.claude/CLAUDE.md\" \"$PROJECT_DIR/.claude/CLAUDE.md\"\n    echo \"Copied user CLAUDE.md\"\nelse\n    echo \"No user CLAUDE.md found, proceeding without\"\nfi\n\n# Create a dummy plan file\ncat > \"$PROJECT_DIR/docs/superpowers/plans/auth-system.md\" << 'EOF'\n# Auth System Implementation Plan\n\n## Task 1: Add User Model\nCreate user model with email and password fields.\n\n## Task 2: Add Auth Routes\nCreate login and register endpoints.\n\n## Task 3: Add JWT Middleware\nProtect routes with JWT validation.\n\n## Task 4: Write Tests\nAdd comprehensive test coverage.\nEOF\n\necho \"\"\n\n# Turn 1: Start brainstorming\necho \">>> Turn 1: Brainstorming request...\"\nclaude -p \"I want to add user authentication to my app. Help me think through this.\" \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn1.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 2: Answer questions\necho \">>> Turn 2: Answering questions...\"\nclaude -p \"Let's use JWT tokens with 24-hour expiry. Email/password registration.\" \\\n    --continue \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn2.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 3: Ask to write a plan\necho \">>> Turn 3: Requesting plan...\"\nclaude -p \"Great, write this up as an implementation plan.\" \\\n    --continue \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 3 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn3.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 4: Confirm plan looks good\necho \">>> Turn 4: Confirming plan...\"\nclaude -p \"The plan looks good. What are my options for executing it?\" \\\n    --continue \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$OUTPUT_DIR/turn4.json\" 2>&1 || true\necho \"Done.\"\n\n# Turn 5: THE CRITICAL TEST\necho \">>> Turn 5: Requesting subagent-driven-development...\"\nFINAL_LOG=\"$OUTPUT_DIR/turn5.json\"\nclaude -p \"subagent-driven-development, please\" \\\n    --continue \\\n    --model haiku \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$FINAL_LOG\" 2>&1 || true\necho \"Done.\"\necho \"\"\n\necho \"=== Results (Haiku) ===\"\n\n# Check final turn\nSKILL_PATTERN='\"skill\":\"([^\"]*:)?subagent-driven-development\"'\nif grep -q '\"name\":\"Skill\"' \"$FINAL_LOG\" && grep -qE \"$SKILL_PATTERN\" \"$FINAL_LOG\"; then\n    echo \"PASS: Skill was triggered\"\n    TRIGGERED=true\nelse\n    echo \"FAIL: Skill was NOT triggered\"\n    TRIGGERED=false\n\n    echo \"\"\n    echo \"Tools invoked in final turn:\"\n    grep '\"type\":\"tool_use\"' \"$FINAL_LOG\" | grep -o '\"name\":\"[^\"]*\"' | head -10 || echo \"  (none)\"\nfi\n\necho \"\"\necho \"Skills triggered:\"\ngrep -o '\"skill\":\"[^\"]*\"' \"$FINAL_LOG\" 2>/dev/null | sort -u || echo \"  (none)\"\n\necho \"\"\necho \"Final turn response (first 500 chars):\"\ngrep '\"type\":\"assistant\"' \"$FINAL_LOG\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo \"  (could not extract)\"\n\necho \"\"\necho \"Logs in: $OUTPUT_DIR\"\n\nif [ \"$TRIGGERED\" = \"true\" ]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/explicit-skill-requests/run-multiturn-test.sh",
    "content": "#!/usr/bin/env bash\n# Test explicit skill requests in multi-turn conversations\n# Usage: ./run-multiturn-test.sh\n#\n# This test builds actual conversation history to reproduce the failure mode\n# where Claude skips skill invocation after extended conversation\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\n\nTIMESTAMP=$(date +%s)\nOUTPUT_DIR=\"/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/multiturn\"\nmkdir -p \"$OUTPUT_DIR\"\n\n# Create project directory (conversation is cwd-based)\nPROJECT_DIR=\"$OUTPUT_DIR/project\"\nmkdir -p \"$PROJECT_DIR/docs/superpowers/plans\"\n\necho \"=== Multi-Turn Explicit Skill Request Test ===\"\necho \"Output dir: $OUTPUT_DIR\"\necho \"Project dir: $PROJECT_DIR\"\necho \"Plugin dir: $PLUGIN_DIR\"\necho \"\"\n\ncd \"$PROJECT_DIR\"\n\n# Create a dummy plan file\ncat > \"$PROJECT_DIR/docs/superpowers/plans/auth-system.md\" << 'EOF'\n# Auth System Implementation Plan\n\n## Task 1: Add User Model\nCreate user model with email and password fields.\n\n## Task 2: Add Auth Routes\nCreate login and register endpoints.\n\n## Task 3: Add JWT Middleware\nProtect routes with JWT validation.\n\n## Task 4: Write Tests\nAdd comprehensive test coverage.\nEOF\n\n# Turn 1: Start a planning conversation\necho \">>> Turn 1: Starting planning conversation...\"\nTURN1_LOG=\"$OUTPUT_DIR/turn1.json\"\nclaude -p \"I need to implement an authentication system. Let's plan this out. The requirements are: user registration with email/password, JWT tokens, and protected routes.\" \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$TURN1_LOG\" 2>&1 || true\n\necho \"Turn 1 complete.\"\necho \"\"\n\n# Turn 2: Continue with more planning detail\necho \">>> Turn 2: Continuing planning...\"\nTURN2_LOG=\"$OUTPUT_DIR/turn2.json\"\nclaude -p \"Good analysis. I've already written the plan to docs/superpowers/plans/auth-system.md. Now I'm ready to implement. What are my options for execution?\" \\\n    --continue \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$TURN2_LOG\" 2>&1 || true\n\necho \"Turn 2 complete.\"\necho \"\"\n\n# Turn 3: The critical test - ask for subagent-driven-development\necho \">>> Turn 3: Requesting subagent-driven-development...\"\nTURN3_LOG=\"$OUTPUT_DIR/turn3.json\"\nclaude -p \"subagent-driven-development, please\" \\\n    --continue \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns 2 \\\n    --output-format stream-json \\\n    > \"$TURN3_LOG\" 2>&1 || true\n\necho \"Turn 3 complete.\"\necho \"\"\n\necho \"=== Results ===\"\n\n# Check if skill was triggered in Turn 3\nSKILL_PATTERN='\"skill\":\"([^\"]*:)?subagent-driven-development\"'\nif grep -q '\"name\":\"Skill\"' \"$TURN3_LOG\" && grep -qE \"$SKILL_PATTERN\" \"$TURN3_LOG\"; then\n    echo \"PASS: Skill 'subagent-driven-development' was triggered in Turn 3\"\n    TRIGGERED=true\nelse\n    echo \"FAIL: Skill 'subagent-driven-development' was NOT triggered in Turn 3\"\n    TRIGGERED=false\nfi\n\n# Show what skills were triggered\necho \"\"\necho \"Skills triggered in Turn 3:\"\ngrep -o '\"skill\":\"[^\"]*\"' \"$TURN3_LOG\" 2>/dev/null | sort -u || echo \"  (none)\"\n\n# Check for premature action in Turn 3\necho \"\"\necho \"Checking for premature action in Turn 3...\"\nFIRST_SKILL_LINE=$(grep -n '\"name\":\"Skill\"' \"$TURN3_LOG\" | head -1 | cut -d: -f1)\nif [ -n \"$FIRST_SKILL_LINE\" ]; then\n    PREMATURE_TOOLS=$(head -n \"$FIRST_SKILL_LINE\" \"$TURN3_LOG\" | \\\n        grep '\"type\":\"tool_use\"' | \\\n        grep -v '\"name\":\"Skill\"' | \\\n        grep -v '\"name\":\"TodoWrite\"' || true)\n    if [ -n \"$PREMATURE_TOOLS\" ]; then\n        echo \"WARNING: Tools invoked BEFORE Skill tool in Turn 3:\"\n        echo \"$PREMATURE_TOOLS\" | head -5\n    else\n        echo \"OK: No premature tool invocations detected\"\n    fi\nelse\n    echo \"WARNING: No Skill invocation found in Turn 3\"\n    # Show what WAS invoked\n    echo \"\"\n    echo \"Tools invoked in Turn 3:\"\n    grep '\"type\":\"tool_use\"' \"$TURN3_LOG\" | grep -o '\"name\":\"[^\"]*\"' | head -10 || echo \"  (none)\"\nfi\n\n# Show Turn 3 assistant response\necho \"\"\necho \"Turn 3 first assistant response (truncated):\"\ngrep '\"type\":\"assistant\"' \"$TURN3_LOG\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo \"  (could not extract)\"\n\necho \"\"\necho \"Logs:\"\necho \"  Turn 1: $TURN1_LOG\"\necho \"  Turn 2: $TURN2_LOG\"\necho \"  Turn 3: $TURN3_LOG\"\necho \"Timestamp: $TIMESTAMP\"\n\nif [ \"$TRIGGERED\" = \"true\" ]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/explicit-skill-requests/run-test.sh",
    "content": "#!/usr/bin/env bash\n# Test explicit skill requests (user names a skill directly)\n# Usage: ./run-test.sh <skill-name> <prompt-file>\n#\n# Tests whether Claude invokes a skill when the user explicitly requests it by name\n# (without using the plugin namespace prefix)\n#\n# Uses isolated HOME to avoid user context interference\n\nset -e\n\nSKILL_NAME=\"$1\"\nPROMPT_FILE=\"$2\"\nMAX_TURNS=\"${3:-3}\"\n\nif [ -z \"$SKILL_NAME\" ] || [ -z \"$PROMPT_FILE\" ]; then\n    echo \"Usage: $0 <skill-name> <prompt-file> [max-turns]\"\n    echo \"Example: $0 subagent-driven-development ./prompts/subagent-driven-development-please.txt\"\n    exit 1\nfi\n\n# Get the directory where this script lives\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n# Get the superpowers plugin root (two levels up)\nPLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\n\nTIMESTAMP=$(date +%s)\nOUTPUT_DIR=\"/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/${SKILL_NAME}\"\nmkdir -p \"$OUTPUT_DIR\"\n\n# Read prompt from file\nPROMPT=$(cat \"$PROMPT_FILE\")\n\necho \"=== Explicit Skill Request Test ===\"\necho \"Skill: $SKILL_NAME\"\necho \"Prompt file: $PROMPT_FILE\"\necho \"Max turns: $MAX_TURNS\"\necho \"Output dir: $OUTPUT_DIR\"\necho \"\"\n\n# Copy prompt for reference\ncp \"$PROMPT_FILE\" \"$OUTPUT_DIR/prompt.txt\"\n\n# Create a minimal project directory for the test\nPROJECT_DIR=\"$OUTPUT_DIR/project\"\nmkdir -p \"$PROJECT_DIR/docs/superpowers/plans\"\n\n# Create a dummy plan file for mid-conversation tests\ncat > \"$PROJECT_DIR/docs/superpowers/plans/auth-system.md\" << 'EOF'\n# Auth System Implementation Plan\n\n## Task 1: Add User Model\nCreate user model with email and password fields.\n\n## Task 2: Add Auth Routes\nCreate login and register endpoints.\n\n## Task 3: Add JWT Middleware\nProtect routes with JWT validation.\nEOF\n\n# Run Claude with isolated environment\nLOG_FILE=\"$OUTPUT_DIR/claude-output.json\"\ncd \"$PROJECT_DIR\"\n\necho \"Plugin dir: $PLUGIN_DIR\"\necho \"Running claude -p with explicit skill request...\"\necho \"Prompt: $PROMPT\"\necho \"\"\n\ntimeout 300 claude -p \"$PROMPT\" \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns \"$MAX_TURNS\" \\\n    --output-format stream-json \\\n    > \"$LOG_FILE\" 2>&1 || true\n\necho \"\"\necho \"=== Results ===\"\n\n# Check if skill was triggered (look for Skill tool invocation)\n# Match either \"skill\":\"skillname\" or \"skill\":\"namespace:skillname\"\nSKILL_PATTERN='\"skill\":\"([^\"]*:)?'\"${SKILL_NAME}\"'\"'\nif grep -q '\"name\":\"Skill\"' \"$LOG_FILE\" && grep -qE \"$SKILL_PATTERN\" \"$LOG_FILE\"; then\n    echo \"PASS: Skill '$SKILL_NAME' was triggered\"\n    TRIGGERED=true\nelse\n    echo \"FAIL: Skill '$SKILL_NAME' was NOT triggered\"\n    TRIGGERED=false\nfi\n\n# Show what skills WERE triggered\necho \"\"\necho \"Skills triggered in this run:\"\ngrep -o '\"skill\":\"[^\"]*\"' \"$LOG_FILE\" 2>/dev/null | sort -u || echo \"  (none)\"\n\n# Check if Claude took action BEFORE invoking the skill (the failure mode)\necho \"\"\necho \"Checking for premature action...\"\n\n# Look for tool invocations before the Skill invocation\n# This detects the failure mode where Claude starts doing work without loading the skill\nFIRST_SKILL_LINE=$(grep -n '\"name\":\"Skill\"' \"$LOG_FILE\" | head -1 | cut -d: -f1)\nif [ -n \"$FIRST_SKILL_LINE\" ]; then\n    # Check if any non-Skill, non-system tools were invoked before the first Skill invocation\n    # Filter out system messages, TodoWrite (planning is ok), and other non-action tools\n    PREMATURE_TOOLS=$(head -n \"$FIRST_SKILL_LINE\" \"$LOG_FILE\" | \\\n        grep '\"type\":\"tool_use\"' | \\\n        grep -v '\"name\":\"Skill\"' | \\\n        grep -v '\"name\":\"TodoWrite\"' || true)\n    if [ -n \"$PREMATURE_TOOLS\" ]; then\n        echo \"WARNING: Tools invoked BEFORE Skill tool:\"\n        echo \"$PREMATURE_TOOLS\" | head -5\n        echo \"\"\n        echo \"This indicates Claude started working before loading the requested skill.\"\n    else\n        echo \"OK: No premature tool invocations detected\"\n    fi\nelse\n    echo \"WARNING: No Skill invocation found at all\"\nfi\n\n# Show first assistant message\necho \"\"\necho \"First assistant response (truncated):\"\ngrep '\"type\":\"assistant\"' \"$LOG_FILE\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo \"  (could not extract)\"\n\necho \"\"\necho \"Full log: $LOG_FILE\"\necho \"Timestamp: $TIMESTAMP\"\n\nif [ \"$TRIGGERED\" = \"true\" ]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/opencode/run-tests.sh",
    "content": "#!/usr/bin/env bash\n# Main test runner for OpenCode plugin test suite\n# Runs all tests and reports results\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\ncd \"$SCRIPT_DIR\"\n\necho \"========================================\"\necho \" OpenCode Plugin Test Suite\"\necho \"========================================\"\necho \"\"\necho \"Repository: $(cd ../.. && pwd)\"\necho \"Test time: $(date)\"\necho \"\"\n\n# Parse command line arguments\nRUN_INTEGRATION=false\nVERBOSE=false\nSPECIFIC_TEST=\"\"\n\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        --integration|-i)\n            RUN_INTEGRATION=true\n            shift\n            ;;\n        --verbose|-v)\n            VERBOSE=true\n            shift\n            ;;\n        --test|-t)\n            SPECIFIC_TEST=\"$2\"\n            shift 2\n            ;;\n        --help|-h)\n            echo \"Usage: $0 [options]\"\n            echo \"\"\n            echo \"Options:\"\n            echo \"  --integration, -i  Run integration tests (requires OpenCode)\"\n            echo \"  --verbose, -v      Show verbose output\"\n            echo \"  --test, -t NAME    Run only the specified test\"\n            echo \"  --help, -h         Show this help\"\n            echo \"\"\n            echo \"Tests:\"\n            echo \"  test-plugin-loading.sh  Verify plugin installation and structure\"\n            echo \"  test-tools.sh           Test use_skill and find_skills tools (integration)\"\n            echo \"  test-priority.sh        Test skill priority resolution (integration)\"\n            exit 0\n            ;;\n        *)\n            echo \"Unknown option: $1\"\n            echo \"Use --help for usage information\"\n            exit 1\n            ;;\n    esac\ndone\n\n# List of tests to run (no external dependencies)\ntests=(\n    \"test-plugin-loading.sh\"\n)\n\n# Integration tests (require OpenCode)\nintegration_tests=(\n    \"test-tools.sh\"\n    \"test-priority.sh\"\n)\n\n# Add integration tests if requested\nif [ \"$RUN_INTEGRATION\" = true ]; then\n    tests+=(\"${integration_tests[@]}\")\nfi\n\n# Filter to specific test if requested\nif [ -n \"$SPECIFIC_TEST\" ]; then\n    tests=(\"$SPECIFIC_TEST\")\nfi\n\n# Track results\npassed=0\nfailed=0\nskipped=0\n\n# Run each test\nfor test in \"${tests[@]}\"; do\n    echo \"----------------------------------------\"\n    echo \"Running: $test\"\n    echo \"----------------------------------------\"\n\n    test_path=\"$SCRIPT_DIR/$test\"\n\n    if [ ! -f \"$test_path\" ]; then\n        echo \"  [SKIP] Test file not found: $test\"\n        skipped=$((skipped + 1))\n        continue\n    fi\n\n    if [ ! -x \"$test_path\" ]; then\n        echo \"  Making $test executable...\"\n        chmod +x \"$test_path\"\n    fi\n\n    start_time=$(date +%s)\n\n    if [ \"$VERBOSE\" = true ]; then\n        if bash \"$test_path\"; then\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"\"\n            echo \"  [PASS] $test (${duration}s)\"\n            passed=$((passed + 1))\n        else\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"\"\n            echo \"  [FAIL] $test (${duration}s)\"\n            failed=$((failed + 1))\n        fi\n    else\n        # Capture output for non-verbose mode\n        if output=$(bash \"$test_path\" 2>&1); then\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"  [PASS] (${duration}s)\"\n            passed=$((passed + 1))\n        else\n            end_time=$(date +%s)\n            duration=$((end_time - start_time))\n            echo \"  [FAIL] (${duration}s)\"\n            echo \"\"\n            echo \"  Output:\"\n            echo \"$output\" | sed 's/^/    /'\n            failed=$((failed + 1))\n        fi\n    fi\n\n    echo \"\"\ndone\n\n# Print summary\necho \"========================================\"\necho \" Test Results Summary\"\necho \"========================================\"\necho \"\"\necho \"  Passed:  $passed\"\necho \"  Failed:  $failed\"\necho \"  Skipped: $skipped\"\necho \"\"\n\nif [ \"$RUN_INTEGRATION\" = false ] && [ ${#integration_tests[@]} -gt 0 ]; then\n    echo \"Note: Integration tests were not run.\"\n    echo \"Use --integration flag to run tests that require OpenCode.\"\n    echo \"\"\nfi\n\nif [ $failed -gt 0 ]; then\n    echo \"STATUS: FAILED\"\n    exit 1\nelse\n    echo \"STATUS: PASSED\"\n    exit 0\nfi\n"
  },
  {
    "path": "tests/opencode/setup.sh",
    "content": "#!/usr/bin/env bash\n# Setup script for OpenCode plugin tests\n# Creates an isolated test environment with proper plugin installation\nset -euo pipefail\n\n# Get the repository root (two levels up from tests/opencode/)\nREPO_ROOT=\"$(cd \"$(dirname \"$0\")/../..\" && pwd)\"\n\n# Create temp home directory for isolation\nexport TEST_HOME=$(mktemp -d)\nexport HOME=\"$TEST_HOME\"\nexport XDG_CONFIG_HOME=\"$TEST_HOME/.config\"\nexport OPENCODE_CONFIG_DIR=\"$TEST_HOME/.config/opencode\"\n\n# Install plugin to test location\nmkdir -p \"$HOME/.config/opencode/superpowers\"\ncp -r \"$REPO_ROOT/lib\" \"$HOME/.config/opencode/superpowers/\"\ncp -r \"$REPO_ROOT/skills\" \"$HOME/.config/opencode/superpowers/\"\n\n# Copy plugin directory\nmkdir -p \"$HOME/.config/opencode/superpowers/.opencode/plugins\"\ncp \"$REPO_ROOT/.opencode/plugins/superpowers.js\" \"$HOME/.config/opencode/superpowers/.opencode/plugins/\"\n\n# Register plugin via symlink\nmkdir -p \"$HOME/.config/opencode/plugins\"\nln -sf \"$HOME/.config/opencode/superpowers/.opencode/plugins/superpowers.js\" \\\n       \"$HOME/.config/opencode/plugins/superpowers.js\"\n\n# Create test skills in different locations for testing\n\n# Personal test skill\nmkdir -p \"$HOME/.config/opencode/skills/personal-test\"\ncat > \"$HOME/.config/opencode/skills/personal-test/SKILL.md\" <<'EOF'\n---\nname: personal-test\ndescription: Test personal skill for verification\n---\n# Personal Test Skill\n\nThis is a personal skill used for testing.\n\nPERSONAL_SKILL_MARKER_12345\nEOF\n\n# Create a project directory for project-level skill tests\nmkdir -p \"$TEST_HOME/test-project/.opencode/skills/project-test\"\ncat > \"$TEST_HOME/test-project/.opencode/skills/project-test/SKILL.md\" <<'EOF'\n---\nname: project-test\ndescription: Test project skill for verification\n---\n# Project Test Skill\n\nThis is a project skill used for testing.\n\nPROJECT_SKILL_MARKER_67890\nEOF\n\necho \"Setup complete: $TEST_HOME\"\necho \"Plugin installed to: $HOME/.config/opencode/superpowers/.opencode/plugins/superpowers.js\"\necho \"Plugin registered at: $HOME/.config/opencode/plugins/superpowers.js\"\necho \"Test project at: $TEST_HOME/test-project\"\n\n# Helper function for cleanup (call from tests or trap)\ncleanup_test_env() {\n    if [ -n \"${TEST_HOME:-}\" ] && [ -d \"$TEST_HOME\" ]; then\n        rm -rf \"$TEST_HOME\"\n    fi\n}\n\n# Export for use in tests\nexport -f cleanup_test_env\nexport REPO_ROOT\n"
  },
  {
    "path": "tests/opencode/test-plugin-loading.sh",
    "content": "#!/usr/bin/env bash\n# Test: Plugin Loading\n# Verifies that the superpowers plugin loads correctly in OpenCode\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\necho \"=== Test: Plugin Loading ===\"\n\n# Source setup to create isolated environment\nsource \"$SCRIPT_DIR/setup.sh\"\n\n# Trap to cleanup on exit\ntrap cleanup_test_env EXIT\n\n# Test 1: Verify plugin file exists and is registered\necho \"Test 1: Checking plugin registration...\"\nif [ -L \"$HOME/.config/opencode/plugins/superpowers.js\" ]; then\n    echo \"  [PASS] Plugin symlink exists\"\nelse\n    echo \"  [FAIL] Plugin symlink not found at $HOME/.config/opencode/plugins/superpowers.js\"\n    exit 1\nfi\n\n# Verify symlink target exists\nif [ -f \"$(readlink -f \"$HOME/.config/opencode/plugins/superpowers.js\")\" ]; then\n    echo \"  [PASS] Plugin symlink target exists\"\nelse\n    echo \"  [FAIL] Plugin symlink target does not exist\"\n    exit 1\nfi\n\n# Test 2: Verify skills directory is populated\necho \"Test 2: Checking skills directory...\"\nskill_count=$(find \"$HOME/.config/opencode/superpowers/skills\" -name \"SKILL.md\" | wc -l)\nif [ \"$skill_count\" -gt 0 ]; then\n    echo \"  [PASS] Found $skill_count skills installed\"\nelse\n    echo \"  [FAIL] No skills found in installed location\"\n    exit 1\nfi\n\n# Test 4: Check using-superpowers skill exists (critical for bootstrap)\necho \"Test 4: Checking using-superpowers skill (required for bootstrap)...\"\nif [ -f \"$HOME/.config/opencode/superpowers/skills/using-superpowers/SKILL.md\" ]; then\n    echo \"  [PASS] using-superpowers skill exists\"\nelse\n    echo \"  [FAIL] using-superpowers skill not found (required for bootstrap)\"\n    exit 1\nfi\n\n# Test 5: Verify plugin JavaScript syntax (basic check)\necho \"Test 5: Checking plugin JavaScript syntax...\"\nplugin_file=\"$HOME/.config/opencode/superpowers/.opencode/plugins/superpowers.js\"\nif node --check \"$plugin_file\" 2>/dev/null; then\n    echo \"  [PASS] Plugin JavaScript syntax is valid\"\nelse\n    echo \"  [FAIL] Plugin has JavaScript syntax errors\"\n    exit 1\nfi\n\n# Test 6: Verify personal test skill was created\necho \"Test 6: Checking test fixtures...\"\nif [ -f \"$HOME/.config/opencode/skills/personal-test/SKILL.md\" ]; then\n    echo \"  [PASS] Personal test skill fixture created\"\nelse\n    echo \"  [FAIL] Personal test skill fixture not found\"\n    exit 1\nfi\n\necho \"\"\necho \"=== All plugin loading tests passed ===\"\n"
  },
  {
    "path": "tests/opencode/test-priority.sh",
    "content": "#!/usr/bin/env bash\n# Test: Skill Priority Resolution\n# Verifies that skills are resolved with correct priority: project > personal > superpowers\n# NOTE: These tests require OpenCode to be installed and configured\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\necho \"=== Test: Skill Priority Resolution ===\"\n\n# Source setup to create isolated environment\nsource \"$SCRIPT_DIR/setup.sh\"\n\n# Trap to cleanup on exit\ntrap cleanup_test_env EXIT\n\n# Create same skill \"priority-test\" in all three locations with different markers\necho \"Setting up priority test fixtures...\"\n\n# 1. Create in superpowers location (lowest priority)\nmkdir -p \"$HOME/.config/opencode/superpowers/skills/priority-test\"\ncat > \"$HOME/.config/opencode/superpowers/skills/priority-test/SKILL.md\" <<'EOF'\n---\nname: priority-test\ndescription: Superpowers version of priority test skill\n---\n# Priority Test Skill (Superpowers Version)\n\nThis is the SUPERPOWERS version of the priority test skill.\n\nPRIORITY_MARKER_SUPERPOWERS_VERSION\nEOF\n\n# 2. Create in personal location (medium priority)\nmkdir -p \"$HOME/.config/opencode/skills/priority-test\"\ncat > \"$HOME/.config/opencode/skills/priority-test/SKILL.md\" <<'EOF'\n---\nname: priority-test\ndescription: Personal version of priority test skill\n---\n# Priority Test Skill (Personal Version)\n\nThis is the PERSONAL version of the priority test skill.\n\nPRIORITY_MARKER_PERSONAL_VERSION\nEOF\n\n# 3. Create in project location (highest priority)\nmkdir -p \"$TEST_HOME/test-project/.opencode/skills/priority-test\"\ncat > \"$TEST_HOME/test-project/.opencode/skills/priority-test/SKILL.md\" <<'EOF'\n---\nname: priority-test\ndescription: Project version of priority test skill\n---\n# Priority Test Skill (Project Version)\n\nThis is the PROJECT version of the priority test skill.\n\nPRIORITY_MARKER_PROJECT_VERSION\nEOF\n\necho \"  Created priority-test skill in all three locations\"\n\n# Test 1: Verify fixture setup\necho \"\"\necho \"Test 1: Verifying test fixtures...\"\n\nif [ -f \"$HOME/.config/opencode/superpowers/skills/priority-test/SKILL.md\" ]; then\n    echo \"  [PASS] Superpowers version exists\"\nelse\n    echo \"  [FAIL] Superpowers version missing\"\n    exit 1\nfi\n\nif [ -f \"$HOME/.config/opencode/skills/priority-test/SKILL.md\" ]; then\n    echo \"  [PASS] Personal version exists\"\nelse\n    echo \"  [FAIL] Personal version missing\"\n    exit 1\nfi\n\nif [ -f \"$TEST_HOME/test-project/.opencode/skills/priority-test/SKILL.md\" ]; then\n    echo \"  [PASS] Project version exists\"\nelse\n    echo \"  [FAIL] Project version missing\"\n    exit 1\nfi\n\n# Check if opencode is available for integration tests\nif ! command -v opencode &> /dev/null; then\n    echo \"\"\n    echo \"  [SKIP] OpenCode not installed - skipping integration tests\"\n    echo \"  To run these tests, install OpenCode: https://opencode.ai\"\n    echo \"\"\n    echo \"=== Priority fixture tests passed (integration tests skipped) ===\"\n    exit 0\nfi\n\n# Test 2: Test that personal overrides superpowers\necho \"\"\necho \"Test 2: Testing personal > superpowers priority...\"\necho \"  Running from outside project directory...\"\n\n# Run from HOME (not in project) - should get personal version\ncd \"$HOME\"\noutput=$(timeout 60s opencode run --print-logs \"Use the use_skill tool to load the priority-test skill. Show me the exact content including any PRIORITY_MARKER text.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n}\n\nif echo \"$output\" | grep -qi \"PRIORITY_MARKER_PERSONAL_VERSION\"; then\n    echo \"  [PASS] Personal version loaded (overrides superpowers)\"\nelif echo \"$output\" | grep -qi \"PRIORITY_MARKER_SUPERPOWERS_VERSION\"; then\n    echo \"  [FAIL] Superpowers version loaded instead of personal\"\n    exit 1\nelse\n    echo \"  [WARN] Could not verify priority marker in output\"\n    echo \"  Output snippet:\"\n    echo \"$output\" | grep -i \"priority\\|personal\\|superpowers\" | head -10\nfi\n\n# Test 3: Test that project overrides both personal and superpowers\necho \"\"\necho \"Test 3: Testing project > personal > superpowers priority...\"\necho \"  Running from project directory...\"\n\n# Run from project directory - should get project version\ncd \"$TEST_HOME/test-project\"\noutput=$(timeout 60s opencode run --print-logs \"Use the use_skill tool to load the priority-test skill. Show me the exact content including any PRIORITY_MARKER text.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n}\n\nif echo \"$output\" | grep -qi \"PRIORITY_MARKER_PROJECT_VERSION\"; then\n    echo \"  [PASS] Project version loaded (highest priority)\"\nelif echo \"$output\" | grep -qi \"PRIORITY_MARKER_PERSONAL_VERSION\"; then\n    echo \"  [FAIL] Personal version loaded instead of project\"\n    exit 1\nelif echo \"$output\" | grep -qi \"PRIORITY_MARKER_SUPERPOWERS_VERSION\"; then\n    echo \"  [FAIL] Superpowers version loaded instead of project\"\n    exit 1\nelse\n    echo \"  [WARN] Could not verify priority marker in output\"\n    echo \"  Output snippet:\"\n    echo \"$output\" | grep -i \"priority\\|project\\|personal\" | head -10\nfi\n\n# Test 4: Test explicit superpowers: prefix bypasses priority\necho \"\"\necho \"Test 4: Testing superpowers: prefix forces superpowers version...\"\n\ncd \"$TEST_HOME/test-project\"\noutput=$(timeout 60s opencode run --print-logs \"Use the use_skill tool to load superpowers:priority-test specifically. Show me the exact content including any PRIORITY_MARKER text.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n}\n\nif echo \"$output\" | grep -qi \"PRIORITY_MARKER_SUPERPOWERS_VERSION\"; then\n    echo \"  [PASS] superpowers: prefix correctly forces superpowers version\"\nelif echo \"$output\" | grep -qi \"PRIORITY_MARKER_PROJECT_VERSION\\|PRIORITY_MARKER_PERSONAL_VERSION\"; then\n    echo \"  [FAIL] superpowers: prefix did not force superpowers version\"\n    exit 1\nelse\n    echo \"  [WARN] Could not verify priority marker in output\"\nfi\n\n# Test 5: Test explicit project: prefix\necho \"\"\necho \"Test 5: Testing project: prefix forces project version...\"\n\ncd \"$HOME\"  # Run from outside project but with project: prefix\noutput=$(timeout 60s opencode run --print-logs \"Use the use_skill tool to load project:priority-test specifically. Show me the exact content.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n}\n\n# Note: This may fail since we're not in the project directory\n# The project: prefix only works when in a project context\nif echo \"$output\" | grep -qi \"not found\\|error\"; then\n    echo \"  [PASS] project: prefix correctly fails when not in project context\"\nelse\n    echo \"  [INFO] project: prefix behavior outside project context may vary\"\nfi\n\necho \"\"\necho \"=== All priority tests passed ===\"\n"
  },
  {
    "path": "tests/opencode/test-tools.sh",
    "content": "#!/usr/bin/env bash\n# Test: Tools Functionality\n# Verifies that use_skill and find_skills tools work correctly\n# NOTE: These tests require OpenCode to be installed and configured\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\necho \"=== Test: Tools Functionality ===\"\n\n# Source setup to create isolated environment\nsource \"$SCRIPT_DIR/setup.sh\"\n\n# Trap to cleanup on exit\ntrap cleanup_test_env EXIT\n\n# Check if opencode is available\nif ! command -v opencode &> /dev/null; then\n    echo \"  [SKIP] OpenCode not installed - skipping integration tests\"\n    echo \"  To run these tests, install OpenCode: https://opencode.ai\"\n    exit 0\nfi\n\n# Test 1: Test find_skills tool via direct invocation\necho \"Test 1: Testing find_skills tool...\"\necho \"  Running opencode with find_skills request...\"\n\n# Use timeout to prevent hanging, capture both stdout and stderr\noutput=$(timeout 60s opencode run --print-logs \"Use the find_skills tool to list available skills. Just call the tool and show me the raw output.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n    echo \"  [WARN] OpenCode returned non-zero exit code: $exit_code\"\n}\n\n# Check for expected patterns in output\nif echo \"$output\" | grep -qi \"superpowers:brainstorming\\|superpowers:using-superpowers\\|Available skills\"; then\n    echo \"  [PASS] find_skills tool discovered superpowers skills\"\nelse\n    echo \"  [FAIL] find_skills did not return expected skills\"\n    echo \"  Output was:\"\n    echo \"$output\" | head -50\n    exit 1\nfi\n\n# Check if personal test skill was found\nif echo \"$output\" | grep -qi \"personal-test\"; then\n    echo \"  [PASS] find_skills found personal test skill\"\nelse\n    echo \"  [WARN] personal test skill not found in output (may be ok if tool returned subset)\"\nfi\n\n# Test 2: Test use_skill tool\necho \"\"\necho \"Test 2: Testing use_skill tool...\"\necho \"  Running opencode with use_skill request...\"\n\noutput=$(timeout 60s opencode run --print-logs \"Use the use_skill tool to load the personal-test skill and show me what you get.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n    echo \"  [WARN] OpenCode returned non-zero exit code: $exit_code\"\n}\n\n# Check for the skill marker we embedded\nif echo \"$output\" | grep -qi \"PERSONAL_SKILL_MARKER_12345\\|Personal Test Skill\\|Launching skill\"; then\n    echo \"  [PASS] use_skill loaded personal-test skill content\"\nelse\n    echo \"  [FAIL] use_skill did not load personal-test skill correctly\"\n    echo \"  Output was:\"\n    echo \"$output\" | head -50\n    exit 1\nfi\n\n# Test 3: Test use_skill with superpowers: prefix\necho \"\"\necho \"Test 3: Testing use_skill with superpowers: prefix...\"\necho \"  Running opencode with superpowers:brainstorming skill...\"\n\noutput=$(timeout 60s opencode run --print-logs \"Use the use_skill tool to load superpowers:brainstorming and tell me the first few lines of what you received.\" 2>&1) || {\n    exit_code=$?\n    if [ $exit_code -eq 124 ]; then\n        echo \"  [FAIL] OpenCode timed out after 60s\"\n        exit 1\n    fi\n    echo \"  [WARN] OpenCode returned non-zero exit code: $exit_code\"\n}\n\n# Check for expected content from brainstorming skill\nif echo \"$output\" | grep -qi \"brainstorming\\|Launching skill\\|skill.*loaded\"; then\n    echo \"  [PASS] use_skill loaded superpowers:brainstorming skill\"\nelse\n    echo \"  [FAIL] use_skill did not load superpowers:brainstorming correctly\"\n    echo \"  Output was:\"\n    echo \"$output\" | head -50\n    exit 1\nfi\n\necho \"\"\necho \"=== All tools tests passed ===\"\n"
  },
  {
    "path": "tests/skill-triggering/prompts/dispatching-parallel-agents.txt",
    "content": "I have 4 independent test failures happening in different modules:\n\n1. tests/auth/login.test.ts - \"should redirect after login\" is failing\n2. tests/api/users.test.ts - \"should return user list\" returns 500\n3. tests/components/Button.test.tsx - snapshot mismatch\n4. tests/utils/date.test.ts - timezone handling broken\n\nThese are unrelated issues in different parts of the codebase. Can you investigate all of them?"
  },
  {
    "path": "tests/skill-triggering/prompts/executing-plans.txt",
    "content": "I have a plan document at docs/superpowers/plans/2024-01-15-auth-system.md that needs to be executed. Please implement it."
  },
  {
    "path": "tests/skill-triggering/prompts/requesting-code-review.txt",
    "content": "I just finished implementing the user authentication feature. All the code is committed. Can you review the changes before I merge to main?\n\nThe commits are between abc123 and def456."
  },
  {
    "path": "tests/skill-triggering/prompts/systematic-debugging.txt",
    "content": "The tests are failing with this error:\n\n```\nFAIL src/utils/parser.test.ts\n  ● Parser › should handle nested objects\n    TypeError: Cannot read property 'value' of undefined\n      at parse (src/utils/parser.ts:42:18)\n      at Object.<anonymous> (src/utils/parser.test.ts:28:20)\n```\n\nCan you figure out what's going wrong and fix it?"
  },
  {
    "path": "tests/skill-triggering/prompts/test-driven-development.txt",
    "content": "I need to add a new feature to validate email addresses. It should:\n- Check that there's an @ symbol\n- Check that there's at least one character before the @\n- Check that there's a dot in the domain part\n- Return true/false\n\nCan you implement this?"
  },
  {
    "path": "tests/skill-triggering/prompts/writing-plans.txt",
    "content": "Here's the spec for our new authentication system:\n\nRequirements:\n- Users can register with email/password\n- Users can log in and receive a JWT token\n- Protected routes require valid JWT\n- Tokens expire after 24 hours\n- Support password reset via email\n\nWe need to implement this. There are multiple steps involved - user model, auth routes, middleware, email service integration."
  },
  {
    "path": "tests/skill-triggering/run-all.sh",
    "content": "#!/usr/bin/env bash\n# Run all skill triggering tests\n# Usage: ./run-all.sh\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPROMPTS_DIR=\"$SCRIPT_DIR/prompts\"\n\nSKILLS=(\n    \"systematic-debugging\"\n    \"test-driven-development\"\n    \"writing-plans\"\n    \"dispatching-parallel-agents\"\n    \"executing-plans\"\n    \"requesting-code-review\"\n)\n\necho \"=== Running Skill Triggering Tests ===\"\necho \"\"\n\nPASSED=0\nFAILED=0\nRESULTS=()\n\nfor skill in \"${SKILLS[@]}\"; do\n    prompt_file=\"$PROMPTS_DIR/${skill}.txt\"\n\n    if [ ! -f \"$prompt_file\" ]; then\n        echo \"⚠️  SKIP: No prompt file for $skill\"\n        continue\n    fi\n\n    echo \"Testing: $skill\"\n\n    if \"$SCRIPT_DIR/run-test.sh\" \"$skill\" \"$prompt_file\" 3 2>&1 | tee /tmp/skill-test-$skill.log; then\n        PASSED=$((PASSED + 1))\n        RESULTS+=(\"✅ $skill\")\n    else\n        FAILED=$((FAILED + 1))\n        RESULTS+=(\"❌ $skill\")\n    fi\n\n    echo \"\"\n    echo \"---\"\n    echo \"\"\ndone\n\necho \"\"\necho \"=== Summary ===\"\nfor result in \"${RESULTS[@]}\"; do\n    echo \"  $result\"\ndone\necho \"\"\necho \"Passed: $PASSED\"\necho \"Failed: $FAILED\"\n\nif [ $FAILED -gt 0 ]; then\n    exit 1\nfi\n"
  },
  {
    "path": "tests/skill-triggering/run-test.sh",
    "content": "#!/usr/bin/env bash\n# Test skill triggering with naive prompts\n# Usage: ./run-test.sh <skill-name> <prompt-file>\n#\n# Tests whether Claude triggers a skill based on a natural prompt\n# (without explicitly mentioning the skill)\n\nset -e\n\nSKILL_NAME=\"$1\"\nPROMPT_FILE=\"$2\"\nMAX_TURNS=\"${3:-3}\"\n\nif [ -z \"$SKILL_NAME\" ] || [ -z \"$PROMPT_FILE\" ]; then\n    echo \"Usage: $0 <skill-name> <prompt-file> [max-turns]\"\n    echo \"Example: $0 systematic-debugging ./test-prompts/debugging.txt\"\n    exit 1\nfi\n\n# Get the directory where this script lives (should be tests/skill-triggering)\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n# Get the superpowers plugin root (two levels up from tests/skill-triggering)\nPLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\n\nTIMESTAMP=$(date +%s)\nOUTPUT_DIR=\"/tmp/superpowers-tests/${TIMESTAMP}/skill-triggering/${SKILL_NAME}\"\nmkdir -p \"$OUTPUT_DIR\"\n\n# Read prompt from file\nPROMPT=$(cat \"$PROMPT_FILE\")\n\necho \"=== Skill Triggering Test ===\"\necho \"Skill: $SKILL_NAME\"\necho \"Prompt file: $PROMPT_FILE\"\necho \"Max turns: $MAX_TURNS\"\necho \"Output dir: $OUTPUT_DIR\"\necho \"\"\n\n# Copy prompt for reference\ncp \"$PROMPT_FILE\" \"$OUTPUT_DIR/prompt.txt\"\n\n# Run Claude\nLOG_FILE=\"$OUTPUT_DIR/claude-output.json\"\ncd \"$OUTPUT_DIR\"\n\necho \"Plugin dir: $PLUGIN_DIR\"\necho \"Running claude -p with naive prompt...\"\ntimeout 300 claude -p \"$PROMPT\" \\\n    --plugin-dir \"$PLUGIN_DIR\" \\\n    --dangerously-skip-permissions \\\n    --max-turns \"$MAX_TURNS\" \\\n    --output-format stream-json \\\n    > \"$LOG_FILE\" 2>&1 || true\n\necho \"\"\necho \"=== Results ===\"\n\n# Check if skill was triggered (look for Skill tool invocation)\n# In stream-json, tool invocations have \"name\":\"Skill\" (not \"tool\":\"Skill\")\n# Match either \"skill\":\"skillname\" or \"skill\":\"namespace:skillname\"\nSKILL_PATTERN='\"skill\":\"([^\"]*:)?'\"${SKILL_NAME}\"'\"'\nif grep -q '\"name\":\"Skill\"' \"$LOG_FILE\" && grep -qE \"$SKILL_PATTERN\" \"$LOG_FILE\"; then\n    echo \"✅ PASS: Skill '$SKILL_NAME' was triggered\"\n    TRIGGERED=true\nelse\n    echo \"❌ FAIL: Skill '$SKILL_NAME' was NOT triggered\"\n    TRIGGERED=false\nfi\n\n# Show what skills WERE triggered\necho \"\"\necho \"Skills triggered in this run:\"\ngrep -o '\"skill\":\"[^\"]*\"' \"$LOG_FILE\" 2>/dev/null | sort -u || echo \"  (none)\"\n\n# Show first assistant message\necho \"\"\necho \"First assistant response (truncated):\"\ngrep '\"type\":\"assistant\"' \"$LOG_FILE\" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo \"  (could not extract)\"\n\necho \"\"\necho \"Full log: $LOG_FILE\"\necho \"Timestamp: $TIMESTAMP\"\n\nif [ \"$TRIGGERED\" = \"true\" ]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/subagent-driven-dev/go-fractals/design.md",
    "content": "# Go Fractals CLI - Design\n\n## Overview\n\nA command-line tool that generates ASCII art fractals. Supports two fractal types with configurable output.\n\n## Usage\n\n```bash\n# Sierpinski triangle\nfractals sierpinski --size 32 --depth 5\n\n# Mandelbrot set\nfractals mandelbrot --width 80 --height 24 --iterations 100\n\n# Custom character\nfractals sierpinski --size 16 --char '#'\n\n# Help\nfractals --help\nfractals sierpinski --help\n```\n\n## Commands\n\n### `sierpinski`\n\nGenerates a Sierpinski triangle using recursive subdivision.\n\nFlags:\n- `--size` (default: 32) - Width of the triangle base in characters\n- `--depth` (default: 5) - Recursion depth\n- `--char` (default: '*') - Character to use for filled points\n\nOutput: Triangle printed to stdout, one line per row.\n\n### `mandelbrot`\n\nRenders the Mandelbrot set as ASCII art. Maps iteration count to characters.\n\nFlags:\n- `--width` (default: 80) - Output width in characters\n- `--height` (default: 24) - Output height in characters\n- `--iterations` (default: 100) - Maximum iterations for escape calculation\n- `--char` (default: gradient) - Single character, or omit for gradient \" .:-=+*#%@\"\n\nOutput: Rectangle printed to stdout.\n\n## Architecture\n\n```\ncmd/\n  fractals/\n    main.go           # Entry point, CLI setup\ninternal/\n  sierpinski/\n    sierpinski.go     # Algorithm\n    sierpinski_test.go\n  mandelbrot/\n    mandelbrot.go     # Algorithm\n    mandelbrot_test.go\n  cli/\n    root.go           # Root command, help\n    sierpinski.go     # Sierpinski subcommand\n    mandelbrot.go     # Mandelbrot subcommand\n```\n\n## Dependencies\n\n- Go 1.21+\n- `github.com/spf13/cobra` for CLI\n\n## Acceptance Criteria\n\n1. `fractals --help` shows usage\n2. `fractals sierpinski` outputs a recognizable triangle\n3. `fractals mandelbrot` outputs a recognizable Mandelbrot set\n4. `--size`, `--width`, `--height`, `--depth`, `--iterations` flags work\n5. `--char` customizes output character\n6. Invalid inputs produce clear error messages\n7. All tests pass\n"
  },
  {
    "path": "tests/subagent-driven-dev/go-fractals/plan.md",
    "content": "# Go Fractals CLI - Implementation Plan\n\nExecute this plan using the `superpowers:subagent-driven-development` skill.\n\n## Context\n\nBuilding a CLI tool that generates ASCII fractals. See `design.md` for full specification.\n\n## Tasks\n\n### Task 1: Project Setup\n\nCreate the Go module and directory structure.\n\n**Do:**\n- Initialize `go.mod` with module name `github.com/superpowers-test/fractals`\n- Create directory structure: `cmd/fractals/`, `internal/sierpinski/`, `internal/mandelbrot/`, `internal/cli/`\n- Create minimal `cmd/fractals/main.go` that prints \"fractals cli\"\n- Add `github.com/spf13/cobra` dependency\n\n**Verify:**\n- `go build ./cmd/fractals` succeeds\n- `./fractals` prints \"fractals cli\"\n\n---\n\n### Task 2: CLI Framework with Help\n\nSet up Cobra root command with help output.\n\n**Do:**\n- Create `internal/cli/root.go` with root command\n- Configure help text showing available subcommands\n- Wire root command into `main.go`\n\n**Verify:**\n- `./fractals --help` shows usage with \"sierpinski\" and \"mandelbrot\" listed as available commands\n- `./fractals` (no args) shows help\n\n---\n\n### Task 3: Sierpinski Algorithm\n\nImplement the Sierpinski triangle generation algorithm.\n\n**Do:**\n- Create `internal/sierpinski/sierpinski.go`\n- Implement `Generate(size, depth int, char rune) []string` that returns lines of the triangle\n- Use recursive midpoint subdivision algorithm\n- Create `internal/sierpinski/sierpinski_test.go` with tests:\n  - Small triangle (size=4, depth=2) matches expected output\n  - Size=1 returns single character\n  - Depth=0 returns filled triangle\n\n**Verify:**\n- `go test ./internal/sierpinski/...` passes\n\n---\n\n### Task 4: Sierpinski CLI Integration\n\nWire the Sierpinski algorithm to a CLI subcommand.\n\n**Do:**\n- Create `internal/cli/sierpinski.go` with `sierpinski` subcommand\n- Add flags: `--size` (default 32), `--depth` (default 5), `--char` (default '*')\n- Call `sierpinski.Generate()` and print result to stdout\n\n**Verify:**\n- `./fractals sierpinski` outputs a triangle\n- `./fractals sierpinski --size 16 --depth 3` outputs smaller triangle\n- `./fractals sierpinski --help` shows flag documentation\n\n---\n\n### Task 5: Mandelbrot Algorithm\n\nImplement the Mandelbrot set ASCII renderer.\n\n**Do:**\n- Create `internal/mandelbrot/mandelbrot.go`\n- Implement `Render(width, height, maxIter int, char string) []string`\n- Map complex plane region (-2.5 to 1.0 real, -1.0 to 1.0 imaginary) to output dimensions\n- Map iteration count to character gradient \" .:-=+*#%@\" (or single char if provided)\n- Create `internal/mandelbrot/mandelbrot_test.go` with tests:\n  - Output dimensions match requested width/height\n  - Known point inside set (0,0) maps to max-iteration character\n  - Known point outside set (2,0) maps to low-iteration character\n\n**Verify:**\n- `go test ./internal/mandelbrot/...` passes\n\n---\n\n### Task 6: Mandelbrot CLI Integration\n\nWire the Mandelbrot algorithm to a CLI subcommand.\n\n**Do:**\n- Create `internal/cli/mandelbrot.go` with `mandelbrot` subcommand\n- Add flags: `--width` (default 80), `--height` (default 24), `--iterations` (default 100), `--char` (default \"\")\n- Call `mandelbrot.Render()` and print result to stdout\n\n**Verify:**\n- `./fractals mandelbrot` outputs recognizable Mandelbrot set\n- `./fractals mandelbrot --width 40 --height 12` outputs smaller version\n- `./fractals mandelbrot --help` shows flag documentation\n\n---\n\n### Task 7: Character Set Configuration\n\nEnsure `--char` flag works consistently across both commands.\n\n**Do:**\n- Verify Sierpinski `--char` flag passes character to algorithm\n- For Mandelbrot, `--char` should use single character instead of gradient\n- Add tests for custom character output\n\n**Verify:**\n- `./fractals sierpinski --char '#'` uses '#' character\n- `./fractals mandelbrot --char '.'` uses '.' for all filled points\n- Tests pass\n\n---\n\n### Task 8: Input Validation and Error Handling\n\nAdd validation for invalid inputs.\n\n**Do:**\n- Sierpinski: size must be > 0, depth must be >= 0\n- Mandelbrot: width/height must be > 0, iterations must be > 0\n- Return clear error messages for invalid inputs\n- Add tests for error cases\n\n**Verify:**\n- `./fractals sierpinski --size 0` prints error, exits non-zero\n- `./fractals mandelbrot --width -1` prints error, exits non-zero\n- Error messages are clear and helpful\n\n---\n\n### Task 9: Integration Tests\n\nAdd integration tests that invoke the CLI.\n\n**Do:**\n- Create `cmd/fractals/main_test.go` or `test/integration_test.go`\n- Test full CLI invocation for both commands\n- Verify output format and exit codes\n- Test error cases return non-zero exit\n\n**Verify:**\n- `go test ./...` passes all tests including integration tests\n\n---\n\n### Task 10: README\n\nDocument usage and examples.\n\n**Do:**\n- Create `README.md` with:\n  - Project description\n  - Installation: `go install ./cmd/fractals`\n  - Usage examples for both commands\n  - Example output (small samples)\n\n**Verify:**\n- README accurately describes the tool\n- Examples in README actually work\n"
  },
  {
    "path": "tests/subagent-driven-dev/go-fractals/scaffold.sh",
    "content": "#!/usr/bin/env bash\n# Scaffold the Go Fractals test project\n# Usage: ./scaffold.sh /path/to/target/directory\n\nset -e\n\nTARGET_DIR=\"${1:?Usage: $0 <target-directory>}\"\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\n# Create target directory\nmkdir -p \"$TARGET_DIR\"\ncd \"$TARGET_DIR\"\n\n# Initialize git repo\ngit init\n\n# Copy design and plan\ncp \"$SCRIPT_DIR/design.md\" .\ncp \"$SCRIPT_DIR/plan.md\" .\n\n# Create .claude settings to allow reads/writes in this directory\nmkdir -p .claude\ncat > .claude/settings.local.json << 'SETTINGS'\n{\n  \"permissions\": {\n    \"allow\": [\n      \"Read(**)\",\n      \"Edit(**)\",\n      \"Write(**)\",\n      \"Bash(go:*)\",\n      \"Bash(mkdir:*)\",\n      \"Bash(git:*)\"\n    ]\n  }\n}\nSETTINGS\n\n# Create initial commit\ngit add .\ngit commit -m \"Initial project setup with design and plan\"\n\necho \"Scaffolded Go Fractals project at: $TARGET_DIR\"\necho \"\"\necho \"To run the test:\"\necho \"  claude -p \\\"Execute this plan using superpowers:subagent-driven-development. Plan: $TARGET_DIR/plan.md\\\" --plugin-dir /path/to/superpowers\"\n"
  },
  {
    "path": "tests/subagent-driven-dev/run-test.sh",
    "content": "#!/usr/bin/env bash\n# Run a subagent-driven-development test\n# Usage: ./run-test.sh <test-name> [--plugin-dir <path>]\n#\n# Example:\n#   ./run-test.sh go-fractals\n#   ./run-test.sh svelte-todo --plugin-dir /path/to/superpowers\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nTEST_NAME=\"${1:?Usage: $0 <test-name> [--plugin-dir <path>]}\"\nshift\n\n# Parse optional arguments\nPLUGIN_DIR=\"\"\nwhile [[ $# -gt 0 ]]; do\n  case $1 in\n    --plugin-dir)\n      PLUGIN_DIR=\"$2\"\n      shift 2\n      ;;\n    *)\n      echo \"Unknown option: $1\"\n      exit 1\n      ;;\n  esac\ndone\n\n# Default plugin dir to parent of tests directory\nif [[ -z \"$PLUGIN_DIR\" ]]; then\n  PLUGIN_DIR=\"$(cd \"$SCRIPT_DIR/../..\" && pwd)\"\nfi\n\n# Verify test exists\nTEST_DIR=\"$SCRIPT_DIR/$TEST_NAME\"\nif [[ ! -d \"$TEST_DIR\" ]]; then\n  echo \"Error: Test '$TEST_NAME' not found at $TEST_DIR\"\n  echo \"Available tests:\"\n  ls -1 \"$SCRIPT_DIR\" | grep -v '\\.sh$' | grep -v '\\.md$'\n  exit 1\nfi\n\n# Create timestamped output directory\nTIMESTAMP=$(date +%s)\nOUTPUT_BASE=\"/tmp/superpowers-tests/$TIMESTAMP/subagent-driven-development\"\nOUTPUT_DIR=\"$OUTPUT_BASE/$TEST_NAME\"\nmkdir -p \"$OUTPUT_DIR\"\n\necho \"=== Subagent-Driven Development Test ===\"\necho \"Test: $TEST_NAME\"\necho \"Output: $OUTPUT_DIR\"\necho \"Plugin: $PLUGIN_DIR\"\necho \"\"\n\n# Scaffold the project\necho \">>> Scaffolding project...\"\n\"$TEST_DIR/scaffold.sh\" \"$OUTPUT_DIR/project\"\necho \"\"\n\n# Prepare the prompt\nPLAN_PATH=\"$OUTPUT_DIR/project/plan.md\"\nPROMPT=\"Execute this plan using superpowers:subagent-driven-development. The plan is at: $PLAN_PATH\"\n\n# Run Claude with JSON output for token tracking\nLOG_FILE=\"$OUTPUT_DIR/claude-output.json\"\necho \">>> Running Claude...\"\necho \"Prompt: $PROMPT\"\necho \"Log file: $LOG_FILE\"\necho \"\"\n\n# Run claude and capture output\n# Using stream-json to get token usage stats\n# --dangerously-skip-permissions for automated testing (subagents don't inherit parent settings)\ncd \"$OUTPUT_DIR/project\"\nclaude -p \"$PROMPT\" \\\n  --plugin-dir \"$PLUGIN_DIR\" \\\n  --dangerously-skip-permissions \\\n  --output-format stream-json \\\n  --verbose \\\n  > \"$LOG_FILE\" 2>&1 || true\n\n# Extract final stats\necho \"\"\necho \">>> Test complete\"\necho \"Project directory: $OUTPUT_DIR/project\"\necho \"Claude log: $LOG_FILE\"\necho \"\"\n\n# Show token usage if available\nif command -v jq &> /dev/null; then\n  echo \">>> Token usage:\"\n  # Extract usage from the last message with usage info\n  jq -s '[.[] | select(.type == \"result\")] | last | .usage' \"$LOG_FILE\" 2>/dev/null || echo \"(could not parse usage)\"\n  echo \"\"\nfi\n\necho \">>> Next steps:\"\necho \"1. Review the project: cd $OUTPUT_DIR/project\"\necho \"2. Review Claude's log: less $LOG_FILE\"\necho \"3. Check if tests pass:\"\nif [[ \"$TEST_NAME\" == \"go-fractals\" ]]; then\n  echo \"   cd $OUTPUT_DIR/project && go test ./...\"\nelif [[ \"$TEST_NAME\" == \"svelte-todo\" ]]; then\n  echo \"   cd $OUTPUT_DIR/project && npm test && npx playwright test\"\nfi\n"
  },
  {
    "path": "tests/subagent-driven-dev/svelte-todo/design.md",
    "content": "# Svelte Todo List - Design\n\n## Overview\n\nA simple todo list application built with Svelte. Supports creating, completing, and deleting todos with localStorage persistence.\n\n## Features\n\n- Add new todos\n- Mark todos as complete/incomplete\n- Delete todos\n- Filter by: All / Active / Completed\n- Clear all completed todos\n- Persist to localStorage\n- Show count of remaining items\n\n## User Interface\n\n```\n┌─────────────────────────────────────────┐\n│  Svelte Todos                           │\n├─────────────────────────────────────────┤\n│  [________________________] [Add]       │\n├─────────────────────────────────────────┤\n│  [ ] Buy groceries                  [x] │\n│  [✓] Walk the dog                   [x] │\n│  [ ] Write code                     [x] │\n├─────────────────────────────────────────┤\n│  2 items left                           │\n│  [All] [Active] [Completed]  [Clear ✓]  │\n└─────────────────────────────────────────┘\n```\n\n## Components\n\n```\nsrc/\n  App.svelte           # Main app, state management\n  lib/\n    TodoInput.svelte   # Text input + Add button\n    TodoList.svelte    # List container\n    TodoItem.svelte    # Single todo with checkbox, text, delete\n    FilterBar.svelte   # Filter buttons + clear completed\n    store.ts           # Svelte store for todos\n    storage.ts         # localStorage persistence\n```\n\n## Data Model\n\n```typescript\ninterface Todo {\n  id: string;        // UUID\n  text: string;      // Todo text\n  completed: boolean;\n}\n\ntype Filter = 'all' | 'active' | 'completed';\n```\n\n## Acceptance Criteria\n\n1. Can add a todo by typing and pressing Enter or clicking Add\n2. Can toggle todo completion by clicking checkbox\n3. Can delete a todo by clicking X button\n4. Filter buttons show correct subset of todos\n5. \"X items left\" shows count of incomplete todos\n6. \"Clear completed\" removes all completed todos\n7. Todos persist across page refresh (localStorage)\n8. Empty state shows helpful message\n9. All tests pass\n"
  },
  {
    "path": "tests/subagent-driven-dev/svelte-todo/plan.md",
    "content": "# Svelte Todo List - Implementation Plan\n\nExecute this plan using the `superpowers:subagent-driven-development` skill.\n\n## Context\n\nBuilding a todo list app with Svelte. See `design.md` for full specification.\n\n## Tasks\n\n### Task 1: Project Setup\n\nCreate the Svelte project with Vite.\n\n**Do:**\n- Run `npm create vite@latest . -- --template svelte-ts`\n- Install dependencies with `npm install`\n- Verify dev server works\n- Clean up default Vite template content from App.svelte\n\n**Verify:**\n- `npm run dev` starts server\n- App shows minimal \"Svelte Todos\" heading\n- `npm run build` succeeds\n\n---\n\n### Task 2: Todo Store\n\nCreate the Svelte store for todo state management.\n\n**Do:**\n- Create `src/lib/store.ts`\n- Define `Todo` interface with id, text, completed\n- Create writable store with initial empty array\n- Export functions: `addTodo(text)`, `toggleTodo(id)`, `deleteTodo(id)`, `clearCompleted()`\n- Create `src/lib/store.test.ts` with tests for each function\n\n**Verify:**\n- Tests pass: `npm run test` (install vitest if needed)\n\n---\n\n### Task 3: localStorage Persistence\n\nAdd persistence layer for todos.\n\n**Do:**\n- Create `src/lib/storage.ts`\n- Implement `loadTodos(): Todo[]` and `saveTodos(todos: Todo[])`\n- Handle JSON parse errors gracefully (return empty array)\n- Integrate with store: load on init, save on change\n- Add tests for load/save/error handling\n\n**Verify:**\n- Tests pass\n- Manual test: add todo, refresh page, todo persists\n\n---\n\n### Task 4: TodoInput Component\n\nCreate the input component for adding todos.\n\n**Do:**\n- Create `src/lib/TodoInput.svelte`\n- Text input bound to local state\n- Add button calls `addTodo()` and clears input\n- Enter key also submits\n- Disable Add button when input is empty\n- Add component tests\n\n**Verify:**\n- Tests pass\n- Component renders input and button\n\n---\n\n### Task 5: TodoItem Component\n\nCreate the single todo item component.\n\n**Do:**\n- Create `src/lib/TodoItem.svelte`\n- Props: `todo: Todo`\n- Checkbox toggles completion (calls `toggleTodo`)\n- Text with strikethrough when completed\n- Delete button (X) calls `deleteTodo`\n- Add component tests\n\n**Verify:**\n- Tests pass\n- Component renders checkbox, text, delete button\n\n---\n\n### Task 6: TodoList Component\n\nCreate the list container component.\n\n**Do:**\n- Create `src/lib/TodoList.svelte`\n- Props: `todos: Todo[]`\n- Renders TodoItem for each todo\n- Shows \"No todos yet\" when empty\n- Add component tests\n\n**Verify:**\n- Tests pass\n- Component renders list of TodoItems\n\n---\n\n### Task 7: FilterBar Component\n\nCreate the filter and status bar component.\n\n**Do:**\n- Create `src/lib/FilterBar.svelte`\n- Props: `todos: Todo[]`, `filter: Filter`, `onFilterChange: (f: Filter) => void`\n- Show count: \"X items left\" (incomplete count)\n- Three filter buttons: All, Active, Completed\n- Active filter is visually highlighted\n- \"Clear completed\" button (hidden when no completed todos)\n- Add component tests\n\n**Verify:**\n- Tests pass\n- Component renders count, filters, clear button\n\n---\n\n### Task 8: App Integration\n\nWire all components together in App.svelte.\n\n**Do:**\n- Import all components and store\n- Add filter state (default: 'all')\n- Compute filtered todos based on filter state\n- Render: heading, TodoInput, TodoList, FilterBar\n- Pass appropriate props to each component\n\n**Verify:**\n- App renders all components\n- Adding todos works\n- Toggling works\n- Deleting works\n\n---\n\n### Task 9: Filter Functionality\n\nEnsure filtering works end-to-end.\n\n**Do:**\n- Verify filter buttons change displayed todos\n- 'all' shows all todos\n- 'active' shows only incomplete todos\n- 'completed' shows only completed todos\n- Clear completed removes completed todos and resets filter if needed\n- Add integration tests\n\n**Verify:**\n- Filter tests pass\n- Manual verification of all filter states\n\n---\n\n### Task 10: Styling and Polish\n\nAdd CSS styling for usability.\n\n**Do:**\n- Style the app to match the design mockup\n- Completed todos have strikethrough and muted color\n- Active filter button is highlighted\n- Input has focus styles\n- Delete button appears on hover (or always on mobile)\n- Responsive layout\n\n**Verify:**\n- App is visually usable\n- Styles don't break functionality\n\n---\n\n### Task 11: End-to-End Tests\n\nAdd Playwright tests for full user flows.\n\n**Do:**\n- Install Playwright: `npm init playwright@latest`\n- Create `tests/todo.spec.ts`\n- Test flows:\n  - Add a todo\n  - Complete a todo\n  - Delete a todo\n  - Filter todos\n  - Clear completed\n  - Persistence (add, reload, verify)\n\n**Verify:**\n- `npx playwright test` passes\n\n---\n\n### Task 12: README\n\nDocument the project.\n\n**Do:**\n- Create `README.md` with:\n  - Project description\n  - Setup: `npm install`\n  - Development: `npm run dev`\n  - Testing: `npm test` and `npx playwright test`\n  - Build: `npm run build`\n\n**Verify:**\n- README accurately describes the project\n- Instructions work\n"
  },
  {
    "path": "tests/subagent-driven-dev/svelte-todo/scaffold.sh",
    "content": "#!/usr/bin/env bash\n# Scaffold the Svelte Todo test project\n# Usage: ./scaffold.sh /path/to/target/directory\n\nset -e\n\nTARGET_DIR=\"${1:?Usage: $0 <target-directory>}\"\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\n# Create target directory\nmkdir -p \"$TARGET_DIR\"\ncd \"$TARGET_DIR\"\n\n# Initialize git repo\ngit init\n\n# Copy design and plan\ncp \"$SCRIPT_DIR/design.md\" .\ncp \"$SCRIPT_DIR/plan.md\" .\n\n# Create .claude settings to allow reads/writes in this directory\nmkdir -p .claude\ncat > .claude/settings.local.json << 'SETTINGS'\n{\n  \"permissions\": {\n    \"allow\": [\n      \"Read(**)\",\n      \"Edit(**)\",\n      \"Write(**)\",\n      \"Bash(npm:*)\",\n      \"Bash(npx:*)\",\n      \"Bash(mkdir:*)\",\n      \"Bash(git:*)\"\n    ]\n  }\n}\nSETTINGS\n\n# Create initial commit\ngit add .\ngit commit -m \"Initial project setup with design and plan\"\n\necho \"Scaffolded Svelte Todo project at: $TARGET_DIR\"\necho \"\"\necho \"To run the test:\"\necho \"  claude -p \\\"Execute this plan using superpowers:subagent-driven-development. Plan: $TARGET_DIR/plan.md\\\" --plugin-dir /path/to/superpowers\"\n"
  }
]