Compare commits

..

221 Commits

Author SHA1 Message Date
Jesse Vincent
b0519329df feat: add architecture and file size checks to review loops
Spec reviewer now checks for unit decomposition with clear boundaries.
Plan reviewer now checks file structure and whether files will grow
too large to reason about.
2026-02-08 16:50:24 -08:00
Jesse Vincent
6ca430a0d3 feat: add file growth check to code quality reviewer
Focus on whether this implementation grew or created large files,
not pre-existing file sizes in brownfield codebases.
2026-02-08 16:50:24 -08:00
Jesse Vincent
6394555d14 fix: address review feedback on architecture guidance
- Define DONE_WITH_CONCERNS handling in SDD controller flow
- Make implementer action explicit when file grows beyond plan intent
- Reword writing-plans file size reasoning (avoid tooling-artifact language)
- Add decomposition awareness to code quality reviewer prompt
2026-02-08 16:50:24 -08:00
Jesse Vincent
5a3137c24f feat: add architecture guidance and capability-aware escalation to skills
Brainstorming: design-for-isolation guidance and brownfield codebase awareness
Writing-plans: file structure section requiring decomposition before task definition
Implementer prompt: code organization awareness, structured escalation protocol
  (DONE/DONE_WITH_CONCERNS/BLOCKED/NEEDS_CONTEXT), explicit permission to stop
Subagent-driven-development: provider-agnostic model selection tiers, escalation handling
2026-02-08 16:50:24 -08:00
Jesse Vincent
03d182bc39 chore: gitignore triage directory 2026-02-08 16:50:12 -08:00
Jesse Vincent
e9b46118db docs: add brainstorm visual companion improvements to release notes 2026-02-08 16:50:12 -08:00
Jesse Vincent
3ed92079c2 docs: restructure brainstorming skill with progressive disclosure
SKILL.md is now minimal: process, principles, and a prompt that notes
the visual companion is new/token-intensive/slow. All visual companion
details move to visual-companion.md as a progressive disclosure document
read only when the user opts in.

Delete CLAUDE-INSTRUCTIONS.md (content folded into visual-companion.md).
Document fragment vs full-document behavior and --project-dir persistence.
2026-02-08 16:50:12 -08:00
Jesse Vincent
b10a3c0995 feat: persist brainstorm mockups to .superpowers/ directory
start-server.sh now accepts --project-dir to store session files under
.superpowers/brainstorm/ instead of /tmp. stop-server.sh only deletes
ephemeral /tmp sessions, keeping persistent ones for later review.

Fix test race condition with polling-based server startup wait.
2026-02-08 16:50:12 -08:00
Jesse Vincent
9133401613 refactor: server-side frame wrapping and helper.js consolidation
Move toggleSelect/send/selectedChoice from frame-template.html inline
script to helper.js so they're auto-injected. Server now detects bare
HTML fragments (no DOCTYPE/html tag) and wraps them in the frame
template automatically. Full documents pass through as before.

Fix dark mode in sendToClaude confirmation (was using hardcoded colors).
Fix test env var bug (BRAINSTORM_SCREEN -> BRAINSTORM_DIR).
Add tests for fragment wrapping, full doc passthrough, and helper.js.
2026-02-08 16:50:12 -08:00
Jesse Vincent
3abf068fed test: rewrite document review test as proper integration test
- Creates test project with spec containing intentional errors
- Runs Claude to actually review using spec-document-reviewer template
- Verifies reviewer catches TODO and "specified later" deferrals
- Checks review format and verdict

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
acb50ce4b3 test: add end-to-end tests for document review system
Tests verify:
- Spec document reviewer checks (completeness, TODOs)
- Plan document reviewer checks (spec alignment, task decomposition)
- Review loops exist in brainstorming and writing-plans skills
- Chunk-by-chunk review for plans with 1000-line limit
- Iteration guidance (5 iterations, escalate to human)
- Checkbox syntax on steps only (not task headings)
- Correct directories (docs/superpowers/specs, docs/superpowers/plans)
- Reviewers are advisory
- Same agent fixes issues (preserves context)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
0d1efaf03d fix: remove checkbox from task headings, keep on steps only
The `- [ ] ### Task N:` syntax was unusual and might not render
correctly in all markdown parsers. Now only steps have checkboxes.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
3c2afcd150 docs: add document review system spec and plan
- Spec: docs/superpowers/specs/2026-01-22-document-review-system-design.md
- Plan: docs/superpowers/plans/2026-01-22-document-review-system.md

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
f093a192ab docs: update plan header to reference checkbox syntax
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
e85234b396 feat: add plan review loop and checkbox syntax to writing-plans skill
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
2754b1a1c0 feat: add plan document reviewer prompt template
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
b2d325ae3b feat: add spec review loop to brainstorming skill
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
7ad7220124 feat: add spec document reviewer prompt template
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
41ff1a92b0 feat: enforce subagent-driven-development on capable harnesses
- Subagent-driven-development is now mandatory when harness supports it
- No longer offer choice between subagent-driven and executing-plans
- Executing-plans reserved for harnesses without subagent capability
- Update plan header to reference both execution paths

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
6915ca4376 feat: enforce brainstorming → writing-plans transition
- Make writing-plans REQUIRED after design approval
- Explicitly forbid platform planning features (EnterPlanMode, etc.)
- Forbid direct implementation without writing-plans skill

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
2538180beb refactor: restructure specs and plans directories
- Specs (brainstorming output) now go to docs/superpowers/specs/
- Plans (writing-plans output) now go to docs/superpowers/plans/
- User preferences for locations override these defaults
- Update all skill references and test files

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
3abe1cf4b4 fix: Windows hook execution for Claude Code 2.1.x (#331)
* fix: convert shell scripts from CRLF to LF line endings

Add .gitattributes to enforce LF line endings for shell scripts,
preventing bash errors like "/usr/bin/bash: line 1: : command not found"
when scripts are checked out on Windows with CRLF.

Fixes #317 (SessionStart hook fails due to CRLF line endings)

Files converted:
- hooks/session-start.sh
- lib/brainstorm-server/start-server.sh
- lib/brainstorm-server/stop-server.sh
- lib/brainstorm-server/wait-for-feedback.sh
- skills/systematic-debugging/find-polluter.sh

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: update Windows hook execution for Claude Code 2.1.x

Claude Code 2.1.x changed the Windows execution model: it now auto-detects
.sh files in hook commands and prepends "bash " automatically. This broke
the polyglot wrapper because:

  Before: "run-hook.cmd" session-start.sh  (wrapper executes)
  After:  bash "run-hook.cmd" session-start.sh  (bash can't run .cmd)

Changes:
- hooks.json now calls session-start.sh directly (Claude Code handles bash)
- Added deprecation comment to run-hook.cmd explaining the change
- Updated RELEASE-NOTES.md

Fixes #317, #313, #275, #292

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
75e037d29b feat(opencode): use native skills and fix agent reset bug (#226) (#330)
* fix use_skill agent context (#290)

* fix: respect OPENCODE_CONFIG_DIR for personal skills lookup (#297)

* fix: respect OPENCODE_CONFIG_DIR for personal skills lookup

The plugin was hardcoded to look for personal skills in ~/.config/opencode/skills,
ignoring users who set OPENCODE_CONFIG_DIR to a custom path (e.g., for dotfiles management).

Now uses OPENCODE_CONFIG_DIR if set, falling back to the default path.

* fix: update help text to use dynamic paths

Use configDir and personalSkillsDir variables in help text so paths
are accurate when OPENCODE_CONFIG_DIR is set.

* fix: normalize OPENCODE_CONFIG_DIR before use

Handle edge cases where the env var might be:
- Empty or whitespace-only
- Using ~ for home directory (common in .env files)
- A relative path

Now trims, expands ~, and resolves to absolute path.

* feat(opencode): use native skills and fix agent reset bug (#226)

- Replace custom use_skill/find_skills tools with OpenCode's native skill tool
- Use experimental.chat.system.transform hook instead of session.prompt
  (fixes #226 agent reset on first message)
- Symlink skills directory into ~/.config/opencode/skills/superpowers/
- Update installation docs with comprehensive Windows support:
  - Command Prompt, PowerShell, and Git Bash instructions
  - Proper symlink vs junction handling
  - Reinstall safety with cleanup steps
  - Verification commands for each shell

* Add OpenCode native skills changes to release notes

Documents:
- Breaking change: switch to native skill tool
- Fix for agent reset bug (#226)
- Fix for Windows installation (#232)

---------

Co-authored-by: Vinicius da Motta <viniciusmotta8@gmail.com>
Co-authored-by: oribi <oribarilan@gmail.com>
2026-02-08 16:50:12 -08:00
Jesse Vincent
00fca66a52 Add instruction priority hierarchy to using-superpowers skill
Clarifies that user instructions (CLAUDE.md, direct requests) always
take precedence over Superpowers skills, which in turn override
default system prompt behavior. Ensures users remain in control.

Also updates RELEASE-NOTES.md with unreleased changes including
the visual companion feature.
2026-02-08 16:50:12 -08:00
Jesse Vincent
e6d3c5ce15 Use semantic filenames for visual companion screens
Server now watches directory for new .html files instead of a single
screen file. Claude writes to semantically named files like
platform.html, style.html, layout.html - each screen is a new file.

Benefits:
- No need to read before write (files are always new)
- Semantic filenames describe what's on screen
- History preserved in directory for debugging
- Server serves newest file by mtime automatically

Updated: index.js, start-server.sh, and all documentation.
2026-02-08 16:49:15 -08:00
Jesse Vincent
5bacd0fd3c docs: improve terminal UX for visual companion
- Never use cat/heredoc for HTML (dumps noise into terminal)
- Read screen_file first before Write tool to avoid errors
- Remind user of URL on every step, not just first
- Give text summary of what's on screen before they look
2026-02-08 16:49:15 -08:00
Jesse Vincent
a1f1c75b23 refactor: simplify visual companion workflow, improve guidance
Scripts:
- Rename show-and-wait.sh -> wait-for-feedback.sh (just waits, no HTML piping)
- Remove wait-for-event.sh (used hanging tail -f)
- Workflow now: Write tool for HTML, wait-for-feedback.sh to block

Documentation rewrite:
- Broader "when to use" (UI, architecture, complex choices, spatial)
- Always ask user first before starting
- Scale fidelity to the question being asked
- Explain the question on each page
- Iterate before moving on - validate changes address feedback
- Use real content (Unsplash images) when it matters
2026-02-08 16:49:15 -08:00
Jesse Vincent
b7774ec82e feat: add show-and-wait.sh helper, fix race condition
- New show-and-wait.sh combines write + wait into one command
- Uses polling instead of tail -f (which hangs on macOS)
- Docs updated: start watcher BEFORE writing screen to avoid race
- Reduces terminal noise by consolidating operations
2026-02-08 16:49:15 -08:00
Jesse Vincent
194cca5a47 fix: session isolation and blocking wait for visual companion
- Each session gets unique temp directory (/tmp/brainstorm-{pid}-{timestamp})
- Server outputs screen_dir and screen_file in startup JSON
- stop-server.sh takes screen_dir arg and cleans up session directory
- Document blocking TaskOutput pattern: 10-min timeouts, retry up to 3x,
  then prompt user "let me know when you want to continue"
2026-02-08 16:49:15 -08:00
Jesse Vincent
e2c6be7174 feat: add visual companion for brainstorming skill
Adds browser-based mockup display to replace ASCII art during
brainstorming sessions. Key components:

- Frame template with OS-aware light/dark theming
- CSS helpers for options, cards, mockups, split views
- Server lifecycle scripts (start/stop with random high port)
- Event watcher using tail+grep for feedback loop
- Claude instructions for using the visual companion

The skill now asks users if they want browser mockups and only
runs in Claude Code environments.
2026-02-08 16:49:15 -08:00
Jesse Vincent
23cb23b5bd feat: add sendToClaude helper and wait-for-event tool
- Add sendToClaude() function to browser helper that shows confirmation
- Add wait-for-event.sh script for watching server output (tail -f | grep -m 1)
- Enables clean event-driven loop: background bash waits for event, completion triggers Claude's turn
2026-02-08 16:49:15 -08:00
Jesse Vincent
9be148f3b8 docs: add visual brainstorming implementation plan 2026-02-08 16:49:15 -08:00
Jesse Vincent
8360e087ff fix: preserve original event type, use source field for wrapper 2026-02-08 16:49:15 -08:00
Jesse Vincent
f4f62cb1af fix: correct visual companion documentation issues 2026-02-08 16:49:15 -08:00
Jesse Vincent
62b588799b feat: add visual companion to brainstorming skill 2026-02-08 16:49:15 -08:00
Jesse Vincent
6a524af4db test: add brainstorm server integration tests 2026-02-08 16:49:15 -08:00
Jesse Vincent
3ec1c2570b fix: ensure user-event type is preserved in WebSocket message output
The spread operator order was causing incoming event types to overwrite
the user-event type marker.
2026-02-08 16:49:15 -08:00
Jesse Vincent
e532c6dbbe feat: add browser helper library for event capture 2026-02-08 16:49:15 -08:00
Jesse Vincent
e3625b93e1 feat: add brainstorm server foundation
Create the initial server for the visual brainstorming companion:
- Express server with WebSocket support for browser communication
- File watcher (chokidar) to detect screen.html changes
- Auto-injects helper.js into served HTML for event capture
- Binds to localhost only (127.0.0.1) for security
- Outputs JSON events to stdout for Claude consumption
2026-02-08 16:49:15 -08:00
Jesse Vincent
a98c5dfc9d Release v4.2.0: Windows fixes, Codex native skill discovery, worktree requirements 2026-02-05 17:34:36 -08:00
Drew Ritter
a72e416979 Fix stale Codex skills path in writing-skills SKILL.md
~/.codex/skills/ is deprecated; Codex uses ~/.agents/skills/ via native discovery.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
8dd31c3da5 Add Windows uninstall instructions and expand migration steps
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
6a07692da1 Drop installer script and AGENTS.md gatekeeper
Testing showed native skill discovery works without the AGENTS.md
gatekeeper — using-superpowers bootstraps itself via SKILL.md
frontmatter. Install is now just clone + symlink, driven by
INSTALL.md. No Node.js dependency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
0771fd7cd1 Fix path resolution and symlink removal in Codex installer
Use fileURLToPath() instead of manual URL pathname parsing to correctly
handle paths with spaces and special characters on all platforms.
Replace execSync rm/rmdir with fs.unlinkSync for stale symlink removal.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
bcccc69271 Polish docs from 5-agent review
- INSTALL.md: add prerequisites, Windows note, verify step, clone
  deletion in uninstall
- README.codex.md: fix Windows section (junctions not symlinks),
  add description field guidance, consistent terminology
- install-codex.mjs: accurate link type labels (symlink vs junction)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
3626ccc53e Rewrite Codex docs for native skill discovery
Replaces bootstrap CLI references with native discovery flow.
Install is now clone + run installer. Documents tool mappings,
personal skills path, and Windows junction fallback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
47d3df7acc Rewrite INSTALL.md for native skill discovery
Two-step install: clone + run installer. Replaces the old manual
setup that required editing AGENTS.md by hand.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
d41f951c4a Add minimal Codex installer for native skill discovery
Creates symlink from ~/.agents/skills/superpowers to repo skills dir,
updates ~/.codex/AGENTS.md with gatekeeper block, removes old bootstrap
block if present. Windows junction fallback when symlinks are blocked.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
b4f56fec1b Remove bootstrap CLI and related files
The bootstrap CLI (superpowers-codex), Windows wrapper, and bootstrap
content file are no longer needed — Codex now has native skill discovery
that replaces this mechanism.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 17:21:25 -08:00
Drew Ritter
1143f9be3d Fix ~/ path expansion on Windows — use $HOME instead
PowerShell doesn't expand ~ when passed as an argument to node,
causing MODULE_NOT_FOUND errors. $HOME expands correctly in both
bash and PowerShell.

Fixes #285

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 12:11:11 -08:00
Drew Ritter
6cc2d8c920 Fix Windows/PowerShell invocation of superpowers-codex
Windows doesn't respect shebangs, so directly invoking the extensionless
superpowers-codex script triggers an "Open with" dialog. Prefix all
invocations with `node` (harmless on Unix, required on Windows) and add
a .cmd wrapper for manual invocation on Windows.

Fixes #285, #243

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 11:54:57 -08:00
Jesse Vincent
038abed026 fix: replace O(n^2) escape_for_json with parameter substitution
The 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, freezing terminal input even with async hooks.

Replaced with bash parameter substitution (${s//old/new}) which runs
each pattern as a single C-level pass. 7x faster on macOS, expected
to be dramatically faster on Windows Git Bash where the original
caused the worst hangs.

Relates to #404, #413
2026-02-05 11:38:06 -08:00
Jesse Vincent
961052e0f9 fix: run SessionStart hook async to prevent Windows terminal freeze
The synchronous SessionStart hook blocked the TUI from entering raw
mode on Windows, freezing all keyboard input. The pure-bash
escape_for_json function is O(n^2) on Git Bash, taking 60+ seconds.

Running the hook async prevents the freeze while still injecting
superpowers context. Multiple users confirmed this workaround.

Fixes #404, #413, #414, #419
2026-02-05 11:33:58 -08:00
Jesse Vincent
689e2a77fc fix: Windows hook execution for Claude Code 2.1.x (#331)
* fix: convert shell scripts from CRLF to LF line endings

Add .gitattributes to enforce LF line endings for shell scripts,
preventing bash errors like "/usr/bin/bash: line 1: : command not found"
when scripts are checked out on Windows with CRLF.

Fixes #317 (SessionStart hook fails due to CRLF line endings)

Files converted:
- hooks/session-start.sh
- lib/brainstorm-server/start-server.sh
- lib/brainstorm-server/stop-server.sh
- lib/brainstorm-server/wait-for-feedback.sh
- skills/systematic-debugging/find-polluter.sh

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: update Windows hook execution for Claude Code 2.1.x

Claude Code 2.1.x changed the Windows execution model: it now auto-detects
.sh files in hook commands and prepends "bash " automatically. This broke
the polyglot wrapper because:

  Before: "run-hook.cmd" session-start.sh  (wrapper executes)
  After:  bash "run-hook.cmd" session-start.sh  (bash can't run .cmd)

Changes:
- hooks.json now calls session-start.sh directly (Claude Code handles bash)
- Added deprecation comment to run-hook.cmd explaining the change
- Updated RELEASE-NOTES.md

Fixes #317, #313, #275, #292

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 11:33:25 -08:00
Jesse Vincent
5e0d2f8175 Simplify installation verification instructions
Remove /help command check and specific slash command list. Skills are
primarily invoked by describing what you want to do, not by running
specific commands.
2026-02-05 11:32:46 -08:00
Jesse Vincent
06b92f3682 Merge pull request #382 from clkao/fix/subagent-worktree-requirement
fix: require worktree setup before subagent-driven-development and executing-plans
2026-01-30 09:51:30 -08:00
Jesse Vincent
9819209bba Merge pull request #361 from deinspanjer/codex-bootstrap-support-collab-subagent
Codex: clarify subagent tool mapping in bootstrap + README
2026-01-30 09:48:29 -08:00
CL Kao
c7816ee2a6 docs: change main branch red flag to require explicit user consent
Instead of prohibiting main branch work entirely, allow it with explicit
user consent. This is more flexible while still ensuring users are aware
of the implications.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 15:12:50 -08:00
CL Kao
b323e35805 docs(executing-plans): add worktree requirement before executing plans
Add Integration section referencing using-git-worktrees skill as required,
consistent with subagent-driven-development skill. Also add reminder to
never start on main/master branch.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:48:24 -08:00
CL Kao
bb2ff5d309 docs(using-git-worktrees): add subagent/executing-plans as callers
Update Integration section to show bidirectional relationship:
subagent-driven-development and executing-plans now list
using-git-worktrees as required, so this skill should list
them as callers.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:46:45 -08:00
CL Kao
b63d485955 docs(subagent-driven-development): add main branch red flag to Never list
Add explicit warning against starting implementation on main/master
branch without first using a worktree for isolation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:45:04 -08:00
CL Kao
fa3f46d4e9 docs(subagent-driven-development): add using-git-worktrees as required skill
Adds using-git-worktrees as the first required workflow skill in the
Integration section. This makes explicit that an isolated workspace
should be set up before starting subagent-driven development.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:43:33 -08:00
CL Kao
f8dbe7b196 test: add Test 9 - main branch red flag warning
TDD: Test verifies that subagent-driven-development skill warns
against starting implementation directly on main/master branch.
Test expects skill to recommend worktree or feature branch instead.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:41:39 -08:00
CL Kao
93cf2ee84f test: add worktree requirement test for subagent-driven-development
Add Test 8 to verify that using-git-worktrees is mentioned as a required
skill for subagent-driven-development. This test will initially fail per
TDD approach - the skill file needs to be updated to pass this test.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:39:50 -08:00
CL Kao
1872f50b64 fix(tests): handle case variations in skill recognition test
The assertion now matches "subagent-driven-development", "Subagent-Driven
Development", and "Subagent Driven" since Claude's responses may use
different casing and formatting styles.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 14:34:38 -08:00
Daniel E.
8904b7d9dc codex: clarify subagent tool mapping in bootstrap 2026-01-25 18:42:22 -05:00
Jesse Vincent
469a6d81eb Merge pull request #349 from obra/fix/opencode-issues
fix(opencode): standardize on plugins/ directory, fix symlink docs
2026-01-23 12:09:13 -08:00
Jesse Vincent
4b6cef98ac chore: bump version to 4.1.1
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 20:08:47 +00:00
Jesse Vincent
03087b13b8 fix(opencode): standardize on plugins/ directory per official docs
OpenCode officially documents ~/.config/opencode/plugins/ (plural) as the
plugin directory. Our docs previously used plugin/ (singular), which also
works but caused confusion.

Changes:
- Renamed .opencode/plugin/ to .opencode/plugins/ in repo structure
- Updated INSTALL.md to use plugins/ everywhere
- Updated README.opencode.md (all platforms: Linux, macOS, Windows CMD,
  PowerShell, Git Bash) to use plugins/
- Updated test scripts to match

Tested: Both singular and plural forms work, but we now match official docs.

Fixes #343

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 18:31:45 +00:00
Jesse Vincent
493ac18dfe fix(opencode): update docs for native skills, fix symlink instructions
Issues addressed:
- #342: INSTALL.md still referenced removed find_skills/use_skill tools
- #339: Symlink instructions could fail if target already exists

Changes:
- INSTALL.md: Added missing skills symlink step, updated to native skill tool
- INSTALL.md: Removed Node.js prerequisite (no longer needed)
- README.opencode.md: Added explicit rm before ln -s (ln -sf doesn't remove dirs)
- Both files: Use ln -s instead of ln -sf for clarity

Note: #343 (plugin vs plugins folder name) not addressed in this commit

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 17:33:23 +00:00
Jesse Vincent
35d4fbcd0b chore: bump plugin version to 4.1.0
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 04:10:23 +00:00
Jesse Vincent
19c70afc99 chore: release v4.1.0
Breaking changes:
- OpenCode: Switched to native skills system (migration required)

Fixes:
- OpenCode: Fixed agent reset on session start (#226)
- OpenCode: Fixed Windows installation (#232)
- Claude Code: Fixed Windows hook execution for 2.1.x

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 04:07:35 +00:00
Jesse Vincent
405a025eea Merge pull request #335 from obra/fixes-for-main
fix: OpenCode native skills + Windows hook execution
2026-01-22 20:06:45 -08:00
Jesse Vincent
36fcd57626 fix: Windows hook execution for Claude Code 2.1.x (#331)
* fix: convert shell scripts from CRLF to LF line endings

Add .gitattributes to enforce LF line endings for shell scripts,
preventing bash errors like "/usr/bin/bash: line 1: : command not found"
when scripts are checked out on Windows with CRLF.

Fixes #317 (SessionStart hook fails due to CRLF line endings)

Files converted:
- hooks/session-start.sh
- lib/brainstorm-server/start-server.sh
- lib/brainstorm-server/stop-server.sh
- lib/brainstorm-server/wait-for-feedback.sh
- skills/systematic-debugging/find-polluter.sh

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: update Windows hook execution for Claude Code 2.1.x

Claude Code 2.1.x changed the Windows execution model: it now auto-detects
.sh files in hook commands and prepends "bash " automatically. This broke
the polyglot wrapper because:

  Before: "run-hook.cmd" session-start.sh  (wrapper executes)
  After:  bash "run-hook.cmd" session-start.sh  (bash can't run .cmd)

Changes:
- hooks.json now calls session-start.sh directly (Claude Code handles bash)
- Added deprecation comment to run-hook.cmd explaining the change
- Updated RELEASE-NOTES.md

Fixes #317, #313, #275, #292

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 03:56:52 +00:00
Jesse Vincent
3964d18670 feat(opencode): use native skills and fix agent reset bug (#226) (#330)
* fix use_skill agent context (#290)

* fix: respect OPENCODE_CONFIG_DIR for personal skills lookup (#297)

* fix: respect OPENCODE_CONFIG_DIR for personal skills lookup

The plugin was hardcoded to look for personal skills in ~/.config/opencode/skills,
ignoring users who set OPENCODE_CONFIG_DIR to a custom path (e.g., for dotfiles management).

Now uses OPENCODE_CONFIG_DIR if set, falling back to the default path.

* fix: update help text to use dynamic paths

Use configDir and personalSkillsDir variables in help text so paths
are accurate when OPENCODE_CONFIG_DIR is set.

* fix: normalize OPENCODE_CONFIG_DIR before use

Handle edge cases where the env var might be:
- Empty or whitespace-only
- Using ~ for home directory (common in .env files)
- A relative path

Now trims, expands ~, and resolves to absolute path.

* feat(opencode): use native skills and fix agent reset bug (#226)

- Replace custom use_skill/find_skills tools with OpenCode's native skill tool
- Use experimental.chat.system.transform hook instead of session.prompt
  (fixes #226 agent reset on first message)
- Symlink skills directory into ~/.config/opencode/skills/superpowers/
- Update installation docs with comprehensive Windows support:
  - Command Prompt, PowerShell, and Git Bash instructions
  - Proper symlink vs junction handling
  - Reinstall safety with cleanup steps
  - Verification commands for each shell

* Add OpenCode native skills changes to release notes

Documents:
- Breaking change: switch to native skill tool
- Fix for agent reset bug (#226)
- Fix for Windows installation (#232)

---------

Co-authored-by: Vinicius da Motta <viniciusmotta8@gmail.com>
Co-authored-by: oribi <oribarilan@gmail.com>
2026-01-23 03:56:12 +00:00
oribi
a01a135fe1 fix: respect OPENCODE_CONFIG_DIR for personal skills lookup (#297)
* fix: respect OPENCODE_CONFIG_DIR for personal skills lookup

The plugin was hardcoded to look for personal skills in ~/.config/opencode/skills,
ignoring users who set OPENCODE_CONFIG_DIR to a custom path (e.g., for dotfiles management).

Now uses OPENCODE_CONFIG_DIR if set, falling back to the default path.

* fix: update help text to use dynamic paths

Use configDir and personalSkillsDir variables in help text so paths
are accurate when OPENCODE_CONFIG_DIR is set.

* fix: normalize OPENCODE_CONFIG_DIR before use

Handle edge cases where the env var might be:
- Empty or whitespace-only
- Using ~ for home directory (common in .env files)
- A relative path

Now trims, expands ~, and resolves to absolute path.
2026-01-19 13:54:50 -08:00
Vinicius da Motta
ac471e69c2 fix use_skill agent context (#290) 2026-01-18 17:02:48 -08:00
Joshua Shanks
a08f088968 docs: fix documentation accuracy issues in skills (#157)
- Fix broken commit message HEREDOC syntax in sharing-skills/SKILL.md
  - Move entire message inside command substitution for valid bash

- Fix contradictory test requirements in systematic-debugging/SKILL.md
  - Clarify automated tests are "strongly preferred"
  - One-off scripts should be documented for regression testing
  - Requirement is for "reproducible test" not escape clause

- Fix typo in testing-skills-with-subagents/SKILL.md
  - "ith" -> "with" in checklist item
2026-01-14 14:21:22 -08:00
Jesse Vincent
b9e16498b9 Release v4.0.3: Strengthen using-superpowers for explicit skill requests 2025-12-26 22:55:32 -06:00
Jesse Vincent
f6d50c74b2 Bump version to 4.0.3 2025-12-26 22:53:58 -06:00
Jesse Vincent
3dac35e0b3 Strengthen using-superpowers for explicit skill requests
Addresses failure mode where Claude skips skill invocation even when
user explicitly requests it by name (e.g., "subagent-driven-development,
please").

Skill changes:
- "Check for skills" → "Invoke relevant or requested skills"
- "BEFORE ANY RESPONSE" → "BEFORE any response or action"
- Added reassurance that wrong skill invocations are okay
- New red flag: "I know what that means"

Tests:
- New test suite for explicit skill requests
- Single-turn and multi-turn scenarios with --continue
- Tests with haiku model and user CLAUDE.md
2025-12-26 22:41:22 -06:00
Jesse Vincent
131c1f189f Release v4.0.2: Make slash commands user-only
- Added disable-model-invocation to /brainstorm, /execute-plan, /write-plan
- Commands now restricted to manual user invocation only
- Underlying skills remain available for autonomous invocation
2025-12-23 23:03:31 -08:00
Jesse Vincent
9baedaa117 Make slash commands user-only with disable-model-invocation
Added disable-model-invocation: true to /brainstorm, /execute-plan, and
/write-plan commands. Claude can still invoke the underlying skills
directly, but the slash commands are now restricted to manual user
invocation only.
2025-12-23 23:03:19 -08:00
Jesse Vincent
66a2dbd80a Add automation-over-documentation guidance to writing-skills
Mechanical constraints should be automated, not documented—save skills
for judgment calls.

Based on insight from @EthanJStark in PR #146.
2025-12-23 23:03:19 -08:00
Jesse Vincent
1455ac0631 Add GitHub thread reply guidance to receiving-code-review
When replying to inline review comments, use the thread API rather than
posting top-level PR comments.

Based on feedback from @ralphbean in PR #79.
2025-12-23 23:03:19 -08:00
egornomic
e64ad670df fix: inherit agent model (#144) 2025-12-23 21:46:15 -08:00
Mike Harrison
c037dcbf4b fix: use git check-ignore for worktree gitignore verification (#160)
* fix: use git check-ignore for worktree gitignore verification

The using-git-worktrees skill previously used grep to check only the
local .gitignore file, missing patterns in global gitignore configurations
(core.excludesfile). This caused unnecessary modifications to local
.gitignore when the directory was already globally ignored.

Changed verification from grep to git check-ignore, which respects Git's
full ignore hierarchy (local, global, and system gitignore files).

Fixes obra/superpowers#101

Tested with: Subagent pressure scenarios verifying correct behavior with
global gitignore configuration. Baseline test confirmed the bug, post-fix
test confirmed correct behavior.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* style: convert bold emphasis to headings in Common Mistakes section

Convert **Title** patterns to ### Title headings for markdown lint
compliance (MD036 - no emphasis as heading).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-23 11:26:33 -08:00
Jesse Vincent
a7a8c08c02 Clarify that Skill tool loads skill content directly
Fixes pattern where Claude would invoke a skill then try to Read the
file separately. The Skill tool already provides the content.

- Add "How to Access Skills" section to using-superpowers
- Change "read the skill" → "invoke the skill"
- Commands now use fully qualified names (superpowers:brainstorming etc)
2025-12-22 14:27:35 -08:00
Jesse Vincent
80643c2604 Update README for v4.0.0 skill consolidations and two-stage review 2025-12-17 18:07:40 -08:00
Jesse Vincent
95c6e16336 Prepare v4.0.0 release
- Rewrite release notes centering new features (two-stage review,
  debugging tools, test infrastructure)
- Bump version to 4.0.0 in plugin.json and marketplace.json
- Remove .claude/settings.local.json from tracking
- Add .claude/ to .gitignore
2025-12-17 16:45:35 -08:00
Jesse Vincent
612fbcdd01 Tweak the brainstorming skill to try to improve triggering 2025-12-17 16:44:52 -08:00
Jesse Vincent
70bf3a9e7f Bump version to v4.0.0 2025-12-17 16:44:52 -08:00
Jesse Vincent
c2125b41e3 Update v3.7.0 release notes with all changes since v3.6.2 2025-12-17 16:44:52 -08:00
Jesse Vincent
ae0ef56b44 Add skill triggering test framework
Creates tests/skill-triggering/ to validate skills trigger correctly from
naive prompts (without explicitly naming the skill). Tests 6 skills:
- systematic-debugging
- test-driven-development
- writing-plans
- dispatching-parallel-agents
- executing-plans
- requesting-code-review

All 6 tests pass - skills trigger correctly based on their descriptions.
2025-12-17 16:44:52 -08:00
Jesse Vincent
030a222af1 Fix skill descriptions: remove workflow summaries that override flowcharts
Testing revealed that descriptions summarizing workflow cause Claude to
follow the description instead of reading the skill body. Changed all
descriptions to "when to use" triggers only:

- dispatching-parallel-agents: 2+ independent tasks without shared state
- executing-plans: have a written plan to execute with review checkpoints
- requesting-code-review: completing tasks, features, or before merging
- systematic-debugging: encountering bugs before proposing fixes
- test-driven-development: implementing features before writing code
- writing-plans: have spec/requirements for multi-step task before coding
- writing-skills: updated with "description trap" documentation

The description trap: workflow summaries in descriptions create shortcuts
Claude takes, skipping the skill body entirely.
2025-12-17 16:44:52 -08:00
Jesse Vincent
2a19be0b78 Document skill description trap: descriptions override flowcharts
Testing revealed that skill descriptions summarizing workflow cause
Claude to follow the description instead of reading the skill body.

- A description saying "code review between tasks" caused ONE review
- The flowchart clearly showed TWO reviews (spec compliance + quality)
- Minimal description ("Use when...") correctly deferred to flowchart

Updated writing-skills with:
- "Description = When to Use, NOT What the Skill Does" section
- Cautionary tale about this actual failure
- Examples of good (triggers only) vs bad (workflow summary) descriptions

Updated subagent-driven-development:
- Removed workflow summary from description
- Now just: "Use when executing implementation plans..."

Updated test runner:
- Added --dangerously-skip-permissions for automated testing
2025-12-17 16:44:52 -08:00
Jesse Vincent
cd83439bb2 Add .claude settings to scaffolds for auto-approved permissions 2025-12-17 16:44:52 -08:00
Jesse Vincent
ed06dcbe27 Fix skill description to match flowchart: two-stage review (spec then quality) 2025-12-17 16:44:52 -08:00
Jesse Vincent
baef5241aa Add test suite for subagent-driven-development skill
Two test projects for validating the skill with full end-to-end runs:
- go-fractals: 10 tasks, CLI tool with Sierpinski and Mandelbrot
- svelte-todo: 12 tasks, CRUD app with localStorage and Playwright

Each test has design.md, plan.md, and scaffold.sh. Run with:
  ./tests/subagent-driven-dev/run-test.sh go-fractals
2025-12-17 16:44:51 -08:00
Jesse Vincent
28ba020000 Add render-graphs.js tool for visualizing skill flowcharts 2025-12-17 16:44:51 -08:00
Jesse Vincent
a9b94ae5d7 Rewrite subagent-driven-development with executable flowcharts
- Add graphviz/dot flowcharts as primary executable instructions
- Extract prompt templates to separate collateral files:
  - ./implementer-prompt.md
  - ./spec-reviewer-prompt.md
  - ./code-quality-reviewer-prompt.md
- Use qualified skill names (superpowers:skill-name)
- Make flowchart labels explicit and action-oriented
- Add "When to Use" decision flowchart
- Keep detailed prose as supporting content
2025-12-17 16:44:51 -08:00
Jesse Vincent
5845b52747 Consolidate debugging techniques into systematic-debugging skill
Move condition-based-waiting, defense-in-depth, and root-cause-tracing
into systematic-debugging as progressive disclosure supporting files.

These techniques are now available as reference material within the
systematic-debugging skill directory, reducing skill count while keeping
content accessible when needed.

Note: Claude Code's SLASH_COMMAND_TOOL_CHAR_BUDGET env variable silently
limits skill discovery, which drove this consolidation to ensure core
skills remain visible.
2025-12-17 16:44:51 -08:00
Jesse Vincent
3f725ff0d4 Strengthen brainstorming skill trigger and add skill priority guidance
- Update brainstorming description to use imperative "You MUST use this"
- Clarify trigger: "before any creative work - creating features, building
  components, adding functionality, or modifying behavior"
- Add Skill Priority section to using-superpowers to ensure process skills
  (brainstorming, debugging) are invoked before implementation skills
2025-12-17 16:44:51 -08:00
Jesse Vincent
b57c27d815 Integrate testing-skills-with-subagents into writing-skills
- Moved testing-skills-with-subagents to writing-skills/testing-skills-with-subagents.md
- Moved examples/ directory to writing-skills/examples/
- Updated writing-skills to reference via @testing-skills-with-subagents.md
- Updated README to reflect consolidation
- Removed standalone skill (now a supporting reference)
2025-12-17 16:44:51 -08:00
Jesse Vincent
718ec45d33 Integrate testing-anti-patterns into test-driven-development
- Moved testing-anti-patterns to test-driven-development/testing-anti-patterns.md
- Added reference in TDD skill for progressive disclosure
- Updated README to reflect consolidation
- Removed standalone skill (now a supporting reference)
2025-12-17 16:44:51 -08:00
Jesse Vincent
c7caee5647 Remove obsolete sharing-skills skill
The contribution workflow is now via standard GitHub PR process,
not a dedicated skill. The skill was documenting an old workflow
that no longer applies.
2025-12-17 16:44:51 -08:00
Jesse Vincent
1f611f5c0c Add v3.7.0 release notes for dev branch changes 2025-12-17 16:44:51 -08:00
Jesse Vincent
2d7408d0c6 Improve using-superpowers skill to prevent rationalization failures
Tested against claude -p with multiple scenarios. Key fixes:
- Clarify skill check comes BEFORE ANY response including clarifications
- Add rationalizations: "I need more context first", "Let me explore first", "This feels productive"
- Flowchart entry point now "User message received" → clearer blocking gate
- Shorter, more scannable format (flowchart + table)

Verified: "Fix login bug" now triggers systematic-debugging first
2025-12-17 16:44:51 -08:00
Jesse Vincent
9464a51779 Add comprehensive testing documentation
Documents:
- How to run integration tests
- subagent-driven-development test details
- Token analysis tool usage
- Troubleshooting common issues
- Writing new integration tests
- Session transcript format
2025-12-17 16:44:51 -08:00
Jesse Vincent
faa65e7163 Add token usage analysis to subagent-driven-development test
- Rewrote analyze-token-usage.py to parse main session file correctly
- Extracts usage from toolUseResult fields for each subagent
- Shows breakdown by agent with descriptions
- Integrated into test-subagent-driven-development-integration.sh
- Displays token usage automatically after each test run
2025-12-17 16:44:50 -08:00
Jesse Vincent
24ca8cd9d5 fix: verify skill usage via session transcript not text output
The skill instructions are internal and don't appear in user-facing
output. Updated verification to parse the session JSONL transcript
and check for actual tool usage:
- Skill tool invocation
- Task tool (subagents)
- TodoWrite (tracking)
- Implementation results
2025-12-17 16:44:50 -08:00
Jesse Vincent
8fbeca830a test: use bypassPermissions mode for unrestricted testing
dontAsk mode was auto-denying Write tool. Use bypassPermissions
instead to allow full tool access in this controlled test environment.
2025-12-17 16:44:50 -08:00
Jesse Vincent
67de772d7f test: auto-approve permissions with --permission-mode dontAsk
Headless tests need automatic permission approval to write files.
Using dontAsk mode to auto-approve permissions for test directory.
2025-12-17 16:44:50 -08:00
Jesse Vincent
cf72863792 test: add --add-dir flag for temp directory access
Claude needs explicit permission to access the temp test directory.
Added --add-dir flag to grant access to the test project.
2025-12-17 16:44:50 -08:00
Jesse Vincent
baa23b16bb test: show Claude output in real-time during integration test
Use tee instead of redirection so test output is visible during
execution while still being saved to file for analysis.
2025-12-17 16:44:50 -08:00
Jesse Vincent
0aba33be1c fix: run integration test from superpowers dir to access local dev skills
The superpowers-dev marketplace makes skills available only when running
from the plugin directory. Updated test to run claude from superpowers
directory while working on the test project.
2025-12-17 16:44:50 -08:00
Jesse Vincent
06310d6f5f Fix tests to use --allowed-tools flag
Claude Code headless mode requires --allowed-tools flag to actually
execute tool calls. Without it, Claude only responds as if it's doing
things but doesn't actually use tools.

Changes:
- Updated run_claude helper to accept allowed_tools parameter
- Updated integration test to use --allowed-tools=all
- This enables actual tool execution (Write, Task, Bash, etc.)

Now the integration test should actually execute the workflow instead
of just talking about it.
2025-12-17 16:44:50 -08:00
Jesse Vincent
dc11a093c3 Fix syntax error in integration test
Simplified command substitution to avoid shell parsing issues.
Instead of nested heredoc in command substitution, write prompt
to file first then read it.
2025-12-17 16:44:50 -08:00
Jesse Vincent
fa946ae465 Add integration test for subagent-driven-development
Created full end-to-end integration test that executes a real plan
and verifies the new workflow improvements actually work.

New test: test-subagent-driven-development-integration.sh
- Creates real Node.js test project
- Generates implementation plan (2 tasks)
- Executes using subagent-driven-development skill
- Verifies 8 key behaviors:
  1. Plan read once at beginning (not per task)
  2. Full task text provided to subagents (not file reading)
  3. Subagents perform self-review
  4. Spec compliance review before code quality
  5. Spec reviewer reads code independently
  6. Working implementation produced
  7. Tests pass
  8. No extra features added (spec compliance)

Integration tests are opt-in (--integration flag) due to 10-30 min runtime.

Updated run-skill-tests.sh:
- Added --integration flag
- Separates fast tests from integration tests
- Shows note when integration tests skipped

Updated README with integration test documentation.

Run with:
  ./run-skill-tests.sh                # Fast tests only
  ./run-skill-tests.sh --integration  # Include integration tests
2025-12-17 16:44:50 -08:00
Jesse Vincent
51a171cd14 Add Claude Code skills test framework
Created automated test suite for testing superpowers skills using
Claude Code CLI in headless mode.

New files:
- tests/claude-code/run-skill-tests.sh - Main test runner
- tests/claude-code/test-helpers.sh - Helper functions for testing
- tests/claude-code/test-subagent-driven-development.sh - First test
- tests/claude-code/README.md - Documentation

Test framework features:
- Run Claude Code with prompts and capture output
- Assertion helpers (contains, not_contains, count, order)
- Test project creation helpers
- Timeout support (default 5 minutes)
- Verbose mode for debugging
- Specific test selection

First test verifies subagent-driven-development skill:
- Skill loading
- Workflow ordering (spec compliance before code quality)
- Self-review requirements
- Plan reading efficiency (read once)
- Spec compliance reviewer skepticism
- Review loops
- Task context provision

Run with: cd tests/claude-code && ./run-skill-tests.sh
2025-12-17 16:44:50 -08:00
Jesse Vincent
466332f698 Emphasize spec compliance review must complete before code quality
Made sequencing explicit:
- Spec compliance review loop must fully complete () before code quality
- Added "Do NOT proceed to code quality review until spec compliance is "
- Code Quality Review section starts with "Only run after spec compliance review is complete"
- Red Flags: Added "Start code quality review before spec compliance is  (wrong order)"

This ensures we don't waste time reviewing code quality of the wrong
implementation. Verify they built the right thing first, then verify
they built it well.
2025-12-17 16:44:49 -08:00
Jesse Vincent
87afde2390 Make spec compliance reviewer skeptical and verification-focused
The spec compliance reviewer now:
- Does NOT trust implementer's report
- Is warned implementer finished suspiciously quickly
- MUST verify everything by reading actual code
- Compares implementation to requirements line by line
- Reports issues with file:line references

Key additions:
- "Do Not Trust the Report" section
- Explicit DO NOT / DO lists
- "Verify by reading code, not by trusting report"
- Changed "What Was Implemented" to "What Implementer Claims They Built"

This prevents rubber-stamping and ensures independent verification
of spec compliance against actual codebase.
2025-12-17 16:44:49 -08:00
Jesse Vincent
2a6a40fe10 Improve subagent-driven-development workflow
Key improvements based on feedback:

1. Read plan once, not per task
   - Extract all tasks in Step 1
   - Reference extracted tasks in Step 2
   - Eliminates redundant file reading

2. Enable questions during work
   - Not just before, but also while working
   - "It's always OK to ask questions"
   - Don't guess or make assumptions

3. Add self-review before reporting
   - Completeness: implemented everything?
   - Quality: best work, clear names?
   - Discipline: avoided overbuilding?
   - Testing: comprehensive, real behavior?
   - Catches issues before handoff

4. Add spec compliance review
   - Separate reviewer checks: built the right thing?
   - Flags missing requirements
   - Flags extra/unneeded work
   - Flags misunderstandings
   - Runs BEFORE code quality review

5. Make reviews loops, not one-shot
   - Reviewer finds issues
   - Implementer fixes
   - Reviewer reviews again
   - Repeat until approved
   - Applies to both spec and code quality

Two-stage review process:
- Stage 1: Spec compliance (right thing?)
- Stage 2: Code quality (built well?)

This enables subagents to do their best work with clear requirements,
opportunities to clarify, self-critique, and thorough review loops.
2025-12-17 16:44:49 -08:00
Jesse Vincent
97ce1f8fe0 Update subagent-driven-development: controller provides full task text
Changed workflow so controller provides complete task context directly
rather than making subagent read plan file.

Key changes:
- Controller reads plan and extracts full task text
- Controller provides scene-setting context (dependencies, architecture)
- Subagent receives complete information in prompt (no file reading)
- Subagent can ask clarifying questions before beginning work
- Controller handles questions/concerns before subagent proceeds

Benefits:
- No file reading overhead for subagent
- Controller curates exactly what context is needed
- Questions surfaced before work begins (not after)
- Subagent has complete information to do best work

This enables subagents to start with clarity rather than ambiguity.
2025-12-17 16:44:49 -08:00
Jesse Vincent
e7e50ac947 Add skills improvement plan from user feedback
Analyzed feedback from two Claude instances using superpowers in real
development scenarios. Identified 8 core problems and proposed improvements
organized by impact and risk.

Key problems:
- Configuration change verification gap (verify success not intent)
- Background process accumulation across subagents
- Context bloat in subagent prompts
- Missing self-reflection before handoff
- Mock-interface drift
- Code reviewer file access issues
- Skills not being read/enforced
- Fix workflow latency

Proposed improvements organized in 3 phases:
- Phase 1: High-impact, low-risk (do first)
- Phase 2: Moderate changes (test carefully)
- Phase 3: Optimization (validate first)

See plan for detailed analysis and open questions.
2025-12-17 16:44:49 -08:00
Joshua Shanks
5faddc4087 fix codex path in release notes (#155)
Signed-off-by: Joshua Shanks <jjshanks@gmail.com>
2025-12-09 22:44:45 -08:00
Joshua Shanks
d2900eae0c fix: correct context window documentation link (#156)
Update relative link to absolute URL for external Anthropic docs.
2025-12-09 22:44:14 -08:00
Shaan Majid
4ac67830d9 chore: gitignore .claude/settings.local.json (#153)
This file contains machine-specific paths and permissions that cause
warnings when cloning the repo fresh.
2025-12-09 12:02:49 -08:00
Jesse Vincent
154d664373 Release v3.6.2: Fix Linux compatibility in polyglot hook wrapper
Fixed POSIX compatibility issue in hooks/run-hook.cmd that caused
"Bad substitution" errors on Ubuntu/Debian systems where /bin/sh is dash.

Changes:
- Replaced bash-specific ${BASH_SOURCE[0]:-$0} with POSIX-compliant $0
- Tested with both bash and sh (POSIX mode) on macOS
- Updated version to 3.6.2 in all required files

Fixes #141
2025-12-03 10:14:19 -08:00
Jesse Vincent
8462c20cce Release v3.6.1: Fix Windows arg forwarding in polyglot wrapper
- Add validation for missing script name
- Forward up to 8 additional arguments to bash on Windows
- Fixes CodeRabbit review feedback from #134
2025-12-01 16:18:56 -08:00
Jesse Vincent
a0c1e73a1d Release v3.6.0: Add Windows support for plugin hooks
New features:
- Cross-platform polyglot wrapper (run-hook.cmd) for Windows/Unix
- Pure bash JSON escaping for Windows compatibility
- Documentation for polyglot hooks setup
2025-12-01 15:52:36 -08:00
Jesse Vincent
94e9e2596c Add Windows support for plugin hooks (#134)
* feat: Add Windows support for session-start hook

- Create polyglot session-start.cmd that works in both CMD and bash
- Update hooks.json to use the .cmd polyglot launcher
- Replace sed/awk with pure bash for JSON escaping (Windows compatibility)

The polyglot script uses a heredoc trick:
- CMD sees the @echo off block and runs bash.exe with cygpath conversion
- Bash sees a heredoc and skips to the Unix section

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Add execute permission to session-start.cmd for Unix

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: Add comprehensive polyglot hooks documentation

- Add docs/windows/polyglot-hooks.md explaining the cross-platform technique
- Add reusable run-hook.cmd wrapper for parameterized hook execution
- Document how the polyglot works in CMD vs bash
- Include troubleshooting section and related GitHub issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* test: Add polyglot hook test script for macOS/Linux

Run ./test-polyglot.sh from repo root to verify:
- Required files exist with execute permissions
- Simple wrapper (session-start.cmd) produces valid JSON
- Parameterized wrapper (run-hook.cmd) works
- Heredoc correctly skips CMD block on Unix

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Use direct pipe to jq in test to avoid variable escaping issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: Use single reusable run-hook.cmd for all hooks

- Remove session-start.cmd in favor of run-hook.cmd
- Update hooks.json to use: run-hook.cmd session-start.sh
- Simplify test script to only test run-hook.cmd

This makes it easy to add more hooks - just create the .sh file
and add a line to hooks.json pointing to run-hook.cmd with the script name.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Simplify run-hook.cmd CMD block

Pass path directly to bash instead of using cygpath in a subshell.
The complex quoting was causing issues on Windows.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: Remove test-polyglot.sh

Testing complete - polyglot hooks work on Windows and macOS.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-01 15:42:12 -08:00
avleen
1b878e4fa1 Remove model name from core-reviewer (#120) 2025-11-30 13:22:56 -08:00
Jesse Vincent
515c86fd07 tweak: clarify skill tool path 2025-11-29 09:29:31 -08:00
Jesse Vincent
e416a0e105 Revert "feat: echo skill base directory in use-skill"
This reverts commit a08f7de64b.
2025-11-28 22:48:40 -08:00
Jesse Vincent
a08f7de64b feat: echo skill base directory in use-skill 2025-11-28 22:43:02 -08:00
Josh Thomas
207a23e4d5 fix(opencode): Use synthetic: true for invisible content injection (#122)
The OpenCode plugin injects the bootstrap and skill content as visible
user messages. While `noReply: true` prevents an AI response, the
injected content still appears in the chat UI which makes it just a bit
noisy.

OpenCode's `TextPartInput` supports a `synthetic` Boolean property that
hides parts from the UI while keeping them visible to the AI -- it's
been available in the v2 message format since around the v1.0.0 version
bump.
2025-11-26 09:38:35 -08:00
Jesse Vincent
c35c5f637e Update README to be a little more human-written (and mention github sponsors) 2025-11-24 13:13:01 -08:00
Jesse Vincent
9a01a0dcc1 chore: bump version to 3.5.1 2025-11-24 12:29:02 -08:00
Jesse Vincent
8c7826c34d fix(opencode): use session.created event for bootstrap injection
Switch from chat.message hook to session.created event for injecting
the using-superpowers skill content. The new approach:

- Injects at session creation via session.prompt() with noReply: true
- Explicitly tells model the skill is already loaded to prevent
  redundant use_skill calls
- Consolidates bootstrap generation into getBootstrapContent() helper
- Removes fallback pattern in favor of single implementation

Tested with 10 consecutive test runs and manual skill trigger validation.
2025-11-24 12:28:11 -08:00
Stefan Otte
4ae8fc8713 Use more generic "#!/usr/bin/env bash" instead of "#!/bin/bash" (#80)
"#!/bin/bash" does not work with nixos.
2025-11-24 09:45:58 -08:00
Jesse Vincent
94089bdce5 chore: bump version to 3.5.0 2025-11-23 20:04:24 -08:00
Jesse Vincent
9297fd24d5 docs: update release notes with test suite and documentation improvements 2025-11-23 19:52:46 -08:00
Claude
d0806ba5af fix: cleanup remaining code review issues
- Remove unused destructured parameters (project, $, worktree) from plugin
- Add test coverage for checkForUpdates function (error handling cases)
2025-11-24 00:25:26 +00:00
Claude
6ecd72c5bf fix: address code review issues in opencode support branch
- Fix test runner exiting early due to ((var++)) returning 1 with set -e
- Remove duplicate frontmatter stripping in superpowers-codex, use shared skillsCore.stripFrontmatter()
- Remove unused promptsDir/promptFile variables from opencode plugin
- Derive superpowers skills path from __dirname for better install flexibility
- Simplify test-skills-core.sh by removing failing ESM import attempt
2025-11-23 23:37:53 +00:00
Jesse Vincent
f600f969f5 docs: remove duplicate sections and fix conflicting information 2025-11-23 14:51:44 -08:00
Jesse Vincent
4ef2f9185d docs: add using-git-worktrees and subagent-driven-development to workflow 2025-11-23 14:05:59 -08:00
Jesse Vincent
8a626e75f3 docs: rewrite workflow in terms of skills, not commands 2025-11-23 14:01:32 -08:00
Jesse Vincent
014b11cf57 docs: emphasize automatic skill activation over manual commands 2025-11-23 13:57:36 -08:00
Jesse Vincent
3f73365155 docs: add workflow section showing brainstorm→plan→execute→finish flow 2025-11-23 13:55:23 -08:00
Jesse Vincent
9f33fc95bf docs: rewrite README to explain problem, solution, and philosophy clearly 2025-11-23 13:53:53 -08:00
Jesse Vincent
9220bb62af docs: simplify opencode readme instructions to match codex style 2025-11-23 13:50:37 -08:00
Jesse Vincent
f5a4002daf docs: reorganize platform installation docs with inline quick-start and detailed guides 2025-11-23 13:49:12 -08:00
Jesse Vincent
9dcf5eaabe fix: add OPENCODE_CONFIG_DIR for proper test isolation 2025-11-23 13:36:26 -08:00
Jesse Vincent
f3d6c331a1 test: add automated test suite for opencode plugin
Create comprehensive tests in tests/opencode/ that verify the plugin
works correctly in an isolated test environment:

- setup.sh: Creates temp HOME and installs plugin with proper symlinks
- test-plugin-loading.sh: Verifies plugin structure and JavaScript syntax
- test-skills-core.sh: Unit tests for skills-core.js library functions
- test-tools.sh: Integration tests for use_skill/find_skills (requires OpenCode)
- test-priority.sh: Tests project > personal > superpowers priority
- run-tests.sh: Main test runner with options for integration tests

Run basic tests: ./tests/opencode/run-tests.sh
Run all tests: ./tests/opencode/run-tests.sh --integration
2025-11-23 12:28:58 -08:00
Jesse Vincent
b0ba2cf15a docs: update documentation with message insertion and project skills features 2025-11-23 12:14:48 -08:00
Jesse Vincent
cbbd8d2edf docs: add project-local skills documentation 2025-11-23 12:13:19 -08:00
Jesse Vincent
9cd6c52acc feat: use message insertion pattern for persistence and add project skills support
- Add project-local skills directory (.opencode/skills/) with highest priority
- Use client.session.prompt() with noReply for skill loading to persist across compaction
- Add session.compacted event handler to re-inject bootstrap after context compaction
- Update find_skills to list skills from project > personal > superpowers directories
- Support project: prefix for explicit project skill loading
- Keep chat.message hook as fallback for initial context injection
2025-11-23 12:10:41 -08:00
Jesse Vincent
107859a748 refactor: remove prompt file, use automatic chat.message injection
- Delete .opencode/prompts/superpowers.txt (no longer needed)
- Simplify INSTALL.md to remove prompt file copying and agent configuration steps
- Installation now relies on plugin's chat.message hook for automatic context injection
- Cleaner, simpler setup process with fewer manual configuration steps
2025-11-23 10:57:48 -08:00
Jesse Vincent
5f5b789e3e feat: add chat.message hook to inject superpowers context automatically 2025-11-23 10:51:26 -08:00
Jesse Vincent
7db10cf540 docs: add implementation plan 2025-11-22 21:09:07 -08:00
Jesse Vincent
67ce04077b fix: use tool() helper function for proper OpenCode tool definitions 2025-11-22 21:07:57 -08:00
Jesse Vincent
d749c620b5 fix: use tool object instead of tools array per opencode api 2025-11-22 21:04:00 -08:00
Jesse Vincent
aa1fe045c6 refactor: use static prompt file instead of dynamic config hook 2025-11-22 20:59:53 -08:00
Jesse Vincent
368674419a fix: use agent prompts instead of event hooks for context injection
OpenCode doesn't support injecting context through event hooks. Instead,
the plugin now generates a prompt file that agents can reference via
{file:./prompts/superpowers.txt} in their configuration.
2025-11-22 16:13:05 -08:00
Jesse Vincent
c940d84f3d fix: use correct event subscription format for opencode 2025-11-22 15:47:38 -08:00
Jesse Vincent
8e7f90a954 fix: use session.created hook instead of session.started 2025-11-22 15:45:58 -08:00
Jesse Vincent
d92de28150 refactor: convert skills-core and plugin to pure ESM for module compatibility 2025-11-22 13:23:05 -08:00
Jesse Vincent
fa53c8f925 fix: use require inside plugin function to load commonjs module 2025-11-22 13:22:17 -08:00
Jesse Vincent
d3e89e8719 fix: convert opencode plugin to ES module syntax
- Replace CommonJS require() with ES import statements
- Use createRequire() for loading CommonJS skills-core module
- Export plugin as 'SuperpowersPlugin' named export
- Maintains compatibility with existing skills-core.js CommonJS module
2025-11-22 12:53:26 -08:00
Jesse Vincent
b746f7587b docs: fix plugin installation instructions for opencode 2025-11-22 12:50:43 -08:00
Jesse Vincent
4eab16380b refactor: extract frontmatter stripping to shared helper function 2025-11-22 12:41:58 -08:00
Jesse Vincent
7ffff61965 docs: add opencode support to release notes 2025-11-22 12:34:35 -08:00
Jesse Vincent
fbd419e394 docs: add opencode support to readme 2025-11-22 12:34:21 -08:00
Jesse Vincent
a131267d7c docs: add opencode installation guide 2025-11-22 12:34:06 -08:00
Jesse Vincent
26c152b37e feat: implement session.started hook for opencode 2025-11-22 12:31:23 -08:00
Jesse Vincent
6ae8ef4733 feat: implement find_skills tool for opencode 2025-11-22 12:30:48 -08:00
Jesse Vincent
1aa29ad52b feat: implement use_skill tool for opencode 2025-11-22 12:30:20 -08:00
Jesse Vincent
6847cf4cfc feat: create opencode plugin scaffold 2025-11-22 12:29:50 -08:00
Jesse Vincent
425b40359c refactor: remove unused whenToUse references from codex 2025-11-22 12:27:31 -08:00
Jesse Vincent
9e5ba91be6 refactor: use shared checkForUpdates in codex 2025-11-22 12:15:14 -08:00
Jesse Vincent
4abd4df171 refactor: use shared findSkillsInDir in codex 2025-11-22 12:12:59 -08:00
Jesse Vincent
5dd31b90ee refactor: use shared extractFrontmatter in codex 2025-11-22 12:12:01 -08:00
Jesse Vincent
0fbdfa3c4a refactor: import shared skills core in codex 2025-11-22 12:08:53 -08:00
Jesse Vincent
a23eead918 feat: add git update checking to core module 2025-11-22 12:06:53 -08:00
Jesse Vincent
4594596e38 feat: add skill path resolution with shadowing support 2025-11-22 12:04:42 -08:00
Jesse Vincent
536fd24603 feat: add skill discovery function to core module 2025-11-22 12:02:15 -08:00
Jesse Vincent
85effaaedb feat: create shared skills core module with frontmatter parser
Extract frontmatter parsing logic into lib/skills-core.js to enable
code reuse between Codex and OpenCode implementations.
2025-11-22 12:01:15 -08:00
Jesse Vincent
6cec629cf3 Remove unused initialize-skills.sh script
- Deleted lib/initialize-skills.sh (no longer called)
- Removed permission entry from .claude/settings.local.json
2025-11-22 11:36:28 -08:00
Jesse Vincent
5dd8871a1b Add OpenCode support design document
- Native OpenCode plugin approach using their JavaScript plugin system
- Shared core module (lib/skills-core.js) for code reuse with Codex
- Custom tools: use_skill and find_skills
- Session startup hook for automatic bootstrap
- Three-phase implementation plan
2025-11-22 11:36:28 -08:00
Jesse Vincent
84283dfc05 Update GitHub funding configuration 2025-11-21 16:46:32 -08:00
Jesse Vincent
d90334e030 Remove duplicate mis-placed "commands" - Fixes #112 2025-11-20 12:08:17 -06:00
Dave Seleno
9a9618489d fix: yaml error in code-reviewer agent (#115) 2025-11-20 10:03:56 -08:00
Roland Huß
02c87670de Update installation instructions for Claude Code (#90)
Refactor installation instructions for installing the plugin so that it can be easy copied & pasted to the CLI, as Claude code expects each command separately.
2025-11-06 12:44:59 -08:00
Jesse Vincent
b187e75a1e Bump version to 3.4.1 2025-10-31 11:16:48 -07:00
Jesse Vincent
8674dc0868 Optimize superpowers bootstrap to eliminate redundant skill execution
- Update session-start hook to clarify that using-superpowers content is provided directly
- Add explicit guidance to use Skill tool only for other skills
- Prevents confusing loop where agents execute using-superpowers manually
- Reduces overhead and improves user experience

Fixes redundant skill execution in bootstrap workflow.
2025-10-31 10:49:39 -07:00
Jesse Vincent
42d44ceaf9 Fix plugin manifest version to match 3.4.0 release
Update .claude-plugin/plugin.json version from 3.2.3 to 3.4.0 to match
the version already set in marketplace.json. This ensures consistency
across all plugin manifest files.
2025-10-31 09:58:07 -07:00
Jesse Vincent
d46dddd32c Bump plugin version to 3.4.0 2025-10-30 20:28:51 -07:00
Jesse Vincent
b1fa6a1a46 Update release notes for v3.4.0 brainstorming simplification 2025-10-30 20:25:45 -07:00
Jesse Vincent
8e38ab86dc Simplify brainstorming skill to match original vision
Remove heavyweight 6-phase process with formal checklists and return to
conversational approach:
- Natural dialogue instead of structured phases
- One question at a time without rigid progression
- 200-300 word design sections with validation
- Keep documentation and implementation handoff
- Remove AskUserQuestion tool requirements and complex flowcharts

This aligns with the original spec: help turn ideas into designs through
collaborative questioning, then present design in small sections.
2025-10-30 20:21:28 -07:00
Jesse Vincent
31fd764285 Update release notes for v3.3.1 writing improvements 2025-10-28 11:10:15 -07:00
Jesse Vincent
e3208f1d93 Apply writing clarity improvements to brainstorming skill
Applied Strunk's "Elements of Style" principles:
- Rule 13: Omitted needless words (removed "already", "genuinely", etc.)
- Rule 11: Converted negative to positive form ("don't ask" → "ask only when")
- Rule 10: Used active voice where appropriate
- Rule 15: Improved parallel construction in lists
- General: Made language more direct and concrete

Changes maintain the skill's functionality while improving readability.
2025-10-28 11:07:55 -07:00
Jesse Vincent
1d21ee842d Refine brainstorming skill for proactive research 2025-10-28 10:59:47 -07:00
Jesse Vincent
aa8c6b4fd0 Clarify personal skill directories for Codex 2025-10-28 10:46:05 -07:00
Jesse Vincent
22f57e7cb0 Improve README and add update checking to bootstrap
- Make README more egalitarian: 'AI coding assistants' vs 'Claude Code'
- Reorganize installation: 'Claude Code (via Plugin Marketplace)' and 'Codex (Experimental)'
- Add update checking to bootstrap with 3-second timeout protection
- Bootstrap now checks if local installation is behind GitHub and suggests 'git pull'
- Network failures or timeouts don't block bootstrap (graceful fallback)
2025-10-28 02:27:32 +00:00
Jesse Vincent
da9f4f1edd Release v3.3.0: Add experimental Codex support
- Restructured Codex files to .codex/ directory
- Updated README with simplified GitHub URL installation
- Added comprehensive release notes for v3.3.0
- Moved superpowers-codex script to .codex/superpowers-codex
- Updated all path references for new structure
- Installation now uses GitHub raw URL for streamlined setup

Codex support includes:
- Unified superpowers-codex script with bootstrap/use-skill/find-skills
- Cross-platform Node.js implementation
- Namespaced skills (superpowers:skill-name)
- Tool mapping (TodoWrite→update_plan, etc.)
- Clean skill display without frontmatter
- Personal skill override system
2025-10-28 02:15:53 +00:00
Jesse Vincent
5831c4dfea Fix AGENTS.md to be minimal one-liner + explanatory text
- AGENTS.md (in user's ~/.codex/) now just tells Codex to run bootstrap
- Bootstrap contains all the critical rules and skill locations
- Updated INSTALL.md to show the simplified AGENTS.md example
- Added explanatory text: 'Superpowers teach you new skills and capabilities'
2025-10-28 01:36:10 +00:00
Jesse Vincent
26487902f8 Add Codex superpowers integration
- Single unified script: superpowers-codex with bootstrap/use-skill/find-skills commands
- Cross-platform Node.js implementation (works on Windows, macOS, Linux)
- Namespaced skills: superpowers:skill-name for superpowers, skill-name for personal
- Personal skills override superpowers skills when names match
- Clean skill display: shows name/description without raw frontmatter
- Helpful context: shows supporting files directory for each skill
- Tool mapping for Codex: TodoWrite→update_plan, subagents→manual fallback, etc.
- Updated terminology: "Superpowers skills" instead of "Core skills"
- Bootstrap integration with AGENTS.md for automatic startup
- Installation guide and bootstrap instructions specific to Codex
2025-10-28 01:19:17 +00:00
Jesse Vincent
19e2997334 Release v3.2.3: Update using-superpowers to use Skill tool 2025-10-23 16:34:55 -07:00
Jesse Vincent
c88b0d674f Update using-superpowers skill to use Skill tool instead of Read tool
The Skill tool is the proper mechanism for invoking skills, not the Read tool.
Updated the bootstrap instructions and anti-rationalization guidance to reflect this.
2025-10-23 16:34:05 -07:00
Jesse Vincent
17bbc2b130 Release v3.2.2: Strengthen using-superpowers against agent rationalization 2025-10-21 20:12:56 -07:00
Jesse Vincent
f6ee98a41a Strengthen using-superpowers skill against agent rationalization
Add three layers of enforcement to prevent agents from skipping skill usage:

1. EXTREMELY-IMPORTANT block with absolute language
   - "If even 1% chance a skill applies, you MUST read it"
   - "You do not have a choice. You cannot rationalize your way out."

2. MANDATORY FIRST RESPONSE PROTOCOL checklist
   - 5-step process agents must complete before any response
   - Explicit "responding without this = failure" consequence

3. Common Rationalizations section with 8 specific patterns
   - "This is just a simple question" → WRONG
   - "I can check files quickly" → WRONG
   - "Let me gather information first" → WRONG
   - Plus 5 more common evasion patterns

These 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 rationalization harder.
2025-10-21 20:01:06 -07:00
Jesse Vincent
e3d881b7b6 Release v3.2.1: Add code-reviewer agent to plugin
Fixes #55

Added superpowers:code-reviewer agent to plugin's agents/ directory.
Previously, skills referenced a code-reviewer agent that users needed
to configure personally, causing failures for new users.

Changes:
- New: agents/code-reviewer.md - Agent definition with systematic review checklist
- Updated: skills/requesting-code-review/SKILL.md - Use superpowers:code-reviewer
- Updated: skills/subagent-driven-development/SKILL.md - Use superpowers:code-reviewer
- Version bump: 3.2.0 -> 3.2.1
- Added: .claude-plugin/marketplace.json for local development testing
2025-10-20 10:19:24 -07:00
Jesse Vincent
184a4c464e bump to 3.2.0 2025-10-20 08:42:32 -07:00
Jesse Vincent
7fc125e5e9 Update RELEASE-NOTES.md for v3.2.0 release 2025-10-18 10:41:29 -07:00
Jesse Vincent
79436abffa Update all superpowers skill references to use namespace prefix
Skills are now namespaced as superpowers:<name> when referenced.
Updated all REQUIRED SUB-SKILL, RECOMMENDED SUB-SKILL, and
REQUIRED BACKGROUND references to use the superpowers: prefix.

Also added -design suffix to brainstorming skill's design document
filename to distinguish from implementation plan documents.

Files updated:
- brainstorming: Added -design suffix, updated skill references
- executing-plans: Updated finishing-a-development-branch reference
- subagent-driven-development: Updated finishing-a-development-branch reference
- systematic-debugging: Updated root-cause-tracing and test-driven-development references
- testing-skills-with-subagents: Updated test-driven-development reference
- writing-plans: Updated executing-plans and subagent-driven-development references
- writing-skills: Updated test-driven-development, systematic-debugging, and testing-skills-with-subagents references
2025-10-18 10:38:54 -07:00
Jesse Vincent
9597f088c4 Add design documentation phase to brainstorming skill
The old brainstorming command included writing the design document
before handing off to implementation planning. This was lost when
the command was converted to a skill.

Added Phase 4: Design Documentation to write the validated design
to docs/plans/YYYY-MM-DD-<topic>.md before proceeding to worktree
setup and planning.

Tested with subagent to verify design document is written and
committed even under time pressure.
2025-10-18 10:19:14 -07:00
Jesse Vincent
7ce751294e Remove test design document 2025-10-18 10:18:57 -07:00
Jesse Vincent
1ef5758621 Add design document for format-on-save feature 2025-10-18 10:18:38 -07:00
Jesse Vincent
accb1231fc Fix command syntax in README to use namespaced format (#44)
Plugin-provided commands are automatically namespaced by Claude Code
to avoid conflicts. Updated all documentation to show correct syntax.

Changes:
- README.md: Updated all command examples to use /superpowers:* format
- plugin.json: Bump version to 3.1.1
- RELEASE-NOTES.md: Added v3.1.1 release entry

Fixes #44
2025-10-17 22:06:12 -07:00
Jesse Vincent
22ec50318e Update README for v3.0+ integrated skills architecture
Removed all references to the separate obra/superpowers-skills repository
and updated documentation to reflect that skills are now included directly
in the plugin using Claude Code's first-party skills system.

Changes:
- Removed outdated architecture section about repository separation
- Removed find-skills tool and SUPERPOWERS_SKILLS_ROOT references
- Removed git-based update and forking workflows
- Updated contributing section for direct repository contributions
- Updated skills list to match current plugin structure
- Simplified installation and update instructions
2025-10-17 18:50:12 -07:00
115 changed files with 12495 additions and 793 deletions

View File

@@ -0,0 +1,20 @@
{
"name": "superpowers-dev",
"description": "Development marketplace for Superpowers core skills library",
"owner": {
"name": "Jesse Vincent",
"email": "jesse@fsck.com"
},
"plugins": [
{
"name": "superpowers",
"description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques",
"version": "4.2.0",
"source": "./",
"author": {
"name": "Jesse Vincent",
"email": "jesse@fsck.com"
}
}
]
}

View File

@@ -1,7 +1,7 @@
{
"name": "superpowers",
"description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques",
"version": "3.0.1",
"version": "4.2.0",
"author": {
"name": "Jesse Vincent",
"email": "jesse@fsck.com"

67
.codex/INSTALL.md Normal file
View File

@@ -0,0 +1,67 @@
# Installing Superpowers for Codex
Enable superpowers skills in Codex via native skill discovery. Just clone and symlink.
## Prerequisites
- Git
## Installation
1. **Clone the superpowers repository:**
```bash
git clone https://github.com/obra/superpowers.git ~/.codex/superpowers
```
2. **Create the skills symlink:**
```bash
mkdir -p ~/.agents/skills
ln -s ~/.codex/superpowers/skills ~/.agents/skills/superpowers
```
**Windows (PowerShell):**
```powershell
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.agents\skills"
cmd /c mklink /J "$env:USERPROFILE\.agents\skills\superpowers" "$env:USERPROFILE\.codex\superpowers\skills"
```
3. **Restart Codex** (quit and relaunch the CLI) to discover the skills.
## Migrating from old bootstrap
If you installed superpowers before native skill discovery, you need to:
1. **Update the repo:**
```bash
cd ~/.codex/superpowers && git pull
```
2. **Create the skills symlink** (step 2 above) — this is the new discovery mechanism.
3. **Remove the old bootstrap block** from `~/.codex/AGENTS.md` — any block referencing `superpowers-codex bootstrap` is no longer needed.
4. **Restart Codex.**
## Verify
```bash
ls -la ~/.agents/skills/superpowers
```
You should see a symlink (or junction on Windows) pointing to your superpowers skills directory.
## Updating
```bash
cd ~/.codex/superpowers && git pull
```
Skills update instantly through the symlink.
## Uninstalling
```bash
rm ~/.agents/skills/superpowers
```
Optionally delete the clone: `rm -rf ~/.codex/superpowers`.

17
.gitattributes vendored Normal file
View File

@@ -0,0 +1,17 @@
# Ensure shell scripts always have LF line endings
*.sh text eol=lf
# Ensure the polyglot wrapper keeps LF (it's parsed by both cmd and bash)
*.cmd text eol=lf
# Common text files
*.md text eol=lf
*.json text eol=lf
*.js text eol=lf
*.mjs text eol=lf
*.ts text eol=lf
# Explicitly mark binary files
*.png binary
*.jpg binary
*.gif binary

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
# These are supported funding model platforms
github: [obra]

4
.gitignore vendored
View File

@@ -1,2 +1,6 @@
.worktrees/
.private-journal/
.claude/
node_modules/
inspo
triage/

119
.opencode/INSTALL.md Normal file
View File

@@ -0,0 +1,119 @@
# Installing Superpowers for OpenCode
## Prerequisites
- [OpenCode.ai](https://opencode.ai) installed
- Git installed
## Installation Steps
### 1. Clone Superpowers
```bash
git clone https://github.com/obra/superpowers.git ~/.config/opencode/superpowers
```
### 2. Register the Plugin
Create a symlink so OpenCode discovers the plugin:
```bash
mkdir -p ~/.config/opencode/plugins
rm -f ~/.config/opencode/plugins/superpowers.js
ln -s ~/.config/opencode/superpowers/.opencode/plugins/superpowers.js ~/.config/opencode/plugins/superpowers.js
```
### 3. Symlink Skills
Create a symlink so OpenCode's native skill tool discovers superpowers skills:
```bash
mkdir -p ~/.config/opencode/skills
rm -rf ~/.config/opencode/skills/superpowers
ln -s ~/.config/opencode/superpowers/skills ~/.config/opencode/skills/superpowers
```
### 4. Restart OpenCode
Restart OpenCode. The plugin will automatically inject superpowers context.
Verify by asking: "do you have superpowers?"
## Usage
### Finding Skills
Use OpenCode's native `skill` tool to list available skills:
```
use skill tool to list skills
```
### Loading a Skill
Use OpenCode's native `skill` tool to load a specific skill:
```
use skill tool to load superpowers/brainstorming
```
### Personal Skills
Create your own skills in `~/.config/opencode/skills/`:
```bash
mkdir -p ~/.config/opencode/skills/my-skill
```
Create `~/.config/opencode/skills/my-skill/SKILL.md`:
```markdown
---
name: my-skill
description: Use when [condition] - [what it does]
---
# My Skill
[Your skill content here]
```
### Project Skills
Create project-specific skills in `.opencode/skills/` within your project.
**Skill Priority:** Project skills > Personal skills > Superpowers skills
## Updating
```bash
cd ~/.config/opencode/superpowers
git pull
```
## Troubleshooting
### Plugin not loading
1. Check plugin symlink: `ls -l ~/.config/opencode/plugins/superpowers.js`
2. Check source exists: `ls ~/.config/opencode/superpowers/.opencode/plugins/superpowers.js`
3. Check OpenCode logs for errors
### Skills not found
1. Check skills symlink: `ls -l ~/.config/opencode/skills/superpowers`
2. Verify it points to: `~/.config/opencode/superpowers/skills`
3. Use `skill` tool to list what's discovered
### Tool mapping
When skills reference Claude Code tools:
- `TodoWrite``update_plan`
- `Task` with subagents → `@mention` syntax
- `Skill` tool → OpenCode's native `skill` tool
- File operations → your native tools
## Getting Help
- Report issues: https://github.com/obra/superpowers/issues
- Full documentation: https://github.com/obra/superpowers/blob/main/docs/README.opencode.md

View File

@@ -0,0 +1,95 @@
/**
* Superpowers plugin for OpenCode.ai
*
* Injects superpowers bootstrap context via system prompt transform.
* Skills are discovered via OpenCode's native skill tool from symlinked directory.
*/
import path from 'path';
import fs from 'fs';
import os from 'os';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Simple frontmatter extraction (avoid dependency on skills-core for bootstrap)
const extractAndStripFrontmatter = (content) => {
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
if (!match) return { frontmatter: {}, content };
const frontmatterStr = match[1];
const body = match[2];
const frontmatter = {};
for (const line of frontmatterStr.split('\n')) {
const colonIdx = line.indexOf(':');
if (colonIdx > 0) {
const key = line.slice(0, colonIdx).trim();
const value = line.slice(colonIdx + 1).trim().replace(/^["']|["']$/g, '');
frontmatter[key] = value;
}
}
return { frontmatter, content: body };
};
// Normalize a path: trim whitespace, expand ~, resolve to absolute
const normalizePath = (p, homeDir) => {
if (!p || typeof p !== 'string') return null;
let normalized = p.trim();
if (!normalized) return null;
if (normalized.startsWith('~/')) {
normalized = path.join(homeDir, normalized.slice(2));
} else if (normalized === '~') {
normalized = homeDir;
}
return path.resolve(normalized);
};
export const SuperpowersPlugin = async ({ client, directory }) => {
const homeDir = os.homedir();
const superpowersSkillsDir = path.resolve(__dirname, '../../skills');
const envConfigDir = normalizePath(process.env.OPENCODE_CONFIG_DIR, homeDir);
const configDir = envConfigDir || path.join(homeDir, '.config/opencode');
// Helper to generate bootstrap content
const getBootstrapContent = () => {
// Try to load using-superpowers skill
const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md');
if (!fs.existsSync(skillPath)) return null;
const fullContent = fs.readFileSync(skillPath, 'utf8');
const { content } = extractAndStripFrontmatter(fullContent);
const toolMapping = `**Tool Mapping for OpenCode:**
When skills reference tools you don't have, substitute OpenCode equivalents:
- \`TodoWrite\`\`update_plan\`
- \`Task\` tool with subagents → Use OpenCode's subagent system (@mention)
- \`Skill\` tool → OpenCode's native \`skill\` tool
- \`Read\`, \`Write\`, \`Edit\`, \`Bash\` → Your native tools
**Skills location:**
Superpowers skills are in \`${configDir}/skills/superpowers/\`
Use OpenCode's native \`skill\` tool to list and load skills.`;
return `<EXTREMELY_IMPORTANT>
You have superpowers.
**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.**
${content}
${toolMapping}
</EXTREMELY_IMPORTANT>`;
};
return {
// Use system prompt transform to inject bootstrap (fixes #226 agent reset bug)
'experimental.chat.system.transform': async (_input, output) => {
const bootstrap = getBootstrapContent();
if (bootstrap) {
(output.system ||= []).push(bootstrap);
}
}
};
};

205
README.md
View File

@@ -1,157 +1,114 @@
# Superpowers
Give Claude Code superpowers with a comprehensive skills library of proven techniques, patterns, and tools.
Superpowers 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.
## Architecture
## How it works
The superpowers plugin is a minimal shim that:
- Clones/updates the [superpowers-skills](https://github.com/obra/superpowers-skills) repository to `~/.config/superpowers/skills/`
- Registers hooks that load skills from the local repository
- Offers users the option to fork the skills repo for contributions
It 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.
All skills, scripts, and documentation live in the separate [superpowers-skills](https://github.com/obra/superpowers-skills) repository. Edit skills locally, commit changes, and contribute back via pull requests.
Once it's teased a spec out of the conversation, it shows it to you in chunks short enough to actually read and digest.
**Skills Repository:** https://github.com/obra/superpowers-skills
After 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.
## What You Get
Next 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.
- **Testing Skills** - TDD, async testing, anti-patterns
- **Debugging Skills** - Systematic debugging, root cause tracing, verification
- **Collaboration Skills** - Brainstorming, planning, code review, parallel agents
- **Meta Skills** - Creating, testing, and contributing skills
There'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.
Plus:
- **Slash Commands** - `/brainstorm`, `/write-plan`, `/execute-plan`
- **Skills Search** - Grep-powered discovery of relevant skills
- **Gap Tracking** - Failed searches logged for skill creation
## Learn More
## Sponsorship
If 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).
Thanks!
- Jesse
Read the introduction: [Superpowers for Claude Code](https://blog.fsck.com/2025/10/09/superpowers/)
## Installation
### Via Plugin Marketplace (Recommended)
**Note:** Installation differs by platform. Claude Code has a built-in plugin system. Codex and OpenCode require manual setup.
### Claude Code (via Plugin Marketplace)
In Claude Code, register the marketplace first:
```bash
# In Claude Code
/plugin marketplace add obra/superpowers-marketplace
```
Then install the plugin from this marketplace:
```bash
/plugin install superpowers@superpowers-marketplace
```
The plugin automatically handles skills repository setup on first run.
### Verify Installation
```bash
# Check that commands appear
/help
Start a new session and ask Claude to help with something that would trigger a skill (e.g., "help me plan this feature" or "let's debug this issue"). Claude should automatically invoke the relevant superpowers skill.
# Should see:
# /brainstorm - Interactive design refinement
# /write-plan - Create implementation plan
# /execute-plan - Execute plan in batches
### Codex
Tell Codex:
```
Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.codex/INSTALL.md
```
## Updating Skills
**Detailed docs:** [docs/README.codex.md](docs/README.codex.md)
The plugin fetches and fast-forwards your local skills repository on each session start. If your local branch has diverged, Claude notifies you to use the pulling-updates-from-skills-repository skill.
### OpenCode
## Contributing Skills
Tell OpenCode:
If you forked the skills repository during setup, you can contribute improvements:
1. Edit skills in `~/.config/superpowers/skills/`
2. Commit your changes
3. Push to your fork
4. Open a PR to `obra/superpowers-skills`
## Quick Start
### Finding Skills
Find skills before starting any task:
```bash
${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/find-skills # All skills with descriptions
${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/find-skills test # Filter by pattern
${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/find-skills 'TDD|debug' # Regex pattern
```
Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.opencode/INSTALL.md
```
### Using Slash Commands
**Detailed docs:** [docs/README.opencode.md](docs/README.opencode.md)
**Brainstorm a design:**
```
/brainstorm
```
## The Basic Workflow
**Create an implementation plan:**
```
/write-plan
```
1. **brainstorming** - Activates before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. Saves design document.
**Execute the plan:**
```
/execute-plan
```
2. **using-git-worktrees** - Activates after design approval. Creates isolated workspace on new branch, runs project setup, verifies clean test baseline.
3. **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.
4. **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.
5. **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.
6. **requesting-code-review** - Activates between tasks. Reviews against plan, reports issues by severity. Critical issues block progress.
7. **finishing-a-development-branch** - Activates when tasks complete. Verifies tests, presents options (merge/PR/keep/discard), cleans up worktree.
**The agent checks for relevant skills before any task.** Mandatory workflows, not suggestions.
## What's Inside
### Skills Library
**Testing** (`skills/testing/`)
- test-driven-development - RED-GREEN-REFACTOR cycle
- condition-based-waiting - Async test patterns
- testing-anti-patterns - Common pitfalls to avoid
**Testing**
- **test-driven-development** - RED-GREEN-REFACTOR cycle (includes testing anti-patterns reference)
**Debugging** (`skills/debugging/`)
- systematic-debugging - 4-phase root cause process
- root-cause-tracing - Find the real problem
- verification-before-completion - Ensure it's actually fixed
- defense-in-depth - Multiple validation layers
**Debugging**
- **systematic-debugging** - 4-phase root cause process (includes root-cause-tracing, defense-in-depth, condition-based-waiting techniques)
- **verification-before-completion** - Ensure it's actually fixed
**Collaboration** (`skills/collaboration/`)
- brainstorming - Socratic design refinement
- writing-plans - Detailed implementation plans
- executing-plans - Batch execution with checkpoints
- dispatching-parallel-agents - Concurrent subagent workflows
- remembering-conversations - Search past work
- using-git-worktrees - Parallel development branches
- requesting-code-review - Pre-review checklist
- receiving-code-review - Responding to feedback
**Collaboration**
- **brainstorming** - Socratic design refinement
- **writing-plans** - Detailed implementation plans
- **executing-plans** - Batch execution with checkpoints
- **dispatching-parallel-agents** - Concurrent subagent workflows
- **requesting-code-review** - Pre-review checklist
- **receiving-code-review** - Responding to feedback
- **using-git-worktrees** - Parallel development branches
- **finishing-a-development-branch** - Merge/PR decision workflow
- **subagent-driven-development** - Fast iteration with two-stage review (spec compliance, then code quality)
**Meta** (`skills/meta/`)
- writing-skills - TDD for documentation, create new skills
- sharing-skills - Contribute skills back via branch and PR
- testing-skills-with-subagents - Validate skill quality
- pulling-updates-from-skills-repository - Sync with upstream
- gardening-skills-wiki - Maintain and improve skills
### Commands
- **brainstorm.md** - Interactive design refinement using Socratic method
- **write-plan.md** - Create detailed implementation plans
- **execute-plan.md** - Execute plans in batches with review checkpoints
### Tools
- **find-skills** - Unified skill discovery with descriptions
- **skill-run** - Generic runner for any skill script
- **search-conversations** - Semantic search of past Claude sessions (in remembering-conversations skill)
**Using tools:**
```bash
${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/find-skills # Show all skills
${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/find-skills pattern # Search skills
${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/skill-run <path> [args] # Run any skill script
```
## How It Works
1. **SessionStart Hook** - Clone/update skills repo, inject skills context
2. **Skills Discovery** - `find-skills` shows all available skills with descriptions
3. **Mandatory Workflow** - Skills become required when they exist for your task
4. **Gap Tracking** - Failed searches logged for skill development
**Meta**
- **writing-skills** - Create new skills following best practices (includes testing methodology)
- **using-superpowers** - Introduction to the skills system
## Philosophy
@@ -159,7 +116,27 @@ ${SUPERPOWERS_SKILLS_ROOT}/skills/using-skills/skill-run <path> [args] # Run an
- **Systematic over ad-hoc** - Process over guessing
- **Complexity reduction** - Simplicity as primary goal
- **Evidence over claims** - Verify before declaring success
- **Domain over implementation** - Work at problem level, not solution level
Read more: [Superpowers for Claude Code](https://blog.fsck.com/2025/10/09/superpowers/)
## Contributing
Skills live directly in this repository. To contribute:
1. Fork the repository
2. Create a branch for your skill
3. Follow the `writing-skills` skill for creating and testing new skills
4. Submit a PR
See `skills/writing-skills/SKILL.md` for the complete guide.
## Updating
Skills update automatically when you update the plugin:
```bash
/plugin update superpowers
```
## License

View File

@@ -1,5 +1,533 @@
# Superpowers Release Notes
## Unreleased
### Breaking Changes
**Specs and plans directory restructured**
- Specs (brainstorming output) now go to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`
- Plans (writing-plans output) now go to `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
- User preferences for spec/plan locations override these defaults
- Migration: move existing files from `docs/plans/` to new locations if desired
**Brainstorming → writing-plans transition enforced**
- After design approval, brainstorming now requires using writing-plans skill
- Platform planning features (e.g., EnterPlanMode) should not be used
- Direct implementation without writing-plans is not allowed
**Subagent-driven development now mandatory on capable harnesses**
- On harnesses with subagent support (Claude Code), subagent-driven-development is now required after plan approval
- No longer offers a choice between subagent-driven and executing-plans
- Executing-plans is only used on harnesses without subagent capability
**OpenCode: Switched to native skills system**
Superpowers 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.
**Migration required:** Skills must be symlinked to `~/.config/opencode/skills/superpowers/` (see updated installation docs).
### Fixes
**OpenCode: Fixed agent reset on session start (#226)**
The 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.
**OpenCode: Fixed Windows installation (#232)**
- Removed dependency on `skills-core.js` (eliminates broken relative imports when file is copied instead of symlinked)
- Added comprehensive Windows installation docs for cmd.exe, PowerShell, and Git Bash
- Documented proper symlink vs junction usage for each platform
### New Features
**Visual companion for brainstorming skill**
Added optional browser-based visual companion for brainstorming sessions. When users have a browser available, brainstorming can display interactive screens showing current phase, questions, and design decisions in a more readable format than terminal output.
Components:
- `lib/brainstorm-server/` - WebSocket server for real-time updates
- `skills/brainstorming/visual-companion.md` - Integration guide
- Helper scripts for session management with proper isolation
- Browser helper library for event capture
The visual companion is opt-in and falls back gracefully to terminal-only operation.
### Bug Fixes
**Fixed Windows hook execution for Claude Code 2.1.x**
Claude 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.
Fix: 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).
**Brainstorming visual companion: reduced token cost and improved persistence**
The visual companion now generates much smaller HTML per screen. The server automatically wraps bare content fragments in the frame template (header, CSS theme, feedback footer, interactive JS), so Claude writes only the content portion (~30 lines instead of ~260). Full HTML documents are still served as-is when Claude needs complete control.
Other improvements:
- `toggleSelect`/`send`/`selectedChoice` moved from inline template script to `helper.js` (auto-injected)
- `start-server.sh --project-dir` persists mockups under `.superpowers/brainstorm/` instead of `/tmp`
- `stop-server.sh` only deletes ephemeral `/tmp` sessions, preserving persistent ones
- Dark mode fix: `sendToClaude` confirmation page now uses CSS variables instead of hardcoded colors
- Skill restructured: SKILL.md is minimal (prompt + pointer); all visual companion details in progressive disclosure doc (`visual-companion.md`)
- Prompt to user now notes the feature is new, token-intensive, and can be slow
- Deleted redundant `CLAUDE-INSTRUCTIONS.md` (content folded into `visual-companion.md`)
- Test fixes: correct env var (`BRAINSTORM_DIR`), polling-based startup wait, new tests for frame wrapping
### Improvements
**Instruction priority clarified in using-superpowers**
Added explicit instruction priority hierarchy to prevent conflicts with user preferences:
1. User's explicit instructions (CLAUDE.md, direct requests) — highest priority
2. Superpowers skills — override default system behavior where they conflict
3. Default system prompt — lowest priority
This ensures users remain in control. If CLAUDE.md says "don't use TDD" and a skill says "always use TDD," CLAUDE.md wins.
## v4.2.0 (2026-02-05)
### Breaking Changes
**Codex: Replaced bootstrap CLI with native skill discovery**
The `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.
Installation is now just clone + symlink (documented in INSTALL.md). No Node.js dependency required. The old `~/.codex/skills/` path is deprecated.
### Fixes
**Windows: Fixed Claude Code 2.1.x hook execution (#331)**
Claude 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.
Fix: 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).
**Windows: SessionStart hook runs async to prevent terminal freeze (#404, #413, #414, #419)**
The 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.
**Windows: Fixed O(n^2) `escape_for_json` performance**
The 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.
**Codex: Fixed Windows/PowerShell invocation (#285, #243)**
- Windows doesn't respect shebangs, so directly invoking the extensionless `superpowers-codex` script triggered an "Open with" dialog. All invocations now prefixed with `node`.
- 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.
**Codex: Fixed path resolution in installer**
Used `fileURLToPath()` instead of manual URL pathname parsing to correctly handle paths with spaces and special characters on all platforms.
**Codex: Fixed stale skills path in writing-skills**
Updated `~/.codex/skills/` reference (deprecated) to `~/.agents/skills/` for native discovery.
### Improvements
**Worktree isolation now required before implementation**
Added `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.
**Main branch protection softened to require explicit consent**
Instead 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.
**Simplified installation verification**
Removed `/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.
**Codex: Clarified subagent tool mapping in bootstrap**
Improved documentation of how Codex tools map to Claude Code equivalents for subagent workflows.
### Tests
- Added worktree requirement test for subagent-driven-development
- Added main branch red flag warning test
- Fixed case sensitivity in skill recognition test assertions
---
## v4.1.1 (2026-01-23)
### Fixes
**OpenCode: Standardized on `plugins/` directory per official docs (#343)**
OpenCode'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.
Changes:
- Renamed `.opencode/plugin/` to `.opencode/plugins/` in repo structure
- Updated all installation docs (INSTALL.md, README.opencode.md) across all platforms
- Updated test scripts to match
**OpenCode: Fixed symlink instructions (#339, #342)**
- Added explicit `rm` before `ln -s` (fixes "file already exists" errors on reinstall)
- Added missing skills symlink step that was absent from INSTALL.md
- Updated from deprecated `use_skill`/`find_skills` to native `skill` tool references
---
## v4.1.0 (2026-01-23)
### Breaking Changes
**OpenCode: Switched to native skills system**
Superpowers 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.
**Migration required:** Skills must be symlinked to `~/.config/opencode/skills/superpowers/` (see updated installation docs).
### Fixes
**OpenCode: Fixed agent reset on session start (#226)**
The 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.
**OpenCode: Fixed Windows installation (#232)**
- Removed dependency on `skills-core.js` (eliminates broken relative imports when file is copied instead of symlinked)
- Added comprehensive Windows installation docs for cmd.exe, PowerShell, and Git Bash
- Documented proper symlink vs junction usage for each platform
**Claude Code: Fixed Windows hook execution for Claude Code 2.1.x**
Claude 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.
Fix: 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).
---
## v4.0.3 (2025-12-26)
### Improvements
**Strengthened using-superpowers skill for explicit skill requests**
Addressed 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.
Changes:
- Updated "The Rule" to say "Invoke relevant or requested skills" instead of "Check for skills" - emphasizing active invocation over passive checking
- Added "BEFORE any response or action" - the original wording only mentioned "response" but Claude would sometimes take action without responding first
- Added reassurance that invoking a wrong skill is okay - reduces hesitation
- Added new red flag: "I know what that means" → Knowing the concept ≠ using the skill
**Added explicit skill request tests**
New 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.
## v4.0.2 (2025-12-23)
### Fixes
**Slash commands now user-only**
Added `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.
The 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.
## v4.0.1 (2025-12-23)
### Fixes
**Clarified how to access skills in Claude Code**
Fixed 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.
- Added "How to Access Skills" section to `using-superpowers`
- Changed "read the skill" → "invoke the skill" in instructions
- Updated slash commands to use fully qualified skill names (e.g., `superpowers:brainstorming`)
**Added GitHub thread reply guidance to receiving-code-review** (h/t @ralphbean)
Added a note about replying to inline review comments in the original thread rather than as top-level PR comments.
**Added automation-over-documentation guidance to writing-skills** (h/t @EthanJStark)
Added guidance that mechanical constraints should be automated, not documented—save skills for judgment calls.
## v4.0.0 (2025-12-17)
### New Features
**Two-stage code review in subagent-driven-development**
Subagent workflows now use two separate review stages after each task:
1. **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.
2. **Code quality review** - Only runs after spec compliance passes. Reviews for clean code, test coverage, maintainability.
This 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.
Other subagent workflow improvements:
- Controller provides full task text to workers (not file references)
- Workers can ask clarifying questions before AND during work
- Self-review checklist before reporting completion
- Plan read once at start, extracted to TodoWrite
New prompt templates in `skills/subagent-driven-development/`:
- `implementer-prompt.md` - Includes self-review checklist, encourages questions
- `spec-reviewer-prompt.md` - Skeptical verification against requirements
- `code-quality-reviewer-prompt.md` - Standard code review
**Debugging techniques consolidated with tools**
`systematic-debugging` now bundles supporting techniques and tools:
- `root-cause-tracing.md` - Trace bugs backward through call stack
- `defense-in-depth.md` - Add validation at multiple layers
- `condition-based-waiting.md` - Replace arbitrary timeouts with condition polling
- `find-polluter.sh` - Bisection script to find which test creates pollution
- `condition-based-waiting-example.ts` - Complete implementation from real debugging session
**Testing anti-patterns reference**
`test-driven-development` now includes `testing-anti-patterns.md` covering:
- Testing mock behavior instead of real behavior
- Adding test-only methods to production classes
- Mocking without understanding dependencies
- Incomplete mocks that hide structural assumptions
**Skill test infrastructure**
Three new test frameworks for validating skill behavior:
`tests/skill-triggering/` - Validates skills trigger from naive prompts without explicit naming. Tests 6 skills to ensure descriptions alone are sufficient.
`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.
`tests/subagent-driven-dev/` - End-to-end workflow validation with two complete test projects:
- `go-fractals/` - CLI tool with Sierpinski/Mandelbrot (10 tasks)
- `svelte-todo/` - CRUD app with localStorage and Playwright (12 tasks)
### Major Changes
**DOT flowcharts as executable specifications**
Rewrote key skills using DOT/GraphViz flowcharts as the authoritative process definition. Prose becomes supporting content.
**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.
**Skill priority in using-superpowers**
When multiple skills apply, process skills (brainstorming, debugging) now explicitly come before implementation skills. "Build X" triggers brainstorming first, then domain skills.
**brainstorming trigger strengthened**
Description changed to imperative: "You MUST use this before any creative work—creating features, building components, adding functionality, or modifying behavior."
### Breaking Changes
**Skill consolidation** - Six standalone skills merged:
- `root-cause-tracing`, `defense-in-depth`, `condition-based-waiting` → bundled in `systematic-debugging/`
- `testing-skills-with-subagents` → bundled in `writing-skills/`
- `testing-anti-patterns` → bundled in `test-driven-development/`
- `sharing-skills` removed (obsolete)
### Other Improvements
- **render-graphs.js** - Tool to extract DOT diagrams from skills and render to SVG
- **Rationalizations table** in using-superpowers - Scannable format including new entries: "I need more context first", "Let me explore first", "This feels productive"
- **docs/testing.md** - Guide to testing skills with Claude Code integration tests
---
## v3.6.2 (2025-12-03)
### Fixed
- **Linux Compatibility**: Fixed polyglot hook wrapper (`run-hook.cmd`) to use POSIX-compliant syntax
- Replaced bash-specific `${BASH_SOURCE[0]:-$0}` with standard `$0` on line 16
- Resolves "Bad substitution" error on Ubuntu/Debian systems where `/bin/sh` is dash
- Fixes #141
---
## v3.5.1 (2025-11-24)
### Changed
- **OpenCode Bootstrap Refactor**: Switched from `chat.message` hook to `session.created` event for bootstrap injection
- Bootstrap now injects at session creation via `session.prompt()` with `noReply: true`
- Explicitly tells the model that using-superpowers is already loaded to prevent redundant skill loading
- Consolidated bootstrap content generation into shared `getBootstrapContent()` helper
- Cleaner single-implementation approach (removed fallback pattern)
---
## v3.5.0 (2025-11-23)
### Added
- **OpenCode Support**: Native JavaScript plugin for OpenCode.ai
- Custom tools: `use_skill` and `find_skills`
- Message insertion pattern for skill persistence across context compaction
- Automatic context injection via chat.message hook
- Auto re-injection on session.compacted events
- Three-tier skill priority: project > personal > superpowers
- Project-local skills support (`.opencode/skills/`)
- Shared core module (`lib/skills-core.js`) for code reuse with Codex
- Automated test suite with proper isolation (`tests/opencode/`)
- Platform-specific documentation (`docs/README.opencode.md`, `docs/README.codex.md`)
### Changed
- **Refactored Codex Implementation**: Now uses shared `lib/skills-core.js` ES module
- Eliminates code duplication between Codex and OpenCode
- Single source of truth for skill discovery and parsing
- Codex successfully loads ES modules via Node.js interop
- **Improved Documentation**: Rewrote README to explain problem/solution clearly
- Removed duplicate sections and conflicting information
- Added complete workflow description (brainstorm → plan → execute → finish)
- Simplified platform installation instructions
- Emphasized skill-checking protocol over automatic activation claims
---
## v3.4.1 (2025-10-31)
### Improvements
- 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.
## v3.4.0 (2025-10-30)
### Improvements
- 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.
## v3.3.1 (2025-10-28)
### Improvements
- Updated `brainstorming` skill to require autonomous recon before questioning, encourage recommendation-driven decisions, and prevent agents from delegating prioritization back to humans.
- 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).
### Bug Fixes
- Clarified `writing-skills` guidance so it points to the correct agent-specific personal skill directories (`~/.claude/skills` for Claude Code, `~/.codex/skills` for Codex).
## v3.3.0 (2025-10-28)
### New Features
**Experimental Codex Support**
- Added unified `superpowers-codex` script with bootstrap/use-skill/find-skills commands
- Cross-platform Node.js implementation (works on Windows, macOS, Linux)
- Namespaced skills: `superpowers:skill-name` for superpowers skills, `skill-name` for personal
- Personal skills override superpowers skills when names match
- Clean skill display: shows name/description without raw frontmatter
- Helpful context: shows supporting files directory for each skill
- Tool mapping for Codex: TodoWrite→update_plan, subagents→manual fallback, etc.
- Bootstrap integration with minimal AGENTS.md for automatic startup
- Complete installation guide and bootstrap instructions specific to Codex
**Key differences from Claude Code integration:**
- Single unified script instead of separate tools
- Tool substitution system for Codex-specific equivalents
- Simplified subagent handling (manual work instead of delegation)
- Updated terminology: "Superpowers skills" instead of "Core skills"
### Files Added
- `.codex/INSTALL.md` - Installation guide for Codex users
- `.codex/superpowers-bootstrap.md` - Bootstrap instructions with Codex adaptations
- `.codex/superpowers-codex` - Unified Node.js executable with all functionality
**Note:** Codex support is experimental. The integration provides core superpowers functionality but may require refinement based on user feedback.
## v3.2.3 (2025-10-23)
### Improvements
**Updated using-superpowers skill to use Skill tool instead of Read tool**
- Changed skill invocation instructions from Read tool to Skill tool
- Updated description: "using Read tool" → "using Skill tool"
- Updated step 3: "Use the Read tool" → "Use the Skill tool to read and run"
- Updated rationalization list: "Read the current version" → "Run the current version"
The 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.
### Files Changed
- Updated: `skills/using-superpowers/SKILL.md` - Changed tool references from Read to Skill
## v3.2.2 (2025-10-21)
### Improvements
**Strengthened using-superpowers skill against agent rationalization**
- Added EXTREMELY-IMPORTANT block with absolute language about mandatory skill checking
- "If even 1% chance a skill applies, you MUST read it"
- "You do not have a choice. You cannot rationalize your way out."
- Added MANDATORY FIRST RESPONSE PROTOCOL checklist
- 5-step process agents must complete before any response
- Explicit "responding without this = failure" consequence
- Added Common Rationalizations section with 8 specific evasion patterns
- "This is just a simple question" → WRONG
- "I can check files quickly" → WRONG
- "Let me gather information first" → WRONG
- Plus 5 more common patterns observed in agent behavior
These 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.
### Files Changed
- Updated: `skills/using-superpowers/SKILL.md` - Added three layers of enforcement to prevent skill-skipping rationalization
## v3.2.1 (2025-10-20)
### New Features
**Code reviewer agent now included in plugin**
- Added `superpowers:code-reviewer` agent to plugin's `agents/` directory
- Agent provides systematic code review against plans and coding standards
- Previously required users to have personal agent configuration
- All skill references updated to use namespaced `superpowers:code-reviewer`
- Fixes #55
### Files Changed
- New: `agents/code-reviewer.md` - Agent definition with review checklist and output format
- Updated: `skills/requesting-code-review/SKILL.md` - References to `superpowers:code-reviewer`
- Updated: `skills/subagent-driven-development/SKILL.md` - References to `superpowers:code-reviewer`
## v3.2.0 (2025-10-18)
### New Features
**Design documentation in brainstorming workflow**
- Added Phase 4: Design Documentation to brainstorming skill
- Design documents now written to `docs/plans/YYYY-MM-DD-<topic>-design.md` before implementation
- Restores functionality from original brainstorming command that was lost during skill conversion
- Documents written before worktree setup and implementation planning
- Tested with subagent to verify compliance under time pressure
### Breaking Changes
**Skill reference namespace standardization**
- All internal skill references now use `superpowers:` namespace prefix
- Updated format: `superpowers:test-driven-development` (previously just `test-driven-development`)
- Affects all REQUIRED SUB-SKILL, RECOMMENDED SUB-SKILL, and REQUIRED BACKGROUND references
- Aligns with how skills are invoked using the Skill tool
- Files updated: brainstorming, executing-plans, subagent-driven-development, systematic-debugging, testing-skills-with-subagents, writing-plans, writing-skills
### Improvements
**Design vs implementation plan naming**
- Design documents use `-design.md` suffix to prevent filename collisions
- Implementation plans continue using existing `YYYY-MM-DD-<feature-name>.md` format
- Both stored in `docs/plans/` directory with clear naming distinction
## v3.1.1 (2025-10-17)
### Bug Fixes
- **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.
## v3.1.0 (2025-10-17)

48
agents/code-reviewer.md Normal file
View File

@@ -0,0 +1,48 @@
---
name: code-reviewer
description: |
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>
model: inherit
---
You 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.
When reviewing completed work, you will:
1. **Plan Alignment Analysis**:
- Compare the implementation against the original planning document or step description
- Identify any deviations from the planned approach, architecture, or requirements
- Assess whether deviations are justified improvements or problematic departures
- Verify that all planned functionality has been implemented
2. **Code Quality Assessment**:
- Review code for adherence to established patterns and conventions
- Check for proper error handling, type safety, and defensive programming
- Evaluate code organization, naming conventions, and maintainability
- Assess test coverage and quality of test implementations
- Look for potential security vulnerabilities or performance issues
3. **Architecture and Design Review**:
- Ensure the implementation follows SOLID principles and established architectural patterns
- Check for proper separation of concerns and loose coupling
- Verify that the code integrates well with existing systems
- Assess scalability and extensibility considerations
4. **Documentation and Standards**:
- Verify that code includes appropriate comments and documentation
- Check that file headers, function documentation, and inline comments are present and accurate
- Ensure adherence to project-specific coding standards and conventions
5. **Issue Identification and Recommendations**:
- Clearly categorize issues as: Critical (must fix), Important (should fix), or Suggestions (nice to have)
- For each issue, provide specific examples and actionable recommendations
- When you identify plan deviations, explain whether they're problematic or beneficial
- Suggest specific improvements with code examples when helpful
6. **Communication Protocol**:
- If you find significant deviations from the plan, ask the coding agent to review and confirm the changes
- If you identify issues with the original plan itself, recommend plan updates
- For implementation problems, provide clear guidance on fixes needed
- Always acknowledge what was done well before highlighting issues
Your 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.

View File

@@ -1,5 +1,6 @@
---
description: Interactive design refinement using Socratic method
description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores requirements and design before implementation."
disable-model-invocation: true
---
Use and follow the brainstorming skill exactly as written
Invoke the superpowers:brainstorming skill and follow it exactly as presented to you

View File

@@ -1,5 +1,6 @@
---
description: Execute plan in batches with review checkpoints
disable-model-invocation: true
---
Use the executing-plans skill exactly as written
Invoke the superpowers:executing-plans skill and follow it exactly as presented to you

View File

@@ -1,5 +1,6 @@
---
description: Create detailed implementation plan with bite-sized tasks
disable-model-invocation: true
---
Use the writing-plans skill exactly as written
Invoke the superpowers:writing-plans skill and follow it exactly as presented to you

120
docs/README.codex.md Normal file
View File

@@ -0,0 +1,120 @@
# Superpowers for Codex
Guide for using Superpowers with OpenAI Codex via native skill discovery.
## Quick Install
Tell Codex:
```
Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.codex/INSTALL.md
```
## Manual Installation
### Prerequisites
- OpenAI Codex CLI
- Git
### Steps
1. Clone the repo:
```bash
git clone https://github.com/obra/superpowers.git ~/.codex/superpowers
```
2. Create the skills symlink:
```bash
mkdir -p ~/.agents/skills
ln -s ~/.codex/superpowers/skills ~/.agents/skills/superpowers
```
3. Restart Codex.
### Windows
Use a junction instead of a symlink (works without Developer Mode):
```powershell
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.agents\skills"
cmd /c mklink /J "$env:USERPROFILE\.agents\skills\superpowers" "$env:USERPROFILE\.codex\superpowers\skills"
```
## How It Works
Codex 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:
```
~/.agents/skills/superpowers/ → ~/.codex/superpowers/skills/
```
The `using-superpowers` skill is discovered automatically and enforces skill usage discipline — no additional configuration needed.
## Usage
Skills are discovered automatically. Codex activates them when:
- You mention a skill by name (e.g., "use brainstorming")
- The task matches a skill's description
- The `using-superpowers` skill directs Codex to use one
### Personal Skills
Create your own skills in `~/.agents/skills/`:
```bash
mkdir -p ~/.agents/skills/my-skill
```
Create `~/.agents/skills/my-skill/SKILL.md`:
```markdown
---
name: my-skill
description: Use when [condition] - [what it does]
---
# My Skill
[Your skill content here]
```
The `description` field is how Codex decides when to activate a skill automatically — write it as a clear trigger condition.
## Updating
```bash
cd ~/.codex/superpowers && git pull
```
Skills update instantly through the symlink.
## Uninstalling
```bash
rm ~/.agents/skills/superpowers
```
**Windows (PowerShell):**
```powershell
Remove-Item "$env:USERPROFILE\.agents\skills\superpowers"
```
Optionally delete the clone: `rm -rf ~/.codex/superpowers` (Windows: `Remove-Item -Recurse -Force "$env:USERPROFILE\.codex\superpowers"`).
## Troubleshooting
### Skills not showing up
1. Verify the symlink: `ls -la ~/.agents/skills/superpowers`
2. Check skills exist: `ls ~/.codex/superpowers/skills`
3. Restart Codex — skills are discovered at startup
### Windows junction issues
Junctions normally work without special permissions. If creation fails, try running PowerShell as administrator.
## Getting Help
- Report issues: https://github.com/obra/superpowers/issues
- Main documentation: https://github.com/obra/superpowers

330
docs/README.opencode.md Normal file
View File

@@ -0,0 +1,330 @@
# Superpowers for OpenCode
Complete guide for using Superpowers with [OpenCode.ai](https://opencode.ai).
## Quick Install
Tell OpenCode:
```
Clone https://github.com/obra/superpowers to ~/.config/opencode/superpowers, then create directory ~/.config/opencode/plugins, then symlink ~/.config/opencode/superpowers/.opencode/plugins/superpowers.js to ~/.config/opencode/plugins/superpowers.js, then symlink ~/.config/opencode/superpowers/skills to ~/.config/opencode/skills/superpowers, then restart opencode.
```
## Manual Installation
### Prerequisites
- [OpenCode.ai](https://opencode.ai) installed
- Git installed
### macOS / Linux
```bash
# 1. Install Superpowers (or update existing)
if [ -d ~/.config/opencode/superpowers ]; then
cd ~/.config/opencode/superpowers && git pull
else
git clone https://github.com/obra/superpowers.git ~/.config/opencode/superpowers
fi
# 2. Create directories
mkdir -p ~/.config/opencode/plugins ~/.config/opencode/skills
# 3. Remove old symlinks/directories if they exist
rm -f ~/.config/opencode/plugins/superpowers.js
rm -rf ~/.config/opencode/skills/superpowers
# 4. Create symlinks
ln -s ~/.config/opencode/superpowers/.opencode/plugins/superpowers.js ~/.config/opencode/plugins/superpowers.js
ln -s ~/.config/opencode/superpowers/skills ~/.config/opencode/skills/superpowers
# 5. Restart OpenCode
```
#### Verify Installation
```bash
ls -l ~/.config/opencode/plugins/superpowers.js
ls -l ~/.config/opencode/skills/superpowers
```
Both should show symlinks pointing to the superpowers directory.
### Windows
**Prerequisites:**
- Git installed
- Either **Developer Mode** enabled OR **Administrator privileges**
- Windows 10: Settings → Update & Security → For developers
- Windows 11: Settings → System → For developers
Pick your shell below: [Command Prompt](#command-prompt) | [PowerShell](#powershell) | [Git Bash](#git-bash)
#### Command Prompt
Run as Administrator, or with Developer Mode enabled:
```cmd
:: 1. Install Superpowers
git clone https://github.com/obra/superpowers.git "%USERPROFILE%\.config\opencode\superpowers"
:: 2. Create directories
mkdir "%USERPROFILE%\.config\opencode\plugins" 2>nul
mkdir "%USERPROFILE%\.config\opencode\skills" 2>nul
:: 3. Remove existing links (safe for reinstalls)
del "%USERPROFILE%\.config\opencode\plugins\superpowers.js" 2>nul
rmdir "%USERPROFILE%\.config\opencode\skills\superpowers" 2>nul
:: 4. Create plugin symlink (requires Developer Mode or Admin)
mklink "%USERPROFILE%\.config\opencode\plugins\superpowers.js" "%USERPROFILE%\.config\opencode\superpowers\.opencode\plugins\superpowers.js"
:: 5. Create skills junction (works without special privileges)
mklink /J "%USERPROFILE%\.config\opencode\skills\superpowers" "%USERPROFILE%\.config\opencode\superpowers\skills"
:: 6. Restart OpenCode
```
#### PowerShell
Run as Administrator, or with Developer Mode enabled:
```powershell
# 1. Install Superpowers
git clone https://github.com/obra/superpowers.git "$env:USERPROFILE\.config\opencode\superpowers"
# 2. Create directories
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.config\opencode\plugins"
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.config\opencode\skills"
# 3. Remove existing links (safe for reinstalls)
Remove-Item "$env:USERPROFILE\.config\opencode\plugins\superpowers.js" -Force -ErrorAction SilentlyContinue
Remove-Item "$env:USERPROFILE\.config\opencode\skills\superpowers" -Force -ErrorAction SilentlyContinue
# 4. Create plugin symlink (requires Developer Mode or Admin)
New-Item -ItemType SymbolicLink -Path "$env:USERPROFILE\.config\opencode\plugins\superpowers.js" -Target "$env:USERPROFILE\.config\opencode\superpowers\.opencode\plugins\superpowers.js"
# 5. Create skills junction (works without special privileges)
New-Item -ItemType Junction -Path "$env:USERPROFILE\.config\opencode\skills\superpowers" -Target "$env:USERPROFILE\.config\opencode\superpowers\skills"
# 6. Restart OpenCode
```
#### Git Bash
Note: Git Bash's native `ln` command copies files instead of creating symlinks. Use `cmd //c mklink` instead (the `//c` is Git Bash syntax for `/c`).
```bash
# 1. Install Superpowers
git clone https://github.com/obra/superpowers.git ~/.config/opencode/superpowers
# 2. Create directories
mkdir -p ~/.config/opencode/plugins ~/.config/opencode/skills
# 3. Remove existing links (safe for reinstalls)
rm -f ~/.config/opencode/plugins/superpowers.js 2>/dev/null
rm -rf ~/.config/opencode/skills/superpowers 2>/dev/null
# 4. Create plugin symlink (requires Developer Mode or Admin)
cmd //c "mklink \"$(cygpath -w ~/.config/opencode/plugins/superpowers.js)\" \"$(cygpath -w ~/.config/opencode/superpowers/.opencode/plugins/superpowers.js)\""
# 5. Create skills junction (works without special privileges)
cmd //c "mklink /J \"$(cygpath -w ~/.config/opencode/skills/superpowers)\" \"$(cygpath -w ~/.config/opencode/superpowers/skills)\""
# 6. Restart OpenCode
```
#### WSL Users
If running OpenCode inside WSL, use the [macOS / Linux](#macos--linux) instructions instead.
#### Verify Installation
**Command Prompt:**
```cmd
dir /AL "%USERPROFILE%\.config\opencode\plugins"
dir /AL "%USERPROFILE%\.config\opencode\skills"
```
**PowerShell:**
```powershell
Get-ChildItem "$env:USERPROFILE\.config\opencode\plugins" | Where-Object { $_.LinkType }
Get-ChildItem "$env:USERPROFILE\.config\opencode\skills" | Where-Object { $_.LinkType }
```
Look for `<SYMLINK>` or `<JUNCTION>` in the output.
#### Troubleshooting Windows
**"You do not have sufficient privilege" error:**
- Enable Developer Mode in Windows Settings, OR
- Right-click your terminal → "Run as Administrator"
**"Cannot create a file when that file already exists":**
- Run the removal commands (step 3) first, then retry
**Symlinks not working after git clone:**
- Run `git config --global core.symlinks true` and re-clone
## Usage
### Finding Skills
Use OpenCode's native `skill` tool to list all available skills:
```
use skill tool to list skills
```
### Loading a Skill
Use OpenCode's native `skill` tool to load a specific skill:
```
use skill tool to load superpowers/brainstorming
```
### Personal Skills
Create your own skills in `~/.config/opencode/skills/`:
```bash
mkdir -p ~/.config/opencode/skills/my-skill
```
Create `~/.config/opencode/skills/my-skill/SKILL.md`:
```markdown
---
name: my-skill
description: Use when [condition] - [what it does]
---
# My Skill
[Your skill content here]
```
### Project Skills
Create project-specific skills in your OpenCode project:
```bash
# In your OpenCode project
mkdir -p .opencode/skills/my-project-skill
```
Create `.opencode/skills/my-project-skill/SKILL.md`:
```markdown
---
name: my-project-skill
description: Use when [condition] - [what it does]
---
# My Project Skill
[Your skill content here]
```
## Skill Locations
OpenCode discovers skills from these locations:
1. **Project skills** (`.opencode/skills/`) - Highest priority
2. **Personal skills** (`~/.config/opencode/skills/`)
3. **Superpowers skills** (`~/.config/opencode/skills/superpowers/`) - via symlink
## Features
### Automatic Context Injection
The plugin automatically injects superpowers context via the `experimental.chat.system.transform` hook. This adds the "using-superpowers" skill content to the system prompt on every request.
### Native Skills Integration
Superpowers uses OpenCode's native `skill` tool for skill discovery and loading. Skills are symlinked into `~/.config/opencode/skills/superpowers/` so they appear alongside your personal and project skills.
### Tool Mapping
Skills written for Claude Code are automatically adapted for OpenCode. The bootstrap provides mapping instructions:
- `TodoWrite``update_plan`
- `Task` with subagents → OpenCode's `@mention` system
- `Skill` tool → OpenCode's native `skill` tool
- File operations → Native OpenCode tools
## Architecture
### Plugin Structure
**Location:** `~/.config/opencode/superpowers/.opencode/plugins/superpowers.js`
**Components:**
- `experimental.chat.system.transform` hook for bootstrap injection
- Reads and injects the "using-superpowers" skill content
### Skills
**Location:** `~/.config/opencode/skills/superpowers/` (symlink to `~/.config/opencode/superpowers/skills/`)
Skills are discovered by OpenCode's native skill system. Each skill has a `SKILL.md` file with YAML frontmatter.
## Updating
```bash
cd ~/.config/opencode/superpowers
git pull
```
Restart OpenCode to load the updates.
## Troubleshooting
### Plugin not loading
1. Check plugin exists: `ls ~/.config/opencode/superpowers/.opencode/plugins/superpowers.js`
2. Check symlink/junction: `ls -l ~/.config/opencode/plugins/` (macOS/Linux) or `dir /AL %USERPROFILE%\.config\opencode\plugins` (Windows)
3. Check OpenCode logs: `opencode run "test" --print-logs --log-level DEBUG`
4. Look for plugin loading message in logs
### Skills not found
1. Verify skills symlink: `ls -l ~/.config/opencode/skills/superpowers` (should point to superpowers/skills/)
2. Use OpenCode's `skill` tool to list available skills
3. Check skill structure: each skill needs a `SKILL.md` file with valid frontmatter
### Windows: Module not found error
If you see `Cannot find module` errors on Windows:
- **Cause:** Git Bash `ln -sf` copies files instead of creating symlinks
- **Fix:** Use `mklink /J` directory junctions instead (see Windows installation steps)
### Bootstrap not appearing
1. Verify using-superpowers skill exists: `ls ~/.config/opencode/superpowers/skills/using-superpowers/SKILL.md`
2. Check OpenCode version supports `experimental.chat.system.transform` hook
3. Restart OpenCode after plugin changes
## Getting Help
- Report issues: https://github.com/obra/superpowers/issues
- Main documentation: https://github.com/obra/superpowers
- OpenCode docs: https://opencode.ai/docs/
## Testing
Verify your installation:
```bash
# Check plugin loads
opencode run --print-logs "hello" 2>&1 | grep -i superpowers
# Check skills are discoverable
opencode run "use skill tool to list all skills" 2>&1 | grep -i superpowers
# Check bootstrap injection
opencode run "what superpowers do you have?"
```
The agent should mention having superpowers and be able to list skills from `superpowers/`.

View File

@@ -0,0 +1,294 @@
# OpenCode Support Design
**Date:** 2025-11-22
**Author:** Bot & Jesse
**Status:** Design Complete, Awaiting Implementation
## Overview
Add full superpowers support for OpenCode.ai using a native OpenCode plugin architecture that shares core functionality with the existing Codex implementation.
## Background
OpenCode.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.
### Key Differences Between Platforms
- **Claude Code**: Native Anthropic plugin system + file-based skills
- **Codex**: No plugin system → bootstrap markdown + CLI script
- **OpenCode**: JavaScript/TypeScript plugins with event hooks and custom tools API
### OpenCode's Agent System
- **Primary agents**: Build (default, full access) and Plan (restricted, read-only)
- **Subagents**: General (research, searching, multi-step tasks)
- **Invocation**: Automatic dispatch by primary agents OR manual `@mention` syntax
- **Configuration**: Custom agents in `opencode.json` or `~/.config/opencode/agent/`
## Architecture
### High-Level Structure
1. **Shared Core Module** (`lib/skills-core.js`)
- Common skill discovery and parsing logic
- Used by both Codex and OpenCode implementations
2. **Platform-Specific Wrappers**
- Codex: CLI script (`.codex/superpowers-codex`)
- OpenCode: Plugin module (`.opencode/plugin/superpowers.js`)
3. **Skill Directories**
- Core: `~/.config/opencode/superpowers/skills/` (or installed location)
- Personal: `~/.config/opencode/skills/` (shadows core skills)
### Code Reuse Strategy
Extract common functionality from `.codex/superpowers-codex` into shared module:
```javascript
// lib/skills-core.js
module.exports = {
extractFrontmatter(filePath), // Parse name + description from YAML
findSkillsInDir(dir, maxDepth), // Recursive SKILL.md discovery
findAllSkills(dirs), // Scan multiple directories
resolveSkillPath(skillName, dirs), // Handle shadowing (personal > core)
checkForUpdates(repoDir) // Git fetch/status check
};
```
### Skill Frontmatter Format
Current format (no `when_to_use` field):
```yaml
---
name: skill-name
description: Use when [condition] - [what it does]; [additional context]
---
```
## OpenCode Plugin Implementation
### Custom Tools
**Tool 1: `use_skill`**
Loads a specific skill's content into the conversation (equivalent to Claude's Skill tool).
```javascript
{
name: 'use_skill',
description: 'Load and read a specific skill to guide your work',
schema: z.object({
skill_name: z.string().describe('Name of skill (e.g., "superpowers:brainstorming")')
}),
execute: async ({ skill_name }) => {
const { skillPath, content, frontmatter } = resolveAndReadSkill(skill_name);
const skillDir = path.dirname(skillPath);
return `# ${frontmatter.name}
# ${frontmatter.description}
# Supporting tools and docs are in ${skillDir}
# ============================================
${content}`;
}
}
```
**Tool 2: `find_skills`**
Lists all available skills with metadata.
```javascript
{
name: 'find_skills',
description: 'List all available skills',
schema: z.object({}),
execute: async () => {
const skills = discoverAllSkills();
return skills.map(s =>
`${s.namespace}:${s.name}
${s.description}
Directory: ${s.directory}
`).join('\n');
}
}
```
### Session Startup Hook
When a new session starts (`session.started` event):
1. **Inject using-superpowers content**
- Full content of the using-superpowers skill
- Establishes mandatory workflows
2. **Run find_skills automatically**
- Display full list of available skills upfront
- Include skill directories for each
3. **Inject tool mapping instructions**
```markdown
**Tool Mapping for OpenCode:**
When skills reference tools you don't have, substitute:
- `TodoWrite` → `update_plan`
- `Task` with subagents → Use OpenCode subagent system (@mention)
- `Skill` tool → `use_skill` custom tool
- Read, Write, Edit, Bash → Your native equivalents
**Skill directories contain:**
- Supporting scripts (run with bash)
- Additional documentation (read with read tool)
- Utilities specific to that skill
```
4. **Check for updates** (non-blocking)
- Quick git fetch with timeout
- Notify if updates available
### Plugin Structure
```javascript
// .opencode/plugin/superpowers.js
const skillsCore = require('../../lib/skills-core');
const path = require('path');
const fs = require('fs');
const { z } = require('zod');
export const SuperpowersPlugin = async ({ client, directory, $ }) => {
const superpowersDir = path.join(process.env.HOME, '.config/opencode/superpowers');
const personalDir = path.join(process.env.HOME, '.config/opencode/skills');
return {
'session.started': async () => {
const usingSuperpowers = await readSkill('using-superpowers');
const skillsList = await findAllSkills();
const toolMapping = getToolMappingInstructions();
return {
context: `${usingSuperpowers}\n\n${skillsList}\n\n${toolMapping}`
};
},
tools: [
{
name: 'use_skill',
description: 'Load and read a specific skill',
schema: z.object({
skill_name: z.string()
}),
execute: async ({ skill_name }) => {
// Implementation using skillsCore
}
},
{
name: 'find_skills',
description: 'List all available skills',
schema: z.object({}),
execute: async () => {
// Implementation using skillsCore
}
}
]
};
};
```
## File Structure
```
superpowers/
├── lib/
│ └── skills-core.js # NEW: Shared skill logic
├── .codex/
│ ├── superpowers-codex # UPDATED: Use skills-core
│ ├── superpowers-bootstrap.md
│ └── INSTALL.md
├── .opencode/
│ ├── plugin/
│ │ └── superpowers.js # NEW: OpenCode plugin
│ └── INSTALL.md # NEW: Installation guide
└── skills/ # Unchanged
```
## Implementation Plan
### Phase 1: Refactor Shared Core
1. Create `lib/skills-core.js`
- Extract frontmatter parsing from `.codex/superpowers-codex`
- Extract skill discovery logic
- Extract path resolution (with shadowing)
- Update to use only `name` and `description` (no `when_to_use`)
2. Update `.codex/superpowers-codex` to use shared core
- Import from `../lib/skills-core.js`
- Remove duplicated code
- Keep CLI wrapper logic
3. Test Codex implementation still works
- Verify bootstrap command
- Verify use-skill command
- Verify find-skills command
### Phase 2: Build OpenCode Plugin
1. Create `.opencode/plugin/superpowers.js`
- Import shared core from `../../lib/skills-core.js`
- Implement plugin function
- Define custom tools (use_skill, find_skills)
- Implement session.started hook
2. Create `.opencode/INSTALL.md`
- Installation instructions
- Directory setup
- Configuration guidance
3. Test OpenCode implementation
- Verify session startup bootstrap
- Verify use_skill tool works
- Verify find_skills tool works
- Verify skill directories are accessible
### Phase 3: Documentation & Polish
1. Update README with OpenCode support
2. Add OpenCode installation to main docs
3. Update RELEASE-NOTES
4. Test both Codex and OpenCode work correctly
## Next Steps
1. **Create isolated workspace** (using git worktrees)
- Branch: `feature/opencode-support`
2. **Follow TDD where applicable**
- Test shared core functions
- Test skill discovery and parsing
- Integration tests for both platforms
3. **Incremental implementation**
- Phase 1: Refactor shared core + update Codex
- Verify Codex still works before moving on
- Phase 2: Build OpenCode plugin
- Phase 3: Documentation and polish
4. **Testing strategy**
- Manual testing with real OpenCode installation
- Verify skill loading, directories, scripts work
- Test both Codex and OpenCode side-by-side
- Verify tool mappings work correctly
5. **PR and merge**
- Create PR with complete implementation
- Test in clean environment
- Merge to main
## Benefits
- **Code reuse**: Single source of truth for skill discovery/parsing
- **Maintainability**: Bug fixes apply to both platforms
- **Extensibility**: Easy to add future platforms (Cursor, Windsurf, etc.)
- **Native integration**: Uses OpenCode's plugin system properly
- **Consistency**: Same skill experience across all platforms

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,711 @@
# Skills Improvements from User Feedback
**Date:** 2025-11-28
**Status:** Draft
**Source:** Two Claude instances using superpowers in real development scenarios
---
## Executive Summary
Two 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.
**Critical insight:** These are problem reports, not just solution proposals. The problems are real; the solutions need careful evaluation.
**Key themes:**
1. **Verification gaps** - We verify operations succeed but not that they achieve intended outcomes
2. **Process hygiene** - Background processes accumulate and interfere across subagents
3. **Context optimization** - Subagents get too much irrelevant information
4. **Self-reflection missing** - No prompt to critique own work before handoff
5. **Mock safety** - Mocks can drift from interfaces without detection
6. **Skill activation** - Skills exist but aren't being read/used
---
## Problems Identified
### Problem 1: Configuration Change Verification Gap
**What happened:**
- Subagent tested "OpenAI integration"
- Set `OPENAI_API_KEY` env var
- Got status 200 responses
- Reported "OpenAI integration working"
- **BUT** response contained `"model": "claude-sonnet-4-20250514"` - was actually using Anthropic
**Root cause:**
`verification-before-completion` checks operations succeed but not that outcomes reflect intended configuration changes.
**Impact:** High - False confidence in integration tests, bugs ship to production
**Example failure pattern:**
- Switch LLM provider → verify status 200 but don't check model name
- Enable feature flag → verify no errors but don't check feature is active
- Change environment → verify deployment succeeds but don't check environment vars
---
### Problem 2: Background Process Accumulation
**What happened:**
- Multiple subagents dispatched during session
- Each started background server processes
- Processes accumulated (4+ servers running)
- Stale processes still bound to ports
- Later E2E test hit stale server with wrong config
- Confusing/incorrect test results
**Root cause:**
Subagents are stateless - don't know about previous subagents' processes. No cleanup protocol.
**Impact:** Medium-High - Tests hit wrong server, false passes/failures, debugging confusion
---
### Problem 3: Context Bloat in Subagent Prompts
**What happened:**
- Standard approach: give subagent full plan file to read
- Experiment: give only task + pattern + file + verify command
- Result: Faster, more focused, single-attempt completion more common
**Root cause:**
Subagents waste tokens and attention on irrelevant plan sections.
**Impact:** Medium - Slower execution, more failed attempts
**What worked:**
```
You are adding a single E2E test to packnplay's test suite.
**Your task:** Add `TestE2E_FeaturePrivilegedMode` to `pkg/runner/e2e_test.go`
**What to test:** A local devcontainer feature that requests `"privileged": true`
in its metadata should result in the container running with `--privileged` flag.
**Follow the exact pattern of TestE2E_FeatureOptionValidation** (at the end of the file)
**After writing, run:** `go test -v ./pkg/runner -run TestE2E_FeaturePrivilegedMode -timeout 5m`
```
---
### Problem 4: No Self-Reflection Before Handoff
**What happened:**
- Added self-reflection prompt: "Look at your work with fresh eyes - what could be better?"
- Implementer for Task 5 identified failing test was due to implementation bug, not test bug
- Traced to line 99: `strings.Join(metadata.Entrypoint, " ")` creating invalid Docker syntax
- Without self-reflection, would have just reported "test fails" without root cause
**Root cause:**
Implementers don't naturally step back and critique their own work before reporting completion.
**Impact:** Medium - Bugs handed off to reviewer that implementer could have caught
---
### Problem 5: Mock-Interface Drift
**What happened:**
```typescript
// Interface defines close()
interface PlatformAdapter {
close(): Promise<void>;
}
// Code (BUGGY) calls cleanup()
await adapter.cleanup();
// Mock (MATCHES BUG) defines cleanup()
vi.mock('web-adapter', () => ({
WebAdapter: vi.fn().mockImplementation(() => ({
cleanup: vi.fn().mockResolvedValue(undefined), // Wrong!
})),
}));
```
- Tests passed
- Runtime crashed: "adapter.cleanup is not a function"
**Root cause:**
Mock derived from what buggy code calls, not from interface definition. TypeScript can't catch inline mocks with wrong method names.
**Impact:** High - Tests give false confidence, runtime crashes
**Why testing-anti-patterns didn't prevent this:**
The skill covers testing mock behavior and mocking without understanding, but not the specific pattern of "derive mock from interface, not implementation."
---
### Problem 6: Code Reviewer File Access
**What happened:**
- Code reviewer subagent dispatched
- Couldn't find test file: "The file doesn't appear to exist in the repository"
- File actually exists
- Reviewer didn't know to explicitly read it first
**Root cause:**
Reviewer prompts don't include explicit file reading instructions.
**Impact:** Low-Medium - Reviews fail or incomplete
---
### Problem 7: Fix Workflow Latency
**What happened:**
- Implementer identifies bug during self-reflection
- Implementer knows the fix
- Current workflow: report → I dispatch fixer → fixer fixes → I verify
- Extra round-trip adds latency without adding value
**Root cause:**
Rigid separation between implementer and fixer roles when implementer has already diagnosed.
**Impact:** Low - Latency, but no correctness issue
---
### Problem 8: Skills Not Being Read
**What happened:**
- `testing-anti-patterns` skill exists
- Neither human nor subagents read it before writing tests
- Would have prevented some issues (though not all - see Problem 5)
**Root cause:**
No enforcement that subagents read relevant skills. No prompt includes skill reading.
**Impact:** Medium - Skill investment wasted if not used
---
## Proposed Improvements
### 1. verification-before-completion: Add Configuration Change Verification
**Add new section:**
```markdown
## Verifying Configuration Changes
When testing changes to configuration, providers, feature flags, or environment:
**Don't just verify the operation succeeded. Verify the output reflects the intended change.**
### Common Failure Pattern
Operation succeeds because *some* valid config exists, but it's not the config you intended to test.
### Examples
| Change | Insufficient | Required |
|--------|-------------|----------|
| Switch LLM provider | Status 200 | Response contains expected model name |
| Enable feature flag | No errors | Feature behavior actually active |
| Change environment | Deploy succeeds | Logs/vars reference new environment |
| Set credentials | Auth succeeds | Authenticated user/context is correct |
### Gate Function
```
BEFORE claiming configuration change works:
1. IDENTIFY: What should be DIFFERENT after this change?
2. LOCATE: Where is that difference observable?
- Response field (model name, user ID)
- Log line (environment, provider)
- Behavior (feature active/inactive)
3. RUN: Command that shows the observable difference
4. VERIFY: Output contains expected difference
5. ONLY THEN: Claim configuration change works
Red flags:
- "Request succeeded" without checking content
- Checking status code but not response body
- Verifying no errors but not positive confirmation
```
**Why this works:**
Forces verification of INTENT, not just operation success.
---
### 2. subagent-driven-development: Add Process Hygiene for E2E Tests
**Add new section:**
```markdown
## Process Hygiene for E2E Tests
When dispatching subagents that start services (servers, databases, message queues):
### Problem
Subagents are stateless - they don't know about processes started by previous subagents. Background processes persist and can interfere with later tests.
### Solution
**Before dispatching E2E test subagent, include cleanup in prompt:**
```
BEFORE starting any services:
1. Kill existing processes: pkill -f "<service-pattern>" 2>/dev/null || true
2. Wait for cleanup: sleep 1
3. Verify port free: lsof -i :<port> && echo "ERROR: Port still in use" || echo "Port free"
AFTER tests complete:
1. Kill the process you started
2. Verify cleanup: pgrep -f "<service-pattern>" || echo "Cleanup successful"
```
### Example
```
Task: Run E2E test of API server
Prompt includes:
"Before starting the server:
- Kill any existing servers: pkill -f 'node.*server.js' 2>/dev/null || true
- Verify port 3001 is free: lsof -i :3001 && exit 1 || echo 'Port available'
After tests:
- Kill the server you started
- Verify: pgrep -f 'node.*server.js' || echo 'Cleanup verified'"
```
### Why This Matters
- Stale processes serve requests with wrong config
- Port conflicts cause silent failures
- Process accumulation slows system
- Confusing test results (hitting wrong server)
```
**Trade-off analysis:**
- Adds boilerplate to prompts
- But prevents very confusing debugging
- Worth it for E2E test subagents
---
### 3. subagent-driven-development: Add Lean Context Option
**Modify Step 2: Execute Task with Subagent**
**Before:**
```
Read that task carefully from [plan-file].
```
**After:**
```
## Context Approaches
**Full Plan (default):**
Use when tasks are complex or have dependencies:
```
Read Task N from [plan-file] carefully.
```
**Lean Context (for independent tasks):**
Use when task is standalone and pattern-based:
```
You are implementing: [1-2 sentence task description]
File to modify: [exact path]
Pattern to follow: [reference to existing function/test]
What to implement: [specific requirement]
Verification: [exact command to run]
[Do NOT include full plan file]
```
**Use lean context when:**
- Task follows existing pattern (add similar test, implement similar feature)
- Task is self-contained (doesn't need context from other tasks)
- Pattern reference is sufficient (e.g., "follow TestE2E_FeatureOptionValidation")
**Use full plan when:**
- Task has dependencies on other tasks
- Requires understanding of overall architecture
- Complex logic that needs context
```
**Example:**
```
Lean context prompt:
"You are adding a test for privileged mode in devcontainer features.
File: pkg/runner/e2e_test.go
Pattern: Follow TestE2E_FeatureOptionValidation (at end of file)
Test: Feature with `"privileged": true` in metadata results in `--privileged` flag
Verify: go test -v ./pkg/runner -run TestE2E_FeaturePrivilegedMode -timeout 5m
Report: Implementation, test results, any issues."
```
**Why this works:**
Reduces token usage, increases focus, faster completion when appropriate.
---
### 4. subagent-driven-development: Add Self-Reflection Step
**Modify Step 2: Execute Task with Subagent**
**Add to prompt template:**
```
When done, BEFORE reporting back:
Take a step back and review your work with fresh eyes.
Ask yourself:
- Does this actually solve the task as specified?
- Are there edge cases I didn't consider?
- Did I follow the pattern correctly?
- If tests are failing, what's the ROOT CAUSE (implementation bug vs test bug)?
- What could be better about this implementation?
If you identify issues during this reflection, fix them now.
Then report:
- What you implemented
- Self-reflection findings (if any)
- Test results
- Files changed
```
**Why this works:**
Catches bugs implementer can find themselves before handoff. Documented case: identified entrypoint bug through self-reflection.
**Trade-off:**
Adds ~30 seconds per task, but catches issues before review.
---
### 5. requesting-code-review: Add Explicit File Reading
**Modify the code-reviewer template:**
**Add at the beginning:**
```markdown
## Files to Review
BEFORE analyzing, read these files:
1. [List specific files that changed in the diff]
2. [Files referenced by changes but not modified]
Use Read tool to load each file.
If you cannot find a file:
- Check exact path from diff
- Try alternate locations
- Report: "Cannot locate [path] - please verify file exists"
DO NOT proceed with review until you've read the actual code.
```
**Why this works:**
Explicit instruction prevents "file not found" issues.
---
### 6. testing-anti-patterns: Add Mock-Interface Drift Anti-Pattern
**Add new Anti-Pattern 6:**
```markdown
## Anti-Pattern 6: Mocks Derived from Implementation
**The violation:**
```typescript
// Code (BUGGY) calls cleanup()
await adapter.cleanup();
// Mock (MATCHES BUG) has cleanup()
const mock = {
cleanup: vi.fn().mockResolvedValue(undefined)
};
// Interface (CORRECT) defines close()
interface PlatformAdapter {
close(): Promise<void>;
}
```
**Why this is wrong:**
- Mock encodes the bug into the test
- TypeScript can't catch inline mocks with wrong method names
- Test passes because both code and mock are wrong
- Runtime crashes when real object is used
**The fix:**
```typescript
// ✅ GOOD: Derive mock from interface
// Step 1: Open interface definition (PlatformAdapter)
// Step 2: List methods defined there (close, initialize, etc.)
// Step 3: Mock EXACTLY those methods
const mock = {
initialize: vi.fn().mockResolvedValue(undefined),
close: vi.fn().mockResolvedValue(undefined), // From interface!
};
// Now test FAILS because code calls cleanup() which doesn't exist
// That failure reveals the bug BEFORE runtime
```
### Gate Function
```
BEFORE writing any mock:
1. STOP - Do NOT look at the code under test yet
2. FIND: The interface/type definition for the dependency
3. READ: The interface file
4. LIST: Methods defined in the interface
5. MOCK: ONLY those methods with EXACTLY those names
6. DO NOT: Look at what your code calls
IF your test fails because code calls something not in mock:
✅ GOOD - The test found a bug in your code
Fix the code to call the correct interface method
NOT the mock
Red flags:
- "I'll mock what the code calls"
- Copying method names from implementation
- Mock written without reading interface
- "The test is failing so I'll add this method to the mock"
```
**Detection:**
When you see runtime error "X is not a function" and tests pass:
1. Check if X is mocked
2. Compare mock methods to interface methods
3. Look for method name mismatches
```
**Why this works:**
Directly addresses the failure pattern from feedback.
---
### 7. subagent-driven-development: Require Skills Reading for Test Subagents
**Add to prompt template when task involves testing:**
```markdown
BEFORE writing any tests:
1. Read testing-anti-patterns skill:
Use Skill tool: superpowers:testing-anti-patterns
2. Apply gate functions from that skill when:
- Writing mocks
- Adding methods to production classes
- Mocking dependencies
This is NOT optional. Tests that violate anti-patterns will be rejected in review.
```
**Why this works:**
Ensures skills are actually used, not just exist.
**Trade-off:**
Adds time to each task, but prevents entire classes of bugs.
---
### 8. subagent-driven-development: Allow Implementer to Fix Self-Identified Issues
**Modify Step 2:**
**Current:**
```
Subagent reports back with summary of work.
```
**Proposed:**
```
Subagent performs self-reflection, then:
IF self-reflection identifies fixable issues:
1. Fix the issues
2. Re-run verification
3. Report: "Initial implementation + self-reflection fix"
ELSE:
Report: "Implementation complete"
Include in report:
- Self-reflection findings
- Whether fixes were applied
- Final verification results
```
**Why this works:**
Reduces latency when implementer already knows the fix. Documented case: would have saved one round-trip for entrypoint bug.
**Trade-off:**
Slightly more complex prompt, but faster end-to-end.
---
## Implementation Plan
### Phase 1: High-Impact, Low-Risk (Do First)
1. **verification-before-completion: Configuration change verification**
- Clear addition, doesn't change existing content
- Addresses high-impact problem (false confidence in tests)
- File: `skills/verification-before-completion/SKILL.md`
2. **testing-anti-patterns: Mock-interface drift**
- Adds new anti-pattern, doesn't modify existing
- Addresses high-impact problem (runtime crashes)
- File: `skills/testing-anti-patterns/SKILL.md`
3. **requesting-code-review: Explicit file reading**
- Simple addition to template
- Fixes concrete problem (reviewers can't find files)
- File: `skills/requesting-code-review/SKILL.md`
### Phase 2: Moderate Changes (Test Carefully)
4. **subagent-driven-development: Process hygiene**
- Adds new section, doesn't change workflow
- Addresses medium-high impact (test reliability)
- File: `skills/subagent-driven-development/SKILL.md`
5. **subagent-driven-development: Self-reflection**
- Changes prompt template (higher risk)
- But documented to catch bugs
- File: `skills/subagent-driven-development/SKILL.md`
6. **subagent-driven-development: Skills reading requirement**
- Adds prompt overhead
- But ensures skills are actually used
- File: `skills/subagent-driven-development/SKILL.md`
### Phase 3: Optimization (Validate First)
7. **subagent-driven-development: Lean context option**
- Adds complexity (two approaches)
- Needs validation that it doesn't cause confusion
- File: `skills/subagent-driven-development/SKILL.md`
8. **subagent-driven-development: Allow implementer to fix**
- Changes workflow (higher risk)
- Optimization, not bug fix
- File: `skills/subagent-driven-development/SKILL.md`
---
## Open Questions
1. **Lean context approach:**
- Should we make it the default for pattern-based tasks?
- How do we decide which approach to use?
- Risk of being too lean and missing important context?
2. **Self-reflection:**
- Will this slow down simple tasks significantly?
- Should it only apply to complex tasks?
- How do we prevent "reflection fatigue" where it becomes rote?
3. **Process hygiene:**
- Should this be in subagent-driven-development or a separate skill?
- Does it apply to other workflows beyond E2E tests?
- How do we handle cases where process SHOULD persist (dev servers)?
4. **Skills reading enforcement:**
- Should we require ALL subagents to read relevant skills?
- How do we keep prompts from becoming too long?
- Risk of over-documenting and losing focus?
---
## Success Metrics
How do we know these improvements work?
1. **Configuration verification:**
- Zero instances of "test passed but wrong config was used"
- Jesse doesn't say "that's not actually testing what you think"
2. **Process hygiene:**
- Zero instances of "test hit wrong server"
- No port conflict errors during E2E test runs
3. **Mock-interface drift:**
- Zero instances of "tests pass but runtime crashes on missing method"
- No method name mismatches between mocks and interfaces
4. **Self-reflection:**
- Measurable: Do implementer reports include self-reflection findings?
- Qualitative: Do fewer bugs make it to code review?
5. **Skills reading:**
- Subagent reports reference skill gate functions
- Fewer anti-pattern violations in code review
---
## Risks and Mitigations
### Risk: Prompt Bloat
**Problem:** Adding all these requirements makes prompts overwhelming
**Mitigation:**
- Phase implementation (don't add everything at once)
- Make some additions conditional (E2E hygiene only for E2E tests)
- Consider templates for different task types
### Risk: Analysis Paralysis
**Problem:** Too much reflection/verification slows execution
**Mitigation:**
- Keep gate functions quick (seconds, not minutes)
- Make lean context opt-in initially
- Monitor task completion times
### Risk: False Sense of Security
**Problem:** Following checklist doesn't guarantee correctness
**Mitigation:**
- Emphasize gate functions are minimums, not maximums
- Keep "use judgment" language in skills
- Document that skills catch common failures, not all failures
### Risk: Skill Divergence
**Problem:** Different skills give conflicting advice
**Mitigation:**
- Review changes across all skills for consistency
- Document how skills interact (Integration sections)
- Test with real scenarios before deployment
---
## Recommendation
**Proceed with Phase 1 immediately:**
- verification-before-completion: Configuration change verification
- testing-anti-patterns: Mock-interface drift
- requesting-code-review: Explicit file reading
**Test Phase 2 with Jesse before finalizing:**
- Get feedback on self-reflection impact
- Validate process hygiene approach
- Confirm skills reading requirement is worth overhead
**Hold Phase 3 pending validation:**
- Lean context needs real-world testing
- Implementer-fix workflow change needs careful evaluation
These changes address real problems documented by users while minimizing risk of making skills worse.

View File

@@ -0,0 +1,571 @@
# Visual Brainstorming Companion Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Give Claude a browser-based visual companion for brainstorming sessions - show mockups, prototypes, and interactive choices alongside terminal conversation.
**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.
**Tech Stack:** Node.js, Express, ws (WebSocket), chokidar (file watching)
---
## Task 1: Create the Server Foundation
**Files:**
- Create: `lib/brainstorm-server/index.js`
- Create: `lib/brainstorm-server/package.json`
**Step 1: Create package.json**
```json
{
"name": "brainstorm-server",
"version": "1.0.0",
"description": "Visual brainstorming companion server for Claude Code",
"main": "index.js",
"dependencies": {
"chokidar": "^3.5.3",
"express": "^4.18.2",
"ws": "^8.14.2"
}
}
```
**Step 2: Create minimal server that starts**
```javascript
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const chokidar = require('chokidar');
const fs = require('fs');
const path = require('path');
const PORT = process.env.BRAINSTORM_PORT || 3333;
const SCREEN_FILE = process.env.BRAINSTORM_SCREEN || '/tmp/brainstorm/screen.html';
const SCREEN_DIR = path.dirname(SCREEN_FILE);
// Ensure screen directory exists
if (!fs.existsSync(SCREEN_DIR)) {
fs.mkdirSync(SCREEN_DIR, { recursive: true });
}
// Create default screen if none exists
if (!fs.existsSync(SCREEN_FILE)) {
fs.writeFileSync(SCREEN_FILE, `<!DOCTYPE html>
<html>
<head>
<title>Brainstorm Companion</title>
<style>
body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
h1 { color: #333; }
p { color: #666; }
</style>
</head>
<body>
<h1>Brainstorm Companion</h1>
<p>Waiting for Claude to push a screen...</p>
</body>
</html>`);
}
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Track connected browsers for reload notifications
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
ws.on('close', () => clients.delete(ws));
ws.on('message', (data) => {
// User interaction event - write to stdout for Claude
const event = JSON.parse(data.toString());
console.log(JSON.stringify({ type: 'user-event', ...event }));
});
});
// Serve current screen with helper.js injected
app.get('/', (req, res) => {
let html = fs.readFileSync(SCREEN_FILE, 'utf-8');
// Inject helper script before </body>
const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
const injection = `<script>\n${helperScript}\n</script>`;
if (html.includes('</body>')) {
html = html.replace('</body>', `${injection}\n</body>`);
} else {
html += injection;
}
res.type('html').send(html);
});
// Watch for screen file changes
chokidar.watch(SCREEN_FILE).on('change', () => {
console.log(JSON.stringify({ type: 'screen-updated', file: SCREEN_FILE }));
// Notify all browsers to reload
clients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'reload' }));
}
});
});
server.listen(PORT, '127.0.0.1', () => {
console.log(JSON.stringify({ type: 'server-started', port: PORT, url: `http://localhost:${PORT}` }));
});
```
**Step 3: Run npm install**
Run: `cd lib/brainstorm-server && npm install`
Expected: Dependencies installed
**Step 4: Test server starts**
Run: `cd lib/brainstorm-server && timeout 3 node index.js || true`
Expected: See JSON with `server-started` and port info
**Step 5: Commit**
```bash
git add lib/brainstorm-server/
git commit -m "feat: add brainstorm server foundation"
```
---
## Task 2: Create the Helper Library
**Files:**
- Create: `lib/brainstorm-server/helper.js`
**Step 1: Create helper.js with event auto-capture**
```javascript
(function() {
const WS_URL = 'ws://' + window.location.host;
let ws = null;
let eventQueue = [];
function connect() {
ws = new WebSocket(WS_URL);
ws.onopen = () => {
// Send any queued events
eventQueue.forEach(e => ws.send(JSON.stringify(e)));
eventQueue = [];
};
ws.onmessage = (msg) => {
const data = JSON.parse(msg.data);
if (data.type === 'reload') {
window.location.reload();
}
};
ws.onclose = () => {
// Reconnect after 1 second
setTimeout(connect, 1000);
};
}
function send(event) {
event.timestamp = Date.now();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(event));
} else {
eventQueue.push(event);
}
}
// Auto-capture clicks on interactive elements
document.addEventListener('click', (e) => {
const target = e.target.closest('button, a, [data-choice], [role="button"], input[type="submit"]');
if (!target) return;
// Don't capture regular link navigation
if (target.tagName === 'A' && !target.dataset.choice) return;
e.preventDefault();
send({
type: 'click',
text: target.textContent.trim(),
choice: target.dataset.choice || null,
id: target.id || null,
className: target.className || null
});
});
// Auto-capture form submissions
document.addEventListener('submit', (e) => {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const data = {};
formData.forEach((value, key) => { data[key] = value; });
send({
type: 'submit',
formId: form.id || null,
formName: form.name || null,
data: data
});
});
// Auto-capture input changes (debounced)
let inputTimeout = null;
document.addEventListener('input', (e) => {
const target = e.target;
if (!target.matches('input, textarea, select')) return;
clearTimeout(inputTimeout);
inputTimeout = setTimeout(() => {
send({
type: 'input',
name: target.name || null,
id: target.id || null,
value: target.value,
inputType: target.type || target.tagName.toLowerCase()
});
}, 500); // 500ms debounce
});
// Expose for explicit use if needed
window.brainstorm = {
send: send,
choice: (value, metadata = {}) => send({ type: 'choice', value, ...metadata })
};
connect();
})();
```
**Step 2: Verify helper.js is syntactically valid**
Run: `node -c lib/brainstorm-server/helper.js`
Expected: No syntax errors
**Step 3: Commit**
```bash
git add lib/brainstorm-server/helper.js
git commit -m "feat: add browser helper library for event capture"
```
---
## Task 3: Write Tests for the Server
**Files:**
- Create: `tests/brainstorm-server/server.test.js`
- Create: `tests/brainstorm-server/package.json`
**Step 1: Create test package.json**
```json
{
"name": "brainstorm-server-tests",
"version": "1.0.0",
"scripts": {
"test": "node server.test.js"
}
}
```
**Step 2: Write server tests**
```javascript
const { spawn } = require('child_process');
const http = require('http');
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const SERVER_PATH = path.join(__dirname, '../../lib/brainstorm-server/index.js');
const TEST_PORT = 3334;
const TEST_SCREEN = '/tmp/brainstorm-test/screen.html';
// Clean up test directory
function cleanup() {
if (fs.existsSync(path.dirname(TEST_SCREEN))) {
fs.rmSync(path.dirname(TEST_SCREEN), { recursive: true });
}
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetch(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve({ status: res.statusCode, body: data }));
}).on('error', reject);
});
}
async function runTests() {
cleanup();
// Start server
const server = spawn('node', [SERVER_PATH], {
env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_SCREEN: TEST_SCREEN }
});
let stdout = '';
server.stdout.on('data', (data) => { stdout += data.toString(); });
server.stderr.on('data', (data) => { console.error('Server stderr:', data.toString()); });
await sleep(1000); // Wait for server to start
try {
// Test 1: Server starts and outputs JSON
console.log('Test 1: Server startup message');
assert(stdout.includes('server-started'), 'Should output server-started');
assert(stdout.includes(TEST_PORT.toString()), 'Should include port');
console.log(' PASS');
// Test 2: GET / returns HTML with helper injected
console.log('Test 2: Serves HTML with helper injected');
const res = await fetch(`http://localhost:${TEST_PORT}/`);
assert.strictEqual(res.status, 200);
assert(res.body.includes('brainstorm'), 'Should include brainstorm content');
assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
console.log(' PASS');
// Test 3: WebSocket connection and event relay
console.log('Test 3: WebSocket relays events to stdout');
stdout = ''; // Reset stdout capture
const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
await new Promise(resolve => ws.on('open', resolve));
ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
await sleep(100);
assert(stdout.includes('user-event'), 'Should relay user events');
assert(stdout.includes('Test Button'), 'Should include event data');
ws.close();
console.log(' PASS');
// Test 4: File change triggers reload notification
console.log('Test 4: File change notifies browsers');
const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);
await new Promise(resolve => ws2.on('open', resolve));
let gotReload = false;
ws2.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (msg.type === 'reload') gotReload = true;
});
// Modify the screen file
fs.writeFileSync(TEST_SCREEN, '<html><body>Updated</body></html>');
await sleep(500);
assert(gotReload, 'Should send reload message on file change');
ws2.close();
console.log(' PASS');
console.log('\nAll tests passed!');
} finally {
server.kill();
cleanup();
}
}
runTests().catch(err => {
console.error('Test failed:', err);
process.exit(1);
});
```
**Step 3: Run tests**
Run: `cd tests/brainstorm-server && npm install ws && node server.test.js`
Expected: All tests pass
**Step 4: Commit**
```bash
git add tests/brainstorm-server/
git commit -m "test: add brainstorm server integration tests"
```
---
## Task 4: Add Visual Companion to Brainstorming Skill
**Files:**
- Modify: `skills/brainstorming/SKILL.md`
- Create: `skills/brainstorming/visual-companion.md` (supporting doc)
**Step 1: Create the supporting documentation**
Create `skills/brainstorming/visual-companion.md`:
```markdown
# Visual Companion Reference
## Starting the Server
Run as a background job:
```bash
node ${PLUGIN_ROOT}/lib/brainstorm-server/index.js
```
Tell the user: "I've started a visual companion at http://localhost:3333 - open it in a browser."
## Pushing Screens
Write HTML to `/tmp/brainstorm/screen.html`. The server watches this file and auto-refreshes the browser.
## Reading User Responses
Check the background task output for JSON events:
```json
{"type":"user-event","type":"click","text":"Option A","choice":"optionA","timestamp":1234567890}
{"type":"user-event","type":"submit","data":{"notes":"My feedback"},"timestamp":1234567891}
```
Event types:
- **click**: User clicked button or `data-choice` element
- **submit**: User submitted form (includes all form data)
- **input**: User typed in field (debounced 500ms)
## HTML Patterns
### Choice Cards
```html
<div class="options">
<button data-choice="optionA">
<h3>Option A</h3>
<p>Description</p>
</button>
<button data-choice="optionB">
<h3>Option B</h3>
<p>Description</p>
</button>
</div>
```
### Interactive Mockup
```html
<div class="mockup">
<header data-choice="header">App Header</header>
<nav data-choice="nav">Navigation</nav>
<main data-choice="main">Content</main>
</div>
```
### Form with Notes
```html
<form>
<label>Priority: <input type="range" name="priority" min="1" max="5"></label>
<textarea name="notes" placeholder="Additional thoughts..."></textarea>
<button type="submit">Submit</button>
</form>
```
### Explicit JavaScript
```html
<button onclick="brainstorm.choice('custom', {extra: 'data'})">Custom</button>
```
```
**Step 2: Add visual companion section to brainstorming skill**
Add after "Key Principles" in `skills/brainstorming/SKILL.md`:
```markdown
## Visual Companion (Optional)
When brainstorming involves visual elements - UI mockups, wireframes, interactive prototypes - use the browser-based visual companion.
**When to use:**
- Presenting UI/UX options that benefit from visual comparison
- Showing wireframes or layout options
- Gathering structured feedback (ratings, forms)
- Prototyping click interactions
**How it works:**
1. Start the server as a background job
2. Tell user to open http://localhost:3333
3. Write HTML to `/tmp/brainstorm/screen.html` (auto-refreshes)
4. Check background task output for user interactions
The terminal remains the primary conversation interface. The browser is a visual aid.
**Reference:** See `visual-companion.md` in this skill directory for HTML patterns and API details.
```
**Step 3: Verify the edits**
Run: `grep -A5 "Visual Companion" skills/brainstorming/SKILL.md`
Expected: Shows the new section
**Step 4: Commit**
```bash
git add skills/brainstorming/
git commit -m "feat: add visual companion to brainstorming skill"
```
---
## Task 5: Add Server to Plugin Ignore (Optional Cleanup)
**Files:**
- Check if `.gitignore` needs node_modules exclusion for lib/brainstorm-server
**Step 1: Check current gitignore**
Run: `cat .gitignore 2>/dev/null || echo "No .gitignore"`
**Step 2: Add node_modules if needed**
If not already present, add:
```
lib/brainstorm-server/node_modules/
```
**Step 3: Commit if changed**
```bash
git add .gitignore
git commit -m "chore: ignore brainstorm-server node_modules"
```
---
## Summary
After completing all tasks:
1. **Server** at `lib/brainstorm-server/` - Node.js server that watches HTML file and relays events
2. **Helper library** auto-injected - captures clicks, forms, inputs
3. **Tests** at `tests/brainstorm-server/` - verifies server behavior
4. **Brainstorming skill** updated with visual companion section and `visual-companion.md` reference doc
**To use:**
1. Start server as background job: `node lib/brainstorm-server/index.js &`
2. Tell user to open `http://localhost:3333`
3. Write HTML to `/tmp/brainstorm/screen.html`
4. Check task output for user events

View File

@@ -0,0 +1,301 @@
# Document Review System Implementation Plan
> **For Claude:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan.
**Goal:** Add spec and plan document review loops to the brainstorming and writing-plans skills.
**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.
**Tech Stack:** Markdown skill files, subagent dispatch via Task tool
**Spec:** docs/superpowers/specs/2026-01-22-document-review-system-design.md
---
## Chunk 1: Spec Document Reviewer
This chunk adds the spec document reviewer to the brainstorming skill.
### Task 1: Create Spec Document Reviewer Prompt Template
**Files:**
- Create: `skills/brainstorming/spec-document-reviewer-prompt.md`
- [ ] **Step 1:** Create the reviewer prompt template file
```markdown
# Spec Document Reviewer Prompt Template
Use this template when dispatching a spec document reviewer subagent.
**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
**Dispatch after:** Spec document is written to docs/superpowers/specs/
```
Task tool (general-purpose):
description: "Review spec document"
prompt: |
You are a spec document reviewer. Verify this spec is complete and ready for planning.
**Spec to review:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, "TBD", incomplete sections |
| Coverage | Missing error handling, edge cases, integration points |
| Consistency | Internal contradictions, conflicting requirements |
| Clarity | Ambiguous requirements |
| YAGNI | Unrequested features, over-engineering |
## CRITICAL
Look especially hard for:
- Any TODO markers or placeholder text
- Sections saying "to be defined later" or "will spec when X is done"
- Sections noticeably less detailed than others
## Output Format
## Spec Review
**Status:** ✅ Approved | ❌ Issues Found
**Issues (if any):**
- [Section X]: [specific issue] - [why it matters]
**Recommendations (advisory):**
- [suggestions that don't block approval]
```
**Reviewer returns:** Status, Issues (if any), Recommendations
```
- [ ] **Step 2:** Verify the file was created correctly
Run: `cat skills/brainstorming/spec-document-reviewer-prompt.md | head -20`
Expected: Shows the header and purpose section
- [ ] **Step 3:** Commit
```bash
git add skills/brainstorming/spec-document-reviewer-prompt.md
git commit -m "feat: add spec document reviewer prompt template"
```
---
### Task 2: Add Review Loop to Brainstorming Skill
**Files:**
- Modify: `skills/brainstorming/SKILL.md`
- [ ] **Step 1:** Read the current brainstorming skill
Run: `cat skills/brainstorming/SKILL.md`
- [ ] **Step 2:** Add the review loop section after "After the Design"
Find the "After the Design" section and add a new "Spec Review Loop" section after documentation but before implementation:
```markdown
**Spec Review Loop:**
After writing the spec document:
1. Dispatch spec-document-reviewer subagent (see spec-document-reviewer-prompt.md)
2. If ❌ Issues Found:
- Fix the issues in the spec document
- Re-dispatch reviewer
- Repeat until ✅ Approved
3. If ✅ Approved: proceed to implementation setup
**Review loop guidance:**
- Same agent that wrote the spec fixes it (preserves context)
- If loop exceeds 5 iterations, surface to human for guidance
- Reviewers are advisory - explain disagreements if you believe feedback is incorrect
```
- [ ] **Step 3:** Verify the changes
Run: `grep -A 15 "Spec Review Loop" skills/brainstorming/SKILL.md`
Expected: Shows the new review loop section
- [ ] **Step 4:** Commit
```bash
git add skills/brainstorming/SKILL.md
git commit -m "feat: add spec review loop to brainstorming skill"
```
---
## Chunk 2: Plan Document Reviewer
This chunk adds the plan document reviewer to the writing-plans skill.
### Task 3: Create Plan Document Reviewer Prompt Template
**Files:**
- Create: `skills/writing-plans/plan-document-reviewer-prompt.md`
- [ ] **Step 1:** Create the reviewer prompt template file
```markdown
# Plan Document Reviewer Prompt Template
Use this template when dispatching a plan document reviewer subagent.
**Purpose:** Verify the plan chunk is complete, matches the spec, and has proper task decomposition.
**Dispatch after:** Each plan chunk is written
```
Task tool (general-purpose):
description: "Review plan chunk N"
prompt: |
You are a plan document reviewer. Verify this plan chunk is complete and ready for implementation.
**Plan chunk to review:** [PLAN_FILE_PATH] - Chunk N only
**Spec for reference:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, incomplete tasks, missing steps |
| Spec Alignment | Chunk covers relevant spec requirements, no scope creep |
| Task Decomposition | Tasks atomic, clear boundaries, steps actionable |
| Task Syntax | Checkbox syntax (`- [ ]`) on tasks and steps |
| Chunk Size | Each chunk under 1000 lines |
## CRITICAL
Look especially hard for:
- Any TODO markers or placeholder text
- Steps that say "similar to X" without actual content
- Incomplete task definitions
- Missing verification steps or expected outputs
## Output Format
## Plan Review - Chunk N
**Status:** ✅ Approved | ❌ Issues Found
**Issues (if any):**
- [Task X, Step Y]: [specific issue] - [why it matters]
**Recommendations (advisory):**
- [suggestions that don't block approval]
```
**Reviewer returns:** Status, Issues (if any), Recommendations
```
- [ ] **Step 2:** Verify the file was created
Run: `cat skills/writing-plans/plan-document-reviewer-prompt.md | head -20`
Expected: Shows the header and purpose section
- [ ] **Step 3:** Commit
```bash
git add skills/writing-plans/plan-document-reviewer-prompt.md
git commit -m "feat: add plan document reviewer prompt template"
```
---
### Task 4: Add Review Loop to Writing-Plans Skill
**Files:**
- Modify: `skills/writing-plans/SKILL.md`
- [ ] **Step 1:** Read current skill file
Run: `cat skills/writing-plans/SKILL.md`
- [ ] **Step 2:** Add chunk-by-chunk review section
Add before the "Execution Handoff" section:
```markdown
## Plan Review Loop
After completing each chunk of the plan:
1. Dispatch plan-document-reviewer subagent for the current chunk
- Provide: chunk content, path to spec document
2. If ❌ Issues Found:
- Fix the issues in the chunk
- Re-dispatch reviewer for that chunk
- Repeat until ✅ Approved
3. If ✅ Approved: proceed to next chunk (or execution handoff if last chunk)
**Chunk boundaries:** Use `## Chunk N: <name>` headings to delimit chunks. Each chunk should be ≤1000 lines and logically self-contained.
```
- [ ] **Step 3:** Update task syntax examples to use checkboxes
Change the Task Structure section to show checkbox syntax:
```markdown
### Task N: [Component Name]
- [ ] **Step 1:** Write the failing test
- File: `tests/path/test.py`
...
```
- [ ] **Step 4:** Verify the review loop section was added
Run: `grep -A 15 "Plan Review Loop" skills/writing-plans/SKILL.md`
Expected: Shows the new review loop section
- [ ] **Step 5:** Verify the task syntax examples were updated
Run: `grep -A 5 "Task N:" skills/writing-plans/SKILL.md`
Expected: Shows checkbox syntax `### Task N:`
- [ ] **Step 6:** Commit
```bash
git add skills/writing-plans/SKILL.md
git commit -m "feat: add plan review loop and checkbox syntax to writing-plans skill"
```
---
## Chunk 3: Update Plan Document Header
This chunk updates the plan document header template to reference the new checkbox syntax requirements.
### Task 5: Update Plan Header Template in Writing-Plans Skill
**Files:**
- Modify: `skills/writing-plans/SKILL.md`
- [ ] **Step 1:** Read current plan header template
Run: `grep -A 20 "Plan Document Header" skills/writing-plans/SKILL.md`
- [ ] **Step 2:** Update the header template to reference checkbox syntax
The plan header should note that tasks and steps use checkbox syntax. Update the header comment:
```markdown
> **For Claude:** 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.
```
- [ ] **Step 3:** Verify the change
Run: `grep -A 5 "For Claude:" skills/writing-plans/SKILL.md`
Expected: Shows updated header with checkbox syntax mention
- [ ] **Step 4:** Commit
```bash
git add skills/writing-plans/SKILL.md
git commit -m "docs: update plan header to reference checkbox syntax"
```

View File

@@ -0,0 +1,136 @@
# Document Review System Design
## Overview
Add two new review stages to the superpowers workflow:
1. **Spec Document Review** - After brainstorming, before writing-plans
2. **Plan Document Review** - After writing-plans, before implementation
Both follow the iterative loop pattern used by implementation reviews.
## Spec Document Reviewer
**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
**Location:** `skills/brainstorming/spec-document-reviewer-prompt.md`
**What it checks for:**
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, "TBD", incomplete sections |
| Coverage | Missing error handling, edge cases, integration points |
| Consistency | Internal contradictions, conflicting requirements |
| Clarity | Ambiguous requirements |
| YAGNI | Unrequested features, over-engineering |
**Output format:**
```
## Spec Review
**Status:** Approved | Issues Found
**Issues (if any):**
- [Section X]: [issue] - [why it matters]
**Recommendations (advisory):**
- [suggestions that don't block approval]
```
**Review loop:** Issues found -> brainstorming agent fixes -> re-review -> repeat until approved.
**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.
## Plan Document Reviewer
**Purpose:** Verify the plan is complete, matches the spec, and has proper task decomposition.
**Location:** `skills/writing-plans/plan-document-reviewer-prompt.md`
**What it checks for:**
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, incomplete tasks |
| Spec Alignment | Plan covers spec requirements, no scope creep |
| Task Decomposition | Tasks atomic, clear boundaries |
| Task Syntax | Checkbox syntax on tasks and steps |
| Chunk Size | Each chunk under 1000 lines |
**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.
**Spec alignment verification:** The reviewer receives both:
1. The plan document (or current chunk)
2. The path to the spec document for reference
The reviewer reads both and compares requirements coverage.
**Output format:** Same as spec reviewer, but scoped to the current chunk.
**Review process (chunk-by-chunk):**
1. Writing-plans creates chunk N
2. Controller dispatches plan-document-reviewer with chunk N content and spec path
3. Reviewer reads chunk and spec, returns verdict
4. If issues: writing-plans agent fixes chunk N, goto step 2
5. If approved: proceed to chunk N+1
6. Repeat until all chunks approved
**Dispatch mechanism:** Same as spec reviewer - Task tool with `subagent_type: general-purpose`.
## Updated Workflow
```
brainstorming -> spec -> SPEC REVIEW LOOP -> writing-plans -> plan -> PLAN REVIEW LOOP -> implementation
```
**Spec Review Loop:**
1. Spec complete
2. Dispatch reviewer
3. If issues: fix -> goto 2
4. If approved: proceed
**Plan Review Loop:**
1. Chunk N complete
2. Dispatch reviewer for chunk N
3. If issues: fix -> goto 2
4. If approved: next chunk or implementation
## Markdown Task Syntax
Tasks and steps use checkbox syntax:
```markdown
- [ ] ### Task 1: Name
- [ ] **Step 1:** Description
- File: path
- Command: cmd
```
## Error Handling
**Review loop termination:**
- No hard iteration limit - loops continue until reviewer approves
- If loop exceeds 5 iterations, the controller should surface this to the human for guidance
- The human can choose to: continue iterating, approve with known issues, or abort
**Disagreement handling:**
- Reviewers are advisory - they flag issues but don't block
- If the agent believes reviewer feedback is incorrect, it should explain why in its fix
- If disagreement persists after 3 iterations on the same issue, surface to human
**Malformed reviewer output:**
- Controller should validate reviewer output has required fields (Status, Issues if applicable)
- If malformed, re-dispatch reviewer with a note about expected format
- After 2 malformed responses, surface to human
## Files to Change
**New files:**
- `skills/brainstorming/spec-document-reviewer-prompt.md`
- `skills/writing-plans/plan-document-reviewer-prompt.md`
**Modified files:**
- `skills/brainstorming/SKILL.md` - add review loop after spec written
- `skills/writing-plans/SKILL.md` - add chunk-by-chunk review loop, update task syntax examples

303
docs/testing.md Normal file
View File

@@ -0,0 +1,303 @@
# Testing Superpowers Skills
This document describes how to test Superpowers skills, particularly the integration tests for complex skills like `subagent-driven-development`.
## Overview
Testing skills that involve subagents, workflows, and complex interactions requires running actual Claude Code sessions in headless mode and verifying their behavior through session transcripts.
## Test Structure
```
tests/
├── claude-code/
│ ├── test-helpers.sh # Shared test utilities
│ ├── test-subagent-driven-development-integration.sh
│ ├── analyze-token-usage.py # Token analysis tool
│ └── run-skill-tests.sh # Test runner (if exists)
```
## Running Tests
### Integration Tests
Integration tests execute real Claude Code sessions with actual skills:
```bash
# Run the subagent-driven-development integration test
cd tests/claude-code
./test-subagent-driven-development-integration.sh
```
**Note:** Integration tests can take 10-30 minutes as they execute real implementation plans with multiple subagents.
### Requirements
- Must run from the **superpowers plugin directory** (not from temp directories)
- Claude Code must be installed and available as `claude` command
- Local dev marketplace must be enabled: `"superpowers@superpowers-dev": true` in `~/.claude/settings.json`
## Integration Test: subagent-driven-development
### What It Tests
The integration test verifies the `subagent-driven-development` skill correctly:
1. **Plan Loading**: Reads the plan once at the beginning
2. **Full Task Text**: Provides complete task descriptions to subagents (doesn't make them read files)
3. **Self-Review**: Ensures subagents perform self-review before reporting
4. **Review Order**: Runs spec compliance review before code quality review
5. **Review Loops**: Uses review loops when issues are found
6. **Independent Verification**: Spec reviewer reads code independently, doesn't trust implementer reports
### How It Works
1. **Setup**: Creates a temporary Node.js project with a minimal implementation plan
2. **Execution**: Runs Claude Code in headless mode with the skill
3. **Verification**: Parses the session transcript (`.jsonl` file) to verify:
- Skill tool was invoked
- Subagents were dispatched (Task tool)
- TodoWrite was used for tracking
- Implementation files were created
- Tests pass
- Git commits show proper workflow
4. **Token Analysis**: Shows token usage breakdown by subagent
### Test Output
```
========================================
Integration Test: subagent-driven-development
========================================
Test project: /tmp/tmp.xyz123
=== Verification Tests ===
Test 1: Skill tool invoked...
[PASS] subagent-driven-development skill was invoked
Test 2: Subagents dispatched...
[PASS] 7 subagents dispatched
Test 3: Task tracking...
[PASS] TodoWrite used 5 time(s)
Test 6: Implementation verification...
[PASS] src/math.js created
[PASS] add function exists
[PASS] multiply function exists
[PASS] test/math.test.js created
[PASS] Tests pass
Test 7: Git commit history...
[PASS] Multiple commits created (3 total)
Test 8: No extra features added...
[PASS] No extra features added
=========================================
Token Usage Analysis
=========================================
Usage Breakdown:
----------------------------------------------------------------------------------------------------
Agent Description Msgs Input Output Cache Cost
----------------------------------------------------------------------------------------------------
main Main session (coordinator) 34 27 3,996 1,213,703 $ 4.09
3380c209 implementing Task 1: Create Add Function 1 2 787 24,989 $ 0.09
34b00fde implementing Task 2: Create Multiply Function 1 4 644 25,114 $ 0.09
3801a732 reviewing whether an implementation matches... 1 5 703 25,742 $ 0.09
4c142934 doing a final code review... 1 6 854 25,319 $ 0.09
5f017a42 a code reviewer. Review Task 2... 1 6 504 22,949 $ 0.08
a6b7fbe4 a code reviewer. Review Task 1... 1 6 515 22,534 $ 0.08
f15837c0 reviewing whether an implementation matches... 1 6 416 22,485 $ 0.07
----------------------------------------------------------------------------------------------------
TOTALS:
Total messages: 41
Input tokens: 62
Output tokens: 8,419
Cache creation tokens: 132,742
Cache read tokens: 1,382,835
Total input (incl cache): 1,515,639
Total tokens: 1,524,058
Estimated cost: $4.67
(at $3/$15 per M tokens for input/output)
========================================
Test Summary
========================================
STATUS: PASSED
```
## Token Analysis Tool
### Usage
Analyze token usage from any Claude Code session:
```bash
python3 tests/claude-code/analyze-token-usage.py ~/.claude/projects/<project-dir>/<session-id>.jsonl
```
### Finding Session Files
Session transcripts are stored in `~/.claude/projects/` with the working directory path encoded:
```bash
# Example for /Users/jesse/Documents/GitHub/superpowers/superpowers
SESSION_DIR="$HOME/.claude/projects/-Users-jesse-Documents-GitHub-superpowers-superpowers"
# Find recent sessions
ls -lt "$SESSION_DIR"/*.jsonl | head -5
```
### What It Shows
- **Main session usage**: Token usage by the coordinator (you or main Claude instance)
- **Per-subagent breakdown**: Each Task invocation with:
- Agent ID
- Description (extracted from prompt)
- Message count
- Input/output tokens
- Cache usage
- Estimated cost
- **Totals**: Overall token usage and cost estimate
### Understanding the Output
- **High cache reads**: Good - means prompt caching is working
- **High input tokens on main**: Expected - coordinator has full context
- **Similar costs per subagent**: Expected - each gets similar task complexity
- **Cost per task**: Typical range is $0.05-$0.15 per subagent depending on task
## Troubleshooting
### Skills Not Loading
**Problem**: Skill not found when running headless tests
**Solutions**:
1. Ensure you're running FROM the superpowers directory: `cd /path/to/superpowers && tests/...`
2. Check `~/.claude/settings.json` has `"superpowers@superpowers-dev": true` in `enabledPlugins`
3. Verify skill exists in `skills/` directory
### Permission Errors
**Problem**: Claude blocked from writing files or accessing directories
**Solutions**:
1. Use `--permission-mode bypassPermissions` flag
2. Use `--add-dir /path/to/temp/dir` to grant access to test directories
3. Check file permissions on test directories
### Test Timeouts
**Problem**: Test takes too long and times out
**Solutions**:
1. Increase timeout: `timeout 1800 claude ...` (30 minutes)
2. Check for infinite loops in skill logic
3. Review subagent task complexity
### Session File Not Found
**Problem**: Can't find session transcript after test run
**Solutions**:
1. Check the correct project directory in `~/.claude/projects/`
2. Use `find ~/.claude/projects -name "*.jsonl" -mmin -60` to find recent sessions
3. Verify test actually ran (check for errors in test output)
## Writing New Integration Tests
### Template
```bash
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"
# Create test project
TEST_PROJECT=$(create_test_project)
trap "cleanup_test_project $TEST_PROJECT" EXIT
# Set up test files...
cd "$TEST_PROJECT"
# Run Claude with skill
PROMPT="Your test prompt here"
cd "$SCRIPT_DIR/../.." && timeout 1800 claude -p "$PROMPT" \
--allowed-tools=all \
--add-dir "$TEST_PROJECT" \
--permission-mode bypassPermissions \
2>&1 | tee output.txt
# Find and analyze session
WORKING_DIR_ESCAPED=$(echo "$SCRIPT_DIR/../.." | sed 's/\\//-/g' | sed 's/^-//')
SESSION_DIR="$HOME/.claude/projects/$WORKING_DIR_ESCAPED"
SESSION_FILE=$(find "$SESSION_DIR" -name "*.jsonl" -type f -mmin -60 | sort -r | head -1)
# Verify behavior by parsing session transcript
if grep -q '"name":"Skill".*"skill":"your-skill-name"' "$SESSION_FILE"; then
echo "[PASS] Skill was invoked"
fi
# Show token analysis
python3 "$SCRIPT_DIR/analyze-token-usage.py" "$SESSION_FILE"
```
### Best Practices
1. **Always cleanup**: Use trap to cleanup temp directories
2. **Parse transcripts**: Don't grep user-facing output - parse the `.jsonl` session file
3. **Grant permissions**: Use `--permission-mode bypassPermissions` and `--add-dir`
4. **Run from plugin dir**: Skills only load when running from the superpowers directory
5. **Show token usage**: Always include token analysis for cost visibility
6. **Test real behavior**: Verify actual files created, tests passing, commits made
## Session Transcript Format
Session transcripts are JSONL (JSON Lines) files where each line is a JSON object representing a message or tool result.
### Key Fields
```json
{
"type": "assistant",
"message": {
"content": [...],
"usage": {
"input_tokens": 27,
"output_tokens": 3996,
"cache_read_input_tokens": 1213703
}
}
}
```
### Tool Results
```json
{
"type": "user",
"toolUseResult": {
"agentId": "3380c209",
"usage": {
"input_tokens": 2,
"output_tokens": 787,
"cache_read_input_tokens": 24989
},
"prompt": "You are implementing Task 1...",
"content": [{"type": "text", "text": "..."}]
}
}
```
The `agentId` field links to subagent sessions, and the `usage` field contains token usage for that specific subagent invocation.

View File

@@ -0,0 +1,212 @@
# Cross-Platform Polyglot Hooks for Claude Code
Claude Code plugins need hooks that work on Windows, macOS, and Linux. This document explains the polyglot wrapper technique that makes this possible.
## The Problem
Claude Code runs hook commands through the system's default shell:
- **Windows**: CMD.exe
- **macOS/Linux**: bash or sh
This creates several challenges:
1. **Script execution**: Windows CMD can't execute `.sh` files directly - it tries to open them in a text editor
2. **Path format**: Windows uses backslashes (`C:\path`), Unix uses forward slashes (`/path`)
3. **Environment variables**: `$VAR` syntax doesn't work in CMD
4. **No `bash` in PATH**: Even with Git Bash installed, `bash` isn't in the PATH when CMD runs
## The Solution: Polyglot `.cmd` Wrapper
A polyglot script is valid syntax in multiple languages simultaneously. Our wrapper is valid in both CMD and bash:
```cmd
: << 'CMDBLOCK'
@echo off
"C:\Program Files\Git\bin\bash.exe" -l -c "\"$(cygpath -u \"$CLAUDE_PLUGIN_ROOT\")/hooks/session-start.sh\""
exit /b
CMDBLOCK
# Unix shell runs from here
"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh"
```
### How It Works
#### On Windows (CMD.exe)
1. `: << 'CMDBLOCK'` - CMD sees `:` as a label (like `:label`) and ignores `<< 'CMDBLOCK'`
2. `@echo off` - Suppresses command echoing
3. The bash.exe command runs with:
- `-l` (login shell) to get proper PATH with Unix utilities
- `cygpath -u` converts Windows path to Unix format (`C:\foo``/c/foo`)
4. `exit /b` - Exits the batch script, stopping CMD here
5. Everything after `CMDBLOCK` is never reached by CMD
#### On Unix (bash/sh)
1. `: << 'CMDBLOCK'` - `:` is a no-op, `<< 'CMDBLOCK'` starts a heredoc
2. Everything until `CMDBLOCK` is consumed by the heredoc (ignored)
3. `# Unix shell runs from here` - Comment
4. The script runs directly with the Unix path
## File Structure
```
hooks/
├── hooks.json # Points to the .cmd wrapper
├── session-start.cmd # Polyglot wrapper (cross-platform entry point)
└── session-start.sh # Actual hook logic (bash script)
```
### hooks.json
```json
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume|clear|compact",
"hooks": [
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.cmd\""
}
]
}
]
}
}
```
Note: The path must be quoted because `${CLAUDE_PLUGIN_ROOT}` may contain spaces on Windows (e.g., `C:\Program Files\...`).
## Requirements
### Windows
- **Git for Windows** must be installed (provides `bash.exe` and `cygpath`)
- Default installation path: `C:\Program Files\Git\bin\bash.exe`
- If Git is installed elsewhere, the wrapper needs modification
### Unix (macOS/Linux)
- Standard bash or sh shell
- The `.cmd` file must have execute permission (`chmod +x`)
## Writing Cross-Platform Hook Scripts
Your actual hook logic goes in the `.sh` file. To ensure it works on Windows (via Git Bash):
### Do:
- Use pure bash builtins when possible
- Use `$(command)` instead of backticks
- Quote all variable expansions: `"$VAR"`
- Use `printf` or here-docs for output
### Avoid:
- External commands that may not be in PATH (sed, awk, grep)
- If you must use them, they're available in Git Bash but ensure PATH is set up (use `bash -l`)
### Example: JSON Escaping Without sed/awk
Instead of:
```bash
escaped=$(echo "$content" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | awk '{printf "%s\\n", $0}')
```
Use pure bash:
```bash
escape_for_json() {
local input="$1"
local output=""
local i char
for (( i=0; i<${#input}; i++ )); do
char="${input:$i:1}"
case "$char" in
$'\\') output+='\\' ;;
'"') output+='\"' ;;
$'\n') output+='\n' ;;
$'\r') output+='\r' ;;
$'\t') output+='\t' ;;
*) output+="$char" ;;
esac
done
printf '%s' "$output"
}
```
## Reusable Wrapper Pattern
For plugins with multiple hooks, you can create a generic wrapper that takes the script name as an argument:
### run-hook.cmd
```cmd
: << 'CMDBLOCK'
@echo off
set "SCRIPT_DIR=%~dp0"
set "SCRIPT_NAME=%~1"
"C:\Program Files\Git\bin\bash.exe" -l -c "cd \"$(cygpath -u \"%SCRIPT_DIR%\")\" && \"./%SCRIPT_NAME%\""
exit /b
CMDBLOCK
# Unix shell runs from here
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
SCRIPT_NAME="$1"
shift
"${SCRIPT_DIR}/${SCRIPT_NAME}" "$@"
```
### hooks.json using the reusable wrapper
```json
{
"hooks": {
"SessionStart": [
{
"matcher": "startup",
"hooks": [
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start.sh"
}
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" validate-bash.sh"
}
]
}
]
}
}
```
## Troubleshooting
### "bash is not recognized"
CMD 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.
### "cygpath: command not found" or "dirname: command not found"
Bash isn't running as a login shell. Ensure `-l` flag is used.
### Path has weird `\/` in it
`${CLAUDE_PLUGIN_ROOT}` expanded to a Windows path ending with backslash, then `/hooks/...` was appended. Use `cygpath` to convert the entire path.
### Script opens in text editor instead of running
The hooks.json is pointing directly to the `.sh` file. Point to the `.cmd` wrapper instead.
### Works in terminal but not as hook
Claude Code may run hooks differently. Test by simulating the hook environment:
```powershell
$env:CLAUDE_PLUGIN_ROOT = "C:\path\to\plugin"
cmd /c "C:\path\to\plugin\hooks\session-start.cmd"
```
## Related Issues
- [anthropics/claude-code#9758](https://github.com/anthropics/claude-code/issues/9758) - .sh scripts open in editor on Windows
- [anthropics/claude-code#3417](https://github.com/anthropics/claude-code/issues/3417) - Hooks don't work on Windows
- [anthropics/claude-code#6023](https://github.com/anthropics/claude-code/issues/6023) - CLAUDE_PROJECT_DIR not found

View File

@@ -6,7 +6,8 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh",
"async": true
}
]
}

43
hooks/run-hook.cmd Executable file
View File

@@ -0,0 +1,43 @@
: << 'CMDBLOCK'
@echo off
REM ============================================================================
REM DEPRECATED: This polyglot wrapper is no longer used as of Claude Code 2.1.x
REM ============================================================================
REM
REM Claude Code 2.1.x changed the Windows execution model for hooks:
REM
REM Before (2.0.x): Hooks ran with shell:true, using the system default shell.
REM This wrapper provided cross-platform compatibility by
REM being both a valid .cmd file (Windows) and bash script.
REM
REM After (2.1.x): Claude Code now auto-detects .sh files in hook commands
REM and prepends "bash " on Windows. This broke the wrapper
REM because the command:
REM "run-hook.cmd" session-start.sh
REM became:
REM bash "run-hook.cmd" session-start.sh
REM ...and bash cannot execute a .cmd file.
REM
REM The fix: hooks.json now calls session-start.sh directly. Claude Code 2.1.x
REM handles the bash invocation automatically on Windows.
REM
REM This file is kept for reference and potential backward compatibility.
REM ============================================================================
REM
REM Original purpose: Polyglot wrapper to run .sh scripts cross-platform
REM Usage: run-hook.cmd <script-name> [args...]
REM The script should be in the same directory as this wrapper
if "%~1"=="" (
echo run-hook.cmd: missing script name >&2
exit /b 1
)
"C:\Program Files\Git\bin\bash.exe" -l "%~dp0%~1" %2 %3 %4 %5 %6 %7 %8 %9
exit /b
CMDBLOCK
# Unix shell runs from here
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT_NAME="$1"
shift
"${SCRIPT_DIR}/${SCRIPT_NAME}" "$@"

View File

@@ -17,16 +17,28 @@ fi
# Read using-superpowers content
using_superpowers_content=$(cat "${PLUGIN_ROOT}/skills/using-superpowers/SKILL.md" 2>&1 || echo "Error reading using-superpowers skill")
# Escape outputs for JSON
using_superpowers_escaped=$(echo "$using_superpowers_content" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | awk '{printf "%s\\n", $0}')
warning_escaped=$(echo "$warning_message" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | awk '{printf "%s\\n", $0}')
# Escape string for JSON embedding using bash parameter substitution.
# Each ${s//old/new} is a single C-level pass - orders of magnitude
# faster than the character-by-character loop this replaces.
escape_for_json() {
local s="$1"
s="${s//\\/\\\\}"
s="${s//\"/\\\"}"
s="${s//$'\n'/\\n}"
s="${s//$'\r'/\\r}"
s="${s//$'\t'/\\t}"
printf '%s' "$s"
}
using_superpowers_escaped=$(escape_for_json "$using_superpowers_content")
warning_escaped=$(escape_for_json "$warning_message")
# Output context injection as JSON
cat <<EOF
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": "<EXTREMELY_IMPORTANT>\nYou have superpowers.\n\n**The content below is from skills/using-superpowers/SKILL.md - your introduction to using skills:**\n\n${using_superpowers_escaped}\n\n${warning_escaped}\n</EXTREMELY_IMPORTANT>"
"additionalContext": "<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>"
}
}
EOF

View File

@@ -0,0 +1,236 @@
<!DOCTYPE html>
<html>
<head>
<title>Brainstorm Companion</title>
<style>
/*
* BRAINSTORM COMPANION FRAME TEMPLATE
*
* This template provides a consistent frame with:
* - OS-aware light/dark theming
* - Fixed header and feedback footer
* - Scrollable main content area
* - CSS helpers for common UI patterns
*
* CLAUDE: Replace the contents of #claude-content with your content.
* Keep the header, main wrapper, and feedback-footer intact.
*/
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; }
/* ===== THEME VARIABLES ===== */
:root {
--bg-primary: #f5f5f7;
--bg-secondary: #ffffff;
--bg-tertiary: #e5e5e7;
--border: #d1d1d6;
--text-primary: #1d1d1f;
--text-secondary: #86868b;
--text-tertiary: #aeaeb2;
--accent: #0071e3;
--accent-hover: #0077ed;
--success: #34c759;
--warning: #ff9f0a;
--error: #ff3b30;
--selected-bg: #e8f4fd;
--selected-border: #0071e3;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #1d1d1f;
--bg-secondary: #2d2d2f;
--bg-tertiary: #3d3d3f;
--border: #424245;
--text-primary: #f5f5f7;
--text-secondary: #86868b;
--text-tertiary: #636366;
--accent: #0a84ff;
--accent-hover: #409cff;
--selected-bg: rgba(10, 132, 255, 0.15);
--selected-border: #0a84ff;
}
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
display: flex;
flex-direction: column;
line-height: 1.5;
}
/* ===== FRAME STRUCTURE ===== */
.header {
background: var(--bg-secondary);
padding: 0.5rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
.header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }
.header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }
.main { flex: 1; overflow-y: auto; }
#claude-content { padding: 2rem; min-height: 100%; }
.feedback-footer {
background: var(--bg-secondary);
border-top: 1px solid var(--border);
padding: 0.75rem 1.5rem;
flex-shrink: 0;
}
.feedback-footer label { display: block; font-size: 0.65rem; color: var(--text-secondary); margin-bottom: 0.4rem; text-transform: uppercase; letter-spacing: 0.05em; }
.feedback-row { display: flex; gap: 0.5rem; }
.feedback-footer textarea {
flex: 1;
background: var(--bg-primary);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.5rem 0.75rem;
color: var(--text-primary);
font-family: inherit;
font-size: 0.85rem;
resize: none;
height: 36px;
}
.feedback-footer textarea:focus { outline: none; border-color: var(--accent); }
.feedback-footer button {
background: var(--accent);
color: white;
border: none;
padding: 0 1rem;
border-radius: 6px;
font-size: 0.8rem;
cursor: pointer;
}
.feedback-footer button:hover { background: var(--accent-hover); }
/* ===== TYPOGRAPHY ===== */
h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
.subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
.section { margin-bottom: 2rem; }
.label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
/* ===== OPTIONS (for A/B/C choices) ===== */
.options { display: flex; flex-direction: column; gap: 0.75rem; }
.option {
background: var(--bg-secondary);
border: 2px solid var(--border);
border-radius: 12px;
padding: 1rem 1.25rem;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
align-items: flex-start;
gap: 1rem;
}
.option:hover { border-color: var(--accent); }
.option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
.option .letter {
background: var(--bg-tertiary);
color: var(--text-secondary);
width: 1.75rem; height: 1.75rem;
border-radius: 6px;
display: flex; align-items: center; justify-content: center;
font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
}
.option.selected .letter { background: var(--accent); color: white; }
.option .content { flex: 1; }
.option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
.option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
/* ===== CARDS (for showing designs/mockups) ===== */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
.card {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
cursor: pointer;
transition: all 0.15s ease;
}
.card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.card.selected { border-color: var(--selected-border); border-width: 2px; }
.card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
.card-body { padding: 1rem; }
.card-body h3 { margin-bottom: 0.25rem; }
.card-body p { color: var(--text-secondary); font-size: 0.85rem; }
/* ===== MOCKUP CONTAINER ===== */
.mockup {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
margin-bottom: 1.5rem;
}
.mockup-header {
background: var(--bg-tertiary);
padding: 0.5rem 1rem;
font-size: 0.75rem;
color: var(--text-secondary);
border-bottom: 1px solid var(--border);
}
.mockup-body { padding: 1.5rem; }
/* ===== SPLIT VIEW (side-by-side comparison) ===== */
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
@media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
/* ===== PROS/CONS ===== */
.pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
.pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
.pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
.cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
.pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
.pros li, .cons li { margin-bottom: 0.25rem; }
/* ===== PLACEHOLDER (for mockup areas) ===== */
.placeholder {
background: var(--bg-tertiary);
border: 2px dashed var(--border);
border-radius: 8px;
padding: 2rem;
text-align: center;
color: var(--text-tertiary);
}
/* ===== INLINE MOCKUP ELEMENTS ===== */
.mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
.mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
.mock-content { padding: 1.5rem; flex: 1; }
.mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
.mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
</style>
</head>
<body>
<div class="header">
<h1>Brainstorm Companion</h1>
<div class="status">Connected</div>
</div>
<div class="main">
<div id="claude-content">
<!-- CLAUDE: Replace this content -->
<h2>Visual Brainstorming</h2>
<p class="subtitle">Claude will show mockups and options here.</p>
</div>
</div>
<div class="feedback-footer">
<label>Feedback for Claude</label>
<div class="feedback-row">
<textarea id="feedback" placeholder="Add notes (optional)..." onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();send()}"></textarea>
<button onclick="send()">Send</button>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,139 @@
(function() {
const WS_URL = 'ws://' + window.location.host;
let ws = null;
let eventQueue = [];
function connect() {
ws = new WebSocket(WS_URL);
ws.onopen = () => {
eventQueue.forEach(e => ws.send(JSON.stringify(e)));
eventQueue = [];
};
ws.onmessage = (msg) => {
const data = JSON.parse(msg.data);
if (data.type === 'reload') {
window.location.reload();
}
};
ws.onclose = () => {
setTimeout(connect, 1000);
};
}
function sendEvent(event) {
event.timestamp = Date.now();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(event));
} else {
eventQueue.push(event);
}
}
// Auto-capture clicks on interactive elements
document.addEventListener('click', (e) => {
const target = e.target.closest('button, a, [data-choice], [role="button"], input[type="submit"]');
if (!target) return;
// Don't capture regular link navigation
if (target.tagName === 'A' && !target.dataset.choice) return;
// Don't capture the Send feedback button (handled by send())
if (target.id === 'send-feedback') return;
e.preventDefault();
sendEvent({
type: 'click',
text: target.textContent.trim(),
choice: target.dataset.choice || null,
id: target.id || null,
className: target.className || null
});
});
// Auto-capture form submissions
document.addEventListener('submit', (e) => {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const data = {};
formData.forEach((value, key) => { data[key] = value; });
sendEvent({
type: 'submit',
formId: form.id || null,
formName: form.name || null,
data: data
});
});
// Auto-capture input changes (debounced)
let inputTimeout = null;
document.addEventListener('input', (e) => {
const target = e.target;
if (!target.matches('input, textarea, select')) return;
clearTimeout(inputTimeout);
inputTimeout = setTimeout(() => {
sendEvent({
type: 'input',
name: target.name || null,
id: target.id || null,
value: target.value,
inputType: target.type || target.tagName.toLowerCase()
});
}, 500);
});
// Send to Claude - triggers feedback delivery
function sendToClaude(feedback) {
sendEvent({
type: 'send-to-claude',
feedback: feedback || null
});
// Show themed confirmation page
document.body.innerHTML = `
<div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif; background: var(--bg-primary, #f5f5f7);">
<div style="text-align: center; color: var(--text-secondary, #86868b);">
<h2 style="color: var(--text-primary, #1d1d1f); margin-bottom: 0.5rem;">Sent to Claude</h2>
<p>Return to the terminal to see Claude's response.</p>
</div>
</div>
`;
}
// Frame UI: selection tracking and feedback send
window.selectedChoice = null;
window.toggleSelect = function(el) {
const container = el.closest('.options') || el.closest('.cards');
if (container) {
container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));
}
el.classList.add('selected');
window.selectedChoice = el.dataset.choice;
};
window.send = function() {
const feedbackEl = document.getElementById('feedback');
const feedback = feedbackEl ? feedbackEl.value.trim() : '';
const payload = {};
if (window.selectedChoice) payload.choice = window.selectedChoice;
if (feedback) payload.feedback = feedback;
if (Object.keys(payload).length === 0) return;
sendToClaude(payload);
if (feedbackEl) feedbackEl.value = '';
};
// Expose API for explicit use
window.brainstorm = {
send: sendEvent,
choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata }),
sendToClaude: sendToClaude
};
connect();
})();

View File

@@ -0,0 +1,132 @@
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const chokidar = require('chokidar');
const fs = require('fs');
const path = require('path');
const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
const SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
if (!fs.existsSync(SCREEN_DIR)) {
fs.mkdirSync(SCREEN_DIR, { recursive: true });
}
// Load frame template and helper script once at startup
const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
const helperInjection = `<script>\n${helperScript}\n</script>`;
// Detect whether content is a full HTML document or a bare fragment
function isFullDocument(html) {
const trimmed = html.trimStart().toLowerCase();
return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
}
// Wrap a content fragment in the frame template
function wrapInFrame(content) {
return frameTemplate.replace(
/(<div id="claude-content">)[\s\S]*?(<\/div>\s*<\/div>\s*<div class="feedback-footer">)/,
`$1\n ${content}\n $2`
);
}
// Find the newest .html file in the directory by mtime
function getNewestScreen() {
const files = fs.readdirSync(SCREEN_DIR)
.filter(f => f.endsWith('.html'))
.map(f => ({
name: f,
path: path.join(SCREEN_DIR, f),
mtime: fs.statSync(path.join(SCREEN_DIR, f)).mtime.getTime()
}))
.sort((a, b) => b.mtime - a.mtime);
return files.length > 0 ? files[0].path : null;
}
const WAITING_PAGE = `<!DOCTYPE html>
<html>
<head>
<title>Brainstorm Companion</title>
<style>
body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
h1 { color: #333; }
p { color: #666; }
</style>
</head>
<body>
<h1>Brainstorm Companion</h1>
<p>Waiting for Claude to push a screen...</p>
</body>
</html>`;
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
ws.on('close', () => clients.delete(ws));
ws.on('message', (data) => {
const event = JSON.parse(data.toString());
console.log(JSON.stringify({ source: 'user-event', ...event }));
});
});
// Serve newest screen with helper.js injected
app.get('/', (req, res) => {
const screenFile = getNewestScreen();
let html;
if (!screenFile) {
html = WAITING_PAGE;
} else {
const raw = fs.readFileSync(screenFile, 'utf-8');
html = isFullDocument(raw) ? raw : wrapInFrame(raw);
}
// Inject helper script
if (html.includes('</body>')) {
html = html.replace('</body>', `${helperInjection}\n</body>`);
} else {
html += helperInjection;
}
res.type('html').send(html);
});
// Watch for new or changed .html files
chokidar.watch(SCREEN_DIR, { ignoreInitial: true })
.on('add', (filePath) => {
if (filePath.endsWith('.html')) {
console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
clients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'reload' }));
}
});
}
})
.on('change', (filePath) => {
if (filePath.endsWith('.html')) {
console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
clients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'reload' }));
}
});
}
});
server.listen(PORT, '127.0.0.1', () => {
console.log(JSON.stringify({
type: 'server-started',
port: PORT,
url: `http://localhost:${PORT}`,
screen_dir: SCREEN_DIR
}));
});

1036
lib/brainstorm-server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
{
"name": "brainstorm-server",
"version": "1.0.0",
"description": "Visual brainstorming companion server for Claude Code",
"main": "index.js",
"dependencies": {
"chokidar": "^3.5.3",
"express": "^4.18.2",
"ws": "^8.14.2"
}
}

View File

@@ -0,0 +1,68 @@
#!/bin/bash
# Start the brainstorm server and output connection info
# Usage: start-server.sh [--project-dir <path>]
#
# Starts server on a random high port, outputs JSON with URL.
# Each session gets its own directory to avoid conflicts.
#
# Options:
# --project-dir <path> Store session files under <path>/.superpowers/brainstorm/
# instead of /tmp. Files persist after server stops.
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Parse arguments
PROJECT_DIR=""
while [[ $# -gt 0 ]]; do
case "$1" in
--project-dir)
PROJECT_DIR="$2"
shift 2
;;
*)
echo "{\"error\": \"Unknown argument: $1\"}"
exit 1
;;
esac
done
# Generate unique session directory
SESSION_ID="$$-$(date +%s)"
if [[ -n "$PROJECT_DIR" ]]; then
SCREEN_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}"
else
SCREEN_DIR="/tmp/brainstorm-${SESSION_ID}"
fi
PID_FILE="${SCREEN_DIR}/.server.pid"
LOG_FILE="${SCREEN_DIR}/.server.log"
# Create fresh session directory
mkdir -p "$SCREEN_DIR"
# Kill any existing server
if [[ -f "$PID_FILE" ]]; then
old_pid=$(cat "$PID_FILE")
kill "$old_pid" 2>/dev/null
rm -f "$PID_FILE"
fi
# Start server, capturing output to log file
cd "$SCRIPT_DIR"
BRAINSTORM_DIR="$SCREEN_DIR" node index.js > "$LOG_FILE" 2>&1 &
SERVER_PID=$!
echo "$SERVER_PID" > "$PID_FILE"
# Wait for server-started message (check log file)
for i in {1..50}; do
if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then
grep "server-started" "$LOG_FILE" | head -1
exit 0
fi
sleep 0.1
done
# Timeout - server didn't start
echo '{"error": "Server failed to start within 5 seconds"}'
exit 1

View File

@@ -0,0 +1,31 @@
#!/bin/bash
# Stop the brainstorm server and clean up
# Usage: stop-server.sh <screen_dir>
#
# Kills the server process. Only deletes session directory if it's
# under /tmp (ephemeral). Persistent directories (.superpowers/) are
# kept so mockups can be reviewed later.
SCREEN_DIR="$1"
if [[ -z "$SCREEN_DIR" ]]; then
echo '{"error": "Usage: stop-server.sh <screen_dir>"}'
exit 1
fi
PID_FILE="${SCREEN_DIR}/.server.pid"
if [[ -f "$PID_FILE" ]]; then
pid=$(cat "$PID_FILE")
kill "$pid" 2>/dev/null
rm -f "$PID_FILE" "${SCREEN_DIR}/.server.log"
# Only delete ephemeral /tmp directories
if [[ "$SCREEN_DIR" == /tmp/* ]]; then
rm -rf "$SCREEN_DIR"
fi
echo '{"status": "stopped"}'
else
echo '{"status": "not_running"}'
fi

View File

@@ -0,0 +1,27 @@
#!/bin/bash
# Wait for user feedback from the brainstorm browser
# Usage: wait-for-feedback.sh <screen_dir>
#
# Blocks until user sends feedback, then outputs the JSON.
# Write HTML to screen_file BEFORE calling this.
SCREEN_DIR="${1:?Usage: wait-for-feedback.sh <screen_dir>}"
LOG_FILE="${SCREEN_DIR}/.server.log"
if [[ ! -d "$SCREEN_DIR" ]]; then
echo '{"error": "Screen directory not found"}' >&2
exit 1
fi
# Record current position in log file
LOG_POS=$(wc -l < "$LOG_FILE" 2>/dev/null || echo 0)
# Poll for new lines containing the event
while true; do
RESULT=$(tail -n +$((LOG_POS + 1)) "$LOG_FILE" 2>/dev/null | grep -m 1 "send-to-claude")
if [[ -n "$RESULT" ]]; then
echo "$RESULT"
exit 0
fi
sleep 0.2
done

View File

@@ -1,88 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SKILLS_DIR="${HOME}/.config/superpowers/skills"
SKILLS_REPO="https://github.com/obra/superpowers-skills.git"
# Check if skills directory exists and is a valid git repo
if [ -d "$SKILLS_DIR/.git" ]; then
cd "$SKILLS_DIR"
# Get the remote name for the current tracking branch
TRACKING_REMOTE=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null | cut -d'/' -f1 || echo "")
# Fetch from tracking remote if set, otherwise try upstream then origin
if [ -n "$TRACKING_REMOTE" ]; then
git fetch "$TRACKING_REMOTE" 2>/dev/null || true
else
git fetch upstream 2>/dev/null || git fetch origin 2>/dev/null || true
fi
# Check if we can fast-forward
LOCAL=$(git rev-parse @ 2>/dev/null || echo "")
REMOTE=$(git rev-parse @{u} 2>/dev/null || echo "")
BASE=$(git merge-base @ @{u} 2>/dev/null || echo "")
# Try to fast-forward merge first
if [ -n "$LOCAL" ] && [ -n "$REMOTE" ] && [ "$LOCAL" != "$REMOTE" ]; then
# Check if we can fast-forward (local is ancestor of remote)
if [ "$LOCAL" = "$BASE" ]; then
# Fast-forward merge is possible - local is behind
echo "Updating skills to latest version..."
if git merge --ff-only @{u} 2>&1; then
echo "✓ Skills updated successfully"
echo "SKILLS_UPDATED=true"
else
echo "Failed to update skills"
fi
elif [ "$REMOTE" != "$BASE" ]; then
# Remote has changes (local is behind or diverged)
echo "SKILLS_BEHIND=true"
fi
# If REMOTE = BASE, local is ahead - no action needed
fi
exit 0
fi
# Skills directory doesn't exist or isn't a git repo - initialize it
echo "Initializing skills repository..."
# Handle migration from old installation
if [ -d "${HOME}/.config/superpowers/.git" ]; then
echo "Found existing installation. Backing up..."
mv "${HOME}/.config/superpowers/.git" "${HOME}/.config/superpowers/.git.bak"
if [ -d "${HOME}/.config/superpowers/skills" ]; then
mv "${HOME}/.config/superpowers/skills" "${HOME}/.config/superpowers/skills.bak"
echo "Your old skills are in ~/.config/superpowers/skills.bak"
fi
fi
# Clone the skills repository
mkdir -p "${HOME}/.config/superpowers"
git clone "$SKILLS_REPO" "$SKILLS_DIR"
cd "$SKILLS_DIR"
# Offer to fork if gh is installed
if command -v gh &> /dev/null; then
echo ""
echo "GitHub CLI detected. Would you like to fork superpowers-skills?"
echo "Forking allows you to share skill improvements with the community."
echo ""
read -p "Fork superpowers-skills? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
gh repo fork obra/superpowers-skills --remote=true
echo "Forked! You can now contribute skills back to the community."
else
git remote add upstream "$SKILLS_REPO"
fi
else
# No gh, just set up upstream remote
git remote add upstream "$SKILLS_REPO"
fi
echo "Skills repository initialized at $SKILLS_DIR"

208
lib/skills-core.js Normal file
View File

@@ -0,0 +1,208 @@
import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
/**
* Extract YAML frontmatter from a skill file.
* Current format:
* ---
* name: skill-name
* description: Use when [condition] - [what it does]
* ---
*
* @param {string} filePath - Path to SKILL.md file
* @returns {{name: string, description: string}}
*/
function extractFrontmatter(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n');
let inFrontmatter = false;
let name = '';
let description = '';
for (const line of lines) {
if (line.trim() === '---') {
if (inFrontmatter) break;
inFrontmatter = true;
continue;
}
if (inFrontmatter) {
const match = line.match(/^(\w+):\s*(.*)$/);
if (match) {
const [, key, value] = match;
switch (key) {
case 'name':
name = value.trim();
break;
case 'description':
description = value.trim();
break;
}
}
}
}
return { name, description };
} catch (error) {
return { name: '', description: '' };
}
}
/**
* Find all SKILL.md files in a directory recursively.
*
* @param {string} dir - Directory to search
* @param {string} sourceType - 'personal' or 'superpowers' for namespacing
* @param {number} maxDepth - Maximum recursion depth (default: 3)
* @returns {Array<{path: string, name: string, description: string, sourceType: string}>}
*/
function findSkillsInDir(dir, sourceType, maxDepth = 3) {
const skills = [];
if (!fs.existsSync(dir)) return skills;
function recurse(currentDir, depth) {
if (depth > maxDepth) return;
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
// Check for SKILL.md in this directory
const skillFile = path.join(fullPath, 'SKILL.md');
if (fs.existsSync(skillFile)) {
const { name, description } = extractFrontmatter(skillFile);
skills.push({
path: fullPath,
skillFile: skillFile,
name: name || entry.name,
description: description || '',
sourceType: sourceType
});
}
// Recurse into subdirectories
recurse(fullPath, depth + 1);
}
}
}
recurse(dir, 0);
return skills;
}
/**
* Resolve a skill name to its file path, handling shadowing
* (personal skills override superpowers skills).
*
* @param {string} skillName - Name like "superpowers:brainstorming" or "my-skill"
* @param {string} superpowersDir - Path to superpowers skills directory
* @param {string} personalDir - Path to personal skills directory
* @returns {{skillFile: string, sourceType: string, skillPath: string} | null}
*/
function resolveSkillPath(skillName, superpowersDir, personalDir) {
// Strip superpowers: prefix if present
const forceSuperpowers = skillName.startsWith('superpowers:');
const actualSkillName = forceSuperpowers ? skillName.replace(/^superpowers:/, '') : skillName;
// Try personal skills first (unless explicitly superpowers:)
if (!forceSuperpowers && personalDir) {
const personalPath = path.join(personalDir, actualSkillName);
const personalSkillFile = path.join(personalPath, 'SKILL.md');
if (fs.existsSync(personalSkillFile)) {
return {
skillFile: personalSkillFile,
sourceType: 'personal',
skillPath: actualSkillName
};
}
}
// Try superpowers skills
if (superpowersDir) {
const superpowersPath = path.join(superpowersDir, actualSkillName);
const superpowersSkillFile = path.join(superpowersPath, 'SKILL.md');
if (fs.existsSync(superpowersSkillFile)) {
return {
skillFile: superpowersSkillFile,
sourceType: 'superpowers',
skillPath: actualSkillName
};
}
}
return null;
}
/**
* Check if a git repository has updates available.
*
* @param {string} repoDir - Path to git repository
* @returns {boolean} - True if updates are available
*/
function checkForUpdates(repoDir) {
try {
// Quick check with 3 second timeout to avoid delays if network is down
const output = execSync('git fetch origin && git status --porcelain=v1 --branch', {
cwd: repoDir,
timeout: 3000,
encoding: 'utf8',
stdio: 'pipe'
});
// Parse git status output to see if we're behind
const statusLines = output.split('\n');
for (const line of statusLines) {
if (line.startsWith('## ') && line.includes('[behind ')) {
return true; // We're behind remote
}
}
return false; // Up to date
} catch (error) {
// Network down, git error, timeout, etc. - don't block bootstrap
return false;
}
}
/**
* Strip YAML frontmatter from skill content, returning just the content.
*
* @param {string} content - Full content including frontmatter
* @returns {string} - Content without frontmatter
*/
function stripFrontmatter(content) {
const lines = content.split('\n');
let inFrontmatter = false;
let frontmatterEnded = false;
const contentLines = [];
for (const line of lines) {
if (line.trim() === '---') {
if (inFrontmatter) {
frontmatterEnded = true;
continue;
}
inFrontmatter = true;
continue;
}
if (frontmatterEnded || !inFrontmatter) {
contentLines.push(line);
}
}
return contentLines.join('\n').trim();
}
export {
extractFrontmatter,
findSkillsInDir,
resolveSkillPath,
checkForUpdates,
stripFrontmatter
};

View File

@@ -1,156 +1,82 @@
---
name: brainstorming
description: Use when creating or developing anything, before writing code or implementation plans - refines rough ideas into fully-formed designs through structured Socratic questioning, alternative exploration, and incremental validation
description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation."
---
# Brainstorming Ideas Into Designs
## Overview
Help turn ideas into fully formed designs and specs through natural collaborative dialogue.
Transform rough ideas into fully-formed designs through structured questioning and alternative exploration.
**Core principle:** Ask questions to understand, explore alternatives, present design incrementally for validation.
**Announce at start:** "I'm using the brainstorming skill to refine your idea into a design."
## Quick Reference
| Phase | Key Activities | Tool Usage | Output |
|-------|---------------|------------|--------|
| **1. Understanding** | Ask questions (one at a time) | AskUserQuestion for choices | Purpose, constraints, criteria |
| **2. Exploration** | Propose 2-3 approaches | AskUserQuestion for approach selection | Architecture options with trade-offs |
| **3. Design Presentation** | Present in 200-300 word sections | Open-ended questions | Complete design with validation |
| **4. Worktree Setup** | Set up isolated workspace | using-git-worktrees skill | Ready development environment |
| **5. Planning Handoff** | Create implementation plan | writing-plans skill | Detailed task breakdown |
Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design in small sections (200-300 words), checking after each section whether it looks right so far.
## The Process
Copy this checklist to track progress:
**Understanding the idea:**
- Check out the current project state first (files, docs, recent commits)
- Ask questions one at a time to refine the idea
- Prefer multiple choice questions when possible, but open-ended is fine too
- Only one question per message - if a topic needs more exploration, break it into multiple questions
- Focus on understanding: purpose, constraints, success criteria
```
Brainstorming Progress:
- [ ] Phase 1: Understanding (purpose, constraints, criteria gathered)
- [ ] Phase 2: Exploration (2-3 approaches proposed and evaluated)
- [ ] Phase 3: Design Presentation (design validated in sections)
- [ ] Phase 4: Worktree Setup (if implementing)
- [ ] Phase 5: Planning Handoff (if implementing)
```
**Exploring approaches:**
- Propose 2-3 different approaches with trade-offs
- Present options conversationally with your recommendation and reasoning
- Lead with your recommended option and explain why
### Phase 1: Understanding
- Check current project state in working directory
- Ask ONE question at a time to refine the idea
- **Use AskUserQuestion tool** when you have multiple choice options
- Gather: Purpose, constraints, success criteria
**Presenting the design:**
- Once you believe you understand what you're building, present the design
- Break it into sections of 200-300 words
- Ask after each section whether it looks right so far
- Cover: architecture, components, data flow, error handling, testing
- Be ready to go back and clarify if something doesn't make sense
**Example using AskUserQuestion:**
```
Question: "Where should the authentication data be stored?"
Options:
- "Session storage" (clears on tab close, more secure)
- "Local storage" (persists across sessions, more convenient)
- "Cookies" (works with SSR, compatible with older approach)
```
**Design for isolation and clarity:**
- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently
- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on?
- Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work.
- Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much.
### Phase 2: Exploration
- Propose 2-3 different approaches
- For each: Core architecture, trade-offs, complexity assessment
- **Use AskUserQuestion tool** to present approaches as structured choices
- Ask your human partner which approach resonates
**Working in existing codebases:**
- Explore the current structure before proposing changes. Follow existing patterns.
- Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in.
- Don't propose unrelated refactoring. Stay focused on what serves the current goal.
**Example using AskUserQuestion:**
```
Question: "Which architectural approach should we use?"
Options:
- "Event-driven with message queue" (scalable, complex setup, eventual consistency)
- "Direct API calls with retry logic" (simple, synchronous, easier to debug)
- "Hybrid with background jobs" (balanced, moderate complexity, best of both)
```
## After the Design
### Phase 3: Design Presentation
- Present in 200-300 word sections
- Cover: Architecture, components, data flow, error handling, testing
- Ask after each section: "Does this look right so far?" (open-ended)
- Use open-ended questions here to allow freeform feedback
**Documentation:**
- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`
- (User preferences for spec location override this default)
- Use elements-of-style:writing-clearly-and-concisely skill if available
- Commit the design document to git
### Phase 4: Worktree Setup (for implementation)
When design is approved and implementation will follow:
- Announce: "I'm using the using-git-worktrees skill to set up an isolated workspace."
- **REQUIRED SUB-SKILL:** Use using-git-worktrees
- Follow that skill's process for directory selection, safety verification, and setup
- Return here when worktree ready
**Spec Review Loop:**
After writing the spec document:
1. Dispatch spec-document-reviewer subagent (see spec-document-reviewer-prompt.md)
2. If Issues Found: fix, re-dispatch, repeat until Approved
3. If loop exceeds 5 iterations, surface to human for guidance
### Phase 5: Planning Handoff
Ask: "Ready to create the implementation plan?"
When your human partner confirms (any affirmative response):
- Announce: "I'm using the writing-plans skill to create the implementation plan."
- **REQUIRED SUB-SKILL:** Use writing-plans
- Create detailed plan in the worktree
## Question Patterns
### When to Use AskUserQuestion Tool
**Use AskUserQuestion for:**
- Phase 1: Clarifying questions with 2-4 clear options
- Phase 2: Architectural approach selection (2-3 alternatives)
- Any decision with distinct, mutually exclusive choices
- When options have clear trade-offs to explain
**Benefits:**
- Structured presentation of options with descriptions
- Clear trade-off visibility for partner
- Forces explicit choice (prevents vague "maybe both" responses)
### When to Use Open-Ended Questions
**Use open-ended questions for:**
- Phase 3: Design validation ("Does this look right so far?")
- When you need detailed feedback or explanation
- When partner should describe their own requirements
- When structured options would limit creative input
**Example decision flow:**
- "What authentication method?" → Use AskUserQuestion (2-4 options)
- "Does this design handle your use case?" → Open-ended (validation)
## When to Revisit Earlier Phases
```dot
digraph revisit_phases {
rankdir=LR;
"New constraint revealed?" [shape=diamond];
"Partner questions approach?" [shape=diamond];
"Requirements unclear?" [shape=diamond];
"Return to Phase 1" [shape=box, style=filled, fillcolor="#ffcccc"];
"Return to Phase 2" [shape=box, style=filled, fillcolor="#ffffcc"];
"Continue forward" [shape=box, style=filled, fillcolor="#ccffcc"];
"New constraint revealed?" -> "Return to Phase 1" [label="yes"];
"New constraint revealed?" -> "Partner questions approach?" [label="no"];
"Partner questions approach?" -> "Return to Phase 2" [label="yes"];
"Partner questions approach?" -> "Requirements unclear?" [label="no"];
"Requirements unclear?" -> "Return to Phase 1" [label="yes"];
"Requirements unclear?" -> "Continue forward" [label="no"];
}
```
**You can and should go backward when:**
- Partner reveals new constraint during Phase 2 or 3 → Return to Phase 1
- Validation shows fundamental gap in requirements → Return to Phase 1
- Partner questions approach during Phase 3 → Return to Phase 2
- Something doesn't make sense → Go back and clarify
**Don't force forward linearly** when going backward would give better results.
**Implementation (if continuing):**
- Ask: "Ready to set up for implementation?"
- Use superpowers:using-git-worktrees to create isolated workspace
- **REQUIRED:** Use superpowers:writing-plans to create detailed implementation plan
- Do NOT use platform planning features (e.g., EnterPlanMode, plan mode)
- Do NOT start implementing directly - the writing-plans skill comes first
## Key Principles
| Principle | Application |
|-----------|-------------|
| **One question at a time** | Phase 1: Single question per message, use AskUserQuestion for choices |
| **Structured choices** | Use AskUserQuestion tool for 2-4 options with trade-offs |
| **YAGNI ruthlessly** | Remove unnecessary features from all designs |
| **Explore alternatives** | Always propose 2-3 approaches before settling |
| **Incremental validation** | Present design in sections, validate each |
| **Flexible progression** | Go backward when needed - flexibility > rigidity |
| **Announce usage** | State skill usage at start of session |
- **One question at a time** - Don't overwhelm with multiple questions
- **Multiple choice preferred** - Easier to answer than open-ended when possible
- **YAGNI ruthlessly** - Remove unnecessary features from all designs
- **Explore alternatives** - Always propose 2-3 approaches before settling
- **Incremental validation** - Present design in sections, validate each
- **Be flexible** - Go back and clarify when something doesn't make sense
## Visual Companion (Claude Code Only)
A browser-based visual companion for showing mockups, diagrams, and options during brainstorming. Use it whenever visual representation would make feedback easier than text descriptions alone.
**When the topic involves visual decisions, ask:**
> "This involves some visual decisions. I can show mockups in a browser window so you can see options and give feedback visually. This feature is still new — it can be token-intensive and a bit slow, but it works well for layout, design, and architecture questions. Want to try it? (Requires opening a local URL)"
If they agree, read the detailed guide before proceeding:
`${CLAUDE_PLUGIN_ROOT}/skills/brainstorming/visual-companion.md`

View File

@@ -0,0 +1,49 @@
# Spec Document Reviewer Prompt Template
Use this template when dispatching a spec document reviewer subagent.
**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
**Dispatch after:** Spec document is written to docs/superpowers/specs/
```
Task tool (general-purpose):
description: "Review spec document"
prompt: |
You are a spec document reviewer. Verify this spec is complete and ready for planning.
**Spec to review:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, "TBD", incomplete sections |
| Coverage | Missing error handling, edge cases, integration points |
| Consistency | Internal contradictions, conflicting requirements |
| Clarity | Ambiguous requirements |
| YAGNI | Unrequested features, over-engineering |
| Architecture | Units with clear boundaries, well-defined interfaces, independently understandable and testable |
## CRITICAL
Look especially hard for:
- Any TODO markers or placeholder text
- Sections saying "to be defined later" or "will spec when X is done"
- Sections noticeably less detailed than others
- Units that lack clear boundaries or interfaces — can you understand what each unit does without reading its internals?
## Output Format
## Spec Review
**Status:** ✅ Approved | ❌ Issues Found
**Issues (if any):**
- [Section X]: [specific issue] - [why it matters]
**Recommendations (advisory):**
- [suggestions that don't block approval]
```
**Reviewer returns:** Status, Issues (if any), Recommendations

View File

@@ -0,0 +1,203 @@
# Visual Companion Guide
Browser-based visual brainstorming companion for showing mockups, diagrams, and options.
## When to Use
Use the visual companion when seeing beats describing:
- **UI mockups** — layouts, navigation, component designs
- **Architecture diagrams** — system components, data flow, relationships
- **Complex choices** — multi-option decisions with visual trade-offs
- **Design polish** — when the question is about look and feel
- **Spatial relationships** — file structures, database schemas, state machines
Don't use it for simple text questions, code review, or when the user prefers terminal-only interaction.
## How It Works
The 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, clicks options or types feedback, and you receive their response as JSON.
**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, feedback footer, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
## Starting a Session
```bash
# Start server with persistence (mockups saved to project)
${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/start-server.sh --project-dir /path/to/project
# Returns: {"type":"server-started","port":52341,"url":"http://localhost:52341",
# "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000"}
```
Save `screen_dir` from the response. Tell user to open the URL.
**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.
## The Loop
1. **Start watcher first** (background bash) — avoids race condition:
```bash
${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/wait-for-feedback.sh $SCREEN_DIR
```
2. **Write HTML** to a new file in `screen_dir`:
- Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
- **Never reuse filenames** — each screen gets a fresh file
- Use Write tool — **never use cat/heredoc** (dumps noise into terminal)
- Server automatically serves the newest file
3. **Tell user what to expect:**
- Remind them of the URL (every step, not just first)
- Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
4. **Wait for feedback** — call `TaskOutput(task_id, block=true, timeout=600000)`
- If timeout, call TaskOutput again (watcher still running)
- After 3 timeouts (30 min), say "Let me know when you want to continue"
5. **Process feedback** — returns JSON like `{"choice": "a", "feedback": "make header smaller"}`
6. **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.
7. Repeat until done.
## Writing Content Fragments
Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, feedback footer, interactive JS).
**Minimal example:**
```html
<h2>Which layout works better?</h2>
<p class="subtitle">Consider readability and visual hierarchy</p>
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Single Column</h3>
<p>Clean, focused reading experience</p>
</div>
</div>
<div class="option" data-choice="b" onclick="toggleSelect(this)">
<div class="letter">B</div>
<div class="content">
<h3>Two Column</h3>
<p>Sidebar navigation with main content</p>
</div>
</div>
</div>
```
That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
## CSS Classes Available
The frame template provides these CSS classes for your content:
### Options (A/B/C choices)
```html
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Title</h3>
<p>Description</p>
</div>
</div>
</div>
```
### Cards (visual designs)
```html
<div class="cards">
<div class="card" data-choice="design1" onclick="toggleSelect(this)">
<div class="card-image"><!-- mockup content --></div>
<div class="card-body">
<h3>Name</h3>
<p>Description</p>
</div>
</div>
</div>
```
### Mockup container
```html
<div class="mockup">
<div class="mockup-header">Preview: Dashboard Layout</div>
<div class="mockup-body"><!-- your mockup HTML --></div>
</div>
```
### Split view (side-by-side)
```html
<div class="split">
<div class="mockup"><!-- left --></div>
<div class="mockup"><!-- right --></div>
</div>
```
### Pros/Cons
```html
<div class="pros-cons">
<div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div>
<div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div>
</div>
```
### Mock elements (wireframe building blocks)
```html
<div class="mock-nav">Logo | Home | About | Contact</div>
<div style="display: flex;">
<div class="mock-sidebar">Navigation</div>
<div class="mock-content">Main content area</div>
</div>
<button class="mock-button">Action Button</button>
<input class="mock-input" placeholder="Input field">
<div class="placeholder">Placeholder area</div>
```
### Typography and sections
- `h2` — page title
- `h3` — section heading
- `.subtitle` — secondary text below title
- `.section` — content block with bottom margin
- `.label` — small uppercase label text
## User Feedback Format
```json
{
"choice": "option-id",
"feedback": "user notes"
}
```
Both fields are optional — user may select without notes, or send notes without a selection.
## Design Tips
- **Scale fidelity to the question** — wireframes for layout, polish for polish questions
- **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
- **Iterate before advancing** — if feedback changes current screen, write a new version
- **2-4 options max** per screen
- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
## File Naming
- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
- Never reuse filenames — each screen must be a new file
- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
- Server serves newest file by modification time
## Cleaning Up
```bash
${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/stop-server.sh $SCREEN_DIR
```
If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
## Reference
- Frame template (CSS reference): `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/frame-template.html`
- Helper script (JS API): `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/helper.js`

View File

@@ -1 +0,0 @@
Use your brainstorming skill.

View File

@@ -1 +0,0 @@
Use your Executing-Plans skill.

View File

@@ -1 +0,0 @@
Use your Writing-Plans skill.

View File

@@ -1,6 +1,6 @@
---
name: dispatching-parallel-agents
description: Use when facing 3+ independent failures that can be investigated without shared state or dependencies - dispatches multiple Claude agents to investigate and fix independent problems concurrently
description: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies
---
# Dispatching Parallel Agents

View File

@@ -1,6 +1,6 @@
---
name: executing-plans
description: Use when partner provides a complete implementation plan to execute in controlled batches with review checkpoints - loads plan, reviews critically, executes tasks in batches, reports for review between batches
description: Use when you have a written implementation plan to execute in a separate session with review checkpoints
---
# Executing Plans
@@ -46,7 +46,7 @@ Based on feedback:
After all tasks complete and verified:
- Announce: "I'm using the finishing-a-development-branch skill to complete this work."
- **REQUIRED SUB-SKILL:** Use finishing-a-development-branch
- **REQUIRED SUB-SKILL:** Use superpowers:finishing-a-development-branch
- Follow that skill to verify tests, present options, execute choice
## When to Stop and Ask for Help
@@ -74,3 +74,11 @@ After all tasks complete and verified:
- Reference skills when plan says to
- Between batches: just report and wait
- Stop when blocked, don't guess
- Never start implementation on main/master branch without explicit user consent
## Integration
**Required workflow skills:**
- **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:finishing-a-development-branch** - Complete development after all tasks

View File

@@ -200,6 +200,10 @@ You understand 1,2,3,6. Unclear on 4,5.
✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing."
```
## GitHub Thread Replies
When 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.
## The Bottom Line
**External feedback = suggestions to evaluate, not orders to follow.**

View File

@@ -1,11 +1,11 @@
---
name: requesting-code-review
description: Use when completing tasks, implementing major features, or before merging to verify work meets requirements - dispatches code-reviewer subagent to review implementation against plan or requirements before proceeding
description: Use when completing tasks, implementing major features, or before merging to verify work meets requirements
---
# Requesting Code Review
Dispatch code-reviewer subagent to catch issues before they cascade.
Dispatch superpowers:code-reviewer subagent to catch issues before they cascade.
**Core principle:** Review early, review often.
@@ -31,7 +31,7 @@ HEAD_SHA=$(git rev-parse HEAD)
**2. Dispatch code-reviewer subagent:**
Use Task tool with code-reviewer type, fill template at `code-reviewer.md`
Use Task tool with superpowers:code-reviewer type, fill template at `code-reviewer.md`
**Placeholders:**
- `{WHAT_WAS_IMPLEMENTED}` - What you just built
@@ -56,9 +56,9 @@ You: Let me request code review before proceeding.
BASE_SHA=$(git log --oneline | grep "Task 1" | head -1 | awk '{print $1}')
HEAD_SHA=$(git rev-parse HEAD)
[Dispatch code-reviewer subagent]
[Dispatch superpowers:code-reviewer subagent]
WHAT_WAS_IMPLEMENTED: Verification and repair functions for conversation index
PLAN_OR_REQUIREMENTS: Task 2 from docs/plans/deployment-plan.md
PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md
BASE_SHA: a7981ec
HEAD_SHA: 3df7661
DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types

View File

@@ -1,194 +0,0 @@
---
name: sharing-skills
description: Use when you've developed a broadly useful skill and want to contribute it upstream via pull request - guides process of branching, committing, pushing, and creating PR to contribute skills back to upstream repository
---
# Sharing Skills
## Overview
Contribute skills from your local branch back to the upstream repository.
**Workflow:** Branch → Edit/Create skill → Commit → Push → PR
## When to Share
**Share when:**
- Skill applies broadly (not project-specific)
- Pattern/technique others would benefit from
- Well-tested and documented
- Follows writing-skills guidelines
**Keep personal when:**
- Project-specific or organization-specific
- Experimental or unstable
- Contains sensitive information
- Too narrow/niche for general use
## Prerequisites
- `gh` CLI installed and authenticated
- Working directory is `~/.config/superpowers/skills/` (your local clone)
- **REQUIRED:** Skill has been tested using writing-skills TDD process
## Sharing Workflow
### 1. Ensure You're on Main and Synced
```bash
cd ~/.config/superpowers/skills/
git checkout main
git pull upstream main
git push origin main # Push to your fork
```
### 2. Create Feature Branch
```bash
# Branch name: add-skillname-skill
skill_name="your-skill-name"
git checkout -b "add-${skill_name}-skill"
```
### 3. Create or Edit Skill
```bash
# Work on your skill in skills/
# Create new skill or edit existing one
# Skill should be in skills/category/skill-name/SKILL.md
```
### 4. Commit Changes
```bash
# Add and commit
git add skills/your-skill-name/
git commit -m "Add ${skill_name} skill
$(cat <<'EOF'
Brief description of what this skill does and why it's useful.
Tested with: [describe testing approach]
EOF
)"
```
### 5. Push to Your Fork
```bash
git push -u origin "add-${skill_name}-skill"
```
### 6. Create Pull Request
```bash
# Create PR to upstream using gh CLI
gh pr create \
--repo upstream-org/upstream-repo \
--title "Add ${skill_name} skill" \
--body "$(cat <<'EOF'
## Summary
Brief description of the skill and what problem it solves.
## Testing
Describe how you tested this skill (pressure scenarios, baseline tests, etc.).
## Context
Any additional context about why this skill is needed and how it should be used.
EOF
)"
```
## Complete Example
Here's a complete example of sharing a skill called "async-patterns":
```bash
# 1. Sync with upstream
cd ~/.config/superpowers/skills/
git checkout main
git pull upstream main
git push origin main
# 2. Create branch
git checkout -b "add-async-patterns-skill"
# 3. Create/edit the skill
# (Work on skills/async-patterns/SKILL.md)
# 4. Commit
git add skills/async-patterns/
git commit -m "Add async-patterns skill
Patterns for handling asynchronous operations in tests and application code.
Tested with: Multiple pressure scenarios testing agent compliance."
# 5. Push
git push -u origin "add-async-patterns-skill"
# 6. Create PR
gh pr create \
--repo upstream-org/upstream-repo \
--title "Add async-patterns skill" \
--body "## Summary
Patterns for handling asynchronous operations correctly in tests and application code.
## Testing
Tested with multiple application scenarios. Agents successfully apply patterns to new code.
## Context
Addresses common async pitfalls like race conditions, improper error handling, and timing issues."
```
## After PR is Merged
Once your PR is merged:
1. Sync your local main branch:
```bash
cd ~/.config/superpowers/skills/
git checkout main
git pull upstream main
git push origin main
```
2. Delete the feature branch:
```bash
git branch -d "add-${skill_name}-skill"
git push origin --delete "add-${skill_name}-skill"
```
## Troubleshooting
**"gh: command not found"**
- Install GitHub CLI: https://cli.github.com/
- Authenticate: `gh auth login`
**"Permission denied (publickey)"**
- Check SSH keys: `gh auth status`
- Set up SSH: https://docs.github.com/en/authentication
**"Skill already exists"**
- You're creating a modified version
- Consider different skill name or coordinate with the skill's maintainer
**PR merge conflicts**
- Rebase on latest upstream: `git fetch upstream && git rebase upstream/main`
- Resolve conflicts
- Force push: `git push -f origin your-branch`
## Multi-Skill Contributions
**Do NOT batch multiple skills in one PR.**
Each skill should:
- Have its own feature branch
- Have its own PR
- Be independently reviewable
**Why?** Individual skills can be reviewed, iterated, and merged independently.
## Related Skills
- **writing-skills** - REQUIRED: How to create well-tested skills before sharing

View File

@@ -1,140 +1,192 @@
---
name: subagent-driven-development
description: Use when executing implementation plans with independent tasks in the current session - dispatches fresh subagent for each task with code review between tasks, enabling fast iteration with quality gates
description: Use when executing implementation plans with independent tasks in the current session
---
# Subagent-Driven Development
Execute plan by dispatching fresh subagent per task, with code review after each.
Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.
**Core principle:** Fresh subagent per task + review between tasks = high quality, fast iteration
**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration
## Overview
## When to Use
```dot
digraph when_to_use {
"Have implementation plan?" [shape=diamond];
"Tasks mostly independent?" [shape=diamond];
"Stay in this session?" [shape=diamond];
"subagent-driven-development" [shape=box];
"executing-plans" [shape=box];
"Manual execution or brainstorm first" [shape=box];
"Have implementation plan?" -> "Tasks mostly independent?" [label="yes"];
"Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"];
"Tasks mostly independent?" -> "Stay in this session?" [label="yes"];
"Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"];
"Stay in this session?" -> "subagent-driven-development" [label="yes"];
"Stay in this session?" -> "executing-plans" [label="no - parallel session"];
}
```
**vs. Executing Plans (parallel session):**
- Same session (no context switch)
- Fresh subagent per task (no context pollution)
- Code review after each task (catch issues early)
- Two-stage review after each task: spec compliance first, then code quality
- Faster iteration (no human-in-loop between tasks)
**When to use:**
- Staying in this session
- Tasks are mostly independent
- Want continuous progress with quality gates
**When NOT to use:**
- Need to review plan first (use executing-plans)
- Tasks are tightly coupled (manual execution better)
- Plan needs revision (brainstorm first)
## The Process
### 1. Load Plan
```dot
digraph process {
rankdir=TB;
Read plan file, create TodoWrite with all tasks.
subgraph cluster_per_task {
label="Per Task";
"Dispatch implementer subagent (./implementer-prompt.md)" [shape=box];
"Implementer subagent asks questions?" [shape=diamond];
"Answer questions, provide context" [shape=box];
"Implementer subagent implements, tests, commits, self-reviews" [shape=box];
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box];
"Spec reviewer subagent confirms code matches spec?" [shape=diamond];
"Implementer subagent fixes spec gaps" [shape=box];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box];
"Code quality reviewer subagent approves?" [shape=diamond];
"Implementer subagent fixes quality issues" [shape=box];
"Mark task complete in TodoWrite" [shape=box];
}
### 2. Execute Task with Subagent
"Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box];
"More tasks remain?" [shape=diamond];
"Dispatch final code reviewer subagent for entire implementation" [shape=box];
"Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
For each task:
**Dispatch fresh subagent:**
```
Task tool (general-purpose):
description: "Implement Task N: [task name]"
prompt: |
You are implementing Task N from [plan-file].
Read that task carefully. Your job is to:
1. Implement exactly what the task specifies
2. Write tests (following TDD if task says to)
3. Verify implementation works
4. Commit your work
5. Report back
Work from: [directory]
Report: What you implemented, what you tested, test results, files changed, any issues
"Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?";
"Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"];
"Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"];
"Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)";
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?";
"Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"];
"Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"];
"Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?";
"Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"];
"Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"];
"Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"];
"Mark task complete in TodoWrite" -> "More tasks remain?";
"More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"];
"More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"];
"Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch";
}
```
**Subagent reports back** with summary of work.
## Model Selection
### 3. Review Subagent's Work
Use the least powerful model that can handle each role to conserve cost and increase speed.
**Dispatch code-reviewer subagent:**
```
Task tool (code-reviewer):
Use template at requesting-code-review/code-reviewer.md
**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.
WHAT_WAS_IMPLEMENTED: [from subagent's report]
PLAN_OR_REQUIREMENTS: Task N from [plan-file]
BASE_SHA: [commit before task]
HEAD_SHA: [current commit]
DESCRIPTION: [task summary]
```
**Integration and judgment tasks** (multi-file coordination, pattern matching, debugging): use a standard model.
**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment
**Architecture, design, and review tasks**: use the most capable available model.
### 4. Apply Review Feedback
**Task complexity signals:**
- Touches 1-2 files with a complete spec → cheap model
- Touches multiple files with integration concerns → standard model
- Requires design judgment or broad codebase understanding → most capable model
**If issues found:**
- Fix Critical issues immediately
- Fix Important issues before next task
- Note Minor issues
## Handling Implementer Status
**Dispatch follow-up subagent if needed:**
```
"Fix issues from code review: [list issues]"
```
Implementer subagents report one of four statuses. Handle each appropriately:
### 5. Mark Complete, Next Task
**DONE:** Proceed to spec compliance review.
- Mark task as completed in TodoWrite
- Move to next task
- Repeat steps 2-5
**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.
### 6. Final Review
**NEEDS_CONTEXT:** The implementer needs information that wasn't provided. Provide the missing context and re-dispatch.
After all tasks complete, dispatch final code-reviewer:
- Reviews entire implementation
- Checks all plan requirements met
- Validates overall architecture
**BLOCKED:** The implementer cannot complete the task. Assess the blocker:
1. If it's a context problem, provide more context and re-dispatch with the same model
2. If the task requires more reasoning, re-dispatch with a more capable model
3. If the task is too large, break it into smaller pieces
4. If the plan itself is wrong, escalate to the human
### 7. Complete Development
**Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change.
After final review passes:
- Announce: "I'm using the finishing-a-development-branch skill to complete this work."
- **REQUIRED SUB-SKILL:** Use finishing-a-development-branch
- Follow that skill to verify tests, present options, execute choice
## Prompt Templates
- `./implementer-prompt.md` - Dispatch implementer subagent
- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent
- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent
## Example Workflow
```
You: I'm using Subagent-Driven Development to execute this plan.
[Load plan, create TodoWrite]
[Read plan file once: docs/superpowers/plans/feature-plan.md]
[Extract all 5 tasks with full text and context]
[Create TodoWrite with all tasks]
Task 1: Hook installation script
[Dispatch implementation subagent]
Subagent: Implemented install-hook with tests, 5/5 passing
[Get Task 1 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
[Get git SHAs, dispatch code-reviewer]
Reviewer: Strengths: Good test coverage. Issues: None. Ready.
Implementer: "Before I begin - should the hook be installed at user or system level?"
You: "User level (~/.config/superpowers/hooks/)"
Implementer: "Got it. Implementing now..."
[Later] Implementer:
- Implemented install-hook command
- Added tests, 5/5 passing
- Self-review: Found I missed --force flag, added it
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra
[Get git SHAs, dispatch code quality reviewer]
Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.
[Mark Task 1 complete]
Task 2: Recovery modes
[Dispatch implementation subagent]
Subagent: Added verify/repair, 8/8 tests passing
[Get Task 2 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
[Dispatch code-reviewer]
Reviewer: Strengths: Solid. Issues (Important): Missing progress reporting
Implementer: [No questions, proceeds]
Implementer:
- Added verify/repair modes
- 8/8 tests passing
- Self-review: All good
- Committed
[Dispatch fix subagent]
Fix subagent: Added progress every 100 conversations
[Dispatch spec compliance reviewer]
Spec reviewer: ❌ Issues:
- Missing: Progress reporting (spec says "report every 100 items")
- Extra: Added --json flag (not requested)
[Verify fix, mark Task 2 complete]
[Implementer fixes issues]
Implementer: Removed --json flag, added progress reporting
[Spec reviewer reviews again]
Spec reviewer: ✅ Spec compliant now
[Dispatch code quality reviewer]
Code reviewer: Strengths: Solid. Issues (Important): Magic number (100)
[Implementer fixes]
Implementer: Extracted PROGRESS_INTERVAL constant
[Code reviewer reviews again]
Code reviewer: ✅ Approved
[Mark Task 2 complete]
...
@@ -151,23 +203,58 @@ Done!
- Subagents follow TDD naturally
- Fresh context per task (no confusion)
- Parallel-safe (subagents don't interfere)
- Subagent can ask questions (before AND during work)
**vs. Executing Plans:**
- Same session (no handoff)
- Continuous progress (no waiting)
- Review checkpoints automatic
**Efficiency gains:**
- No file reading overhead (controller provides full text)
- Controller curates exactly what context is needed
- Subagent gets complete information upfront
- Questions surfaced before work begins (not after)
**Quality gates:**
- Self-review catches issues before handoff
- Two-stage review: spec compliance, then code quality
- Review loops ensure fixes actually work
- Spec compliance prevents over/under-building
- Code quality ensures implementation is well-built
**Cost:**
- More subagent invocations
- More subagent invocations (implementer + 2 reviewers per task)
- Controller does more prep work (extracting all tasks upfront)
- Review loops add iterations
- But catches issues early (cheaper than debugging later)
## Red Flags
**Never:**
- Skip code review between tasks
- Proceed with unfixed Critical issues
- Start implementation on main/master branch without explicit user consent
- Skip reviews (spec compliance OR code quality)
- Proceed with unfixed issues
- Dispatch multiple implementation subagents in parallel (conflicts)
- Implement without reading plan task
- Make subagent read plan file (provide full text instead)
- Skip scene-setting context (subagent needs to understand where task fits)
- Ignore subagent questions (answer before letting them proceed)
- Accept "close enough" on spec compliance (spec reviewer found issues = not done)
- Skip review loops (reviewer found issues = implementer fixes = review again)
- Let implementer self-review replace actual review (both are needed)
- **Start code quality review before spec compliance is ✅** (wrong order)
- Move to next task while either review has open issues
**If subagent asks questions:**
- Answer clearly and completely
- Provide additional context if needed
- Don't rush them into implementation
**If reviewer finds issues:**
- Implementer (same subagent) fixes them
- Reviewer reviews again
- Repeat until approved
- Don't skip the re-review
**If subagent fails task:**
- Dispatch fix subagent with specific instructions
@@ -176,14 +263,13 @@ Done!
## Integration
**Required workflow skills:**
- **writing-plans** - REQUIRED: Creates the plan that this skill executes
- **requesting-code-review** - REQUIRED: Review after each task (see Step 3)
- **finishing-a-development-branch** - REQUIRED: Complete development after all tasks (see Step 7)
- **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:requesting-code-review** - Code review template for reviewer subagents
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
**Subagents must use:**
- **test-driven-development** - Subagents follow TDD for each task
**Subagents should use:**
- **superpowers:test-driven-development** - Subagents follow TDD for each task
**Alternative workflow:**
- **executing-plans** - Use for parallel session instead of same-session execution
See code-reviewer template: requesting-code-review/code-reviewer.md
- **superpowers:executing-plans** - Use for parallel session instead of same-session execution

View File

@@ -0,0 +1,26 @@
# Code Quality Reviewer Prompt Template
Use this template when dispatching a code quality reviewer subagent.
**Purpose:** Verify implementation is well-built (clean, tested, maintainable)
**Only dispatch after spec compliance review passes.**
```
Task tool (superpowers:code-reviewer):
Use template at requesting-code-review/code-reviewer.md
WHAT_WAS_IMPLEMENTED: [from implementer's report]
PLAN_OR_REQUIREMENTS: Task N from [plan-file]
BASE_SHA: [commit before task]
HEAD_SHA: [current commit]
DESCRIPTION: [task summary]
```
**In addition to standard code quality concerns, the reviewer should check:**
- Does each file have one clear responsibility with a well-defined interface?
- Are units decomposed so they can be understood and tested independently?
- Is the implementation following the file structure from the plan?
- 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.)
**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment

View File

@@ -0,0 +1,113 @@
# Implementer Subagent Prompt Template
Use this template when dispatching an implementer subagent.
```
Task tool (general-purpose):
description: "Implement Task N: [task name]"
prompt: |
You are implementing Task N: [task name]
## Task Description
[FULL TEXT of task from plan - paste it here, don't make subagent read file]
## Context
[Scene-setting: where this fits, dependencies, architectural context]
## Before You Begin
If you have questions about:
- The requirements or acceptance criteria
- The approach or implementation strategy
- Dependencies or assumptions
- Anything unclear in the task description
**Ask them now.** Raise any concerns before starting work.
## Your Job
Once you're clear on requirements:
1. Implement exactly what the task specifies
2. Write tests (following TDD if task says to)
3. Verify implementation works
4. Commit your work
5. Self-review (see below)
6. Report back
Work from: [directory]
**While you work:** If you encounter something unexpected or unclear, **ask questions**.
It's always OK to pause and clarify. Don't guess or make assumptions.
## Code Organization
You reason best about code you can hold in context at once, and your edits are more
reliable when files are focused. Keep this in mind:
- Follow the file structure defined in the plan
- Each file should have one clear responsibility with a well-defined interface
- If a file you're creating is growing beyond the plan's intent, stop and report
it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance
- If an existing file you're modifying is already large or tangled, work carefully
and note it as a concern in your report
- In existing codebases, follow established patterns. Improve code you're touching
the way a good developer would, but don't restructure things outside your task.
## When You're in Over Your Head
It is always OK to stop and say "this is too hard for me." Bad work is worse than
no work. You will not be penalized for escalating.
**STOP and escalate when:**
- The task requires architectural decisions with multiple valid approaches
- You need to understand code beyond what was provided and can't find clarity
- You feel uncertain about whether your approach is correct
- The task involves restructuring existing code in ways the plan didn't anticipate
- You've been reading file after file trying to understand the system without progress
**How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe
specifically what you're stuck on, what you've tried, and what kind of help you need.
The controller can provide more context, re-dispatch with a more capable model,
or break the task into smaller pieces.
## Before Reporting Back: Self-Review
Review your work with fresh eyes. Ask yourself:
**Completeness:**
- Did I fully implement everything in the spec?
- Did I miss any requirements?
- Are there edge cases I didn't handle?
**Quality:**
- Is this my best work?
- Are names clear and accurate (match what things do, not how they work)?
- Is the code clean and maintainable?
**Discipline:**
- Did I avoid overbuilding (YAGNI)?
- Did I only build what was requested?
- Did I follow existing patterns in the codebase?
**Testing:**
- Do tests actually verify behavior (not just mock behavior)?
- Did I follow TDD if required?
- Are tests comprehensive?
If you find issues during self-review, fix them now before reporting.
## Report Format
When done, report:
- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
- What you implemented (or what you attempted, if blocked)
- What you tested and test results
- Files changed
- Self-review findings (if any)
- Any issues or concerns
Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.
Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need
information that wasn't provided. Never silently produce work you're unsure about.
```

View File

@@ -0,0 +1,61 @@
# Spec Compliance Reviewer Prompt Template
Use this template when dispatching a spec compliance reviewer subagent.
**Purpose:** Verify implementer built what was requested (nothing more, nothing less)
```
Task tool (general-purpose):
description: "Review spec compliance for Task N"
prompt: |
You are reviewing whether an implementation matches its specification.
## What Was Requested
[FULL TEXT of task requirements]
## What Implementer Claims They Built
[From implementer's report]
## CRITICAL: Do Not Trust the Report
The implementer finished suspiciously quickly. Their report may be incomplete,
inaccurate, or optimistic. You MUST verify everything independently.
**DO NOT:**
- Take their word for what they implemented
- Trust their claims about completeness
- Accept their interpretation of requirements
**DO:**
- Read the actual code they wrote
- Compare actual implementation to requirements line by line
- Check for missing pieces they claimed to implement
- Look for extra features they didn't mention
## Your Job
Read the implementation code and verify:
**Missing requirements:**
- Did they implement everything that was requested?
- Are there requirements they skipped or missed?
- Did they claim something works but didn't actually implement it?
**Extra/unneeded work:**
- Did they build things that weren't requested?
- Did they over-engineer or add unnecessary features?
- Did they add "nice to haves" that weren't in spec?
**Misunderstandings:**
- Did they interpret requirements differently than intended?
- Did they solve the wrong problem?
- Did they implement the right feature but wrong way?
**Verify by reading code, not by trusting report.**
Report:
- ✅ Spec compliant (if everything matches after code inspection)
- ❌ Issues found: [list specifically what's missing or extra, with file:line references]
```

View File

@@ -1,6 +1,6 @@
---
name: systematic-debugging
description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes - four-phase framework (root cause investigation, pattern analysis, hypothesis testing, implementation) that ensures understanding before attempting solutions
description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
---
# Systematic Debugging
@@ -111,7 +111,7 @@ You MUST complete each phase before proceeding to the next.
**WHEN error is deep in call stack:**
**REQUIRED SUB-SKILL:** Use root-cause-tracing for backward tracing technique
See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
**Quick version:**
- Where does bad value originate?
@@ -176,7 +176,7 @@ You MUST complete each phase before proceeding to the next.
- Automated test if possible
- One-off test script if no framework
- MUST have before fixing
- **REQUIRED SUB-SKILL:** Use test-driven-development for writing proper failing tests
- Use the `superpowers:test-driven-development` skill for writing proper failing tests
2. **Implement Single Fix**
- Address the root cause identified
@@ -275,16 +275,17 @@ If systematic investigation reveals issue is truly environmental, timing-depende
**But:** 95% of "no root cause" cases are incomplete investigation.
## Integration with Other Skills
## Supporting Techniques
**This skill requires using:**
- **root-cause-tracing** - REQUIRED when error is deep in call stack (see Phase 1, Step 5)
- **test-driven-development** - REQUIRED for creating failing test case (see Phase 4, Step 1)
These techniques are part of systematic debugging and available in this directory:
**Complementary skills:**
- **defense-in-depth** - Add validation at multiple layers after finding root cause
- **condition-based-waiting** - Replace arbitrary timeouts identified in Phase 2
- **verification-before-completion** - Verify fix worked before claiming success
- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
**Related skills:**
- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)
- **superpowers:verification-before-completion** - Verify fix worked before claiming success
## Real-World Impact

View File

@@ -1,8 +1,3 @@
---
name: condition-based-waiting
description: Use when tests have race conditions, timing dependencies, or inconsistent pass/fail behavior - replaces arbitrary timeouts with condition polling to wait for actual state changes, eliminating flaky tests from timing guesses
---
# Condition-Based Waiting
## Overview
@@ -84,7 +79,7 @@ async function waitFor<T>(
}
```
See @example.ts for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
## Common Mistakes

View File

@@ -1,8 +1,3 @@
---
name: defense-in-depth
description: Use when invalid data causes failures deep in execution, requiring validation at multiple system layers - validates at every layer data passes through to make bugs structurally impossible
---
# Defense-in-Depth Validation
## Overview

View File

@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Bisection script to find which test creates unwanted files/state
# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'

View File

@@ -1,8 +1,3 @@
---
name: root-cause-tracing
description: Use when errors occur deep in execution and you need to trace back to find the original trigger - systematically traces bugs backward through call stack, adding instrumentation when needed, to identify source of invalid data or incorrect behavior
---
# Root Cause Tracing
## Overview
@@ -103,7 +98,7 @@ npm test 2>&1 | grep 'DEBUG git init'
If something appears during tests but you don't know which test:
Use the bisection script: @find-polluter.sh
Use the bisection script `find-polluter.sh` in this directory:
```bash
./find-polluter.sh '.git' 'src/**/*.test.ts'

View File

@@ -1,6 +1,6 @@
---
name: test-driven-development
description: Use when implementing any feature or bugfix, before writing implementation code - write the test first, watch it fail, write minimal code to pass; ensures tests actually verify behavior by requiring failure first
description: Use when implementing any feature or bugfix, before writing implementation code
---
# Test-Driven Development (TDD)
@@ -354,6 +354,13 @@ Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix
Never fix bugs without a test.
## Testing Anti-Patterns
When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
- Testing mock behavior instead of real behavior
- Adding test-only methods to production classes
- Mocking without understanding dependencies
## Final Rule
```

View File

@@ -1,10 +1,7 @@
---
name: testing-anti-patterns
description: Use when writing or changing tests, adding mocks, or tempted to add test-only methods to production code - prevents testing mock behavior, production pollution with test-only methods, and mocking without understanding dependencies
---
# Testing Anti-Patterns
**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.
## Overview
Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.

View File

@@ -52,14 +52,14 @@ Which would you prefer?
### For Project-Local Directories (.worktrees or worktrees)
**MUST verify .gitignore before creating worktree:**
**MUST verify directory is ignored before creating worktree:**
```bash
# Check if directory pattern in .gitignore
grep -q "^\.worktrees/$" .gitignore || grep -q "^worktrees/$" .gitignore
# Check if directory is ignored (respects local, global, and system gitignore)
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
```
**If NOT in .gitignore:**
**If NOT ignored:**
Per Jesse's rule "Fix broken things immediately":
1. Add appropriate line to .gitignore
@@ -145,29 +145,33 @@ Ready to implement <feature-name>
| Situation | Action |
|-----------|--------|
| `.worktrees/` exists | Use it (verify .gitignore) |
| `worktrees/` exists | Use it (verify .gitignore) |
| `.worktrees/` exists | Use it (verify ignored) |
| `worktrees/` exists | Use it (verify ignored) |
| Both exist | Use `.worktrees/` |
| Neither exists | Check CLAUDE.md → Ask user |
| Directory not in .gitignore | Add it immediately + commit |
| Directory not ignored | Add to .gitignore + commit |
| Tests fail during baseline | Report failures + ask |
| No package.json/Cargo.toml | Skip dependency install |
## Common Mistakes
**Skipping .gitignore verification**
- **Problem:** Worktree contents get tracked, pollute git status
- **Fix:** Always grep .gitignore before creating project-local worktree
### Skipping ignore verification
- **Problem:** Worktree contents get tracked, pollute git status
- **Fix:** Always use `git check-ignore` before creating project-local worktree
### Assuming directory location
**Assuming directory location**
- **Problem:** Creates inconsistency, violates project conventions
- **Fix:** Follow priority: existing > CLAUDE.md > ask
**Proceeding with failing tests**
### Proceeding with failing tests
- **Problem:** Can't distinguish new bugs from pre-existing issues
- **Fix:** Report failures, get explicit permission to proceed
**Hardcoding setup commands**
### Hardcoding setup commands
- **Problem:** Breaks on projects using different tools
- **Fix:** Auto-detect from project files (package.json, etc.)
@@ -177,7 +181,7 @@ Ready to implement <feature-name>
You: I'm using the using-git-worktrees skill to set up an isolated workspace.
[Check .worktrees/ - exists]
[Verify .gitignore - contains .worktrees/]
[Verify ignored - git check-ignore confirms .worktrees/ is ignored]
[Create worktree: git worktree add .worktrees/auth -b feature/auth]
[Run npm install]
[Run npm test - 47 passing]
@@ -190,7 +194,7 @@ Ready to implement auth feature
## Red Flags
**Never:**
- Create worktree without .gitignore verification (project-local)
- Create worktree without verifying it's ignored (project-local)
- Skip baseline test verification
- Proceed with failing tests without asking
- Assume directory location when ambiguous
@@ -198,7 +202,7 @@ Ready to implement auth feature
**Always:**
- Follow directory priority: existing > CLAUDE.md > ask
- Verify .gitignore for project-local
- Verify directory is ignored for project-local
- Auto-detect and run project setup
- Verify clean test baseline
@@ -206,8 +210,9 @@ Ready to implement auth feature
**Called by:**
- **brainstorming** (Phase 4) - REQUIRED when design is approved and implementation follows
- **subagent-driven-development** - REQUIRED before executing any tasks
- **executing-plans** - REQUIRED before executing any tasks
- Any skill needing isolated workspace
**Pairs with:**
- **finishing-a-development-branch** - REQUIRED for cleanup after work complete
- **executing-plans** or **subagent-driven-development** - Work happens in this worktree

View File

@@ -1,79 +1,97 @@
---
name: using-superpowers
description: Use when starting any conversation - establishes mandatory workflows for finding and using skills, including using Read tool before announcing usage, following brainstorming before coding, and creating TodoWrite todos for checklists
description: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions
---
# Getting Started with Skills
<EXTREMELY-IMPORTANT>
If you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill.
## Critical Rules
IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.
1. **Follow mandatory workflows.** Brainstorming before coding. Check for relevant skills before ANY task.
This is not negotiable. This is not optional. You cannot rationalize your way out of this.
</EXTREMELY-IMPORTANT>
2. Execute skills with the Skill tool
## Instruction Priority
## Mandatory: Before ANY Task
Superpowers skills override default system prompt behavior, but **user instructions always take precedence**:
**1. If a relevant skill exists, YOU MUST use it:**
1. **User's explicit instructions** (CLAUDE.md, direct requests) — highest priority
2. **Superpowers skills** — override default system behavior where they conflict
3. **Default system prompt** — lowest priority
- Announce: "I've read [Skill Name] skill and I'm using it to [purpose]"
- Follow it exactly
If CLAUDE.md says "don't use TDD" and a skill says "always use TDD," follow CLAUDE.md. The user is in control.
**Don't rationalize:**
- "I remember this skill" - Skills evolve. Read the current version.
- "This doesn't count as a task" - It counts. Find and read skills.
## How to Access Skills
**Why:** Skills document proven techniques that save time and prevent mistakes. Not using available skills means repeating solved problems and making known errors.
**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.
If a skill for your task exists, you must use it or you will fail at your task.
**In other environments:** Check your platform's documentation for how skills are loaded.
## Skills with Checklists
# Using Skills
If a skill has a checklist, YOU MUST create TodoWrite todos for EACH item.
## The Rule
**Don't:**
- Work through checklist mentally
- Skip creating todos "to save time"
- Batch multiple items into one todo
- Mark complete without doing them
**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.
**Why:** Checklists without TodoWrite tracking = steps get skipped. Every time. The overhead of TodoWrite is tiny compared to the cost of missing steps.
```dot
digraph skill_flow {
"User message received" [shape=doublecircle];
"Might any skill apply?" [shape=diamond];
"Invoke Skill tool" [shape=box];
"Announce: 'Using [skill] to [purpose]'" [shape=box];
"Has checklist?" [shape=diamond];
"Create TodoWrite todo per item" [shape=box];
"Follow skill exactly" [shape=box];
"Respond (including clarifications)" [shape=doublecircle];
## Announcing Skill Usage
"User message received" -> "Might any skill apply?";
"Might any skill apply?" -> "Invoke Skill tool" [label="yes, even 1%"];
"Might any skill apply?" -> "Respond (including clarifications)" [label="definitely not"];
"Invoke Skill tool" -> "Announce: 'Using [skill] to [purpose]'";
"Announce: 'Using [skill] to [purpose]'" -> "Has checklist?";
"Has checklist?" -> "Create TodoWrite todo per item" [label="yes"];
"Has checklist?" -> "Follow skill exactly" [label="no"];
"Create TodoWrite todo per item" -> "Follow skill exactly";
}
```
Before using a skill, announce that you are using it.
"I'm using [Skill Name] to [what you're doing]."
## Red Flags
**Examples:**
- "I'm using the brainstorming skill to refine your idea into a design."
- "I'm using the test-driven-development skill to implement this feature."
These thoughts mean STOP—you're rationalizing:
**Why:** Transparency helps your human partner understand your process and catch errors early. It also confirms you actually read the skill.
| Thought | Reality |
|---------|---------|
| "This is just a simple question" | Questions are tasks. Check for skills. |
| "I need more context first" | Skill check comes BEFORE clarifying questions. |
| "Let me explore the codebase first" | Skills tell you HOW to explore. Check first. |
| "I can check git/files quickly" | Files lack conversation context. Check for skills. |
| "Let me gather information first" | Skills tell you HOW to gather information. |
| "This doesn't need a formal skill" | If a skill exists, use it. |
| "I remember this skill" | Skills evolve. Read current version. |
| "This doesn't count as a task" | Action = task. Check for skills. |
| "The skill is overkill" | Simple things become complex. Use it. |
| "I'll just do this one thing first" | Check BEFORE doing anything. |
| "This feels productive" | Undisciplined action wastes time. Skills prevent this. |
| "I know what that means" | Knowing the concept ≠ using the skill. Invoke it. |
# About these skills
## Skill Priority
**Many skills contain rigid rules (TDD, debugging, verification).** Follow them exactly. Don't adapt away the discipline.
When multiple skills could apply, use this order:
**Some skills are flexible patterns (architecture, naming).** Adapt core principles to your context.
1. **Process skills first** (brainstorming, debugging) - these determine HOW to approach the task
2. **Implementation skills second** (frontend-design, mcp-builder) - these guide execution
The skill itself tells you which type it is.
"Let's build X" → brainstorming first, then implementation skills.
"Fix this bug" → debugging first, then domain-specific skills.
## Instructions ≠ Permission to Skip Workflows
## Skill Types
Your human partner's specific instructions describe WHAT to do, not HOW.
**Rigid** (TDD, debugging): Follow exactly. Don't adapt away discipline.
"Add X", "Fix Y" = the goal, NOT permission to skip brainstorming, TDD, or RED-GREEN-REFACTOR.
**Flexible** (patterns): Adapt principles to context.
**Red flags:** "Instruction was specific" • "Seems simple" • "Workflow is overkill"
The skill itself tells you which.
**Why:** Specific instructions mean clear requirements, which is when workflows matter MOST. Skipping process on "simple" tasks is how simple tasks become complex problems.
## User Instructions
## Summary
**Starting any task:**
1. If relevant skill exists → Use the skill
3. Announce you're using it
4. Follow what it says
**Skill has checklist?** TodoWrite for every item.
**Finding a relevant skill = mandatory to read and use it. Not optional.**
Instructions say WHAT, not HOW. "Add X" or "Fix Y" doesn't mean skip workflows.

View File

@@ -1,6 +1,6 @@
---
name: writing-plans
description: Use when design is complete and you need detailed implementation tasks for engineers with zero codebase context - creates comprehensive implementation plans with exact file paths, complete code examples, and verification steps assuming engineer has minimal domain knowledge
description: Use when you have a spec or requirements for a multi-step task, before touching code
---
# Writing Plans
@@ -15,7 +15,19 @@ Assume they are a skilled developer, but know almost nothing about our toolset o
**Context:** This should be run in a dedicated worktree (created by brainstorming skill).
**Save plans to:** `docs/plans/YYYY-MM-DD-<feature-name>.md`
**Save plans to:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
- (User preferences for plan location override this default)
## File Structure
Before 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.
- Design units with clear boundaries and well-defined interfaces. Each file should have one clear responsibility.
- 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.
- Files that change together should live together. Split by responsibility, not by technical layer.
- 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.
This structure informs the task decomposition. Each task should produce self-contained changes that make sense independently.
## Bite-Sized Task Granularity
@@ -33,7 +45,7 @@ Assume they are a skilled developer, but know almost nothing about our toolset o
```markdown
# [Feature Name] Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use executing-plans to implement this plan task-by-task.
> **For Claude:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** [One sentence describing what this builds]
@@ -54,7 +66,7 @@ Assume they are a skilled developer, but know almost nothing about our toolset o
- Modify: `exact/path/to/existing.py:123-145`
- Test: `tests/exact/path/to/test.py`
**Step 1: Write the failing test**
- [ ] **Step 1: Write the failing test**
```python
def test_specific_behavior():
@@ -62,24 +74,24 @@ def test_specific_behavior():
assert result == expected
```
**Step 2: Run test to verify it fails**
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/path/test.py::test_name -v`
Expected: FAIL with "function not defined"
**Step 3: Write minimal implementation**
- [ ] **Step 3: Write minimal implementation**
```python
def function(input):
return expected
```
**Step 4: Run test to verify it passes**
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/path/test.py::test_name -v`
Expected: PASS
**Step 5: Commit**
- [ ] **Step 5: Commit**
```bash
git add tests/path/test.py src/path/file.py
@@ -94,23 +106,38 @@ git commit -m "feat: add specific feature"
- Reference relevant skills with @ syntax
- DRY, YAGNI, TDD, frequent commits
## Plan Review Loop
After completing each chunk of the plan:
1. Dispatch plan-document-reviewer subagent (see plan-document-reviewer-prompt.md) for the current chunk
- Provide: chunk content, path to spec document
2. If ❌ Issues Found:
- Fix the issues in the chunk
- Re-dispatch reviewer for that chunk
- Repeat until ✅ Approved
3. If ✅ Approved: proceed to next chunk (or execution handoff if last chunk)
**Chunk boundaries:** Use `## Chunk N: <name>` headings to delimit chunks. Each chunk should be ≤1000 lines and logically self-contained.
**Review loop guidance:**
- Same agent that wrote the plan fixes it (preserves context)
- If loop exceeds 5 iterations, surface to human for guidance
- Reviewers are advisory - explain disagreements if you believe feedback is incorrect
## Execution Handoff
After saving the plan, offer execution choice:
After saving the plan:
**"Plan complete and saved to `docs/plans/<filename>.md`. Two execution options:**
**"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Ready to execute?"**
**1. Subagent-Driven (this session)** - I dispatch fresh subagent per task, review between tasks, fast iteration
**Execution path depends on harness capabilities:**
**2. Parallel Session (separate)** - Open new session with executing-plans, batch execution with checkpoints
**If harness has subagents (Claude Code, etc.):**
- **REQUIRED:** Use superpowers:subagent-driven-development
- Do NOT offer a choice - subagent-driven is the standard approach
- Fresh subagent per task + two-stage review
**Which approach?"**
**If Subagent-Driven chosen:**
- **REQUIRED SUB-SKILL:** Use subagent-driven-development
- Stay in this session
- Fresh subagent per task + code review
**If Parallel Session chosen:**
- Guide them to open new session in worktree
- **REQUIRED SUB-SKILL:** New session uses executing-plans
**If harness does NOT have subagents:**
- Execute plan in current session using superpowers:executing-plans
- Batch execution with checkpoints for review

View File

@@ -0,0 +1,52 @@
# Plan Document Reviewer Prompt Template
Use this template when dispatching a plan document reviewer subagent.
**Purpose:** Verify the plan chunk is complete, matches the spec, and has proper task decomposition.
**Dispatch after:** Each plan chunk is written
```
Task tool (general-purpose):
description: "Review plan chunk N"
prompt: |
You are a plan document reviewer. Verify this plan chunk is complete and ready for implementation.
**Plan chunk to review:** [PLAN_FILE_PATH] - Chunk N only
**Spec for reference:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, incomplete tasks, missing steps |
| Spec Alignment | Chunk covers relevant spec requirements, no scope creep |
| Task Decomposition | Tasks atomic, clear boundaries, steps actionable |
| File Structure | Files have clear single responsibilities, split by responsibility not layer |
| File Size | Would any new or modified file likely grow large enough to be hard to reason about as a whole? |
| Task Syntax | Checkbox syntax (`- [ ]`) on steps for tracking |
| Chunk Size | Each chunk under 1000 lines |
## CRITICAL
Look especially hard for:
- Any TODO markers or placeholder text
- Steps that say "similar to X" without actual content
- Incomplete task definitions
- Missing verification steps or expected outputs
- Files planned to hold multiple responsibilities or likely to grow unwieldy
## Output Format
## Plan Review - Chunk N
**Status:** Approved | Issues Found
**Issues (if any):**
- [Task X, Step Y]: [specific issue] - [why it matters]
**Recommendations (advisory):**
- [suggestions that don't block approval]
```
**Reviewer returns:** Status, Issues (if any), Recommendations

View File

@@ -1,6 +1,6 @@
---
name: writing-skills
description: Use when creating new skills, editing existing skills, or verifying skills work before deployment - applies TDD to process documentation by testing with subagents before writing, iterating until bulletproof against rationalization
description: Use when creating new skills, editing existing skills, or verifying skills work before deployment
---
# Writing Skills
@@ -9,13 +9,13 @@ description: Use when creating new skills, editing existing skills, or verifying
**Writing skills IS Test-Driven Development applied to process documentation.**
**Personal skills are written to `~/.claude/skills`**
**Personal skills live in agent-specific directories (`~/.claude/skills` for Claude Code, `~/.agents/skills/` for Codex)**
You 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).
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.
**REQUIRED BACKGROUND:** You MUST understand test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
**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.
**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.
@@ -56,6 +56,7 @@ The entire skill creation process follows RED-GREEN-REFACTOR.
- One-off solutions
- Standard practices well-documented elsewhere
- Project-specific conventions (put in CLAUDE.md)
- Mechanical constraints (if it's enforceable with regex/validation, automate it—save documentation for judgment calls)
## Skill Types
@@ -95,15 +96,16 @@ skills/
- Only two fields supported: `name` and `description`
- Max 1024 characters total
- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
- `description`: Third-person, includes BOTH what it does AND when to use it
- `description`: Third-person, describes ONLY when to use (NOT what it does)
- Start with "Use when..." to focus on triggering conditions
- Include specific symptoms, situations, and contexts
- **NEVER summarize the skill's process or workflow** (see CSO section for why)
- Keep under 500 characters if possible
```markdown
---
name: Skill-Name-With-Hyphens
description: Use when [specific triggering conditions and symptoms] - [what the skill does and how it helps, written in third person]
description: Use when [specific triggering conditions and symptoms]
---
# Skill Name
@@ -143,7 +145,31 @@ Concrete results
**Purpose:** Claude reads description to decide which skills to load for a given task. Make it answer: "Should I read this skill right now?"
**Format:** Start with "Use when..." to focus on triggering conditions, then explain what it does
**Format:** Start with "Use when..." to focus on triggering conditions
**CRITICAL: Description = When to Use, NOT What the Skill Does**
The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.
**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).
When 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.
**The trap:** Descriptions that summarize workflow create a shortcut Claude will take. The skill body becomes documentation Claude skips.
```yaml
# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill
description: Use when executing plans - dispatches subagent per task with code review between tasks
# ❌ BAD: Too much process detail
description: Use for TDD - write test first, watch it fail, write minimal code, refactor
# ✅ GOOD: Just triggering conditions, no workflow summary
description: Use when executing implementation plans with independent tasks in the current session
# ✅ GOOD: Triggering conditions only
description: Use when implementing any feature or bugfix, before writing implementation code
```
**Content:**
- Use concrete triggers, symptoms, and situations that signal this skill applies
@@ -151,6 +177,7 @@ Concrete results
- Keep triggers technology-agnostic unless the skill itself is technology-specific
- If skill is technology-specific, make that explicit in the trigger
- Write in third person (injected into system prompt)
- **NEVER summarize the skill's process or workflow**
```yaml
# ❌ BAD: Too abstract, vague, doesn't include when to use
@@ -162,11 +189,11 @@ description: I can help you with async tests when they're flaky
# ❌ BAD: Mentions technology but skill isn't specific to it
description: Use when tests use setTimeout/sleep and are flaky
# ✅ GOOD: Starts with "Use when", describes problem, then what it does
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently - replaces arbitrary timeouts with condition polling for reliable async tests
# ✅ GOOD: Starts with "Use when", describes problem, no workflow
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
# ✅ GOOD: Technology-specific skill with explicit trigger
description: Use when using React Router and handling authentication redirects - provides patterns for protected routes and auth state management
description: Use when using React Router and handling authentication redirects
```
### 2. Keyword Coverage
@@ -181,7 +208,7 @@ Use words Claude would search for:
**Use active voice, verb-first:**
-`creating-skills` not `skill-creation`
-`testing-skills-with-subagents` not `subagent-skill-testing`
-`condition-based-waiting` not `async-test-helpers`
### 4. Token Efficiency (Critical)
@@ -253,8 +280,8 @@ wc -w skills/path/SKILL.md
**When writing documentation that references other skills:**
Use skill name only, with explicit requirement markers:
- ✅ Good: `**REQUIRED SUB-SKILL:** Use test-driven-development`
- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand systematic-debugging`
- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`
- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`
- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
- ❌ Bad: `@skills/testing/test-driven-development/SKILL.md` (force-loads, burns context)
@@ -288,6 +315,12 @@ digraph when_flowchart {
See @graphviz-conventions.dot for graphviz style rules.
**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
```bash
./render-graphs.js ../some-skill # Each diagram separately
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
```
## Code Examples
**One excellent example beats many mediocre ones**
@@ -357,7 +390,7 @@ Edit skill without testing? Same violation.
- Don't "adapt" while running tests
- Delete means delete
**REQUIRED BACKGROUND:** The test-driven-development skill explains why this matters. Same principles apply to documentation.
**REQUIRED BACKGROUND:** The superpowers:test-driven-development skill explains why this matters. Same principles apply to documentation.
## Testing All Skill Types
@@ -520,7 +553,7 @@ Run same scenarios WITH skill. Agent should now comply.
Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
**REQUIRED SUB-SKILL:** Use testing-skills-with-subagents for the complete testing methodology:
**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:
- How to write pressure scenarios
- Pressure types (time, sunk cost, authority, exhaustion)
- Plugging holes systematically

View File

@@ -10,7 +10,7 @@ For conceptual background on how Skills work, see the [Skills overview](/en/docs
### Concise is key
The [context window](/en/docs/build-with-claude/context-windows) is a public good. Your Skill shares the context window with everything else Claude needs to know, including:
The [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:
* The system prompt
* Conversation history

View File

@@ -0,0 +1,168 @@
#!/usr/bin/env node
/**
* Render graphviz diagrams from a skill's SKILL.md to SVG files.
*
* Usage:
* ./render-graphs.js <skill-directory> # Render each diagram separately
* ./render-graphs.js <skill-directory> --combine # Combine all into one diagram
*
* Extracts all ```dot blocks from SKILL.md and renders to SVG.
* Useful for helping your human partner visualize the process flows.
*
* Requires: graphviz (dot) installed on system
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
function extractDotBlocks(markdown) {
const blocks = [];
const regex = /```dot\n([\s\S]*?)```/g;
let match;
while ((match = regex.exec(markdown)) !== null) {
const content = match[1].trim();
// Extract digraph name
const nameMatch = content.match(/digraph\s+(\w+)/);
const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;
blocks.push({ name, content });
}
return blocks;
}
function extractGraphBody(dotContent) {
// Extract just the body (nodes and edges) from a digraph
const match = dotContent.match(/digraph\s+\w+\s*\{([\s\S]*)\}/);
if (!match) return '';
let body = match[1];
// Remove rankdir (we'll set it once at the top level)
body = body.replace(/^\s*rankdir\s*=\s*\w+\s*;?\s*$/gm, '');
return body.trim();
}
function combineGraphs(blocks, skillName) {
const bodies = blocks.map((block, i) => {
const body = extractGraphBody(block.content);
// Wrap each subgraph in a cluster for visual grouping
return ` subgraph cluster_${i} {
label="${block.name}";
${body.split('\n').map(line => ' ' + line).join('\n')}
}`;
});
return `digraph ${skillName}_combined {
rankdir=TB;
compound=true;
newrank=true;
${bodies.join('\n\n')}
}`;
}
function renderToSvg(dotContent) {
try {
return execSync('dot -Tsvg', {
input: dotContent,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024
});
} catch (err) {
console.error('Error running dot:', err.message);
if (err.stderr) console.error(err.stderr.toString());
return null;
}
}
function main() {
const args = process.argv.slice(2);
const combine = args.includes('--combine');
const skillDirArg = args.find(a => !a.startsWith('--'));
if (!skillDirArg) {
console.error('Usage: render-graphs.js <skill-directory> [--combine]');
console.error('');
console.error('Options:');
console.error(' --combine Combine all diagrams into one SVG');
console.error('');
console.error('Example:');
console.error(' ./render-graphs.js ../subagent-driven-development');
console.error(' ./render-graphs.js ../subagent-driven-development --combine');
process.exit(1);
}
const skillDir = path.resolve(skillDirArg);
const skillFile = path.join(skillDir, 'SKILL.md');
const skillName = path.basename(skillDir).replace(/-/g, '_');
if (!fs.existsSync(skillFile)) {
console.error(`Error: ${skillFile} not found`);
process.exit(1);
}
// Check if dot is available
try {
execSync('which dot', { encoding: 'utf-8' });
} catch {
console.error('Error: graphviz (dot) not found. Install with:');
console.error(' brew install graphviz # macOS');
console.error(' apt install graphviz # Linux');
process.exit(1);
}
const markdown = fs.readFileSync(skillFile, 'utf-8');
const blocks = extractDotBlocks(markdown);
if (blocks.length === 0) {
console.log('No ```dot blocks found in', skillFile);
process.exit(0);
}
console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);
const outputDir = path.join(skillDir, 'diagrams');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
if (combine) {
// Combine all graphs into one
const combined = combineGraphs(blocks, skillName);
const svg = renderToSvg(combined);
if (svg) {
const outputPath = path.join(outputDir, `${skillName}_combined.svg`);
fs.writeFileSync(outputPath, svg);
console.log(` Rendered: ${skillName}_combined.svg`);
// Also write the dot source for debugging
const dotPath = path.join(outputDir, `${skillName}_combined.dot`);
fs.writeFileSync(dotPath, combined);
console.log(` Source: ${skillName}_combined.dot`);
} else {
console.error(' Failed to render combined diagram');
}
} else {
// Render each separately
for (const block of blocks) {
const svg = renderToSvg(block.content);
if (svg) {
const outputPath = path.join(outputDir, `${block.name}.svg`);
fs.writeFileSync(outputPath, svg);
console.log(` Rendered: ${block.name}.svg`);
} else {
console.error(` Failed: ${block.name}`);
}
}
}
console.log(`\nOutput: ${outputDir}/`);
}
main();

View File

@@ -1,10 +1,7 @@
---
name: testing-skills-with-subagents
description: Use when creating or editing skills, before deployment, to verify they work under pressure and resist rationalization - applies RED-GREEN-REFACTOR cycle to process documentation by running baseline without skill, writing to address failures, iterating to close loopholes
---
# Testing Skills With Subagents
**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
## Overview
**Testing skills is just TDD applied to process documentation.**
@@ -13,7 +10,7 @@ You run scenarios without the skill (RED - watch agent fail), write skill addres
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
**REQUIRED BACKGROUND:** You MUST understand 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).
**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).
**Complete worked example:** See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.
@@ -327,7 +324,7 @@ Before deploying skill, verify you followed RED-GREEN-REFACTOR:
- [ ] Added explicit counters for each loophole
- [ ] Updated rationalization table
- [ ] Updated red flags list
- [ ] Updated description ith violation symptoms
- [ ] Updated description with violation symptoms
- [ ] Re-tested - agent still complies
- [ ] Meta-tested to verify clarity
- [ ] Agent follows rule under maximum pressure

View File

@@ -0,0 +1,36 @@
{
"name": "brainstorm-server-tests",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "brainstorm-server-tests",
"version": "1.0.0",
"dependencies": {
"ws": "^8.19.0"
}
},
"node_modules/ws": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz",
"integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

View File

@@ -0,0 +1,10 @@
{
"name": "brainstorm-server-tests",
"version": "1.0.0",
"scripts": {
"test": "node server.test.js"
},
"dependencies": {
"ws": "^8.19.0"
}
}

View File

@@ -0,0 +1,162 @@
const { spawn } = require('child_process');
const http = require('http');
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const SERVER_PATH = path.join(__dirname, '../../lib/brainstorm-server/index.js');
const TEST_PORT = 3334;
const TEST_DIR = '/tmp/brainstorm-test';
function cleanup() {
if (fs.existsSync(TEST_DIR)) {
fs.rmSync(TEST_DIR, { recursive: true });
}
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetch(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve({ status: res.statusCode, body: data }));
}).on('error', reject);
});
}
function startServer() {
return spawn('node', [SERVER_PATH], {
env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR }
});
}
async function runTests() {
cleanup();
fs.mkdirSync(TEST_DIR, { recursive: true });
const server = startServer();
let stdout = '';
let stderr = '';
server.stdout.on('data', (data) => { stdout += data.toString(); });
server.stderr.on('data', (data) => { stderr += data.toString(); });
// Wait for server to start (up to 3 seconds)
for (let i = 0; i < 30; i++) {
if (stdout.includes('server-started')) break;
await sleep(100);
}
if (stderr) console.error('Server stderr:', stderr);
try {
// Test 1: Server starts and outputs JSON
console.log('Test 1: Server startup message');
assert(stdout.includes('server-started'), 'Should output server-started');
assert(stdout.includes(TEST_PORT.toString()), 'Should include port');
console.log(' PASS');
// Test 2: GET / returns waiting page with helper injected when no screens exist
console.log('Test 2: Serves waiting page with helper injected');
const res = await fetch(`http://localhost:${TEST_PORT}/`);
assert.strictEqual(res.status, 200);
assert(res.body.includes('Waiting for Claude'), 'Should show waiting message');
assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
console.log(' PASS');
// Test 3: WebSocket connection and event relay
console.log('Test 3: WebSocket relays events to stdout');
stdout = '';
const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
await new Promise(resolve => ws.on('open', resolve));
ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
await sleep(300);
assert(stdout.includes('"source":"user-event"'), 'Should relay user events with source field');
assert(stdout.includes('Test Button'), 'Should include event data');
ws.close();
console.log(' PASS');
// Test 4: File change triggers reload notification
console.log('Test 4: File change notifies browsers');
const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);
await new Promise(resolve => ws2.on('open', resolve));
let gotReload = false;
ws2.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (msg.type === 'reload') gotReload = true;
});
fs.writeFileSync(path.join(TEST_DIR, 'test-screen.html'), '<html><body>Full doc</body></html>');
await sleep(500);
assert(gotReload, 'Should send reload message on file change');
ws2.close();
console.log(' PASS');
// Test 5: Full HTML document served as-is (not wrapped)
console.log('Test 5: Full HTML document served without frame wrapping');
const fullDoc = '<!DOCTYPE html>\n<html><head><title>Custom</title></head><body><h1>Custom Page</h1></body></html>';
fs.writeFileSync(path.join(TEST_DIR, 'full-doc.html'), fullDoc);
await sleep(300);
const fullRes = await fetch(`http://localhost:${TEST_PORT}/`);
assert(fullRes.body.includes('<h1>Custom Page</h1>'), 'Should contain original content');
assert(fullRes.body.includes('WebSocket'), 'Should still inject helper.js');
// Should NOT have the frame template's feedback footer
assert(!fullRes.body.includes('feedback-footer') || fullDoc.includes('feedback-footer'),
'Should not wrap full documents in frame template');
console.log(' PASS');
// Test 6: Bare HTML fragment gets wrapped in frame template
console.log('Test 6: Content fragment wrapped in frame template');
const fragment = '<h2>Pick a layout</h2>\n<p class="subtitle">Choose one</p>\n<div class="options"><div class="option" data-choice="a"><div class="letter">A</div><div class="content"><h3>Simple</h3></div></div></div>';
fs.writeFileSync(path.join(TEST_DIR, 'fragment.html'), fragment);
await sleep(300);
const fragRes = await fetch(`http://localhost:${TEST_PORT}/`);
// Should have the frame template structure
assert(fragRes.body.includes('feedback-footer'), 'Fragment should get feedback footer from frame');
assert(fragRes.body.includes('Brainstorm Companion'), 'Fragment should get header from frame');
assert(fragRes.body.includes('--bg-primary'), 'Fragment should get theme CSS from frame');
// Should have the original content inside
assert(fragRes.body.includes('Pick a layout'), 'Fragment content should be present');
assert(fragRes.body.includes('data-choice="a"'), 'Fragment content should be intact');
// Should have helper.js injected
assert(fragRes.body.includes('WebSocket'), 'Fragment should have helper.js injected');
console.log(' PASS');
// Test 7: Helper.js includes toggleSelect and send functions
console.log('Test 7: Helper.js provides toggleSelect and send');
const helperContent = fs.readFileSync(
path.join(__dirname, '../../lib/brainstorm-server/helper.js'), 'utf-8'
);
assert(helperContent.includes('toggleSelect'), 'helper.js should define toggleSelect');
assert(helperContent.includes('send'), 'helper.js should define send function');
assert(helperContent.includes('selectedChoice'), 'helper.js should track selectedChoice');
console.log(' PASS');
// Test 8: sendToClaude confirmation uses CSS variables (dark mode support)
console.log('Test 8: sendToClaude confirmation respects theming');
assert(!helperContent.includes('color: #666'), 'Should not use hardcoded light-mode colors');
assert(!helperContent.includes('color: #333'), 'Should not use hardcoded light-mode colors');
console.log(' PASS');
console.log('\nAll tests passed!');
} finally {
server.kill();
cleanup();
}
}
runTests().catch(err => {
console.error('Test failed:', err);
process.exit(1);
});

158
tests/claude-code/README.md Normal file
View File

@@ -0,0 +1,158 @@
# Claude Code Skills Tests
Automated tests for superpowers skills using Claude Code CLI.
## Overview
This 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.
## Requirements
- Claude Code CLI installed and in PATH (`claude --version` should work)
- Local superpowers plugin installed (see main README for installation)
## Running Tests
### Run all fast tests (recommended):
```bash
./run-skill-tests.sh
```
### Run integration tests (slow, 10-30 minutes):
```bash
./run-skill-tests.sh --integration
```
### Run specific test:
```bash
./run-skill-tests.sh --test test-subagent-driven-development.sh
```
### Run with verbose output:
```bash
./run-skill-tests.sh --verbose
```
### Set custom timeout:
```bash
./run-skill-tests.sh --timeout 1800 # 30 minutes for integration tests
```
## Test Structure
### test-helpers.sh
Common functions for skills testing:
- `run_claude "prompt" [timeout]` - Run Claude with prompt
- `assert_contains output pattern name` - Verify pattern exists
- `assert_not_contains output pattern name` - Verify pattern absent
- `assert_count output pattern count name` - Verify exact count
- `assert_order output pattern_a pattern_b name` - Verify order
- `create_test_project` - Create temp test directory
- `create_test_plan project_dir` - Create sample plan file
### Test Files
Each test file:
1. Sources `test-helpers.sh`
2. Runs Claude Code with specific prompts
3. Verifies expected behavior using assertions
4. Returns 0 on success, non-zero on failure
## Example Test
```bash
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"
echo "=== Test: My Skill ==="
# Ask Claude about the skill
output=$(run_claude "What does the my-skill skill do?" 30)
# Verify response
assert_contains "$output" "expected behavior" "Skill describes behavior"
echo "=== All tests passed ==="
```
## Current Tests
### Fast Tests (run by default)
#### test-subagent-driven-development.sh
Tests skill content and requirements (~2 minutes):
- Skill loading and accessibility
- Workflow ordering (spec compliance before code quality)
- Self-review requirements documented
- Plan reading efficiency documented
- Spec compliance reviewer skepticism documented
- Review loops documented
- Task context provision documented
### Integration Tests (use --integration flag)
#### test-subagent-driven-development-integration.sh
Full workflow execution test (~10-30 minutes):
- Creates real test project with Node.js setup
- Creates implementation plan with 2 tasks
- Executes plan using subagent-driven-development
- Verifies actual behaviors:
- Plan read once at start (not per task)
- Full task text provided in subagent prompts
- Subagents perform self-review before reporting
- Spec compliance review happens before code quality
- Spec reviewer reads code independently
- Working implementation is produced
- Tests pass
- Proper git commits created
**What it tests:**
- The workflow actually works end-to-end
- Our improvements are actually applied
- Subagents follow the skill correctly
- Final code is functional and tested
## Adding New Tests
1. Create new test file: `test-<skill-name>.sh`
2. Source test-helpers.sh
3. Write tests using `run_claude` and assertions
4. Add to test list in `run-skill-tests.sh`
5. Make executable: `chmod +x test-<skill-name>.sh`
## Timeout Considerations
- Default timeout: 5 minutes per test
- Claude Code may take time to respond
- Adjust with `--timeout` if needed
- Tests should be focused to avoid long runs
## Debugging Failed Tests
With `--verbose`, you'll see full Claude output:
```bash
./run-skill-tests.sh --verbose --test test-subagent-driven-development.sh
```
Without verbose, only failures show output.
## CI/CD Integration
To run in CI:
```bash
# Run with explicit timeout for CI environments
./run-skill-tests.sh --timeout 900
# Exit code 0 = success, non-zero = failure
```
## Notes
- Tests verify skill *instructions*, not full execution
- Full workflow tests would be very slow
- Focus on verifying key skill requirements
- Tests should be deterministic
- Avoid testing implementation details

View File

@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""
Analyze token usage from Claude Code session transcripts.
Breaks down usage by main session and individual subagents.
"""
import json
import sys
from pathlib import Path
from collections import defaultdict
def analyze_main_session(filepath):
"""Analyze a session file and return token usage broken down by agent."""
main_usage = {
'input_tokens': 0,
'output_tokens': 0,
'cache_creation': 0,
'cache_read': 0,
'messages': 0
}
# Track usage per subagent
subagent_usage = defaultdict(lambda: {
'input_tokens': 0,
'output_tokens': 0,
'cache_creation': 0,
'cache_read': 0,
'messages': 0,
'description': None
})
with open(filepath, 'r') as f:
for line in f:
try:
data = json.loads(line)
# Main session assistant messages
if data.get('type') == 'assistant' and 'message' in data:
main_usage['messages'] += 1
msg_usage = data['message'].get('usage', {})
main_usage['input_tokens'] += msg_usage.get('input_tokens', 0)
main_usage['output_tokens'] += msg_usage.get('output_tokens', 0)
main_usage['cache_creation'] += msg_usage.get('cache_creation_input_tokens', 0)
main_usage['cache_read'] += msg_usage.get('cache_read_input_tokens', 0)
# Subagent tool results
if data.get('type') == 'user' and 'toolUseResult' in data:
result = data['toolUseResult']
if 'usage' in result and 'agentId' in result:
agent_id = result['agentId']
usage = result['usage']
# Get description from prompt if available
if subagent_usage[agent_id]['description'] is None:
prompt = result.get('prompt', '')
# Extract first line as description
first_line = prompt.split('\n')[0] if prompt else f"agent-{agent_id}"
if first_line.startswith('You are '):
first_line = first_line[8:] # Remove "You are "
subagent_usage[agent_id]['description'] = first_line[:60]
subagent_usage[agent_id]['messages'] += 1
subagent_usage[agent_id]['input_tokens'] += usage.get('input_tokens', 0)
subagent_usage[agent_id]['output_tokens'] += usage.get('output_tokens', 0)
subagent_usage[agent_id]['cache_creation'] += usage.get('cache_creation_input_tokens', 0)
subagent_usage[agent_id]['cache_read'] += usage.get('cache_read_input_tokens', 0)
except:
pass
return main_usage, dict(subagent_usage)
def format_tokens(n):
"""Format token count with thousands separators."""
return f"{n:,}"
def calculate_cost(usage, input_cost_per_m=3.0, output_cost_per_m=15.0):
"""Calculate estimated cost in dollars."""
total_input = usage['input_tokens'] + usage['cache_creation'] + usage['cache_read']
input_cost = total_input * input_cost_per_m / 1_000_000
output_cost = usage['output_tokens'] * output_cost_per_m / 1_000_000
return input_cost + output_cost
def main():
if len(sys.argv) < 2:
print("Usage: analyze-token-usage.py <session-file.jsonl>")
sys.exit(1)
main_session_file = sys.argv[1]
if not Path(main_session_file).exists():
print(f"Error: Session file not found: {main_session_file}")
sys.exit(1)
# Analyze the session
main_usage, subagent_usage = analyze_main_session(main_session_file)
print("=" * 100)
print("TOKEN USAGE ANALYSIS")
print("=" * 100)
print()
# Print breakdown
print("Usage Breakdown:")
print("-" * 100)
print(f"{'Agent':<15} {'Description':<35} {'Msgs':>5} {'Input':>10} {'Output':>10} {'Cache':>10} {'Cost':>8}")
print("-" * 100)
# Main session
cost = calculate_cost(main_usage)
print(f"{'main':<15} {'Main session (coordinator)':<35} "
f"{main_usage['messages']:>5} "
f"{format_tokens(main_usage['input_tokens']):>10} "
f"{format_tokens(main_usage['output_tokens']):>10} "
f"{format_tokens(main_usage['cache_read']):>10} "
f"${cost:>7.2f}")
# Subagents (sorted by agent ID)
for agent_id in sorted(subagent_usage.keys()):
usage = subagent_usage[agent_id]
cost = calculate_cost(usage)
desc = usage['description'] or f"agent-{agent_id}"
print(f"{agent_id:<15} {desc:<35} "
f"{usage['messages']:>5} "
f"{format_tokens(usage['input_tokens']):>10} "
f"{format_tokens(usage['output_tokens']):>10} "
f"{format_tokens(usage['cache_read']):>10} "
f"${cost:>7.2f}")
print("-" * 100)
# Calculate totals
total_usage = {
'input_tokens': main_usage['input_tokens'],
'output_tokens': main_usage['output_tokens'],
'cache_creation': main_usage['cache_creation'],
'cache_read': main_usage['cache_read'],
'messages': main_usage['messages']
}
for usage in subagent_usage.values():
total_usage['input_tokens'] += usage['input_tokens']
total_usage['output_tokens'] += usage['output_tokens']
total_usage['cache_creation'] += usage['cache_creation']
total_usage['cache_read'] += usage['cache_read']
total_usage['messages'] += usage['messages']
total_input = total_usage['input_tokens'] + total_usage['cache_creation'] + total_usage['cache_read']
total_tokens = total_input + total_usage['output_tokens']
total_cost = calculate_cost(total_usage)
print()
print("TOTALS:")
print(f" Total messages: {format_tokens(total_usage['messages'])}")
print(f" Input tokens: {format_tokens(total_usage['input_tokens'])}")
print(f" Output tokens: {format_tokens(total_usage['output_tokens'])}")
print(f" Cache creation tokens: {format_tokens(total_usage['cache_creation'])}")
print(f" Cache read tokens: {format_tokens(total_usage['cache_read'])}")
print()
print(f" Total input (incl cache): {format_tokens(total_input)}")
print(f" Total tokens: {format_tokens(total_tokens)}")
print()
print(f" Estimated cost: ${total_cost:.2f}")
print(" (at $3/$15 per M tokens for input/output)")
print()
print("=" * 100)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,187 @@
#!/usr/bin/env bash
# Test runner for Claude Code skills
# Tests skills by invoking Claude Code CLI and verifying behavior
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"
echo "========================================"
echo " Claude Code Skills Test Suite"
echo "========================================"
echo ""
echo "Repository: $(cd ../.. && pwd)"
echo "Test time: $(date)"
echo "Claude version: $(claude --version 2>/dev/null || echo 'not found')"
echo ""
# Check if Claude Code is available
if ! command -v claude &> /dev/null; then
echo "ERROR: Claude Code CLI not found"
echo "Install Claude Code first: https://code.claude.com"
exit 1
fi
# Parse command line arguments
VERBOSE=false
SPECIFIC_TEST=""
TIMEOUT=300 # Default 5 minute timeout per test
RUN_INTEGRATION=false
while [[ $# -gt 0 ]]; do
case $1 in
--verbose|-v)
VERBOSE=true
shift
;;
--test|-t)
SPECIFIC_TEST="$2"
shift 2
;;
--timeout)
TIMEOUT="$2"
shift 2
;;
--integration|-i)
RUN_INTEGRATION=true
shift
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --verbose, -v Show verbose output"
echo " --test, -t NAME Run only the specified test"
echo " --timeout SECONDS Set timeout per test (default: 300)"
echo " --integration, -i Run integration tests (slow, 10-30 min)"
echo " --help, -h Show this help"
echo ""
echo "Tests:"
echo " test-subagent-driven-development.sh Test skill loading and requirements"
echo ""
echo "Integration Tests (use --integration):"
echo " test-subagent-driven-development-integration.sh Full workflow execution"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information"
exit 1
;;
esac
done
# List of skill tests to run (fast unit tests)
tests=(
"test-subagent-driven-development.sh"
)
# Integration tests (slow, full execution)
integration_tests=(
"test-subagent-driven-development-integration.sh"
)
# Add integration tests if requested
if [ "$RUN_INTEGRATION" = true ]; then
tests+=("${integration_tests[@]}")
fi
# Filter to specific test if requested
if [ -n "$SPECIFIC_TEST" ]; then
tests=("$SPECIFIC_TEST")
fi
# Track results
passed=0
failed=0
skipped=0
# Run each test
for test in "${tests[@]}"; do
echo "----------------------------------------"
echo "Running: $test"
echo "----------------------------------------"
test_path="$SCRIPT_DIR/$test"
if [ ! -f "$test_path" ]; then
echo " [SKIP] Test file not found: $test"
skipped=$((skipped + 1))
continue
fi
if [ ! -x "$test_path" ]; then
echo " Making $test executable..."
chmod +x "$test_path"
fi
start_time=$(date +%s)
if [ "$VERBOSE" = true ]; then
if timeout "$TIMEOUT" bash "$test_path"; then
end_time=$(date +%s)
duration=$((end_time - start_time))
echo ""
echo " [PASS] $test (${duration}s)"
passed=$((passed + 1))
else
exit_code=$?
end_time=$(date +%s)
duration=$((end_time - start_time))
echo ""
if [ $exit_code -eq 124 ]; then
echo " [FAIL] $test (timeout after ${TIMEOUT}s)"
else
echo " [FAIL] $test (${duration}s)"
fi
failed=$((failed + 1))
fi
else
# Capture output for non-verbose mode
if output=$(timeout "$TIMEOUT" bash "$test_path" 2>&1); then
end_time=$(date +%s)
duration=$((end_time - start_time))
echo " [PASS] (${duration}s)"
passed=$((passed + 1))
else
exit_code=$?
end_time=$(date +%s)
duration=$((end_time - start_time))
if [ $exit_code -eq 124 ]; then
echo " [FAIL] (timeout after ${TIMEOUT}s)"
else
echo " [FAIL] (${duration}s)"
fi
echo ""
echo " Output:"
echo "$output" | sed 's/^/ /'
failed=$((failed + 1))
fi
fi
echo ""
done
# Print summary
echo "========================================"
echo " Test Results Summary"
echo "========================================"
echo ""
echo " Passed: $passed"
echo " Failed: $failed"
echo " Skipped: $skipped"
echo ""
if [ "$RUN_INTEGRATION" = false ] && [ ${#integration_tests[@]} -gt 0 ]; then
echo "Note: Integration tests were not run (they take 10-30 minutes)."
echo "Use --integration flag to run full workflow execution tests."
echo ""
fi
if [ $failed -gt 0 ]; then
echo "STATUS: FAILED"
exit 1
else
echo "STATUS: PASSED"
exit 0
fi

View File

@@ -0,0 +1,177 @@
#!/usr/bin/env bash
# Integration Test: Document Review System
# Actually runs spec/plan review and verifies reviewers catch issues
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"
echo "========================================"
echo " Integration Test: Document Review System"
echo "========================================"
echo ""
echo "This test verifies the document review system by:"
echo " 1. Creating a spec with intentional errors"
echo " 2. Running the spec document reviewer"
echo " 3. Verifying the reviewer catches the errors"
echo ""
# Create test project
TEST_PROJECT=$(create_test_project)
echo "Test project: $TEST_PROJECT"
# Trap to cleanup
trap "cleanup_test_project $TEST_PROJECT" EXIT
cd "$TEST_PROJECT"
# Create directory structure
mkdir -p docs/superpowers/specs
# Create a spec document WITH INTENTIONAL ERRORS for the reviewer to catch
cat > docs/superpowers/specs/test-feature-design.md <<'EOF'
# Test Feature Design
## Overview
This is a test feature that does something useful.
## Requirements
1. The feature should work correctly
2. It should be fast
3. TODO: Add more requirements here
## Architecture
The feature will use a simple architecture with:
- A frontend component
- A backend service
- Error handling will be specified later once we understand the failure modes better
## Data Flow
Data flows from the frontend to the backend.
## Testing Strategy
Tests will be written to cover the main functionality.
EOF
# Initialize git repo
git init --quiet
git config user.email "test@test.com"
git config user.name "Test User"
git add .
git commit -m "Initial commit with test spec" --quiet
echo ""
echo "Created test spec with intentional errors:"
echo " - TODO placeholder in Requirements section"
echo " - 'specified later' deferral in Architecture section"
echo ""
echo "Running spec document reviewer..."
echo ""
# Run Claude to review the spec
OUTPUT_FILE="$TEST_PROJECT/claude-output.txt"
PROMPT="You are testing the spec document reviewer.
Read the spec-document-reviewer-prompt.md template in skills/brainstorming/ to understand the review format.
Then review the spec at $TEST_PROJECT/docs/superpowers/specs/test-feature-design.md using the criteria from that template.
Look for:
- TODOs, placeholders, 'TBD', incomplete sections
- Sections saying 'to be defined later' or 'will spec when X is done'
- Sections noticeably less detailed than others
Output your review in the format specified in the template."
echo "================================================================================"
cd "$SCRIPT_DIR/../.." && timeout 120 claude -p "$PROMPT" --permission-mode bypassPermissions 2>&1 | tee "$OUTPUT_FILE" || {
echo ""
echo "================================================================================"
echo "EXECUTION FAILED (exit code: $?)"
exit 1
}
echo "================================================================================"
echo ""
echo "Analyzing reviewer output..."
echo ""
# Verification tests
FAILED=0
echo "=== Verification Tests ==="
echo ""
# Test 1: Reviewer found the TODO
echo "Test 1: Reviewer found TODO..."
if grep -qi "TODO" "$OUTPUT_FILE" && grep -qi "requirements\|Requirements" "$OUTPUT_FILE"; then
echo " [PASS] Reviewer identified TODO in Requirements section"
else
echo " [FAIL] Reviewer did not identify TODO"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 2: Reviewer found the "specified later" deferral
echo "Test 2: Reviewer found 'specified later' deferral..."
if grep -qi "specified later\|later\|defer\|incomplete\|error handling" "$OUTPUT_FILE"; then
echo " [PASS] Reviewer identified deferred content"
else
echo " [FAIL] Reviewer did not identify deferred content"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 3: Reviewer output includes Issues section
echo "Test 3: Review output format..."
if grep -qi "issues\|Issues" "$OUTPUT_FILE"; then
echo " [PASS] Review includes Issues section"
else
echo " [FAIL] Review missing Issues section"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 4: Reviewer did NOT approve (found issues)
echo "Test 4: Reviewer verdict..."
if grep -qi "Issues Found\|❌\|not approved\|issues found" "$OUTPUT_FILE"; then
echo " [PASS] Reviewer correctly found issues (not approved)"
elif grep -qi "Approved\|✅" "$OUTPUT_FILE" && ! grep -qi "Issues Found\|❌" "$OUTPUT_FILE"; then
echo " [FAIL] Reviewer incorrectly approved spec with errors"
FAILED=$((FAILED + 1))
else
echo " [PASS] Reviewer identified problems (ambiguous format but found issues)"
fi
echo ""
# Summary
echo "========================================"
echo " Test Summary"
echo "========================================"
echo ""
if [ $FAILED -eq 0 ]; then
echo "STATUS: PASSED"
echo "All verification tests passed!"
echo ""
echo "The spec document reviewer correctly:"
echo " ✓ Found TODO placeholder"
echo " ✓ Found 'specified later' deferral"
echo " ✓ Produced properly formatted review"
echo " ✓ Did not approve spec with errors"
exit 0
else
echo "STATUS: FAILED"
echo "Failed $FAILED verification tests"
echo ""
echo "Output saved to: $OUTPUT_FILE"
echo ""
echo "Review the output to see what went wrong."
exit 1
fi

202
tests/claude-code/test-helpers.sh Executable file
View File

@@ -0,0 +1,202 @@
#!/usr/bin/env bash
# Helper functions for Claude Code skill tests
# Run Claude Code with a prompt and capture output
# Usage: run_claude "prompt text" [timeout_seconds] [allowed_tools]
run_claude() {
local prompt="$1"
local timeout="${2:-60}"
local allowed_tools="${3:-}"
local output_file=$(mktemp)
# Build command
local cmd="claude -p \"$prompt\""
if [ -n "$allowed_tools" ]; then
cmd="$cmd --allowed-tools=$allowed_tools"
fi
# Run Claude in headless mode with timeout
if timeout "$timeout" bash -c "$cmd" > "$output_file" 2>&1; then
cat "$output_file"
rm -f "$output_file"
return 0
else
local exit_code=$?
cat "$output_file" >&2
rm -f "$output_file"
return $exit_code
fi
}
# Check if output contains a pattern
# Usage: assert_contains "output" "pattern" "test name"
assert_contains() {
local output="$1"
local pattern="$2"
local test_name="${3:-test}"
if echo "$output" | grep -q "$pattern"; then
echo " [PASS] $test_name"
return 0
else
echo " [FAIL] $test_name"
echo " Expected to find: $pattern"
echo " In output:"
echo "$output" | sed 's/^/ /'
return 1
fi
}
# Check if output does NOT contain a pattern
# Usage: assert_not_contains "output" "pattern" "test name"
assert_not_contains() {
local output="$1"
local pattern="$2"
local test_name="${3:-test}"
if echo "$output" | grep -q "$pattern"; then
echo " [FAIL] $test_name"
echo " Did not expect to find: $pattern"
echo " In output:"
echo "$output" | sed 's/^/ /'
return 1
else
echo " [PASS] $test_name"
return 0
fi
}
# Check if output matches a count
# Usage: assert_count "output" "pattern" expected_count "test name"
assert_count() {
local output="$1"
local pattern="$2"
local expected="$3"
local test_name="${4:-test}"
local actual=$(echo "$output" | grep -c "$pattern" || echo "0")
if [ "$actual" -eq "$expected" ]; then
echo " [PASS] $test_name (found $actual instances)"
return 0
else
echo " [FAIL] $test_name"
echo " Expected $expected instances of: $pattern"
echo " Found $actual instances"
echo " In output:"
echo "$output" | sed 's/^/ /'
return 1
fi
}
# Check if pattern A appears before pattern B
# Usage: assert_order "output" "pattern_a" "pattern_b" "test name"
assert_order() {
local output="$1"
local pattern_a="$2"
local pattern_b="$3"
local test_name="${4:-test}"
# Get line numbers where patterns appear
local line_a=$(echo "$output" | grep -n "$pattern_a" | head -1 | cut -d: -f1)
local line_b=$(echo "$output" | grep -n "$pattern_b" | head -1 | cut -d: -f1)
if [ -z "$line_a" ]; then
echo " [FAIL] $test_name: pattern A not found: $pattern_a"
return 1
fi
if [ -z "$line_b" ]; then
echo " [FAIL] $test_name: pattern B not found: $pattern_b"
return 1
fi
if [ "$line_a" -lt "$line_b" ]; then
echo " [PASS] $test_name (A at line $line_a, B at line $line_b)"
return 0
else
echo " [FAIL] $test_name"
echo " Expected '$pattern_a' before '$pattern_b'"
echo " But found A at line $line_a, B at line $line_b"
return 1
fi
}
# Create a temporary test project directory
# Usage: test_project=$(create_test_project)
create_test_project() {
local test_dir=$(mktemp -d)
echo "$test_dir"
}
# Cleanup test project
# Usage: cleanup_test_project "$test_dir"
cleanup_test_project() {
local test_dir="$1"
if [ -d "$test_dir" ]; then
rm -rf "$test_dir"
fi
}
# Create a simple plan file for testing
# Usage: create_test_plan "$project_dir" "$plan_name"
create_test_plan() {
local project_dir="$1"
local plan_name="${2:-test-plan}"
local plan_file="$project_dir/docs/superpowers/plans/$plan_name.md"
mkdir -p "$(dirname "$plan_file")"
cat > "$plan_file" <<'EOF'
# Test Implementation Plan
## Task 1: Create Hello Function
Create a simple hello function that returns "Hello, World!".
**File:** `src/hello.js`
**Implementation:**
```javascript
export function hello() {
return "Hello, World!";
}
```
**Tests:** Write a test that verifies the function returns the expected string.
**Verification:** `npm test`
## Task 2: Create Goodbye Function
Create a goodbye function that takes a name and returns a goodbye message.
**File:** `src/goodbye.js`
**Implementation:**
```javascript
export function goodbye(name) {
return `Goodbye, ${name}!`;
}
```
**Tests:** Write tests for:
- Default name
- Custom name
- Edge cases (empty string, null)
**Verification:** `npm test`
EOF
echo "$plan_file"
}
# Export functions for use in tests
export -f run_claude
export -f assert_contains
export -f assert_not_contains
export -f assert_count
export -f assert_order
export -f create_test_project
export -f cleanup_test_project
export -f create_test_plan

View File

@@ -0,0 +1,314 @@
#!/usr/bin/env bash
# Integration Test: subagent-driven-development workflow
# Actually executes a plan and verifies the new workflow behaviors
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"
echo "========================================"
echo " Integration Test: subagent-driven-development"
echo "========================================"
echo ""
echo "This test executes a real plan using the skill and verifies:"
echo " 1. Plan is read once (not per task)"
echo " 2. Full task text provided to subagents"
echo " 3. Subagents perform self-review"
echo " 4. Spec compliance review before code quality"
echo " 5. Review loops when issues found"
echo " 6. Spec reviewer reads code independently"
echo ""
echo "WARNING: This test may take 10-30 minutes to complete."
echo ""
# Create test project
TEST_PROJECT=$(create_test_project)
echo "Test project: $TEST_PROJECT"
# Trap to cleanup
trap "cleanup_test_project $TEST_PROJECT" EXIT
# Set up minimal Node.js project
cd "$TEST_PROJECT"
cat > package.json <<'EOF'
{
"name": "test-project",
"version": "1.0.0",
"type": "module",
"scripts": {
"test": "node --test"
}
}
EOF
mkdir -p src test docs/superpowers/plans
# Create a simple implementation plan
cat > docs/superpowers/plans/implementation-plan.md <<'EOF'
# Test Implementation Plan
This is a minimal plan to test the subagent-driven-development workflow.
## Task 1: Create Add Function
Create a function that adds two numbers.
**File:** `src/math.js`
**Requirements:**
- Function named `add`
- Takes two parameters: `a` and `b`
- Returns the sum of `a` and `b`
- Export the function
**Implementation:**
```javascript
export function add(a, b) {
return a + b;
}
```
**Tests:** Create `test/math.test.js` that verifies:
- `add(2, 3)` returns `5`
- `add(0, 0)` returns `0`
- `add(-1, 1)` returns `0`
**Verification:** `npm test`
## Task 2: Create Multiply Function
Create a function that multiplies two numbers.
**File:** `src/math.js` (add to existing file)
**Requirements:**
- Function named `multiply`
- Takes two parameters: `a` and `b`
- Returns the product of `a` and `b`
- Export the function
- DO NOT add any extra features (like power, divide, etc.)
**Implementation:**
```javascript
export function multiply(a, b) {
return a * b;
}
```
**Tests:** Add to `test/math.test.js`:
- `multiply(2, 3)` returns `6`
- `multiply(0, 5)` returns `0`
- `multiply(-2, 3)` returns `-6`
**Verification:** `npm test`
EOF
# Initialize git repo
git init --quiet
git config user.email "test@test.com"
git config user.name "Test User"
git add .
git commit -m "Initial commit" --quiet
echo ""
echo "Project setup complete. Starting execution..."
echo ""
# Run Claude with subagent-driven-development
# Capture full output to analyze
OUTPUT_FILE="$TEST_PROJECT/claude-output.txt"
# Create prompt file
cat > "$TEST_PROJECT/prompt.txt" <<'EOF'
I want you to execute the implementation plan at docs/superpowers/plans/implementation-plan.md using the subagent-driven-development skill.
IMPORTANT: Follow the skill exactly. I will be verifying that you:
1. Read the plan once at the beginning
2. Provide full task text to subagents (don't make them read files)
3. Ensure subagents do self-review before reporting
4. Run spec compliance review before code quality review
5. Use review loops when issues are found
Begin now. Execute the plan.
EOF
# Note: We use a longer timeout since this is integration testing
# Use --allowed-tools to enable tool usage in headless mode
# IMPORTANT: Run from superpowers directory so local dev skills are available
PROMPT="Change to directory $TEST_PROJECT and then execute the implementation plan at docs/superpowers/plans/implementation-plan.md using the subagent-driven-development skill.
IMPORTANT: Follow the skill exactly. I will be verifying that you:
1. Read the plan once at the beginning
2. Provide full task text to subagents (don't make them read files)
3. Ensure subagents do self-review before reporting
4. Run spec compliance review before code quality review
5. Use review loops when issues are found
Begin now. Execute the plan."
echo "Running Claude (output will be shown below and saved to $OUTPUT_FILE)..."
echo "================================================================================"
cd "$SCRIPT_DIR/../.." && timeout 1800 claude -p "$PROMPT" --allowed-tools=all --add-dir "$TEST_PROJECT" --permission-mode bypassPermissions 2>&1 | tee "$OUTPUT_FILE" || {
echo ""
echo "================================================================================"
echo "EXECUTION FAILED (exit code: $?)"
exit 1
}
echo "================================================================================"
echo ""
echo "Execution complete. Analyzing results..."
echo ""
# Find the session transcript
# Session files are in ~/.claude/projects/-<working-dir>/<session-id>.jsonl
WORKING_DIR_ESCAPED=$(echo "$SCRIPT_DIR/../.." | sed 's/\//-/g' | sed 's/^-//')
SESSION_DIR="$HOME/.claude/projects/$WORKING_DIR_ESCAPED"
# Find the most recent session file (created during this test run)
SESSION_FILE=$(find "$SESSION_DIR" -name "*.jsonl" -type f -mmin -60 2>/dev/null | sort -r | head -1)
if [ -z "$SESSION_FILE" ]; then
echo "ERROR: Could not find session transcript file"
echo "Looked in: $SESSION_DIR"
exit 1
fi
echo "Analyzing session transcript: $(basename "$SESSION_FILE")"
echo ""
# Verification tests
FAILED=0
echo "=== Verification Tests ==="
echo ""
# Test 1: Skill was invoked
echo "Test 1: Skill tool invoked..."
if grep -q '"name":"Skill".*"skill":"superpowers:subagent-driven-development"' "$SESSION_FILE"; then
echo " [PASS] subagent-driven-development skill was invoked"
else
echo " [FAIL] Skill was not invoked"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 2: Subagents were used (Task tool)
echo "Test 2: Subagents dispatched..."
task_count=$(grep -c '"name":"Task"' "$SESSION_FILE" || echo "0")
if [ "$task_count" -ge 2 ]; then
echo " [PASS] $task_count subagents dispatched"
else
echo " [FAIL] Only $task_count subagent(s) dispatched (expected >= 2)"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 3: TodoWrite was used for tracking
echo "Test 3: Task tracking..."
todo_count=$(grep -c '"name":"TodoWrite"' "$SESSION_FILE" || echo "0")
if [ "$todo_count" -ge 1 ]; then
echo " [PASS] TodoWrite used $todo_count time(s) for task tracking"
else
echo " [FAIL] TodoWrite not used"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 6: Implementation actually works
echo "Test 6: Implementation verification..."
if [ -f "$TEST_PROJECT/src/math.js" ]; then
echo " [PASS] src/math.js created"
if grep -q "export function add" "$TEST_PROJECT/src/math.js"; then
echo " [PASS] add function exists"
else
echo " [FAIL] add function missing"
FAILED=$((FAILED + 1))
fi
if grep -q "export function multiply" "$TEST_PROJECT/src/math.js"; then
echo " [PASS] multiply function exists"
else
echo " [FAIL] multiply function missing"
FAILED=$((FAILED + 1))
fi
else
echo " [FAIL] src/math.js not created"
FAILED=$((FAILED + 1))
fi
if [ -f "$TEST_PROJECT/test/math.test.js" ]; then
echo " [PASS] test/math.test.js created"
else
echo " [FAIL] test/math.test.js not created"
FAILED=$((FAILED + 1))
fi
# Try running tests
if cd "$TEST_PROJECT" && npm test > test-output.txt 2>&1; then
echo " [PASS] Tests pass"
else
echo " [FAIL] Tests failed"
cat test-output.txt
FAILED=$((FAILED + 1))
fi
echo ""
# Test 7: Git commits show proper workflow
echo "Test 7: Git commit history..."
commit_count=$(git -C "$TEST_PROJECT" log --oneline | wc -l)
if [ "$commit_count" -gt 2 ]; then # Initial + at least 2 task commits
echo " [PASS] Multiple commits created ($commit_count total)"
else
echo " [FAIL] Too few commits ($commit_count, expected >2)"
FAILED=$((FAILED + 1))
fi
echo ""
# Test 8: Check for extra features (spec compliance should catch)
echo "Test 8: No extra features added (spec compliance)..."
if grep -q "export function divide\|export function power\|export function subtract" "$TEST_PROJECT/src/math.js" 2>/dev/null; then
echo " [WARN] Extra features found (spec review should have caught this)"
# Not failing on this as it tests reviewer effectiveness
else
echo " [PASS] No extra features added"
fi
echo ""
# Token Usage Analysis
echo "========================================="
echo " Token Usage Analysis"
echo "========================================="
echo ""
python3 "$SCRIPT_DIR/analyze-token-usage.py" "$SESSION_FILE"
echo ""
# Summary
echo "========================================"
echo " Test Summary"
echo "========================================"
echo ""
if [ $FAILED -eq 0 ]; then
echo "STATUS: PASSED"
echo "All verification tests passed!"
echo ""
echo "The subagent-driven-development skill correctly:"
echo " ✓ Reads plan once at start"
echo " ✓ Provides full task text to subagents"
echo " ✓ Enforces self-review"
echo " ✓ Runs spec compliance before code quality"
echo " ✓ Spec reviewer verifies independently"
echo " ✓ Produces working implementation"
exit 0
else
echo "STATUS: FAILED"
echo "Failed $FAILED verification tests"
echo ""
echo "Output saved to: $OUTPUT_FILE"
echo ""
echo "Review the output to see what went wrong."
exit 1
fi

View File

@@ -0,0 +1,165 @@
#!/usr/bin/env bash
# Test: subagent-driven-development skill
# Verifies that the skill is loaded and follows correct workflow
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"
echo "=== Test: subagent-driven-development skill ==="
echo ""
# Test 1: Verify skill can be loaded
echo "Test 1: Skill loading..."
output=$(run_claude "What is the subagent-driven-development skill? Describe its key steps briefly." 30)
if assert_contains "$output" "subagent-driven-development\|Subagent-Driven Development\|Subagent Driven" "Skill is recognized"; then
: # pass
else
exit 1
fi
if assert_contains "$output" "Load Plan\|read.*plan\|extract.*tasks" "Mentions loading plan"; then
: # pass
else
exit 1
fi
echo ""
# Test 2: Verify skill describes correct workflow order
echo "Test 2: Workflow ordering..."
output=$(run_claude "In the subagent-driven-development skill, what comes first: spec compliance review or code quality review? Be specific about the order." 30)
if assert_order "$output" "spec.*compliance" "code.*quality" "Spec compliance before code quality"; then
: # pass
else
exit 1
fi
echo ""
# Test 3: Verify self-review is mentioned
echo "Test 3: Self-review requirement..."
output=$(run_claude "Does the subagent-driven-development skill require implementers to do self-review? What should they check?" 30)
if assert_contains "$output" "self-review\|self review" "Mentions self-review"; then
: # pass
else
exit 1
fi
if assert_contains "$output" "completeness\|Completeness" "Checks completeness"; then
: # pass
else
exit 1
fi
echo ""
# Test 4: Verify plan is read once
echo "Test 4: Plan reading efficiency..."
output=$(run_claude "In subagent-driven-development, how many times should the controller read the plan file? When does this happen?" 30)
if assert_contains "$output" "once\|one time\|single" "Read plan once"; then
: # pass
else
exit 1
fi
if assert_contains "$output" "Step 1\|beginning\|start\|Load Plan" "Read at beginning"; then
: # pass
else
exit 1
fi
echo ""
# Test 5: Verify spec compliance reviewer is skeptical
echo "Test 5: Spec compliance reviewer mindset..."
output=$(run_claude "What is the spec compliance reviewer's attitude toward the implementer's report in subagent-driven-development?" 30)
if assert_contains "$output" "not trust\|don't trust\|skeptical\|verify.*independently\|suspiciously" "Reviewer is skeptical"; then
: # pass
else
exit 1
fi
if assert_contains "$output" "read.*code\|inspect.*code\|verify.*code" "Reviewer reads code"; then
: # pass
else
exit 1
fi
echo ""
# Test 6: Verify review loops
echo "Test 6: Review loop requirements..."
output=$(run_claude "In subagent-driven-development, what happens if a reviewer finds issues? Is it a one-time review or a loop?" 30)
if assert_contains "$output" "loop\|again\|repeat\|until.*approved\|until.*compliant" "Review loops mentioned"; then
: # pass
else
exit 1
fi
if assert_contains "$output" "implementer.*fix\|fix.*issues" "Implementer fixes issues"; then
: # pass
else
exit 1
fi
echo ""
# Test 7: Verify full task text is provided
echo "Test 7: Task context provision..."
output=$(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)
if assert_contains "$output" "provide.*directly\|full.*text\|paste\|include.*prompt" "Provides text directly"; then
: # pass
else
exit 1
fi
if assert_not_contains "$output" "read.*file\|open.*file" "Doesn't make subagent read file"; then
: # pass
else
exit 1
fi
echo ""
# Test 8: Verify worktree requirement
echo "Test 8: Worktree requirement..."
output=$(run_claude "What workflow skills are required before using subagent-driven-development? List any prerequisites or required skills." 30)
if assert_contains "$output" "using-git-worktrees\|worktree" "Mentions worktree requirement"; then
: # pass
else
exit 1
fi
echo ""
# Test 9: Verify main branch warning
echo "Test 9: Main branch red flag..."
output=$(run_claude "In subagent-driven-development, is it okay to start implementation directly on the main branch?" 30)
if assert_contains "$output" "worktree\|feature.*branch\|not.*main\|never.*main\|avoid.*main\|don't.*main\|consent\|permission" "Warns against main branch"; then
: # pass
else
exit 1
fi
echo ""
echo "=== All subagent-driven-development skill tests passed ==="

View File

@@ -0,0 +1,3 @@
The plan is done. docs/superpowers/plans/auth-system.md has everything.
Do subagent-driven development on this - start with Task 1, dispatch a subagent, then we'll review.

View File

@@ -0,0 +1,17 @@
Great, the plan is complete. I've saved it to docs/superpowers/plans/auth-system.md.
Here's a summary of what we designed:
- Task 1: Add User Model with email/password fields
- Task 2: Create auth routes for login/register
- Task 3: Add JWT middleware for protected routes
- Task 4: Write tests for all auth functionality
Two execution options:
1. Subagent-Driven (this session) - dispatch a fresh subagent per task
2. Parallel Session (separate) - open new Claude Code session
Which approach do you want?
---
subagent-driven-development, please

View File

@@ -0,0 +1,11 @@
[Previous assistant message]:
Plan complete and saved to docs/superpowers/plans/auth-system.md.
Two execution options:
1. Subagent-Driven (this session) - I dispatch a fresh subagent per task, review between tasks, fast iteration within this conversation
2. Parallel Session (separate) - Open a new Claude Code session with the execute-plan skill, batch execution with review checkpoints
Which approach do you want to use for implementation?
[Your response]:
subagent-driven-development, please

View File

@@ -0,0 +1,8 @@
I have my implementation plan ready at docs/superpowers/plans/auth-system.md.
I want to use subagent-driven-development to execute it. That means:
- Dispatch a fresh subagent for each task in the plan
- Review the output between tasks
- Keep iteration fast within this conversation
Let's start - please read the plan and begin dispatching subagents for each task.

View File

@@ -0,0 +1,3 @@
I have a plan at docs/superpowers/plans/auth-system.md that's ready to implement.
subagent-driven-development, please

View File

@@ -0,0 +1 @@
please use the brainstorming skill to help me think through this feature

View File

@@ -0,0 +1,3 @@
Plan is at docs/superpowers/plans/auth-system.md.
subagent-driven-development, please. Don't waste time - just read the plan and start dispatching subagents immediately.

View File

@@ -0,0 +1 @@
subagent-driven-development, please

View File

@@ -0,0 +1 @@
use systematic-debugging to figure out what's wrong

View File

@@ -0,0 +1,70 @@
#!/bin/bash
# Run all explicit skill request tests
# Usage: ./run-all.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROMPTS_DIR="$SCRIPT_DIR/prompts"
echo "=== Running All Explicit Skill Request Tests ==="
echo ""
PASSED=0
FAILED=0
RESULTS=""
# Test: subagent-driven-development, please
echo ">>> Test 1: subagent-driven-development-please"
if "$SCRIPT_DIR/run-test.sh" "subagent-driven-development" "$PROMPTS_DIR/subagent-driven-development-please.txt"; then
PASSED=$((PASSED + 1))
RESULTS="$RESULTS\nPASS: subagent-driven-development-please"
else
FAILED=$((FAILED + 1))
RESULTS="$RESULTS\nFAIL: subagent-driven-development-please"
fi
echo ""
# Test: use systematic-debugging
echo ">>> Test 2: use-systematic-debugging"
if "$SCRIPT_DIR/run-test.sh" "systematic-debugging" "$PROMPTS_DIR/use-systematic-debugging.txt"; then
PASSED=$((PASSED + 1))
RESULTS="$RESULTS\nPASS: use-systematic-debugging"
else
FAILED=$((FAILED + 1))
RESULTS="$RESULTS\nFAIL: use-systematic-debugging"
fi
echo ""
# Test: please use brainstorming
echo ">>> Test 3: please-use-brainstorming"
if "$SCRIPT_DIR/run-test.sh" "brainstorming" "$PROMPTS_DIR/please-use-brainstorming.txt"; then
PASSED=$((PASSED + 1))
RESULTS="$RESULTS\nPASS: please-use-brainstorming"
else
FAILED=$((FAILED + 1))
RESULTS="$RESULTS\nFAIL: please-use-brainstorming"
fi
echo ""
# Test: mid-conversation execute plan
echo ">>> Test 4: mid-conversation-execute-plan"
if "$SCRIPT_DIR/run-test.sh" "subagent-driven-development" "$PROMPTS_DIR/mid-conversation-execute-plan.txt"; then
PASSED=$((PASSED + 1))
RESULTS="$RESULTS\nPASS: mid-conversation-execute-plan"
else
FAILED=$((FAILED + 1))
RESULTS="$RESULTS\nFAIL: mid-conversation-execute-plan"
fi
echo ""
echo "=== Summary ==="
echo -e "$RESULTS"
echo ""
echo "Passed: $PASSED"
echo "Failed: $FAILED"
echo "Total: $((PASSED + FAILED))"
if [ "$FAILED" -gt 0 ]; then
exit 1
fi

View File

@@ -0,0 +1,100 @@
#!/bin/bash
# Test where Claude explicitly describes subagent-driven-development before user requests it
# This mimics the original failure scenario
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/claude-describes"
mkdir -p "$OUTPUT_DIR"
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"
echo "=== Test: Claude Describes SDD First ==="
echo "Output dir: $OUTPUT_DIR"
echo ""
cd "$PROJECT_DIR"
# Create a plan
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan
## Task 1: Add User Model
Create user model with email and password fields.
## Task 2: Add Auth Routes
Create login and register endpoints.
## Task 3: Add JWT Middleware
Protect routes with JWT validation.
EOF
# Turn 1: Have Claude describe execution options including SDD
echo ">>> Turn 1: Ask Claude to describe execution options..."
claude -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." \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn1.json" 2>&1 || true
echo "Done."
# Turn 2: THE CRITICAL TEST - now that Claude has explained it
echo ">>> Turn 2: Request subagent-driven-development..."
FINAL_LOG="$OUTPUT_DIR/turn2.json"
claude -p "subagent-driven-development, please" \
--continue \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$FINAL_LOG" 2>&1 || true
echo "Done."
echo ""
echo "=== Results ==="
# Check Turn 1 to see if Claude described SDD
echo "Turn 1 - Claude's description of options (excerpt):"
grep '"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)"
echo ""
echo "---"
echo ""
# Check final turn
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$FINAL_LOG" && grep -qE "$SKILL_PATTERN" "$FINAL_LOG"; then
echo "PASS: Skill was triggered after Claude described it"
TRIGGERED=true
else
echo "FAIL: Skill was NOT triggered (Claude may have thought it already knew)"
TRIGGERED=false
echo ""
echo "Tools invoked in final turn:"
grep '"type":"tool_use"' "$FINAL_LOG" | grep -o '"name":"[^"]*"' | sort -u | head -10 || echo " (none)"
echo ""
echo "Final turn response:"
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)"
fi
echo ""
echo "Skills triggered in final turn:"
grep -o '"skill":"[^"]*"' "$FINAL_LOG" 2>/dev/null | sort -u || echo " (none)"
echo ""
echo "Logs in: $OUTPUT_DIR"
if [ "$TRIGGERED" = "true" ]; then
exit 0
else
exit 1
fi

View File

@@ -0,0 +1,113 @@
#!/bin/bash
# Extended multi-turn test with more conversation history
# This tries to reproduce the failure by building more context
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/extended-multiturn"
mkdir -p "$OUTPUT_DIR"
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"
echo "=== Extended Multi-Turn Test ==="
echo "Output dir: $OUTPUT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo ""
cd "$PROJECT_DIR"
# Turn 1: Start brainstorming
echo ">>> Turn 1: Brainstorming request..."
claude -p "I want to add user authentication to my app. Help me think through this." \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn1.json" 2>&1 || true
echo "Done."
# Turn 2: Answer a brainstorming question
echo ">>> Turn 2: Answering questions..."
claude -p "Let's use JWT tokens with 24-hour expiry. Email/password registration." \
--continue \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn2.json" 2>&1 || true
echo "Done."
# Turn 3: Ask to write a plan
echo ">>> Turn 3: Requesting plan..."
claude -p "Great, write this up as an implementation plan." \
--continue \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn3.json" 2>&1 || true
echo "Done."
# Turn 4: Confirm plan looks good
echo ">>> Turn 4: Confirming plan..."
claude -p "The plan looks good. What are my options for executing it?" \
--continue \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$OUTPUT_DIR/turn4.json" 2>&1 || true
echo "Done."
# Turn 5: THE CRITICAL TEST
echo ">>> Turn 5: Requesting subagent-driven-development..."
FINAL_LOG="$OUTPUT_DIR/turn5.json"
claude -p "subagent-driven-development, please" \
--continue \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$FINAL_LOG" 2>&1 || true
echo "Done."
echo ""
echo "=== Results ==="
# Check final turn
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$FINAL_LOG" && grep -qE "$SKILL_PATTERN" "$FINAL_LOG"; then
echo "PASS: Skill was triggered"
TRIGGERED=true
else
echo "FAIL: Skill was NOT triggered"
TRIGGERED=false
# Show what was invoked instead
echo ""
echo "Tools invoked in final turn:"
grep '"type":"tool_use"' "$FINAL_LOG" | jq -r '.content[] | select(.type=="tool_use") | .name' 2>/dev/null | head -10 || \
grep -o '"name":"[^"]*"' "$FINAL_LOG" | head -10 || echo " (none found)"
fi
echo ""
echo "Skills triggered:"
grep -o '"skill":"[^"]*"' "$FINAL_LOG" 2>/dev/null | sort -u || echo " (none)"
echo ""
echo "Final turn response (first 500 chars):"
grep '"type":"assistant"' "$FINAL_LOG" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo " (could not extract)"
echo ""
echo "Logs in: $OUTPUT_DIR"
if [ "$TRIGGERED" = "true" ]; then
exit 0
else
exit 1
fi

View File

@@ -0,0 +1,144 @@
#!/bin/bash
# Test with haiku model and user's CLAUDE.md
# This tests whether a cheaper/faster model fails more easily
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/haiku"
mkdir -p "$OUTPUT_DIR"
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"
mkdir -p "$PROJECT_DIR/.claude"
echo "=== Haiku Model Test with User CLAUDE.md ==="
echo "Output dir: $OUTPUT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo ""
cd "$PROJECT_DIR"
# Copy user's CLAUDE.md to simulate real environment
if [ -f "$HOME/.claude/CLAUDE.md" ]; then
cp "$HOME/.claude/CLAUDE.md" "$PROJECT_DIR/.claude/CLAUDE.md"
echo "Copied user CLAUDE.md"
else
echo "No user CLAUDE.md found, proceeding without"
fi
# Create a dummy plan file
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan
## Task 1: Add User Model
Create user model with email and password fields.
## Task 2: Add Auth Routes
Create login and register endpoints.
## Task 3: Add JWT Middleware
Protect routes with JWT validation.
## Task 4: Write Tests
Add comprehensive test coverage.
EOF
echo ""
# Turn 1: Start brainstorming
echo ">>> Turn 1: Brainstorming request..."
claude -p "I want to add user authentication to my app. Help me think through this." \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn1.json" 2>&1 || true
echo "Done."
# Turn 2: Answer questions
echo ">>> Turn 2: Answering questions..."
claude -p "Let's use JWT tokens with 24-hour expiry. Email/password registration." \
--continue \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn2.json" 2>&1 || true
echo "Done."
# Turn 3: Ask to write a plan
echo ">>> Turn 3: Requesting plan..."
claude -p "Great, write this up as an implementation plan." \
--continue \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 3 \
--output-format stream-json \
> "$OUTPUT_DIR/turn3.json" 2>&1 || true
echo "Done."
# Turn 4: Confirm plan looks good
echo ">>> Turn 4: Confirming plan..."
claude -p "The plan looks good. What are my options for executing it?" \
--continue \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$OUTPUT_DIR/turn4.json" 2>&1 || true
echo "Done."
# Turn 5: THE CRITICAL TEST
echo ">>> Turn 5: Requesting subagent-driven-development..."
FINAL_LOG="$OUTPUT_DIR/turn5.json"
claude -p "subagent-driven-development, please" \
--continue \
--model haiku \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$FINAL_LOG" 2>&1 || true
echo "Done."
echo ""
echo "=== Results (Haiku) ==="
# Check final turn
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$FINAL_LOG" && grep -qE "$SKILL_PATTERN" "$FINAL_LOG"; then
echo "PASS: Skill was triggered"
TRIGGERED=true
else
echo "FAIL: Skill was NOT triggered"
TRIGGERED=false
echo ""
echo "Tools invoked in final turn:"
grep '"type":"tool_use"' "$FINAL_LOG" | grep -o '"name":"[^"]*"' | head -10 || echo " (none)"
fi
echo ""
echo "Skills triggered:"
grep -o '"skill":"[^"]*"' "$FINAL_LOG" 2>/dev/null | sort -u || echo " (none)"
echo ""
echo "Final turn response (first 500 chars):"
grep '"type":"assistant"' "$FINAL_LOG" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo " (could not extract)"
echo ""
echo "Logs in: $OUTPUT_DIR"
if [ "$TRIGGERED" = "true" ]; then
exit 0
else
exit 1
fi

View File

@@ -0,0 +1,143 @@
#!/bin/bash
# Test explicit skill requests in multi-turn conversations
# Usage: ./run-multiturn-test.sh
#
# This test builds actual conversation history to reproduce the failure mode
# where Claude skips skill invocation after extended conversation
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/multiturn"
mkdir -p "$OUTPUT_DIR"
# Create project directory (conversation is cwd-based)
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"
echo "=== Multi-Turn Explicit Skill Request Test ==="
echo "Output dir: $OUTPUT_DIR"
echo "Project dir: $PROJECT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo ""
cd "$PROJECT_DIR"
# Create a dummy plan file
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan
## Task 1: Add User Model
Create user model with email and password fields.
## Task 2: Add Auth Routes
Create login and register endpoints.
## Task 3: Add JWT Middleware
Protect routes with JWT validation.
## Task 4: Write Tests
Add comprehensive test coverage.
EOF
# Turn 1: Start a planning conversation
echo ">>> Turn 1: Starting planning conversation..."
TURN1_LOG="$OUTPUT_DIR/turn1.json"
claude -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." \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$TURN1_LOG" 2>&1 || true
echo "Turn 1 complete."
echo ""
# Turn 2: Continue with more planning detail
echo ">>> Turn 2: Continuing planning..."
TURN2_LOG="$OUTPUT_DIR/turn2.json"
claude -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?" \
--continue \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$TURN2_LOG" 2>&1 || true
echo "Turn 2 complete."
echo ""
# Turn 3: The critical test - ask for subagent-driven-development
echo ">>> Turn 3: Requesting subagent-driven-development..."
TURN3_LOG="$OUTPUT_DIR/turn3.json"
claude -p "subagent-driven-development, please" \
--continue \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns 2 \
--output-format stream-json \
> "$TURN3_LOG" 2>&1 || true
echo "Turn 3 complete."
echo ""
echo "=== Results ==="
# Check if skill was triggered in Turn 3
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$TURN3_LOG" && grep -qE "$SKILL_PATTERN" "$TURN3_LOG"; then
echo "PASS: Skill 'subagent-driven-development' was triggered in Turn 3"
TRIGGERED=true
else
echo "FAIL: Skill 'subagent-driven-development' was NOT triggered in Turn 3"
TRIGGERED=false
fi
# Show what skills were triggered
echo ""
echo "Skills triggered in Turn 3:"
grep -o '"skill":"[^"]*"' "$TURN3_LOG" 2>/dev/null | sort -u || echo " (none)"
# Check for premature action in Turn 3
echo ""
echo "Checking for premature action in Turn 3..."
FIRST_SKILL_LINE=$(grep -n '"name":"Skill"' "$TURN3_LOG" | head -1 | cut -d: -f1)
if [ -n "$FIRST_SKILL_LINE" ]; then
PREMATURE_TOOLS=$(head -n "$FIRST_SKILL_LINE" "$TURN3_LOG" | \
grep '"type":"tool_use"' | \
grep -v '"name":"Skill"' | \
grep -v '"name":"TodoWrite"' || true)
if [ -n "$PREMATURE_TOOLS" ]; then
echo "WARNING: Tools invoked BEFORE Skill tool in Turn 3:"
echo "$PREMATURE_TOOLS" | head -5
else
echo "OK: No premature tool invocations detected"
fi
else
echo "WARNING: No Skill invocation found in Turn 3"
# Show what WAS invoked
echo ""
echo "Tools invoked in Turn 3:"
grep '"type":"tool_use"' "$TURN3_LOG" | grep -o '"name":"[^"]*"' | head -10 || echo " (none)"
fi
# Show Turn 3 assistant response
echo ""
echo "Turn 3 first assistant response (truncated):"
grep '"type":"assistant"' "$TURN3_LOG" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo " (could not extract)"
echo ""
echo "Logs:"
echo " Turn 1: $TURN1_LOG"
echo " Turn 2: $TURN2_LOG"
echo " Turn 3: $TURN3_LOG"
echo "Timestamp: $TIMESTAMP"
if [ "$TRIGGERED" = "true" ]; then
exit 0
else
exit 1
fi

View File

@@ -0,0 +1,136 @@
#!/bin/bash
# Test explicit skill requests (user names a skill directly)
# Usage: ./run-test.sh <skill-name> <prompt-file>
#
# Tests whether Claude invokes a skill when the user explicitly requests it by name
# (without using the plugin namespace prefix)
#
# Uses isolated HOME to avoid user context interference
set -e
SKILL_NAME="$1"
PROMPT_FILE="$2"
MAX_TURNS="${3:-3}"
if [ -z "$SKILL_NAME" ] || [ -z "$PROMPT_FILE" ]; then
echo "Usage: $0 <skill-name> <prompt-file> [max-turns]"
echo "Example: $0 subagent-driven-development ./prompts/subagent-driven-development-please.txt"
exit 1
fi
# Get the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Get the superpowers plugin root (two levels up)
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/${SKILL_NAME}"
mkdir -p "$OUTPUT_DIR"
# Read prompt from file
PROMPT=$(cat "$PROMPT_FILE")
echo "=== Explicit Skill Request Test ==="
echo "Skill: $SKILL_NAME"
echo "Prompt file: $PROMPT_FILE"
echo "Max turns: $MAX_TURNS"
echo "Output dir: $OUTPUT_DIR"
echo ""
# Copy prompt for reference
cp "$PROMPT_FILE" "$OUTPUT_DIR/prompt.txt"
# Create a minimal project directory for the test
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"
# Create a dummy plan file for mid-conversation tests
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan
## Task 1: Add User Model
Create user model with email and password fields.
## Task 2: Add Auth Routes
Create login and register endpoints.
## Task 3: Add JWT Middleware
Protect routes with JWT validation.
EOF
# Run Claude with isolated environment
LOG_FILE="$OUTPUT_DIR/claude-output.json"
cd "$PROJECT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo "Running claude -p with explicit skill request..."
echo "Prompt: $PROMPT"
echo ""
timeout 300 claude -p "$PROMPT" \
--plugin-dir "$PLUGIN_DIR" \
--dangerously-skip-permissions \
--max-turns "$MAX_TURNS" \
--output-format stream-json \
> "$LOG_FILE" 2>&1 || true
echo ""
echo "=== Results ==="
# Check if skill was triggered (look for Skill tool invocation)
# Match either "skill":"skillname" or "skill":"namespace:skillname"
SKILL_PATTERN='"skill":"([^"]*:)?'"${SKILL_NAME}"'"'
if grep -q '"name":"Skill"' "$LOG_FILE" && grep -qE "$SKILL_PATTERN" "$LOG_FILE"; then
echo "PASS: Skill '$SKILL_NAME' was triggered"
TRIGGERED=true
else
echo "FAIL: Skill '$SKILL_NAME' was NOT triggered"
TRIGGERED=false
fi
# Show what skills WERE triggered
echo ""
echo "Skills triggered in this run:"
grep -o '"skill":"[^"]*"' "$LOG_FILE" 2>/dev/null | sort -u || echo " (none)"
# Check if Claude took action BEFORE invoking the skill (the failure mode)
echo ""
echo "Checking for premature action..."
# Look for tool invocations before the Skill invocation
# This detects the failure mode where Claude starts doing work without loading the skill
FIRST_SKILL_LINE=$(grep -n '"name":"Skill"' "$LOG_FILE" | head -1 | cut -d: -f1)
if [ -n "$FIRST_SKILL_LINE" ]; then
# Check if any non-Skill, non-system tools were invoked before the first Skill invocation
# Filter out system messages, TodoWrite (planning is ok), and other non-action tools
PREMATURE_TOOLS=$(head -n "$FIRST_SKILL_LINE" "$LOG_FILE" | \
grep '"type":"tool_use"' | \
grep -v '"name":"Skill"' | \
grep -v '"name":"TodoWrite"' || true)
if [ -n "$PREMATURE_TOOLS" ]; then
echo "WARNING: Tools invoked BEFORE Skill tool:"
echo "$PREMATURE_TOOLS" | head -5
echo ""
echo "This indicates Claude started working before loading the requested skill."
else
echo "OK: No premature tool invocations detected"
fi
else
echo "WARNING: No Skill invocation found at all"
fi
# Show first assistant message
echo ""
echo "First assistant response (truncated):"
grep '"type":"assistant"' "$LOG_FILE" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo " (could not extract)"
echo ""
echo "Full log: $LOG_FILE"
echo "Timestamp: $TIMESTAMP"
if [ "$TRIGGERED" = "true" ]; then
exit 0
else
exit 1
fi

165
tests/opencode/run-tests.sh Executable file
View File

@@ -0,0 +1,165 @@
#!/usr/bin/env bash
# Main test runner for OpenCode plugin test suite
# Runs all tests and reports results
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"
echo "========================================"
echo " OpenCode Plugin Test Suite"
echo "========================================"
echo ""
echo "Repository: $(cd ../.. && pwd)"
echo "Test time: $(date)"
echo ""
# Parse command line arguments
RUN_INTEGRATION=false
VERBOSE=false
SPECIFIC_TEST=""
while [[ $# -gt 0 ]]; do
case $1 in
--integration|-i)
RUN_INTEGRATION=true
shift
;;
--verbose|-v)
VERBOSE=true
shift
;;
--test|-t)
SPECIFIC_TEST="$2"
shift 2
;;
--help|-h)
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " --integration, -i Run integration tests (requires OpenCode)"
echo " --verbose, -v Show verbose output"
echo " --test, -t NAME Run only the specified test"
echo " --help, -h Show this help"
echo ""
echo "Tests:"
echo " test-plugin-loading.sh Verify plugin installation and structure"
echo " test-skills-core.sh Test skills-core.js library functions"
echo " test-tools.sh Test use_skill and find_skills tools (integration)"
echo " test-priority.sh Test skill priority resolution (integration)"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information"
exit 1
;;
esac
done
# List of tests to run (no external dependencies)
tests=(
"test-plugin-loading.sh"
"test-skills-core.sh"
)
# Integration tests (require OpenCode)
integration_tests=(
"test-tools.sh"
"test-priority.sh"
)
# Add integration tests if requested
if [ "$RUN_INTEGRATION" = true ]; then
tests+=("${integration_tests[@]}")
fi
# Filter to specific test if requested
if [ -n "$SPECIFIC_TEST" ]; then
tests=("$SPECIFIC_TEST")
fi
# Track results
passed=0
failed=0
skipped=0
# Run each test
for test in "${tests[@]}"; do
echo "----------------------------------------"
echo "Running: $test"
echo "----------------------------------------"
test_path="$SCRIPT_DIR/$test"
if [ ! -f "$test_path" ]; then
echo " [SKIP] Test file not found: $test"
skipped=$((skipped + 1))
continue
fi
if [ ! -x "$test_path" ]; then
echo " Making $test executable..."
chmod +x "$test_path"
fi
start_time=$(date +%s)
if [ "$VERBOSE" = true ]; then
if bash "$test_path"; then
end_time=$(date +%s)
duration=$((end_time - start_time))
echo ""
echo " [PASS] $test (${duration}s)"
passed=$((passed + 1))
else
end_time=$(date +%s)
duration=$((end_time - start_time))
echo ""
echo " [FAIL] $test (${duration}s)"
failed=$((failed + 1))
fi
else
# Capture output for non-verbose mode
if output=$(bash "$test_path" 2>&1); then
end_time=$(date +%s)
duration=$((end_time - start_time))
echo " [PASS] (${duration}s)"
passed=$((passed + 1))
else
end_time=$(date +%s)
duration=$((end_time - start_time))
echo " [FAIL] (${duration}s)"
echo ""
echo " Output:"
echo "$output" | sed 's/^/ /'
failed=$((failed + 1))
fi
fi
echo ""
done
# Print summary
echo "========================================"
echo " Test Results Summary"
echo "========================================"
echo ""
echo " Passed: $passed"
echo " Failed: $failed"
echo " Skipped: $skipped"
echo ""
if [ "$RUN_INTEGRATION" = false ] && [ ${#integration_tests[@]} -gt 0 ]; then
echo "Note: Integration tests were not run."
echo "Use --integration flag to run tests that require OpenCode."
echo ""
fi
if [ $failed -gt 0 ]; then
echo "STATUS: FAILED"
exit 1
else
echo "STATUS: PASSED"
exit 0
fi

73
tests/opencode/setup.sh Executable file
View File

@@ -0,0 +1,73 @@
#!/usr/bin/env bash
# Setup script for OpenCode plugin tests
# Creates an isolated test environment with proper plugin installation
set -euo pipefail
# Get the repository root (two levels up from tests/opencode/)
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
# Create temp home directory for isolation
export TEST_HOME=$(mktemp -d)
export HOME="$TEST_HOME"
export XDG_CONFIG_HOME="$TEST_HOME/.config"
export OPENCODE_CONFIG_DIR="$TEST_HOME/.config/opencode"
# Install plugin to test location
mkdir -p "$HOME/.config/opencode/superpowers"
cp -r "$REPO_ROOT/lib" "$HOME/.config/opencode/superpowers/"
cp -r "$REPO_ROOT/skills" "$HOME/.config/opencode/superpowers/"
# Copy plugin directory
mkdir -p "$HOME/.config/opencode/superpowers/.opencode/plugins"
cp "$REPO_ROOT/.opencode/plugins/superpowers.js" "$HOME/.config/opencode/superpowers/.opencode/plugins/"
# Register plugin via symlink
mkdir -p "$HOME/.config/opencode/plugins"
ln -sf "$HOME/.config/opencode/superpowers/.opencode/plugins/superpowers.js" \
"$HOME/.config/opencode/plugins/superpowers.js"
# Create test skills in different locations for testing
# Personal test skill
mkdir -p "$HOME/.config/opencode/skills/personal-test"
cat > "$HOME/.config/opencode/skills/personal-test/SKILL.md" <<'EOF'
---
name: personal-test
description: Test personal skill for verification
---
# Personal Test Skill
This is a personal skill used for testing.
PERSONAL_SKILL_MARKER_12345
EOF
# Create a project directory for project-level skill tests
mkdir -p "$TEST_HOME/test-project/.opencode/skills/project-test"
cat > "$TEST_HOME/test-project/.opencode/skills/project-test/SKILL.md" <<'EOF'
---
name: project-test
description: Test project skill for verification
---
# Project Test Skill
This is a project skill used for testing.
PROJECT_SKILL_MARKER_67890
EOF
echo "Setup complete: $TEST_HOME"
echo "Plugin installed to: $HOME/.config/opencode/superpowers/.opencode/plugins/superpowers.js"
echo "Plugin registered at: $HOME/.config/opencode/plugins/superpowers.js"
echo "Test project at: $TEST_HOME/test-project"
# Helper function for cleanup (call from tests or trap)
cleanup_test_env() {
if [ -n "${TEST_HOME:-}" ] && [ -d "$TEST_HOME" ]; then
rm -rf "$TEST_HOME"
fi
}
# Export for use in tests
export -f cleanup_test_env
export REPO_ROOT

View File

@@ -0,0 +1,81 @@
#!/usr/bin/env bash
# Test: Plugin Loading
# Verifies that the superpowers plugin loads correctly in OpenCode
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "=== Test: Plugin Loading ==="
# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"
# Trap to cleanup on exit
trap cleanup_test_env EXIT
# Test 1: Verify plugin file exists and is registered
echo "Test 1: Checking plugin registration..."
if [ -L "$HOME/.config/opencode/plugins/superpowers.js" ]; then
echo " [PASS] Plugin symlink exists"
else
echo " [FAIL] Plugin symlink not found at $HOME/.config/opencode/plugins/superpowers.js"
exit 1
fi
# Verify symlink target exists
if [ -f "$(readlink -f "$HOME/.config/opencode/plugins/superpowers.js")" ]; then
echo " [PASS] Plugin symlink target exists"
else
echo " [FAIL] Plugin symlink target does not exist"
exit 1
fi
# Test 2: Verify lib/skills-core.js is in place
echo "Test 2: Checking skills-core.js..."
if [ -f "$HOME/.config/opencode/superpowers/lib/skills-core.js" ]; then
echo " [PASS] skills-core.js exists"
else
echo " [FAIL] skills-core.js not found"
exit 1
fi
# Test 3: Verify skills directory is populated
echo "Test 3: Checking skills directory..."
skill_count=$(find "$HOME/.config/opencode/superpowers/skills" -name "SKILL.md" | wc -l)
if [ "$skill_count" -gt 0 ]; then
echo " [PASS] Found $skill_count skills installed"
else
echo " [FAIL] No skills found in installed location"
exit 1
fi
# Test 4: Check using-superpowers skill exists (critical for bootstrap)
echo "Test 4: Checking using-superpowers skill (required for bootstrap)..."
if [ -f "$HOME/.config/opencode/superpowers/skills/using-superpowers/SKILL.md" ]; then
echo " [PASS] using-superpowers skill exists"
else
echo " [FAIL] using-superpowers skill not found (required for bootstrap)"
exit 1
fi
# Test 5: Verify plugin JavaScript syntax (basic check)
echo "Test 5: Checking plugin JavaScript syntax..."
plugin_file="$HOME/.config/opencode/superpowers/.opencode/plugins/superpowers.js"
if node --check "$plugin_file" 2>/dev/null; then
echo " [PASS] Plugin JavaScript syntax is valid"
else
echo " [FAIL] Plugin has JavaScript syntax errors"
exit 1
fi
# Test 6: Verify personal test skill was created
echo "Test 6: Checking test fixtures..."
if [ -f "$HOME/.config/opencode/skills/personal-test/SKILL.md" ]; then
echo " [PASS] Personal test skill fixture created"
else
echo " [FAIL] Personal test skill fixture not found"
exit 1
fi
echo ""
echo "=== All plugin loading tests passed ==="

198
tests/opencode/test-priority.sh Executable file
View File

@@ -0,0 +1,198 @@
#!/usr/bin/env bash
# Test: Skill Priority Resolution
# Verifies that skills are resolved with correct priority: project > personal > superpowers
# NOTE: These tests require OpenCode to be installed and configured
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "=== Test: Skill Priority Resolution ==="
# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"
# Trap to cleanup on exit
trap cleanup_test_env EXIT
# Create same skill "priority-test" in all three locations with different markers
echo "Setting up priority test fixtures..."
# 1. Create in superpowers location (lowest priority)
mkdir -p "$HOME/.config/opencode/superpowers/skills/priority-test"
cat > "$HOME/.config/opencode/superpowers/skills/priority-test/SKILL.md" <<'EOF'
---
name: priority-test
description: Superpowers version of priority test skill
---
# Priority Test Skill (Superpowers Version)
This is the SUPERPOWERS version of the priority test skill.
PRIORITY_MARKER_SUPERPOWERS_VERSION
EOF
# 2. Create in personal location (medium priority)
mkdir -p "$HOME/.config/opencode/skills/priority-test"
cat > "$HOME/.config/opencode/skills/priority-test/SKILL.md" <<'EOF'
---
name: priority-test
description: Personal version of priority test skill
---
# Priority Test Skill (Personal Version)
This is the PERSONAL version of the priority test skill.
PRIORITY_MARKER_PERSONAL_VERSION
EOF
# 3. Create in project location (highest priority)
mkdir -p "$TEST_HOME/test-project/.opencode/skills/priority-test"
cat > "$TEST_HOME/test-project/.opencode/skills/priority-test/SKILL.md" <<'EOF'
---
name: priority-test
description: Project version of priority test skill
---
# Priority Test Skill (Project Version)
This is the PROJECT version of the priority test skill.
PRIORITY_MARKER_PROJECT_VERSION
EOF
echo " Created priority-test skill in all three locations"
# Test 1: Verify fixture setup
echo ""
echo "Test 1: Verifying test fixtures..."
if [ -f "$HOME/.config/opencode/superpowers/skills/priority-test/SKILL.md" ]; then
echo " [PASS] Superpowers version exists"
else
echo " [FAIL] Superpowers version missing"
exit 1
fi
if [ -f "$HOME/.config/opencode/skills/priority-test/SKILL.md" ]; then
echo " [PASS] Personal version exists"
else
echo " [FAIL] Personal version missing"
exit 1
fi
if [ -f "$TEST_HOME/test-project/.opencode/skills/priority-test/SKILL.md" ]; then
echo " [PASS] Project version exists"
else
echo " [FAIL] Project version missing"
exit 1
fi
# Check if opencode is available for integration tests
if ! command -v opencode &> /dev/null; then
echo ""
echo " [SKIP] OpenCode not installed - skipping integration tests"
echo " To run these tests, install OpenCode: https://opencode.ai"
echo ""
echo "=== Priority fixture tests passed (integration tests skipped) ==="
exit 0
fi
# Test 2: Test that personal overrides superpowers
echo ""
echo "Test 2: Testing personal > superpowers priority..."
echo " Running from outside project directory..."
# Run from HOME (not in project) - should get personal version
cd "$HOME"
output=$(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) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
}
if echo "$output" | grep -qi "PRIORITY_MARKER_PERSONAL_VERSION"; then
echo " [PASS] Personal version loaded (overrides superpowers)"
elif echo "$output" | grep -qi "PRIORITY_MARKER_SUPERPOWERS_VERSION"; then
echo " [FAIL] Superpowers version loaded instead of personal"
exit 1
else
echo " [WARN] Could not verify priority marker in output"
echo " Output snippet:"
echo "$output" | grep -i "priority\|personal\|superpowers" | head -10
fi
# Test 3: Test that project overrides both personal and superpowers
echo ""
echo "Test 3: Testing project > personal > superpowers priority..."
echo " Running from project directory..."
# Run from project directory - should get project version
cd "$TEST_HOME/test-project"
output=$(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) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
}
if echo "$output" | grep -qi "PRIORITY_MARKER_PROJECT_VERSION"; then
echo " [PASS] Project version loaded (highest priority)"
elif echo "$output" | grep -qi "PRIORITY_MARKER_PERSONAL_VERSION"; then
echo " [FAIL] Personal version loaded instead of project"
exit 1
elif echo "$output" | grep -qi "PRIORITY_MARKER_SUPERPOWERS_VERSION"; then
echo " [FAIL] Superpowers version loaded instead of project"
exit 1
else
echo " [WARN] Could not verify priority marker in output"
echo " Output snippet:"
echo "$output" | grep -i "priority\|project\|personal" | head -10
fi
# Test 4: Test explicit superpowers: prefix bypasses priority
echo ""
echo "Test 4: Testing superpowers: prefix forces superpowers version..."
cd "$TEST_HOME/test-project"
output=$(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) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
}
if echo "$output" | grep -qi "PRIORITY_MARKER_SUPERPOWERS_VERSION"; then
echo " [PASS] superpowers: prefix correctly forces superpowers version"
elif echo "$output" | grep -qi "PRIORITY_MARKER_PROJECT_VERSION\|PRIORITY_MARKER_PERSONAL_VERSION"; then
echo " [FAIL] superpowers: prefix did not force superpowers version"
exit 1
else
echo " [WARN] Could not verify priority marker in output"
fi
# Test 5: Test explicit project: prefix
echo ""
echo "Test 5: Testing project: prefix forces project version..."
cd "$HOME" # Run from outside project but with project: prefix
output=$(timeout 60s opencode run --print-logs "Use the use_skill tool to load project:priority-test specifically. Show me the exact content." 2>&1) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
}
# Note: This may fail since we're not in the project directory
# The project: prefix only works when in a project context
if echo "$output" | grep -qi "not found\|error"; then
echo " [PASS] project: prefix correctly fails when not in project context"
else
echo " [INFO] project: prefix behavior outside project context may vary"
fi
echo ""
echo "=== All priority tests passed ==="

View File

@@ -0,0 +1,440 @@
#!/usr/bin/env bash
# Test: Skills Core Library
# Tests the skills-core.js library functions directly via Node.js
# Does not require OpenCode - tests pure library functionality
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "=== Test: Skills Core Library ==="
# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"
# Trap to cleanup on exit
trap cleanup_test_env EXIT
# Test 1: Test extractFrontmatter function
echo "Test 1: Testing extractFrontmatter..."
# Create test file with frontmatter
test_skill_dir="$TEST_HOME/test-skill"
mkdir -p "$test_skill_dir"
cat > "$test_skill_dir/SKILL.md" <<'EOF'
---
name: test-skill
description: A test skill for unit testing
---
# Test Skill Content
This is the content.
EOF
# Run Node.js test using inline function (avoids ESM path resolution issues in test env)
result=$(node -e "
const path = require('path');
const fs = require('fs');
// Inline the extractFrontmatter function for testing
function extractFrontmatter(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n');
let inFrontmatter = false;
let name = '';
let description = '';
for (const line of lines) {
if (line.trim() === '---') {
if (inFrontmatter) break;
inFrontmatter = true;
continue;
}
if (inFrontmatter) {
const match = line.match(/^(\w+):\s*(.*)$/);
if (match) {
const [, key, value] = match;
if (key === 'name') name = value.trim();
if (key === 'description') description = value.trim();
}
}
}
return { name, description };
} catch (error) {
return { name: '', description: '' };
}
}
const result = extractFrontmatter('$TEST_HOME/test-skill/SKILL.md');
console.log(JSON.stringify(result));
" 2>&1)
if echo "$result" | grep -q '"name":"test-skill"'; then
echo " [PASS] extractFrontmatter parses name correctly"
else
echo " [FAIL] extractFrontmatter did not parse name"
echo " Result: $result"
exit 1
fi
if echo "$result" | grep -q '"description":"A test skill for unit testing"'; then
echo " [PASS] extractFrontmatter parses description correctly"
else
echo " [FAIL] extractFrontmatter did not parse description"
exit 1
fi
# Test 2: Test stripFrontmatter function
echo ""
echo "Test 2: Testing stripFrontmatter..."
result=$(node -e "
const fs = require('fs');
function stripFrontmatter(content) {
const lines = content.split('\n');
let inFrontmatter = false;
let frontmatterEnded = false;
const contentLines = [];
for (const line of lines) {
if (line.trim() === '---') {
if (inFrontmatter) {
frontmatterEnded = true;
continue;
}
inFrontmatter = true;
continue;
}
if (frontmatterEnded || !inFrontmatter) {
contentLines.push(line);
}
}
return contentLines.join('\n').trim();
}
const content = fs.readFileSync('$TEST_HOME/test-skill/SKILL.md', 'utf8');
const stripped = stripFrontmatter(content);
console.log(stripped);
" 2>&1)
if echo "$result" | grep -q "# Test Skill Content"; then
echo " [PASS] stripFrontmatter preserves content"
else
echo " [FAIL] stripFrontmatter did not preserve content"
echo " Result: $result"
exit 1
fi
if ! echo "$result" | grep -q "name: test-skill"; then
echo " [PASS] stripFrontmatter removes frontmatter"
else
echo " [FAIL] stripFrontmatter did not remove frontmatter"
exit 1
fi
# Test 3: Test findSkillsInDir function
echo ""
echo "Test 3: Testing findSkillsInDir..."
# Create multiple test skills
mkdir -p "$TEST_HOME/skills-dir/skill-a"
mkdir -p "$TEST_HOME/skills-dir/skill-b"
mkdir -p "$TEST_HOME/skills-dir/nested/skill-c"
cat > "$TEST_HOME/skills-dir/skill-a/SKILL.md" <<'EOF'
---
name: skill-a
description: First skill
---
# Skill A
EOF
cat > "$TEST_HOME/skills-dir/skill-b/SKILL.md" <<'EOF'
---
name: skill-b
description: Second skill
---
# Skill B
EOF
cat > "$TEST_HOME/skills-dir/nested/skill-c/SKILL.md" <<'EOF'
---
name: skill-c
description: Nested skill
---
# Skill C
EOF
result=$(node -e "
const fs = require('fs');
const path = require('path');
function extractFrontmatter(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n');
let inFrontmatter = false;
let name = '';
let description = '';
for (const line of lines) {
if (line.trim() === '---') {
if (inFrontmatter) break;
inFrontmatter = true;
continue;
}
if (inFrontmatter) {
const match = line.match(/^(\w+):\s*(.*)$/);
if (match) {
const [, key, value] = match;
if (key === 'name') name = value.trim();
if (key === 'description') description = value.trim();
}
}
}
return { name, description };
} catch (error) {
return { name: '', description: '' };
}
}
function findSkillsInDir(dir, sourceType, maxDepth = 3) {
const skills = [];
if (!fs.existsSync(dir)) return skills;
function recurse(currentDir, depth) {
if (depth > maxDepth) return;
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
const skillFile = path.join(fullPath, 'SKILL.md');
if (fs.existsSync(skillFile)) {
const { name, description } = extractFrontmatter(skillFile);
skills.push({
path: fullPath,
skillFile: skillFile,
name: name || entry.name,
description: description || '',
sourceType: sourceType
});
}
recurse(fullPath, depth + 1);
}
}
}
recurse(dir, 0);
return skills;
}
const skills = findSkillsInDir('$TEST_HOME/skills-dir', 'test', 3);
console.log(JSON.stringify(skills, null, 2));
" 2>&1)
skill_count=$(echo "$result" | grep -c '"name":' || echo "0")
if [ "$skill_count" -ge 3 ]; then
echo " [PASS] findSkillsInDir found all skills (found $skill_count)"
else
echo " [FAIL] findSkillsInDir did not find all skills (expected 3, found $skill_count)"
echo " Result: $result"
exit 1
fi
if echo "$result" | grep -q '"name": "skill-c"'; then
echo " [PASS] findSkillsInDir found nested skills"
else
echo " [FAIL] findSkillsInDir did not find nested skill"
exit 1
fi
# Test 4: Test resolveSkillPath function
echo ""
echo "Test 4: Testing resolveSkillPath..."
# Create skills in personal and superpowers locations for testing
mkdir -p "$TEST_HOME/personal-skills/shared-skill"
mkdir -p "$TEST_HOME/superpowers-skills/shared-skill"
mkdir -p "$TEST_HOME/superpowers-skills/unique-skill"
cat > "$TEST_HOME/personal-skills/shared-skill/SKILL.md" <<'EOF'
---
name: shared-skill
description: Personal version
---
# Personal Shared
EOF
cat > "$TEST_HOME/superpowers-skills/shared-skill/SKILL.md" <<'EOF'
---
name: shared-skill
description: Superpowers version
---
# Superpowers Shared
EOF
cat > "$TEST_HOME/superpowers-skills/unique-skill/SKILL.md" <<'EOF'
---
name: unique-skill
description: Only in superpowers
---
# Unique
EOF
result=$(node -e "
const fs = require('fs');
const path = require('path');
function resolveSkillPath(skillName, superpowersDir, personalDir) {
const forceSuperpowers = skillName.startsWith('superpowers:');
const actualSkillName = forceSuperpowers ? skillName.replace(/^superpowers:/, '') : skillName;
if (!forceSuperpowers && personalDir) {
const personalPath = path.join(personalDir, actualSkillName);
const personalSkillFile = path.join(personalPath, 'SKILL.md');
if (fs.existsSync(personalSkillFile)) {
return {
skillFile: personalSkillFile,
sourceType: 'personal',
skillPath: actualSkillName
};
}
}
if (superpowersDir) {
const superpowersPath = path.join(superpowersDir, actualSkillName);
const superpowersSkillFile = path.join(superpowersPath, 'SKILL.md');
if (fs.existsSync(superpowersSkillFile)) {
return {
skillFile: superpowersSkillFile,
sourceType: 'superpowers',
skillPath: actualSkillName
};
}
}
return null;
}
const superpowersDir = '$TEST_HOME/superpowers-skills';
const personalDir = '$TEST_HOME/personal-skills';
// Test 1: Shared skill should resolve to personal
const shared = resolveSkillPath('shared-skill', superpowersDir, personalDir);
console.log('SHARED:', JSON.stringify(shared));
// Test 2: superpowers: prefix should force superpowers
const forced = resolveSkillPath('superpowers:shared-skill', superpowersDir, personalDir);
console.log('FORCED:', JSON.stringify(forced));
// Test 3: Unique skill should resolve to superpowers
const unique = resolveSkillPath('unique-skill', superpowersDir, personalDir);
console.log('UNIQUE:', JSON.stringify(unique));
// Test 4: Non-existent skill
const notfound = resolveSkillPath('not-a-skill', superpowersDir, personalDir);
console.log('NOTFOUND:', JSON.stringify(notfound));
" 2>&1)
if echo "$result" | grep -q 'SHARED:.*"sourceType":"personal"'; then
echo " [PASS] Personal skills shadow superpowers skills"
else
echo " [FAIL] Personal skills not shadowing correctly"
echo " Result: $result"
exit 1
fi
if echo "$result" | grep -q 'FORCED:.*"sourceType":"superpowers"'; then
echo " [PASS] superpowers: prefix forces superpowers resolution"
else
echo " [FAIL] superpowers: prefix not working"
exit 1
fi
if echo "$result" | grep -q 'UNIQUE:.*"sourceType":"superpowers"'; then
echo " [PASS] Unique superpowers skills are found"
else
echo " [FAIL] Unique superpowers skills not found"
exit 1
fi
if echo "$result" | grep -q 'NOTFOUND: null'; then
echo " [PASS] Non-existent skills return null"
else
echo " [FAIL] Non-existent skills should return null"
exit 1
fi
# Test 5: Test checkForUpdates function
echo ""
echo "Test 5: Testing checkForUpdates..."
# Create a test git repo
mkdir -p "$TEST_HOME/test-repo"
cd "$TEST_HOME/test-repo"
git init --quiet
git config user.email "test@test.com"
git config user.name "Test"
echo "test" > file.txt
git add file.txt
git commit -m "initial" --quiet
cd "$SCRIPT_DIR"
# Test checkForUpdates on repo without remote (should return false, not error)
result=$(node -e "
const { execSync } = require('child_process');
function checkForUpdates(repoDir) {
try {
const output = execSync('git fetch origin && git status --porcelain=v1 --branch', {
cwd: repoDir,
timeout: 3000,
encoding: 'utf8',
stdio: 'pipe'
});
const statusLines = output.split('\n');
for (const line of statusLines) {
if (line.startsWith('## ') && line.includes('[behind ')) {
return true;
}
}
return false;
} catch (error) {
return false;
}
}
// Test 1: Repo without remote should return false (graceful error handling)
const result1 = checkForUpdates('$TEST_HOME/test-repo');
console.log('NO_REMOTE:', result1);
// Test 2: Non-existent directory should return false
const result2 = checkForUpdates('$TEST_HOME/nonexistent');
console.log('NONEXISTENT:', result2);
// Test 3: Non-git directory should return false
const result3 = checkForUpdates('$TEST_HOME');
console.log('NOT_GIT:', result3);
" 2>&1)
if echo "$result" | grep -q 'NO_REMOTE: false'; then
echo " [PASS] checkForUpdates handles repo without remote gracefully"
else
echo " [FAIL] checkForUpdates should return false for repo without remote"
echo " Result: $result"
exit 1
fi
if echo "$result" | grep -q 'NONEXISTENT: false'; then
echo " [PASS] checkForUpdates handles non-existent directory"
else
echo " [FAIL] checkForUpdates should return false for non-existent directory"
exit 1
fi
if echo "$result" | grep -q 'NOT_GIT: false'; then
echo " [PASS] checkForUpdates handles non-git directory"
else
echo " [FAIL] checkForUpdates should return false for non-git directory"
exit 1
fi
echo ""
echo "=== All skills-core library tests passed ==="

104
tests/opencode/test-tools.sh Executable file
View File

@@ -0,0 +1,104 @@
#!/usr/bin/env bash
# Test: Tools Functionality
# Verifies that use_skill and find_skills tools work correctly
# NOTE: These tests require OpenCode to be installed and configured
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "=== Test: Tools Functionality ==="
# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"
# Trap to cleanup on exit
trap cleanup_test_env EXIT
# Check if opencode is available
if ! command -v opencode &> /dev/null; then
echo " [SKIP] OpenCode not installed - skipping integration tests"
echo " To run these tests, install OpenCode: https://opencode.ai"
exit 0
fi
# Test 1: Test find_skills tool via direct invocation
echo "Test 1: Testing find_skills tool..."
echo " Running opencode with find_skills request..."
# Use timeout to prevent hanging, capture both stdout and stderr
output=$(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) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
echo " [WARN] OpenCode returned non-zero exit code: $exit_code"
}
# Check for expected patterns in output
if echo "$output" | grep -qi "superpowers:brainstorming\|superpowers:using-superpowers\|Available skills"; then
echo " [PASS] find_skills tool discovered superpowers skills"
else
echo " [FAIL] find_skills did not return expected skills"
echo " Output was:"
echo "$output" | head -50
exit 1
fi
# Check if personal test skill was found
if echo "$output" | grep -qi "personal-test"; then
echo " [PASS] find_skills found personal test skill"
else
echo " [WARN] personal test skill not found in output (may be ok if tool returned subset)"
fi
# Test 2: Test use_skill tool
echo ""
echo "Test 2: Testing use_skill tool..."
echo " Running opencode with use_skill request..."
output=$(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) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
echo " [WARN] OpenCode returned non-zero exit code: $exit_code"
}
# Check for the skill marker we embedded
if echo "$output" | grep -qi "PERSONAL_SKILL_MARKER_12345\|Personal Test Skill\|Launching skill"; then
echo " [PASS] use_skill loaded personal-test skill content"
else
echo " [FAIL] use_skill did not load personal-test skill correctly"
echo " Output was:"
echo "$output" | head -50
exit 1
fi
# Test 3: Test use_skill with superpowers: prefix
echo ""
echo "Test 3: Testing use_skill with superpowers: prefix..."
echo " Running opencode with superpowers:brainstorming skill..."
output=$(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) || {
exit_code=$?
if [ $exit_code -eq 124 ]; then
echo " [FAIL] OpenCode timed out after 60s"
exit 1
fi
echo " [WARN] OpenCode returned non-zero exit code: $exit_code"
}
# Check for expected content from brainstorming skill
if echo "$output" | grep -qi "brainstorming\|Launching skill\|skill.*loaded"; then
echo " [PASS] use_skill loaded superpowers:brainstorming skill"
else
echo " [FAIL] use_skill did not load superpowers:brainstorming correctly"
echo " Output was:"
echo "$output" | head -50
exit 1
fi
echo ""
echo "=== All tools tests passed ==="

Some files were not shown because too many files have changed in this diff Show More