Gugu8 commited on
Commit
7fe7448
·
verified ·
1 Parent(s): df7c92a

Add github_code/obra__superpowers from GitHub - direct commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. github_code/obra__superpowers/.agents/plugins/marketplace.json +20 -0
  2. github_code/obra__superpowers/.claude-plugin/marketplace.json +20 -0
  3. github_code/obra__superpowers/.claude-plugin/plugin.json +20 -0
  4. github_code/obra__superpowers/.codex-plugin/plugin.json +48 -0
  5. github_code/obra__superpowers/.cursor-plugin/plugin.json +23 -0
  6. github_code/obra__superpowers/.devin-plugin/plugin.json +22 -0
  7. github_code/obra__superpowers/.gitattributes +18 -0
  8. github_code/obra__superpowers/.github/FUNDING.yml +3 -0
  9. github_code/obra__superpowers/.github/ISSUE_TEMPLATE/bug_report.md +55 -0
  10. github_code/obra__superpowers/.github/ISSUE_TEMPLATE/config.yml +5 -0
  11. github_code/obra__superpowers/.github/ISSUE_TEMPLATE/feature_request.md +47 -0
  12. github_code/obra__superpowers/.github/ISSUE_TEMPLATE/platform_support.md +34 -0
  13. github_code/obra__superpowers/.github/PULL_REQUEST_TEMPLATE.md +143 -0
  14. github_code/obra__superpowers/.gitignore +19 -0
  15. github_code/obra__superpowers/.hermes-plugin/__init__.py +104 -0
  16. github_code/obra__superpowers/.hermes-plugin/plugin.yaml +6 -0
  17. github_code/obra__superpowers/.kimi-plugin/plugin.json +38 -0
  18. github_code/obra__superpowers/.opencode/INSTALL.md +115 -0
  19. github_code/obra__superpowers/.opencode/plugins/superpowers.js +139 -0
  20. github_code/obra__superpowers/.pi/extensions/superpowers.ts +121 -0
  21. github_code/obra__superpowers/.pre-commit-config.yaml +21 -0
  22. github_code/obra__superpowers/.version-bump.json +23 -0
  23. github_code/obra__superpowers/AGENTS.md +1 -0
  24. github_code/obra__superpowers/CLAUDE.md +115 -0
  25. github_code/obra__superpowers/CODE_OF_CONDUCT.md +128 -0
  26. github_code/obra__superpowers/GEMINI.md +2 -0
  27. github_code/obra__superpowers/LICENSE +21 -0
  28. github_code/obra__superpowers/README.md +346 -0
  29. github_code/obra__superpowers/RELEASE-NOTES.md +1400 -0
  30. github_code/obra__superpowers/assets/app-icon.png +0 -0
  31. github_code/obra__superpowers/assets/superpowers-small.svg +1 -0
  32. github_code/obra__superpowers/docs/README.kimi.md +88 -0
  33. github_code/obra__superpowers/docs/README.opencode.md +163 -0
  34. github_code/obra__superpowers/docs/plans/2025-11-22-opencode-support-design.md +294 -0
  35. github_code/obra__superpowers/docs/plans/2025-11-22-opencode-support-implementation.md +1095 -0
  36. github_code/obra__superpowers/docs/plans/2025-11-28-skills-improvements-from-user-feedback.md +711 -0
  37. github_code/obra__superpowers/docs/plans/2026-01-17-visual-brainstorming.md +571 -0
  38. github_code/obra__superpowers/docs/porting-to-a-new-harness.md +827 -0
  39. github_code/obra__superpowers/docs/superpowers/plans/2026-01-22-document-review-system.md +301 -0
  40. github_code/obra__superpowers/docs/superpowers/plans/2026-02-19-visual-brainstorming-refactor.md +523 -0
  41. github_code/obra__superpowers/docs/superpowers/plans/2026-03-11-zero-dep-brainstorm-server.md +479 -0
  42. github_code/obra__superpowers/docs/superpowers/plans/2026-03-23-codex-app-compatibility.md +566 -0
  43. github_code/obra__superpowers/docs/superpowers/plans/2026-04-06-worktree-rototill.md +866 -0
  44. github_code/obra__superpowers/docs/superpowers/plans/2026-05-06-lift-drill-into-evals.md +1374 -0
  45. github_code/obra__superpowers/docs/superpowers/plans/2026-05-07-pi-extension-and-evals.md +143 -0
  46. github_code/obra__superpowers/docs/superpowers/plans/2026-06-09-sdd-task-scoped-review-dispatch.md +774 -0
  47. github_code/obra__superpowers/docs/superpowers/plans/2026-06-09-visual-companion-issues.md +352 -0
  48. github_code/obra__superpowers/docs/superpowers/plans/2026-06-10-visual-companion-auth-hardening.md +785 -0
  49. github_code/obra__superpowers/docs/superpowers/plans/2026-06-11-visual-companion-final-hardening-fixup.md +1126 -0
  50. github_code/obra__superpowers/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md +1134 -0
github_code/obra__superpowers/.agents/plugins/marketplace.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers-dev",
3
+ "interface": {
4
+ "displayName": "Superpowers Dev"
5
+ },
6
+ "plugins": [
7
+ {
8
+ "name": "superpowers",
9
+ "source": {
10
+ "source": "url",
11
+ "url": "./"
12
+ },
13
+ "policy": {
14
+ "installation": "AVAILABLE",
15
+ "authentication": "ON_INSTALL"
16
+ },
17
+ "category": "Developer Tools"
18
+ }
19
+ ]
20
+ }
github_code/obra__superpowers/.claude-plugin/marketplace.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers-dev",
3
+ "description": "Development marketplace for Superpowers core skills library",
4
+ "owner": {
5
+ "name": "Jesse Vincent",
6
+ "email": "jesse@fsck.com"
7
+ },
8
+ "plugins": [
9
+ {
10
+ "name": "superpowers",
11
+ "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques",
12
+ "version": "6.3.0",
13
+ "source": "./",
14
+ "author": {
15
+ "name": "Jesse Vincent",
16
+ "email": "jesse@fsck.com"
17
+ }
18
+ }
19
+ ]
20
+ }
github_code/obra__superpowers/.claude-plugin/plugin.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers",
3
+ "description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques",
4
+ "version": "6.3.0",
5
+ "author": {
6
+ "name": "Jesse Vincent",
7
+ "email": "jesse@fsck.com"
8
+ },
9
+ "homepage": "https://github.com/obra/superpowers",
10
+ "repository": "https://github.com/obra/superpowers",
11
+ "license": "MIT",
12
+ "keywords": [
13
+ "skills",
14
+ "tdd",
15
+ "debugging",
16
+ "collaboration",
17
+ "best-practices",
18
+ "workflows"
19
+ ]
20
+ }
github_code/obra__superpowers/.codex-plugin/plugin.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers",
3
+ "version": "6.3.0",
4
+ "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.",
5
+ "author": {
6
+ "name": "Jesse Vincent",
7
+ "email": "jesse@fsck.com",
8
+ "url": "https://github.com/obra"
9
+ },
10
+ "homepage": "https://github.com/obra/superpowers",
11
+ "repository": "https://github.com/obra/superpowers",
12
+ "license": "MIT",
13
+ "keywords": [
14
+ "brainstorming",
15
+ "subagent-driven-development",
16
+ "skills",
17
+ "planning",
18
+ "tdd",
19
+ "debugging",
20
+ "code-review",
21
+ "workflow"
22
+ ],
23
+ "skills": "./skills/",
24
+ "hooks": {},
25
+ "interface": {
26
+ "displayName": "Superpowers",
27
+ "shortDescription": "Planning, TDD, debugging, and delivery workflows for coding agents",
28
+ "longDescription": "Use Superpowers to guide agent work through brainstorming, implementation planning, test-driven development, systematic debugging, parallel execution, code review, and finish-the-branch workflows.",
29
+ "developerName": "Jesse Vincent",
30
+ "category": "Developer Tools",
31
+ "capabilities": [
32
+ "Interactive",
33
+ "Read",
34
+ "Write"
35
+ ],
36
+ "defaultPrompt": [
37
+ "I've got an idea for something I'd like to build.",
38
+ "Let's add a feature to this project."
39
+ ],
40
+ "websiteURL": "https://github.com/obra/superpowers",
41
+ "privacyPolicyURL": "https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement",
42
+ "termsOfServiceURL": "https://docs.github.com/en/site-policy/github-terms/github-terms-of-service",
43
+ "brandColor": "#F59E0B",
44
+ "composerIcon": "./assets/superpowers-small.svg",
45
+ "logo": "./assets/app-icon.png",
46
+ "screenshots": []
47
+ }
48
+ }
github_code/obra__superpowers/.cursor-plugin/plugin.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers",
3
+ "displayName": "Superpowers",
4
+ "description": "Core skills library: TDD, debugging, collaboration patterns, and proven techniques",
5
+ "version": "6.3.0",
6
+ "author": {
7
+ "name": "Jesse Vincent",
8
+ "email": "jesse@fsck.com"
9
+ },
10
+ "homepage": "https://github.com/obra/superpowers",
11
+ "repository": "https://github.com/obra/superpowers",
12
+ "license": "MIT",
13
+ "keywords": [
14
+ "skills",
15
+ "tdd",
16
+ "debugging",
17
+ "collaboration",
18
+ "best-practices",
19
+ "workflows"
20
+ ],
21
+ "skills": "./skills/",
22
+ "hooks": "./hooks/hooks-cursor.json"
23
+ }
github_code/obra__superpowers/.devin-plugin/plugin.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers",
3
+ "version": "6.3.0",
4
+ "description": "An agentic skills framework & software development methodology that works: planning, TDD, debugging, and collaboration workflows.",
5
+ "author": {
6
+ "name": "Jesse Vincent",
7
+ "email": "jesse@fsck.com"
8
+ },
9
+ "homepage": "https://github.com/obra/superpowers",
10
+ "repository": "https://github.com/obra/superpowers",
11
+ "license": "MIT",
12
+ "keywords": [
13
+ "brainstorming",
14
+ "subagent-driven-development",
15
+ "skills",
16
+ "planning",
17
+ "tdd",
18
+ "debugging",
19
+ "code-review",
20
+ "workflow"
21
+ ]
22
+ }
github_code/obra__superpowers/.gitattributes ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ensure shell scripts always have LF line endings
2
+ *.sh text eol=lf
3
+ hooks/session-start text eol=lf
4
+
5
+ # Ensure the polyglot wrapper keeps LF (it's parsed by both cmd and bash)
6
+ *.cmd text eol=lf
7
+
8
+ # Common text files
9
+ *.md text eol=lf
10
+ *.json text eol=lf
11
+ *.js text eol=lf
12
+ *.mjs text eol=lf
13
+ *.ts text eol=lf
14
+
15
+ # Explicitly mark binary files
16
+ *.png binary
17
+ *.jpg binary
18
+ *.gif binary
github_code/obra__superpowers/.github/FUNDING.yml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: [obra]
github_code/obra__superpowers/.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug Report
3
+ about: Something isn't working as expected
4
+ labels: bug
5
+ ---
6
+
7
+ <!--
8
+ BEFORE FILING: Search open AND closed issues. The Windows SessionStart
9
+ hook alone has been reported 29 times. If your issue already exists,
10
+ add a comment or reaction to the existing one instead.
11
+ -->
12
+
13
+ - [ ] I searched existing issues and this is not a duplicate
14
+
15
+ ## Environment (required)
16
+ <!-- Required. We assume an agent filed this report — tell us which one and
17
+ where it ran. We weigh reports by what produced them. -->
18
+
19
+ | Field | Value |
20
+ |-------|-------|
21
+ | Superpowers version | |
22
+ | Harness (Claude Code, Cursor, etc.) | |
23
+ | Harness version | |
24
+ | Your model + version | |
25
+ | All plugins installed | |
26
+ | OS + shell | |
27
+
28
+ ## Is this a Superpowers issue or a platform issue?
29
+ <!-- Superpowers is a plugin. Some reported "bugs" are actually issues
30
+ in the underlying platform or model. If you're not sure, try
31
+ reproducing without Superpowers installed.
32
+
33
+ If the problem persists without Superpowers, file the issue with
34
+ your platform instead. -->
35
+
36
+ - [ ] I confirmed this issue does not occur without Superpowers installed
37
+
38
+ ## What happened?
39
+ <!-- Be specific. "It doesn't work" is not a bug report. -->
40
+
41
+ ## Steps to reproduce
42
+ 1.
43
+ 2.
44
+ 3.
45
+
46
+ ## Expected behavior
47
+ <!-- What should have happened? -->
48
+
49
+ ## Actual behavior
50
+ <!-- What happened instead? -->
51
+
52
+ ## Debug log or conversation transcript
53
+ <!-- A debug log or conversation transcript showing the issue is the
54
+ single most helpful thing you can include. Without one, we're
55
+ guessing. Screenshots of error output are also useful. -->
github_code/obra__superpowers/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ blank_issues_enabled: false
2
+ contact_links:
3
+ - name: Questions & Help
4
+ url: https://discord.gg/35wsABTejz
5
+ about: For usage questions, troubleshooting help, and general discussion, please visit our Discord instead of opening an issue.
github_code/obra__superpowers/.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature Request
3
+ about: Propose a change or addition to Superpowers
4
+ labels: enhancement
5
+ ---
6
+
7
+ <!--
8
+ BEFORE FILING: Search open AND closed issues. Many features have been
9
+ requested before — some were implemented differently, some are in
10
+ progress, and some were intentionally declined.
11
+ -->
12
+
13
+ - [ ] I searched existing issues and this has not been proposed before
14
+
15
+ ## What problem does this solve?
16
+ <!-- Describe the problem from your own experience. What were you doing,
17
+ what went wrong or was missing, and why did it matter?
18
+
19
+ "It would be cool if..." is not a problem statement. -->
20
+
21
+ ## Proposed solution
22
+ <!-- What specifically do you want to happen? Be concrete. -->
23
+
24
+ ## What alternatives did you consider?
25
+ <!-- What other approaches could solve the same problem? Why is your
26
+ proposal better? -->
27
+
28
+ ## Is this appropriate for core Superpowers?
29
+ <!-- Would this benefit someone working on a completely different kind
30
+ of project? If this is specific to your domain, workflow, or a
31
+ third-party tool, it may belong as its own plugin instead. -->
32
+
33
+ ## Environment (required)
34
+ <!-- Required. We assume an agent wrote this request — tell us which one and
35
+ where it ran. We weigh proposals reasoned from documentation differently
36
+ than ones grounded in a real session where the problem actually came up. -->
37
+
38
+ | Field | Value |
39
+ |-------|-------|
40
+ | Superpowers version | |
41
+ | Harness (Claude Code, Cursor, etc.) | |
42
+ | Harness version | |
43
+ | Your model + version | |
44
+ | All plugins installed | |
45
+
46
+ ## Context
47
+ <!-- Optional: the workflow where you hit this, links, transcripts. -->
github_code/obra__superpowers/.github/ISSUE_TEMPLATE/platform_support.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: IDE / Platform Support Request
3
+ about: Request support for a new IDE, editor, or AI coding tool
4
+ labels: platform-support
5
+ ---
6
+
7
+ <!--
8
+ BEFORE FILING: Search existing issues — your IDE may already be
9
+ requested or discussed.
10
+ -->
11
+
12
+ - [ ] I searched existing issues for this IDE/platform
13
+
14
+ ## Which IDE or platform?
15
+ <!-- Name and link -->
16
+
17
+ ## Does this tool have a plugin or extension system?
18
+ <!-- If yes, link to the docs. If no, explain how third-party
19
+ integrations typically work with this tool. -->
20
+
21
+ ## Have you tried manual installation?
22
+ <!-- Many tools work with Superpowers through manual setup even without
23
+ official support. Did you try? What happened? -->
24
+
25
+ ## Environment (required)
26
+ <!-- Required. We assume an agent wrote this request — tell us which one and
27
+ where it ran. -->
28
+
29
+ | Field | Value |
30
+ |-------|-------|
31
+ | Harness you currently use (Claude Code, Cursor, etc.) | |
32
+ | Harness version | |
33
+ | Your model + version | |
34
+ | All plugins installed | |
github_code/obra__superpowers/.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ BEFORE SUBMITTING: Read every word of this template. PRs that leave
3
+ sections blank, contain multiple unrelated changes, or show no evidence
4
+ of human involvement will be closed without review.
5
+ -->
6
+
7
+ > **This PR MUST target the `dev` branch, not `main`.** `main` is the
8
+ > released branch; active work lands on `dev` first. PRs opened against
9
+ > `main` will be asked to retarget `dev` before review.
10
+
11
+ ## Who is submitting this PR? (required)
12
+ <!-- Required. PRs that omit this will be closed. We assume an agent wrote
13
+ this PR — tell us which one and where it ran. We weigh contributions by
14
+ what produced them: content reasoned from documentation is held to a
15
+ different bar than work grounded in a real session. -->
16
+
17
+ | Field | Value |
18
+ |-------|-------|
19
+ | Your model + version | |
20
+ | Harness + version | |
21
+ | All plugins installed | |
22
+ | Human partner who reviewed this diff | |
23
+
24
+ ## What problem are you trying to solve?
25
+ <!-- Describe the specific problem you encountered. If this was a session
26
+ issue, include: what you were doing, what went wrong, the model's
27
+ exact failure mode, and ideally a transcript or session log.
28
+
29
+ "Improving" something is not a problem statement. What broke? What
30
+ failed? What was the user experience that motivated this? -->
31
+
32
+ ## What does this PR change?
33
+ <!-- 1-3 sentences. What, not why — the "why" belongs above. -->
34
+
35
+ ## Is this change appropriate for the core library?
36
+ <!-- Superpowers core contains general-purpose skills and infrastructure
37
+ that benefit all users. Ask yourself:
38
+
39
+ - Would this be useful to someone working on a completely different
40
+ kind of project than yours?
41
+ - Is this project-specific, team-specific, or tool-specific?
42
+ - Does this integrate or promote a third-party service?
43
+
44
+ If your change is a new skill for a specific domain, workflow tool,
45
+ or third-party integration, it belongs in its own plugin — not here.
46
+ See the plugin development docs for how to publish it separately. -->
47
+
48
+ ## What alternatives did you consider?
49
+ <!-- What other approaches did you try or evaluate before landing on this
50
+ one? Why were they worse? If you didn't consider alternatives, say so
51
+ — but know that's a red flag. -->
52
+
53
+ ## Does this PR contain multiple unrelated changes?
54
+ <!-- If yes: stop. Split it into separate PRs. Bundled PRs will be closed.
55
+ If you believe the changes are related, explain the dependency. -->
56
+
57
+ ## Existing PRs
58
+ - [ ] I have reviewed all open AND closed PRs for duplicates or prior art
59
+ - Related PRs: <!-- #number, #number, or "none found" -->
60
+
61
+ <!-- If a related closed PR exists, explain what's different about your
62
+ approach and why it should succeed where the other didn't. -->
63
+
64
+ ## Environment tested
65
+
66
+ | Harness (e.g. Claude Code, Cursor) | Harness version | Model | Model version/ID |
67
+ |-------------------------------------|-----------------|-------|------------------|
68
+ | | | | |
69
+
70
+ ## New harness support (required if this PR adds a new harness)
71
+
72
+ <!-- If this PR adds support for a new harness (IDE, CLI tool, agent
73
+ runner), you MUST include a session transcript proving the
74
+ integration actually works.
75
+
76
+ A real integration loads the `using-superpowers` bootstrap at session
77
+ start. The bootstrap is what causes skills to auto-trigger. Without
78
+ it, the skills are dead weight — present on disk but never invoked
79
+ at the right moments.
80
+
81
+ ACCEPTANCE TEST: Open a clean session in the new harness and send
82
+ exactly this user message:
83
+
84
+ Let's make a react todo list
85
+
86
+ A working integration auto-triggers the `brainstorming` skill before
87
+ any code is written. Paste the complete transcript below.
88
+
89
+ These are NOT real integrations and PRs that ship them will be closed:
90
+
91
+ - Manually copying skill files into the harness
92
+ - Wrapping with `npx skills` or similar at-runtime shims
93
+ - Anything that requires the user to opt in to skills per-session
94
+ - Anything where brainstorming does not auto-trigger on the test above
95
+
96
+ If you are not sure whether your integration loads the bootstrap at
97
+ session start, it does not.
98
+ -->
99
+
100
+ <details>
101
+ <summary>Clean-session transcript for "Let's make a react todo list"</summary>
102
+
103
+ ```
104
+ paste the complete transcript here
105
+ ```
106
+
107
+ </details>
108
+
109
+ ## Evaluation
110
+ - What was the initial prompt you (or your human partner) used to start
111
+ the session that led to this change?
112
+ - How many eval sessions did you run AFTER making the change?
113
+ - How did outcomes change compared to before the change?
114
+
115
+ <!-- "It works" is not evaluation. Describe the before/after difference
116
+ you observed across multiple sessions. -->
117
+
118
+ ## Rigor
119
+
120
+ - [ ] If this is a skills change: I used `superpowers:writing-skills` and
121
+ completed adversarial pressure testing (paste results below)
122
+ - [ ] This change was tested adversarially, not just on the happy path
123
+ - [ ] I did not modify carefully-tuned content (Red Flags table,
124
+ rationalizations, "human partner" language) without extensive evals
125
+ showing the change is an improvement
126
+
127
+ <!-- If you changed wording in skills that shape agent behavior, show your
128
+ eval methodology and results. These are not prose — they are code. -->
129
+
130
+ ## Human review
131
+ - [ ] A human has reviewed the COMPLETE proposed diff before submission
132
+
133
+ <!--
134
+ STOP. If the checkbox above is not checked, do not submit this PR.
135
+
136
+ PRs will be closed without review if they:
137
+ - Show no evidence of human involvement
138
+ - Contain multiple unrelated changes
139
+ - Promote or integrate third-party services or tools
140
+ - Submit project-specific or personal configuration as core changes
141
+ - Leave required sections blank or use placeholder text
142
+ - Modify behavior-shaping content without eval evidence
143
+ -->
github_code/obra__superpowers/.gitignore ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .worktrees/
2
+ .private-journal/
3
+ .claude/
4
+ .superpowers/
5
+ .DS_Store
6
+ node_modules/
7
+ inspo
8
+ triage/
9
+
10
+ # Eval harness lives in its own repository, cloned into evals/ for local
11
+ # development (see CLAUDE.md / README.md). It is not part of the published
12
+ # plugin, so the whole directory is ignored here.
13
+ evals/
14
+
15
+ # Python
16
+ __pycache__/
17
+ *.pyc
18
+ *.pyo
19
+ .pytest_cache/
github_code/obra__superpowers/.hermes-plugin/__init__.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from pathlib import Path
4
+
5
+ BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes"
6
+
7
+
8
+ def _skills_dir() -> str:
9
+ """Locate the stock skills/ tree for either supported install layout.
10
+
11
+ - git-clone install (`hermes plugins install obra/superpowers`): the plugin
12
+ dir is the repo root, so `.hermes-plugin/` and `skills/` are siblings and
13
+ this module resolves `../skills`.
14
+ - flattened install (plugin files copied to the plugin dir root): `skills/`
15
+ sits next to this module.
16
+
17
+ Raises loudly when neither matches — a bootstrap that silently skips is how
18
+ a broken install masquerades as a working one.
19
+ """
20
+ here = os.path.dirname(os.path.realpath(__file__))
21
+ candidates = (
22
+ os.path.realpath(os.path.join(here, "..", "skills")),
23
+ os.path.realpath(os.path.join(here, "skills")),
24
+ )
25
+ for cand in candidates:
26
+ if os.path.isfile(os.path.join(cand, "using-superpowers", "SKILL.md")):
27
+ return cand
28
+ raise RuntimeError(
29
+ "superpowers plugin: cannot find the skills/ tree "
30
+ f"(looked at {candidates}). Reinstall with "
31
+ "`hermes plugins install obra/superpowers`."
32
+ )
33
+
34
+
35
+ def _strip_frontmatter(content: str) -> str:
36
+ match = re.match(r"^---\n[\s\S]*?\n---\n([\s\S]*)$", content)
37
+ return (match.group(1) if match else content).strip()
38
+
39
+
40
+ def _build_bootstrap(skills_dir: str) -> str:
41
+ with open(
42
+ os.path.join(skills_dir, "using-superpowers", "SKILL.md"),
43
+ encoding="utf-8",
44
+ ) as f:
45
+ body = _strip_frontmatter(f.read())
46
+
47
+ tools_path = os.path.join(
48
+ skills_dir, "using-superpowers", "references", "hermes-tools.md"
49
+ )
50
+ with open(tools_path, encoding="utf-8") as f:
51
+ tool_mapping = f.read().strip()
52
+
53
+ return (
54
+ f"<EXTREMELY_IMPORTANT>\n"
55
+ f"{BOOTSTRAP_MARKER}\n\n"
56
+ f"You have superpowers.\n\n"
57
+ f"The using-superpowers skill content is included below and is already "
58
+ f"loaded for this Hermes session. Follow it now. "
59
+ f"Do not try to load using-superpowers again.\n\n"
60
+ f"{body}\n\n"
61
+ f"## Loading Superpowers Skills on Hermes\n\n"
62
+ f"Superpowers skills are registered with Hermes' native skill loader: "
63
+ f'invoke one with `skill_view("superpowers:skill-name")` '
64
+ f'(for example `skill_view("superpowers:brainstorming")`). '
65
+ f"If a namespaced lookup returns 'not found', read the skill file "
66
+ f"directly instead:\n"
67
+ f'`read_file("{skills_dir}/skill-name/SKILL.md")`\n\n'
68
+ f"The superpowers skills directory is: `{skills_dir}`\n\n"
69
+ f"{tool_mapping}\n"
70
+ f"</EXTREMELY_IMPORTANT>"
71
+ )
72
+
73
+
74
+ def register(ctx):
75
+ skills_dir = _skills_dir()
76
+ bootstrap = _build_bootstrap(skills_dir)
77
+
78
+ # Register every stock skill with Hermes' native loader so skill_view can
79
+ # load them on demand. Standard markdown; no conversion (plugin guide).
80
+ # register_skill requires a pathlib.Path — a str raises AttributeError and
81
+ # hermes silently disables the whole plugin (verified 2026-07-23).
82
+ for name in sorted(os.listdir(skills_dir)):
83
+ skill_md = os.path.join(skills_dir, name, "SKILL.md")
84
+ if os.path.isfile(skill_md):
85
+ ctx.register_skill(name, Path(skill_md))
86
+
87
+ # pre_llm_call returning {"context": ...} is the documented injection path
88
+ # (on_session_start return values are ignored, and ctx.inject_message
89
+ # refuses from that hook — verified empirically 2026-07-23). The context is
90
+ # appended to the first turn's user message.
91
+ def pre_llm_call(
92
+ session_id=None,
93
+ user_message=None,
94
+ conversation_history=None,
95
+ is_first_turn=None,
96
+ model=None,
97
+ platform=None,
98
+ **kwargs,
99
+ ):
100
+ if is_first_turn:
101
+ return {"context": bootstrap}
102
+ return None
103
+
104
+ ctx.register_hook("pre_llm_call", pre_llm_call)
github_code/obra__superpowers/.hermes-plugin/plugin.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ name: superpowers
2
+ version: 6.3.0
3
+ description: Superpowers skills and workflow bootstrap for Hermes Agent
4
+ author: obra
5
+ provides_hooks:
6
+ - pre_llm_call
github_code/obra__superpowers/.kimi-plugin/plugin.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "superpowers",
3
+ "version": "6.3.0",
4
+ "description": "An agentic skills framework and software development methodology.",
5
+ "author": {
6
+ "name": "Jesse Vincent",
7
+ "email": "jesse@fsck.com"
8
+ },
9
+ "homepage": "https://github.com/obra/superpowers",
10
+ "license": "MIT",
11
+ "keywords": [
12
+ "brainstorming",
13
+ "subagent-driven-development",
14
+ "skills",
15
+ "planning",
16
+ "tdd",
17
+ "debugging",
18
+ "code-review",
19
+ "workflow"
20
+ ],
21
+ "skills": "./skills/",
22
+ "sessionStart": {
23
+ "skill": "using-superpowers"
24
+ },
25
+ "skillInstructions": "Kimi Code tool mapping for Superpowers skills:\n\n- When a Superpowers skill says to ask the user, ask clarifying questions, ask one question at a time, present multiple-choice options, use the terminal for a question, or wait for the user's choice, call Kimi Code's `AskUserQuestion` tool. Do not render those choices as plain assistant text unless `AskUserQuestion` is unavailable or the session is in auto permission mode.\n- For `AskUserQuestion`, provide 1 question with 2-4 concrete options when possible. Put the recommended option first and suffix its label with `(Recommended)`.\n- When a Superpowers skill refers to `TodoWrite`, use Kimi Code's `TodoList` tool.\n- When a Superpowers skill says `Task tool (general-purpose)` or asks you to dispatch an implementer/reviewer subagent, use Kimi Code's `Agent` tool with a Kimi subagent type. Do not pass `general-purpose` as `subagent_type`.\n- For implementation, code review, spec review, quality review, and filled Superpowers subagent prompt templates, call `Agent` with `subagent_type: \"coder\"`, paste the fully filled prompt into `prompt`, and provide a short `description`.\n- For read-only codebase exploration that would take several searches, use `Agent` with `subagent_type: \"explore\"`.\n- For read-only planning or architecture design, use `Agent` with `subagent_type: \"plan\"`.\n- Keep dependent Superpowers subagent steps sequential. Use multiple `Agent` calls, or `run_in_background: true` only when the work is independent and background agents are available.\n- When a Superpowers skill refers to the `Skill` tool, use Kimi Code's native `Skill` tool.\n- Use Kimi Code's `Read`, `Write`, `Edit`, `Bash`, `Grep`, `Glob`, `FetchURL`, `WebSearch`, and MCP tools by their actual exposed names.\n- When a skill asks to search file contents, use `Grep`; when it asks to find files by path or pattern, use `Glob`; when it asks to fetch a URL, use `FetchURL`; when it asks to search the web, use `WebSearch`.",
26
+ "interface": {
27
+ "displayName": "Superpowers",
28
+ "shortDescription": "Planning, TDD, debugging, and delivery workflows for coding agents",
29
+ "longDescription": "Use Superpowers to guide agent work through brainstorming, implementation planning, test-driven development, systematic debugging, parallel execution, code review, and finish-the-branch workflows.",
30
+ "developerName": "Jesse Vincent",
31
+ "capabilities": [
32
+ "Interactive",
33
+ "Read",
34
+ "Write"
35
+ ],
36
+ "websiteURL": "https://github.com/obra/superpowers"
37
+ }
38
+ }
github_code/obra__superpowers/.opencode/INSTALL.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installing Superpowers for OpenCode
2
+
3
+ ## Prerequisites
4
+
5
+ - [OpenCode.ai](https://opencode.ai) installed
6
+
7
+ ## Installation
8
+
9
+ Add superpowers to the `plugin` array in your `opencode.json` (global or project-level):
10
+
11
+ ```json
12
+ {
13
+ "plugin": ["superpowers@git+https://github.com/obra/superpowers.git"]
14
+ }
15
+ ```
16
+
17
+ Restart OpenCode. The plugin installs through OpenCode's plugin manager and
18
+ registers all skills.
19
+
20
+ Verify by asking: "Tell me about your superpowers"
21
+
22
+ OpenCode uses its own plugin install. If you also use Claude Code, Codex, or
23
+ another harness, install Superpowers separately for each one.
24
+
25
+ ## Migrating from the old symlink-based install
26
+
27
+ If you previously installed superpowers using `git clone` and symlinks, remove the old setup:
28
+
29
+ ```bash
30
+ # Remove old symlinks
31
+ rm -f ~/.config/opencode/plugins/superpowers.js
32
+ rm -rf ~/.config/opencode/skills/superpowers
33
+
34
+ # Optionally remove the cloned repo
35
+ rm -rf ~/.config/opencode/superpowers
36
+
37
+ # Remove skills.paths from opencode.json if you added one for superpowers
38
+ ```
39
+
40
+ Then follow the installation steps above.
41
+
42
+ ## Usage
43
+
44
+ Use OpenCode's native `skill` tool:
45
+
46
+ ```
47
+ use skill tool to list skills
48
+ use skill tool to load brainstorming
49
+ ```
50
+
51
+ ## Updating
52
+
53
+ OpenCode installs Superpowers through a git-backed package spec. Some OpenCode
54
+ and Bun versions pin that resolved git dependency in a lockfile or cache, so a
55
+ restart may not pick up the newest Superpowers commit. If updates do not appear,
56
+ clear OpenCode's package cache or reinstall the plugin.
57
+
58
+ To pin a specific version:
59
+
60
+ ```json
61
+ {
62
+ "plugin": ["superpowers@git+https://github.com/obra/superpowers.git#v5.0.3"]
63
+ }
64
+ ```
65
+
66
+ ## Troubleshooting
67
+
68
+ ### Plugin not loading
69
+
70
+ 1. Check logs: `opencode run --print-logs "hello" 2>&1 | grep -i superpowers`
71
+ 2. Verify the plugin line in your `opencode.json`
72
+ 3. Make sure you're running a recent version of OpenCode
73
+
74
+ ### Windows install issues
75
+
76
+ Some Windows OpenCode builds have upstream installer issues with git-backed
77
+ plugin specs, including cache paths for `git+https` URLs and Bun not finding
78
+ `git.exe` even when it works in a normal terminal. If OpenCode cannot install
79
+ the plugin, try installing with system npm and pointing OpenCode at the local
80
+ package:
81
+
82
+ ```powershell
83
+ npm install superpowers@git+https://github.com/obra/superpowers.git --prefix "$HOME\.config\opencode"
84
+ ```
85
+
86
+ Then use the installed package path in `opencode.json`:
87
+
88
+ ```json
89
+ {
90
+ "plugin": ["~/.config/opencode/node_modules/superpowers"]
91
+ }
92
+ ```
93
+
94
+ ### Skills not found
95
+
96
+ 1. Use `skill` tool to list what's discovered
97
+ 2. Check that the plugin is loading (see above)
98
+
99
+ ### Tool mapping
100
+
101
+ Skills speak in actions ("create a todo", "dispatch a subagent", "read a file"). On OpenCode these resolve to:
102
+
103
+ - "Create a todo" / "mark complete in todo list" → `todowrite`
104
+ - `Subagent (general-purpose):` template → `task` tool with `subagent_type: "general"` (or `"explore"` for codebase exploration)
105
+ - "Invoke a skill" → OpenCode's native `skill` tool
106
+ - "Read a file" → `read`
107
+ - "Create a file" / "edit a file" / "delete a file" → `apply_patch`
108
+ - "Run a shell command" → `bash`
109
+ - "Search file contents" / "find files by name" → `grep`, `glob`
110
+ - "Fetch a URL" → `webfetch`
111
+
112
+ ## Getting Help
113
+
114
+ - Report issues: https://github.com/obra/superpowers/issues
115
+ - Full documentation: https://github.com/obra/superpowers/blob/main/docs/README.opencode.md
github_code/obra__superpowers/.opencode/plugins/superpowers.js ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Superpowers plugin for OpenCode.ai
3
+ *
4
+ * Injects superpowers bootstrap context via message transform.
5
+ * Auto-registers skills directory via config hook (no symlinks needed).
6
+ */
7
+
8
+ import path from 'path';
9
+ import fs from 'fs';
10
+ import os from 'os';
11
+ import { fileURLToPath } from 'url';
12
+
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
+
15
+ // Simple frontmatter extraction (avoid dependency on skills-core for bootstrap)
16
+ const extractAndStripFrontmatter = (content) => {
17
+ const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
18
+ if (!match) return { frontmatter: {}, content };
19
+
20
+ const frontmatterStr = match[1];
21
+ const body = match[2];
22
+ const frontmatter = {};
23
+
24
+ for (const line of frontmatterStr.split('\n')) {
25
+ const colonIdx = line.indexOf(':');
26
+ if (colonIdx > 0) {
27
+ const key = line.slice(0, colonIdx).trim();
28
+ const value = line.slice(colonIdx + 1).trim().replace(/^["']|["']$/g, '');
29
+ frontmatter[key] = value;
30
+ }
31
+ }
32
+
33
+ return { frontmatter, content: body };
34
+ };
35
+
36
+ // Normalize a path: trim whitespace, expand ~, resolve to absolute
37
+ const normalizePath = (p, homeDir) => {
38
+ if (!p || typeof p !== 'string') return null;
39
+ let normalized = p.trim();
40
+ if (!normalized) return null;
41
+ if (normalized.startsWith('~/')) {
42
+ normalized = path.join(homeDir, normalized.slice(2));
43
+ } else if (normalized === '~') {
44
+ normalized = homeDir;
45
+ }
46
+ return path.resolve(normalized);
47
+ };
48
+
49
+ // Module-level cache for bootstrap content.
50
+ // The SKILL.md file does not change during a session, so reading + parsing it
51
+ // once eliminates redundant fs.existsSync + fs.readFileSync + regex work on
52
+ // every agent step. See #1202 for the full analysis.
53
+ let _bootstrapCache = undefined; // undefined = not yet loaded, null = file missing
54
+
55
+ export const SuperpowersPlugin = async ({ client, directory }) => {
56
+ const homeDir = os.homedir();
57
+ const superpowersSkillsDir = path.resolve(__dirname, '../../skills');
58
+ const envConfigDir = normalizePath(process.env.OPENCODE_CONFIG_DIR, homeDir);
59
+ const configDir = envConfigDir || path.join(homeDir, '.config/opencode');
60
+
61
+ // Helper to generate bootstrap content (cached after first call)
62
+ const getBootstrapContent = () => {
63
+ // Return cached result on subsequent calls
64
+ if (_bootstrapCache !== undefined) return _bootstrapCache;
65
+
66
+ // Try to load using-superpowers skill
67
+ const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md');
68
+ if (!fs.existsSync(skillPath)) {
69
+ _bootstrapCache = null;
70
+ return null;
71
+ }
72
+
73
+ const fullContent = fs.readFileSync(skillPath, 'utf8');
74
+ const { content } = extractAndStripFrontmatter(fullContent);
75
+
76
+ const toolMapping = `**Tool Mapping for OpenCode:**
77
+ When skills request actions, substitute OpenCode equivalents:
78
+ - Create or update todos → \`todowrite\`
79
+ - \`Subagent (general-purpose):\` → \`task\` with \`subagent_type: "general"\`
80
+ - Invoke a skill → OpenCode's native \`skill\` tool
81
+ - Read files → \`read\`
82
+ - Create, edit, or delete files → \`apply_patch\`
83
+ - Run shell commands → \`bash\`
84
+ - Search files → \`grep\`, \`glob\`
85
+ - Fetch a URL → \`webfetch\`
86
+
87
+ Use OpenCode's native \`skill\` tool to list and load skills.`;
88
+
89
+ _bootstrapCache = `<EXTREMELY_IMPORTANT>
90
+ You have superpowers.
91
+
92
+ **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.**
93
+
94
+ ${content}
95
+
96
+ ${toolMapping}
97
+ </EXTREMELY_IMPORTANT>`;
98
+
99
+ return _bootstrapCache;
100
+ };
101
+
102
+ return {
103
+ // Inject skills path into live config so OpenCode discovers superpowers skills
104
+ // without requiring manual symlinks or config file edits.
105
+ // This works because Config.get() returns a cached singleton — modifications
106
+ // here are visible when skills are lazily discovered later.
107
+ config: async (config) => {
108
+ config.skills = config.skills || {};
109
+ config.skills.paths = config.skills.paths || [];
110
+ if (!config.skills.paths.includes(superpowersSkillsDir)) {
111
+ config.skills.paths.push(superpowersSkillsDir);
112
+ }
113
+ },
114
+
115
+ // Inject bootstrap into the first user message of each session.
116
+ // Using a user message instead of a system message avoids:
117
+ // 1. Token bloat from system messages repeated every turn (#750)
118
+ // 2. Multiple system messages breaking Qwen and other models (#894)
119
+ //
120
+ // The hook fires on every agent step (not just every turn) because
121
+ // opencode's prompt.ts reloads messages from DB each step. Fresh message
122
+ // arrays may need injection again, so getBootstrapContent() must not do
123
+ // repeated disk work.
124
+ 'experimental.chat.messages.transform': async (_input, output) => {
125
+ const bootstrap = getBootstrapContent();
126
+ if (!bootstrap || !output.messages.length) return;
127
+ const firstUser = output.messages.find(m => m.info.role === 'user');
128
+ if (!firstUser || !firstUser.parts.length) return;
129
+
130
+ // Guard: skip if first user message already contains bootstrap.
131
+ // This prevents double injection when OpenCode passes an already
132
+ // transformed in-memory message array through the hook again.
133
+ if (firstUser.parts.some(p => p.type === 'text' && p.text.includes('EXTREMELY_IMPORTANT'))) return;
134
+
135
+ const ref = firstUser.parts[0];
136
+ firstUser.parts.unshift({ ...ref, type: 'text', text: bootstrap });
137
+ }
138
+ };
139
+ };
github_code/obra__superpowers/.pi/extensions/superpowers.ts ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+
6
+ const EXTREMELY_IMPORTANT_MARKER = "<EXTREMELY_IMPORTANT>";
7
+ const BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for pi";
8
+
9
+ const extensionDir = dirname(fileURLToPath(import.meta.url));
10
+ const packageRoot = resolve(extensionDir, "../..");
11
+ const skillsDir = resolve(packageRoot, "skills");
12
+ const bootstrapSkillPath = resolve(skillsDir, "using-superpowers", "SKILL.md");
13
+
14
+ let cachedBootstrap: string | null | undefined;
15
+
16
+ export default function superpowersPiExtension(pi: ExtensionAPI) {
17
+ let injectBootstrap = true;
18
+
19
+ pi.on("resources_discover", async () => ({
20
+ skillPaths: [skillsDir],
21
+ }));
22
+
23
+ pi.on("session_start", async () => {
24
+ injectBootstrap = true;
25
+ });
26
+
27
+ pi.on("session_compact", async () => {
28
+ injectBootstrap = true;
29
+ });
30
+
31
+ pi.on("agent_end", async () => {
32
+ injectBootstrap = false;
33
+ });
34
+
35
+ pi.on("context", async (event) => {
36
+ if (!injectBootstrap) return;
37
+ if (event.messages.some(messageContainsBootstrap)) return;
38
+
39
+ const bootstrap = getBootstrapContent();
40
+ if (!bootstrap) return;
41
+
42
+ const bootstrapMessage = {
43
+ role: "user" as const,
44
+ content: [{ type: "text" as const, text: bootstrap }],
45
+ timestamp: Date.now(),
46
+ };
47
+
48
+ const insertAt = firstNonCompactionSummaryIndex(event.messages);
49
+ return {
50
+ messages: [
51
+ ...event.messages.slice(0, insertAt),
52
+ bootstrapMessage,
53
+ ...event.messages.slice(insertAt),
54
+ ],
55
+ };
56
+ });
57
+ }
58
+
59
+ function getBootstrapContent(): string | null {
60
+ if (cachedBootstrap !== undefined) return cachedBootstrap;
61
+
62
+ try {
63
+ const skillContent = readFileSync(bootstrapSkillPath, "utf8");
64
+ const body = stripFrontmatter(skillContent);
65
+ cachedBootstrap = `${EXTREMELY_IMPORTANT_MARKER}
66
+ ${BOOTSTRAP_MARKER}
67
+
68
+ You have superpowers.
69
+
70
+ The using-superpowers skill content is included below and is already loaded for this Pi session. Follow it now. Do not try to load using-superpowers again.
71
+
72
+ ${body}
73
+
74
+ ${piToolMapping()}
75
+ </EXTREMELY_IMPORTANT>`;
76
+ return cachedBootstrap;
77
+ } catch {
78
+ cachedBootstrap = null;
79
+ return null;
80
+ }
81
+ }
82
+
83
+ function stripFrontmatter(content: string): string {
84
+ const match = content.match(/^---\n[\s\S]*?\n---\n([\s\S]*)$/);
85
+ return (match ? match[1] : content).trim();
86
+ }
87
+
88
+ function piToolMapping(): string {
89
+ return `## Pi tool mapping
90
+
91
+ Pi has native skills but does not expose Claude Code's \`Skill\` tool. When a Superpowers instruction says to invoke a skill, use Pi's native skill system instead: load the relevant \`SKILL.md\` with \`read\` when the skill applies, or let a human invoke \`/skill:name\` explicitly.
92
+
93
+ Pi's built-in coding tools are lowercase: \`read\`, \`write\`, \`edit\`, \`bash\`, plus optional \`grep\`, \`find\`, and \`ls\`. Use those for the corresponding actions: read a file, create or edit files, run shell commands, search file contents, find files by name, and list directories.
94
+
95
+ Pi does not ship a standard subagent tool. If a subagent tool such as \`subagent\` from \`pi-subagents\` is available, use it for Superpowers subagent workflows. If no subagent tool is available, do the work in this session or explain the missing capability instead of inventing \`Task\` calls.
96
+
97
+ Pi does not ship a standard task-list tool. If an installed todo/task tool is available, use it. Otherwise track work in plan files or a repo-local \`TODO.md\` when task tracking is needed. Treat older \`TodoWrite\` references as this task-tracking action.`;
98
+ }
99
+
100
+ function messageContainsBootstrap(message: unknown): boolean {
101
+ const content = (message as { content?: unknown }).content;
102
+ if (typeof content === "string") return content.includes(BOOTSTRAP_MARKER);
103
+ if (!Array.isArray(content)) return false;
104
+ return content.some((part) => {
105
+ return (
106
+ part &&
107
+ typeof part === "object" &&
108
+ (part as { type?: unknown }).type === "text" &&
109
+ typeof (part as { text?: unknown }).text === "string" &&
110
+ (part as { text: string }).text.includes(BOOTSTRAP_MARKER)
111
+ );
112
+ });
113
+ }
114
+
115
+ function firstNonCompactionSummaryIndex(messages: unknown[]): number {
116
+ let index = 0;
117
+ while ((messages[index] as { role?: unknown } | undefined)?.role === "compactionSummary") {
118
+ index += 1;
119
+ }
120
+ return index;
121
+ }
github_code/obra__superpowers/.pre-commit-config.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: local
3
+ hooks:
4
+ - id: evals-ruff-check
5
+ name: evals ruff check
6
+ entry: uv --project evals run ruff check
7
+ language: system
8
+ files: ^evals/.*\.py$
9
+
10
+ - id: evals-ruff-format-check
11
+ name: evals ruff format --check
12
+ entry: uv --project evals run ruff format --check
13
+ language: system
14
+ files: ^evals/.*\.py$
15
+
16
+ - id: evals-ty-check
17
+ name: evals ty check
18
+ entry: uv --directory evals run ty check
19
+ language: system
20
+ pass_filenames: false
21
+ files: ^evals/.*\.py$
github_code/obra__superpowers/.version-bump.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [
3
+ { "path": "package.json", "field": "version" },
4
+ { "path": ".hermes-plugin/plugin.yaml", "field": "version" },
5
+ { "path": ".claude-plugin/plugin.json", "field": "version" },
6
+ { "path": ".cursor-plugin/plugin.json", "field": "version" },
7
+ { "path": ".codex-plugin/plugin.json", "field": "version" },
8
+ { "path": ".devin-plugin/plugin.json", "field": "version" },
9
+ { "path": ".kimi-plugin/plugin.json", "field": "version" },
10
+ { "path": ".claude-plugin/marketplace.json", "field": "plugins.0.version" },
11
+ { "path": "gemini-extension.json", "field": "version" }
12
+ ],
13
+ "audit": {
14
+ "exclude": [
15
+ "CHANGELOG.md",
16
+ "RELEASE-NOTES.md",
17
+ "node_modules",
18
+ ".git",
19
+ ".version-bump.json",
20
+ "scripts/bump-version.sh"
21
+ ]
22
+ }
23
+ }
github_code/obra__superpowers/AGENTS.md ADDED
@@ -0,0 +1 @@
 
 
1
+ CLAUDE.md
github_code/obra__superpowers/CLAUDE.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Superpowers — Contributor Guidelines
2
+
3
+ ## If You Are an AI Agent
4
+
5
+ Stop. Read this section before doing anything.
6
+
7
+ This repo has a 94% PR rejection rate. Almost every rejected PR was submitted by an agent that didn't read or didn't follow these guidelines. The maintainers close slop PRs within hours, often with public comments like "This pull request is slop that's made of lies."
8
+
9
+ **Your job is to protect your human partner from that outcome.** Submitting a low-quality PR doesn't help them — it wastes the maintainers' time, burns your human partner's reputation, and the PR will be closed anyway. That is not being helpful. That is being a tool of embarrassment.
10
+
11
+ Before you open a PR against this repo, you MUST:
12
+
13
+ 1. **Read the entire PR template** at `.github/PULL_REQUEST_TEMPLATE.md` and fill in every section with real, specific answers. Not summaries. Not placeholders.
14
+ 2. **Search for existing PRs** — open AND closed — that address the same problem. If duplicates exist, STOP and tell your human partner. Do not open another duplicate.
15
+ 3. **Verify this is a real problem.** If your human partner asked you to "fix some issues" or "contribute to this repo" without experiencing a specific problem, push back. Ask them what broke, what failed, what the user experience was.
16
+ 4. **Confirm the change belongs in core.** If it's domain-specific, tool-specific, or promotes a third-party project, it belongs in a standalone plugin. Tell your human partner.
17
+ 5. **Identify yourself.** Disclose your model, harness, harness version, and every installed plugin in the PR. Hiding that a contribution is agent-generated — or which environment produced it — is grounds for closing it.
18
+ 6. **Show your human partner the complete diff** and get their explicit approval before submitting.
19
+
20
+ If any of these checks fail, do not open the PR. Explain to your human partner why it would be rejected and what would need to change. They will thank you for saving them the embarrassment.
21
+
22
+ ## Pull Request Requirements
23
+
24
+ **Every PR must fully complete the PR template.** No section may be left blank or filled with placeholder text. PRs that skip sections will be closed without review.
25
+
26
+ **Before opening a PR, you MUST search for existing PRs** — both open AND closed — that address the same problem or a related area. Reference what you found in the "Existing PRs" section. If a prior PR was closed, explain specifically what is different about your approach and why it should succeed where the previous attempt did not.
27
+
28
+ **PRs that show no evidence of human involvement will be closed.** A human must review the complete proposed diff before submission.
29
+
30
+ **Submitters MUST identify themselves.** Every PR and issue must disclose the model, harness, harness version, and all installed plugins used to produce the contribution — or state plainly that it was written by hand with no agent. This is not optional. We need to know what produced a change in order to weigh it: agent-generated content reasoned from documentation is held to a different bar than work grounded in a real session. Contributions that hide their authoring environment will be closed.
31
+
32
+ **All PRs MUST target the `dev` branch, not `main`.** `main` is the released branch; active work lands on `dev` first. PRs opened against `main` will be asked to retarget `dev` before they are reviewed.
33
+
34
+ ## What We Will Not Accept
35
+
36
+ ### Third-party dependencies
37
+
38
+ PRs that add optional or required dependencies on third-party projects will not be accepted unless they are adding support for a new harness (e.g., a new IDE or CLI tool). Superpowers is a zero-dependency plugin by design. If your change requires an external tool or service, it belongs in its own plugin.
39
+
40
+ ### "Compliance" changes to skills
41
+
42
+ Our internal skill philosophy differs from Anthropic's published guidance on writing skills. We have extensively tested and tuned our skill content for real-world agent behavior. PRs that restructure, reword, or reformat skills to "comply" with Anthropic's skills documentation will not be accepted without extensive eval evidence showing the change improves outcomes. The bar for modifying behavior-shaping content is very high.
43
+
44
+ ### Project-specific or personal configuration
45
+
46
+ Skills, hooks, or configuration that only benefit a specific project, team, domain, or workflow do not belong in core. Publish these as a separate plugin.
47
+
48
+ ### Bulk or spray-and-pray PRs
49
+
50
+ Do not trawl the issue tracker and open PRs for multiple issues in a single session. Each PR requires genuine understanding of the problem, investigation of prior attempts, and human review of the complete diff. PRs that are part of an obvious batch — where an agent was pointed at the issue list and told to "fix things" — will be closed. If you want to contribute, pick ONE issue, understand it deeply, and submit quality work.
51
+
52
+ ### Speculative or theoretical fixes
53
+
54
+ Every PR must solve a real problem that someone actually experienced. "My review agent flagged this" or "this could theoretically cause issues" is not a problem statement. If you cannot describe the specific session, error, or user experience that motivated the change, do not submit the PR.
55
+
56
+ ### Domain-specific skills
57
+
58
+ Superpowers core contains general-purpose skills that benefit all users regardless of their project. Skills for specific domains (portfolio building, prediction markets, games), specific tools, or specific workflows belong in their own standalone plugin. Ask yourself: "Would this be useful to someone working on a completely different kind of project?" If not, publish it separately.
59
+
60
+ ### Fork-specific changes
61
+
62
+ If you maintain a fork with customizations, do not open PRs to sync your fork or push fork-specific changes upstream. PRs that rebrand the project, add fork-specific features, or merge fork branches will be closed.
63
+
64
+ ### Fabricated content
65
+
66
+ PRs containing invented claims, fabricated problem descriptions, or hallucinated functionality will be closed immediately. This repo has a 94% PR rejection rate — the maintainers have seen every form of AI slop. They will notice.
67
+
68
+ ### Bundled unrelated changes
69
+
70
+ PRs containing multiple unrelated changes will be closed. Split them into separate PRs.
71
+
72
+ ## New Harness Support
73
+
74
+ If your PR adds support for a new harness (IDE, CLI tool, agent runner), you MUST include a session transcript proving the integration works end-to-end.
75
+
76
+ A real integration loads the `using-superpowers` bootstrap at session start. The bootstrap is what causes skills to auto-trigger at the right moments. Without it, the skills are dead weight — present on disk but never invoked.
77
+
78
+ **The acceptance test.** Open a clean session in the new harness and send exactly this user message:
79
+
80
+ > Let's make a react todo list
81
+
82
+ A working integration auto-triggers the `brainstorming` skill before any code is written. Paste the complete transcript in the PR.
83
+
84
+ **These are not real integrations and will be closed:**
85
+
86
+ - Manually copying skill files into the harness
87
+ - Wrapping with `npx skills` or similar at-runtime shims
88
+ - Anything that requires the user to opt in to skills per-session
89
+ - Anything where `brainstorming` does not auto-trigger on the acceptance test above
90
+
91
+ If you are not sure whether your integration loads the bootstrap at session start, it does not.
92
+
93
+ ## Skill Changes Require Evaluation
94
+
95
+ Skills are not prose — they are code that shapes agent behavior. If you modify skill content:
96
+
97
+ - Use `superpowers:writing-skills` to develop and test changes
98
+ - Run adversarial pressure testing across multiple sessions
99
+ - Show before/after eval results in your PR
100
+ - Do not modify carefully-tuned content (Red Flags tables, rationalization lists, "human partner" language) without evidence the change is an improvement
101
+
102
+ ## Eval harness
103
+
104
+ Skill-behavior evals live in [superpowers-evals](https://github.com/prime-radiant-inc/superpowers-evals/), cloned into `evals/` — see `evals/README.md` for setup. Drill (the harness) drives real tmux sessions of Claude Code / Codex / Gemini CLI and judges skill compliance with an LLM verifier. Plugin-infrastructure tests still live at `tests/`.
105
+
106
+ ## Understand the Project Before Contributing
107
+
108
+ Before proposing changes to skill design, workflow philosophy, or architecture, read existing skills and understand the project's design decisions. Superpowers has its own tested philosophy about skill design, agent behavior shaping, and terminology (e.g., "your human partner" is deliberate, not interchangeable with "the user"). Changes that rewrite the project's voice or restructure its approach without understanding why it exists will be rejected.
109
+
110
+ ## General
111
+
112
+ - Read `.github/PULL_REQUEST_TEMPLATE.md` before submitting
113
+ - One problem per PR
114
+ - Test on at least one harness and report results in the environment table
115
+ - Describe the problem you solved, not just what you changed
github_code/obra__superpowers/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ jesse@primeradiant.com.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
github_code/obra__superpowers/GEMINI.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ @./skills/using-superpowers/SKILL.md
2
+ @./skills/using-superpowers/references/gemini-tools.md
github_code/obra__superpowers/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Jesse Vincent
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
github_code/obra__superpowers/README.md ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Superpowers
2
+
3
+ Superpowers is a complete software development methodology for your coding agents, built on top of a set of composable skills and some initial instructions that make sure your agent uses them.
4
+
5
+ ## Table of Contents
6
+
7
+ - [How it works](#how-it-works)
8
+ - [Commercial Services](#commercial-services)
9
+ - [Getting Started](#installation)
10
+ - [Claude Code](#claude-code)
11
+ - [Antigravity](#antigravity)
12
+ - [Codex App](#codex-app)
13
+ - [Codex CLI](#codex-cli)
14
+ - [Cursor](#cursor)
15
+ - [Devin CLI](#devin-cli)
16
+ - [Factory Droid](#factory-droid)
17
+ - [Gemini CLI](#gemini-cli)
18
+ - [GitHub Copilot CLI](#github-copilot-cli)
19
+ - [Grok Build CLI](#grok-build-cli)
20
+ - [Kimi Code](#kimi-code)
21
+ - [OpenCode](#opencode)
22
+ - [Pi](#pi)
23
+ - [Hermes Agent](#hermes-agent)
24
+ - [The Basic Workflow](#the-basic-workflow)
25
+ - [Community](#community)
26
+ - [What's Inside](#whats-inside)
27
+ - [Philosophy](#philosophy)
28
+ - [Contributing](#contributing)
29
+ - [Updating](#updating)
30
+ - [License](#license)
31
+ - [Visual companion telemetry](#visual-companion-telemetry)
32
+
33
+ ## How it works
34
+
35
+ 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.
36
+
37
+ Once it's teased a spec out of the conversation, it shows it to you in chunks short enough to actually read and digest.
38
+
39
+ 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.
40
+
41
+ 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 your agent to work autonomously for a couple hours at a time without deviating from the plan you put together.
42
+
43
+ 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.
44
+
45
+ ## Commercial Services
46
+
47
+ If you're using Superpowers in enterprise and could benefit from commercial support, additional tooling, or managed spending, please don't hesitate to drop us a line at sales@primeradiant.com.
48
+
49
+ ## Installation
50
+
51
+ Installation differs by harness. If you use more than one, install Superpowers separately for each one.
52
+
53
+ ### Claude Code
54
+
55
+ Superpowers is available via the [official Claude plugin marketplace](https://claude.com/plugins/superpowers)
56
+
57
+ #### Official Marketplace
58
+
59
+ - Install the plugin from Anthropic's official marketplace:
60
+
61
+ ```bash
62
+ /plugin install superpowers@claude-plugins-official
63
+ ```
64
+
65
+ #### Superpowers Marketplace
66
+
67
+ The Superpowers marketplace provides Superpowers and some other related plugins for Claude Code.
68
+
69
+ - Register the marketplace:
70
+
71
+ ```bash
72
+ /plugin marketplace add obra/superpowers-marketplace
73
+ ```
74
+
75
+ - Install the plugin from this marketplace:
76
+
77
+ ```bash
78
+ /plugin install superpowers@superpowers-marketplace
79
+ ```
80
+
81
+ ### Antigravity
82
+
83
+ Install Superpowers as a plugin from this repository:
84
+
85
+ ```bash
86
+ agy plugin install https://github.com/obra/superpowers
87
+ ```
88
+
89
+ Antigravity runs the plugin's session-start hook, so Superpowers is active from
90
+ the first message. Reinstall with the same command to update.
91
+
92
+ ### Codex App
93
+
94
+ Superpowers is available via the [official Codex plugin marketplace](https://github.com/openai/plugins).
95
+
96
+ - In the Codex app, click on Plugins in the sidebar.
97
+ - You should see `Superpowers` in the Coding section.
98
+ - Click the `+` next to Superpowers and follow the prompts.
99
+
100
+ ### Codex CLI
101
+
102
+ Superpowers is available via the [official Codex plugin marketplace](https://github.com/openai/plugins).
103
+
104
+ - Open the plugin search interface:
105
+
106
+ ```bash
107
+ /plugins
108
+ ```
109
+
110
+ - Search for Superpowers:
111
+
112
+ ```bash
113
+ superpowers
114
+ ```
115
+
116
+ - Select `Install Plugin`.
117
+
118
+ ### Cursor
119
+
120
+ - In Cursor Agent chat, install from marketplace:
121
+
122
+ ```text
123
+ /add-plugin superpowers
124
+ ```
125
+
126
+ - Or search for "superpowers" in the plugin marketplace.
127
+
128
+ ### Devin CLI
129
+
130
+ - Install the plugin from this repository:
131
+
132
+ ```bash
133
+ devin plugins install obra/superpowers
134
+ ```
135
+
136
+ - Update to the latest version with:
137
+
138
+ ```bash
139
+ devin plugins update superpowers
140
+ ```
141
+
142
+ ### Factory Droid
143
+
144
+ - Register the marketplace:
145
+
146
+ ```bash
147
+ droid plugin marketplace add https://github.com/obra/superpowers
148
+ ```
149
+
150
+ - Install the plugin:
151
+
152
+ ```bash
153
+ droid plugin install superpowers@superpowers
154
+ ```
155
+
156
+ ### Gemini CLI
157
+
158
+ - Install the extension:
159
+
160
+ ```bash
161
+ gemini extensions install https://github.com/obra/superpowers
162
+ ```
163
+
164
+ - Update later:
165
+
166
+ ```bash
167
+ gemini extensions update superpowers
168
+ ```
169
+
170
+ ### GitHub Copilot CLI
171
+
172
+ - Register the marketplace:
173
+
174
+ ```bash
175
+ copilot plugin marketplace add obra/superpowers-marketplace
176
+ ```
177
+
178
+ - Install the plugin:
179
+
180
+ ```bash
181
+ copilot plugin install superpowers@superpowers-marketplace
182
+ ```
183
+
184
+ ### Grok Build CLI
185
+
186
+ Superpowers is available via the [official Grok plugin marketplace](https://github.com/xai-org/plugin-marketplace).
187
+
188
+ - Install the plugin from xAI's official marketplace:
189
+
190
+ ```bash
191
+ grok plugin install superpowers@xai-official --trust
192
+ ```
193
+
194
+ - Or open the marketplace in the TUI, search for Superpowers, and install it:
195
+
196
+ ```text
197
+ /marketplace
198
+ ```
199
+
200
+ ### Kimi Code
201
+
202
+ Superpowers is available in Kimi Code's plugin marketplace.
203
+
204
+ - Open Kimi Code's plugin manager:
205
+
206
+ ```text
207
+ /plugins
208
+ ```
209
+
210
+ - Go to `Marketplace` > `Superpowers` and install it.
211
+
212
+ - Or install directly from this repository:
213
+
214
+ ```text
215
+ /plugins install https://github.com/obra/superpowers
216
+ ```
217
+
218
+ - Detailed docs: [docs/README.kimi.md](docs/README.kimi.md)
219
+
220
+ ### OpenCode
221
+
222
+ OpenCode uses its own plugin install; install Superpowers separately even if you
223
+ already use it in another harness.
224
+
225
+ - Tell OpenCode:
226
+
227
+ ```
228
+ Fetch and follow instructions from https://raw.githubusercontent.com/obra/superpowers/refs/heads/main/.opencode/INSTALL.md
229
+ ```
230
+
231
+ - Detailed docs: [docs/README.opencode.md](docs/README.opencode.md)
232
+
233
+ ### Pi
234
+
235
+ Install Superpowers as a Pi package from this repository:
236
+
237
+ ```bash
238
+ pi install git:github.com/obra/superpowers
239
+ ```
240
+
241
+ For local development, run Pi with this checkout loaded as a temporary package:
242
+
243
+ ```bash
244
+ pi -e /path/to/superpowers
245
+ ```
246
+
247
+ The Pi package loads the Superpowers skills and a small extension that injects the `using-superpowers` bootstrap at session startup and again after compaction. Pi has native skills, so no compatibility `Skill` tool is required. Subagent and task-list tools remain optional Pi companion packages.
248
+
249
+ ### Hermes Agent
250
+
251
+ Install Superpowers as a Hermes plugin from this repository:
252
+
253
+ ```bash
254
+ hermes plugins install obra/superpowers --enable
255
+ ```
256
+
257
+ Restart any active Hermes sessions after installing. Note: Hermes has no
258
+ post-compaction hook, so a very long session that compacts over its first
259
+ turn loses the bootstrap — start a fresh session if skills stop triggering.
260
+
261
+ ## The Basic Workflow
262
+
263
+ 1. **brainstorming** - Activates before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. Saves design document.
264
+
265
+ 2. **using-git-worktrees** - Activates after design approval. Creates isolated workspace on new branch, runs project setup, verifies clean test baseline.
266
+
267
+ 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.
268
+
269
+ 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.
270
+
271
+ 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.
272
+
273
+ 6. **requesting-code-review** - Activates between tasks. Reviews against plan, reports issues by severity. Critical issues block progress.
274
+
275
+ 7. **finishing-a-development-branch** - Activates when tasks complete. Verifies tests, presents options (merge/PR/keep/discard), cleans up worktree.
276
+
277
+ **The agent checks for relevant skills before any task.** Mandatory workflows, not suggestions.
278
+
279
+ ## Community
280
+
281
+ Superpowers is built by [Jesse Vincent](https://blog.fsck.com) and the rest of the folks at [Prime Radiant](https://primeradiant.com).
282
+
283
+ - **Discord**: [Join us](https://discord.gg/35wsABTejz) for community support, questions, and sharing what you're building with Superpowers
284
+ - **Issues**: https://github.com/obra/superpowers/issues
285
+ - **Release announcements**: [Sign up](https://primeradiant.com/superpowers/) to get notified about new versions
286
+
287
+ ## What's Inside
288
+
289
+ ### Skills Library
290
+
291
+ **Testing**
292
+ - **test-driven-development** - RED-GREEN-REFACTOR cycle (includes testing anti-patterns reference)
293
+
294
+ **Debugging**
295
+ - **systematic-debugging** - 4-phase root cause process (includes root-cause-tracing, defense-in-depth, condition-based-waiting techniques)
296
+ - **verification-before-completion** - Ensure it's actually fixed
297
+
298
+ **Collaboration**
299
+ - **brainstorming** - Socratic design refinement
300
+ - **writing-plans** - Detailed implementation plans
301
+ - **executing-plans** - Batch execution with checkpoints
302
+ - **dispatching-parallel-agents** - Concurrent subagent workflows
303
+ - **requesting-code-review** - Pre-review checklist
304
+ - **receiving-code-review** - Responding to feedback
305
+ - **using-git-worktrees** - Parallel development branches
306
+ - **finishing-a-development-branch** - Merge/PR decision workflow
307
+ - **subagent-driven-development** - Fast iteration with two-stage review (spec compliance, then code quality)
308
+
309
+ **Meta**
310
+ - **writing-skills** - Create new skills following best practices (includes testing methodology)
311
+ - **using-superpowers** - Introduction to the skills system
312
+
313
+ ## Philosophy
314
+
315
+ - **Test-Driven Development** - Write tests first, always
316
+ - **Systematic over ad-hoc** - Process over guessing
317
+ - **Complexity reduction** - Simplicity as primary goal
318
+ - **Evidence over claims** - Verify before declaring success
319
+
320
+ Read [the original release announcement](https://blog.fsck.com/2025/10/09/superpowers/).
321
+
322
+ ## Contributing
323
+
324
+ The general contribution process for Superpowers is below. Keep in mind that we don't generally accept contributions of new skills and that any updates to skills must work across all of the coding agents we support.
325
+
326
+ 1. Fork the repository
327
+ 2. Switch to the 'dev' branch
328
+ 3. Create a branch for your work
329
+ 4. Follow the `writing-skills` skill for creating and testing new and modified skills
330
+ 5. Submit a PR, being sure to fill in the pull request template.
331
+
332
+ Skill-behavior tests use the drill eval harness from [superpowers-evals](https://github.com/prime-radiant-inc/superpowers-evals/), cloned into `evals/` — see `evals/README.md` for setup. Plugin-infrastructure tests live at `tests/` and run via the relevant `run-*.sh` or `npm test`.
333
+
334
+ See `skills/writing-skills/SKILL.md` for the complete guide.
335
+
336
+ ## Updating
337
+
338
+ Superpowers updates are somewhat coding-agent dependent, but are often automatic.
339
+
340
+ ## License
341
+
342
+ MIT License - see LICENSE file for details
343
+
344
+ ## Visual companion telemetry
345
+
346
+ Because skills and plugins don't provide any feedback to creators, we have no idea how many of you are using Superpowers. By default, the Prime Radiant logo on brainstorming's optional visual companion feature is loaded from our website. It includes the version of Superpowers in use. It does not include any details about your project, prompt, or coding agent. We don't see your clicks or anything about what you're building. This helps us have a rough idea of how many folks are using Superpowers and which version of Superpowers they're using. It's 100% optional. To disable this, set the environment variable `SUPERPOWERS_DISABLE_TELEMETRY` to any true value. Superpowers also honors Claude Code's `DISABLE_TELEMETRY` and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` opt-outs.
github_code/obra__superpowers/RELEASE-NOTES.md ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Superpowers Release Notes
2
+
3
+ ## v6.3.0 (2026-08-12)
4
+
5
+ ### Harness Support
6
+
7
+ - **Devin CLI**: `devin plugins install obra/superpowers` now works, and skills auto-trigger at session start. (#1995)
8
+ - **Hermes Agent**: install from a git clone; skills register with Hermes' native loader and the bootstrap loads on the first turn. (#1922, #2025)
9
+ - **Grok Build CLI** added to the install docs. (#1919)
10
+
11
+ ### Brainstorming
12
+
13
+ - **Ceremony now scales to the task.** Requests are classified as spike, bounded, or architectural; small tasks skip the two-document ritual. Every path still stops for your approval before implementation. (#2063)
14
+
15
+ ### Subagent-Driven Development
16
+
17
+ - **Controllers no longer stall on plan conflicts.** Non-catastrophic conflicts and ambiguities get a recorded ruling and work continues; only destructive or irreversible actions still stop for a human. One donated session had sat blocked for almost nine hours on a question the controller could have decided. (#2077)
18
+ - **The pre-dispatch conflict scan records its checks in the ledger** instead of just asserting the plan is clean. (#2080)
19
+ - **Small same-shape tasks batch into one dispatch**, cutting subagent cost sharply on micro-task plans; batch reviews verify every file in the brief made it into the diff. (#2078)
20
+ - **Implementers and reviewers may not spawn their own subagents**, which was producing duplicate reviews. (#2059)
21
+ - **Plans carry a `Spec:` pointer** and SDD reads the spec at setup, so plan conflicts get resolved against the design instead of guessed at. (#2086)
22
+ - Reviewers re-read evidence they find illegible instead of re-running the test suite (#2089), and circuit-breaker rulings now show up in the Finish report.
23
+
24
+ ### Codex
25
+
26
+ - Subagent waits are event-driven instead of poll-heavy, spawns pin model and reasoning effort explicitly, and the multi-agent reference is corrected against Codex source. (#2060, #2061, #2062)
27
+
28
+ ### Finishing a Development Branch
29
+
30
+ - **Worktree removal no longer destroys untracked files.** When `git worktree remove` refuses because the tree holds uncommitted work, the skill stops, names the files, and asks — instead of reaching for `--force`. (#2016, #1223, #2024)
31
+
32
+ ### Fixes
33
+
34
+ - `render-graphs.js` in writing-skills works on Windows.
35
+ - Corrected Copilot CLI backgrounding guidance for Windows. (#1929, #2006)
36
+ - `bump-version.sh` covers the Hermes manifest.
37
+
38
+ ### Documentation
39
+
40
+ - README: added a table of contents and reorganized Getting Started.
41
+
42
+ ## v6.2.0 (2026-07-23)
43
+
44
+ ### Subagent-Driven Development
45
+
46
+ Two structural changes to how SDD tracks progress and closes out review findings, both developed against live eval campaigns.
47
+
48
+ - **The workspace is now plan-scoped.** `.superpowers/sdd/` had no plan identity and no end-of-life: a follow-up plan in the same working tree could read the previous plan's ledger as its own progress (observed in the wild, with multiple contamination rounds and ad-hoc workarounds). `sdd-workspace` now requires the plan file and resolves a per-plan directory, `.superpowers/sdd/<plan-basename>/`; `task-brief` and `review-package` write into their plan's directory (`review-package` gains the plan file as its first argument); the ledger names its plan on its first line; and the workspace is deleted once the final review is clean — git history is the durable record. Baseline evals showed controllers already refused foreign ledgers, but at a cost of 6–13 tool calls of cross-plan git forensics per resume; plan-scoping makes the answer structural instead. (25/25 baseline and GREEN eval runs documented in `docs/specs/` and `docs/plans/`.)
49
+ - **The review-fix loop resumes the implementer.** The lifecycle restructure gives fix rounds resume-the-implementer semantics instead of fresh dispatches, adds a scoped re-review prompt (`re-review-prompt.md`) so the re-reviewer checks the fixes rather than re-reading the whole task, and installs a five-round circuit breaker with controller adjudication when it trips. SKILL.md reorganizes by lifecycle, and its Red Flags convert to the house rationalization-table form.
50
+
51
+ ### Skills
52
+
53
+ A branch-wide compression campaign: recap sections, social proof, and benefits-selling prose aimed at a reader who has already invoked the skill are gone, with every load-bearing argument folded into a rationalization-table row or moved to its point of use. Each cut was micro-tested with subagent probes, and the one cut that measurably degraded behavior was reworked rather than shipped.
54
+
55
+ - **`testing-anti-patterns.md` is now `writing-good-tests.md`.** The TDD reference doc is rebuilt as a positive catalog — six rules that lead with the GOOD example — and absorbs a falsifiability discipline: name the production change that would fail the test, derive expectations independently of the code under test, and a closing mutation check. It closes two holes by name: the string-presence trap (grep-style tests on scripts, skills, and prompts counterfeit falsifiability — the observable is behavior, never text) and the change-detector trap (a constant assertion can fail and still protect nothing), each with a hard stop in the gate function. Trivial code and human prose earn no test; the trigger broadens from "adding mocks" to any test writing.
56
+ - **TDD's "Why Order Matters" rebuttals survive as rationalization rows.** Deleting the section outright measurably degraded test-first behavior under "just write it, tests after" pressure (control 8/10 → treatment 5/10, corroborated on Claude and Codex), so each prose rebuttal now lives in its Common Rationalizations row — the section is gone but the arguments fire where an agent hits them mid-rationalization.
57
+ - **`finishing-a-development-branch` no longer offers to discard your work.** The completion menu dates from when throwing away branches was routine; "Discard this work" next to "Merge" advertised destroying finished, passing work. Discard survives as an explicit-request-only path with the same typed-confirmation ritual. The same pass made PR creation forge-agnostic (your forge's CLI or the URL printed on push, not a blessed list of tools) and fixed a real bug: the worktree path was recomputed after cleanup had already changed directory, so provenance checks never matched and cleanup silently no-oped.
58
+ - **Recap and persuasion prose removed across the library.** `brainstorming`, `systematic-debugging`, `dispatching-parallel-agents`, `verification-before-completion`, `executing-plans`, `subagent-driven-development`, `requesting-code-review`, `receiving-code-review`, `using-git-worktrees`, `writing-plans`, and `writing-skills` all drop their Bottom Line / Key Principles / Real-World Impact / Advantages sections; `using-git-worktrees` and `finishing-a-development-branch` convert their guard sections to the house Excuse/Reality rationalization table.
59
+
60
+ ### Windows
61
+
62
+ - **The SessionStart hook now dispatches via Git Bash.** The hook's command string starts with a quoted path, which broke both shells Claude Code might hand it to: PowerShell parsed the quoted string as an expression and died with a parser error (#1751), and cmd.exe's quote-stripping rule truncated the command when the profile path contained a metacharacter like `(` (#1918) — either way the bootstrap silently never loaded. The hook now declares `shell: "bash"`, which Claude Code ≥ 2.1.81 resolves to Git for Windows directly, and which surfaces an actionable install prompt when Git Bash is missing. Older Claude Code versions ignore the unknown key and behave as before. Verified end-to-end on Linux, Windows 11 with Git Bash under a hostile path, and Windows 11 without Git Bash.
63
+
64
+ ### Harness Support
65
+
66
+ - **Gemini CLI support is restored.** The v6.1.0 removal (on the news that Google had EOLed the Gemini CLI) was premature; the install docs and the `gemini-tools.md` tool-mapping reference are back while permanent removal gets a proper evaluation. (#1959)
67
+
68
+ ### Fixes
69
+
70
+ - **`find-polluter.sh` actually finds test files now.** `find .` emits `./`-prefixed paths, so the documented `-path "src/**/*.test.ts"` pattern matched nothing — and `wc -l` on empty input then reported "Found 1". Fixed the prefix mismatch (#2008, #2011), plus two follow-ups: a caller-supplied `./`-prefixed pattern no longer double-prefixes into a never-matching form, and `**/` is also matched collapsed so tests directly under the base directory (`src/top.test.ts` vs `src/**/*.test.ts`) aren't silently skipped. The script gains a deterministic test suite.
71
+ - **The Codex package script works beyond macOS.** Deterministic-metadata tar flags were bsdtar-only spellings, staged file modes depended on two umasks canceling out, and the test's timestamp assertion parsed bsdtar's column layout in a US timezone. GNU tar now gets equivalent flags producing byte-identical headers, modes are pinned canonical, and the test asserts mtime via `tarfile`.
72
+ - **SDD's skill test no longer flakes.** The file's worst case exceeded the runner's per-file ceiling (raised to 900s), and the assert helpers matched free-form model prose case-sensitively; matching is now case-insensitive and `assert_order` dumps output on failure so the next flake is diagnosable.
73
+ - **Docs and test cleanup after the v6.1.0 reference pruning.** Dead links to the deleted `claude-code-tools.md`/`copilot-tools.md` are replaced with the current architecture (#1969), a dangling `#subagent-support` anchor in the Antigravity reference is dropped (#2010), and the Antigravity/Pi mapping tests assert only the surviving harness-specific mappings — scoped to the table so they fail again if it's deleted.
74
+
75
+ ## v6.1.1 (2026-07-02)
76
+
77
+ ### Codex
78
+
79
+ - **Codex no longer re-registers the Claude SessionStart hook.** v6.1.0 removed the Codex hook config and its manifest `hooks` pointer, meaning to stop Codex from installing a SessionStart hook — but with no `hooks` field, Codex fell back to auto-discovering `hooks/hooks.json`, the Claude Code SessionStart hook that the marketplace ships from the repo root, and re-registered it along with its install-time trust prompt. The Codex manifest now declares an explicit empty hooks object (`hooks: {}`), which Codex reads as "no hooks" instead of reaching the auto-discovery fallback. An absent field, `[]`, and an empty inline list all collapse back to the fallback, so the value has to be exactly `{}`.
80
+ - **Removed orphaned Codex session-start dead code.** `hooks/session-start-codex` had no caller once the Codex hook config was deleted, so it and its redundant test cases are gone. The worked shell-hook example in `docs/porting-to-a-new-harness.md` moves from Codex — now native skill discovery with no session-start hook — to Cursor, a live shell-hook harness, and the stale `hooks-codex.json` pointer in `docs/windows/polyglot-hooks.md` is corrected. The Codex plugin category is also fixed to "Developer Tools".
81
+
82
+ ### Packaging
83
+
84
+ - **New `package-codex-plugin.sh` for building the Codex portal package.** A maintainer script produces a deterministic Codex "portal" archive — `.zip` by default, `tar.gz` on request — that normalizes entry timestamps, preserves executable modes, verifies every packaged skill ships its OpenAI metadata, includes the app and composer icons, and refuses to run against a dirty worktree. The packaged manifest keeps the source `hooks: {}` object so a portal-installed plugin avoids the same SessionStart auto-discovery, and the script can rebuild a byte-identical archive from a saved metadata source. Covered by a new test suite.
85
+
86
+ ## v6.1.0 (2026-06-30)
87
+
88
+ ### Lower Per-Session Token Cost
89
+
90
+ The `using-superpowers` bootstrap is injected into every session, so its size is paid for constantly. This release trims it and the per-harness references it points to, without dropping behavior-shaping content.
91
+
92
+ - **Compressed the `using-superpowers` bootstrap.** Replaced the graphviz skill-flow diagram with the prose it encoded, folded the standalone Instruction-Priority section into User Instructions, dropped the per-platform "How to Access Skills" walkthrough, and trimmed the Platform Adaptation pointer to the harnesses that still ship a reference file. The full Red Flags rationalization table and the user-instruction precedence rules are unchanged.
93
+ - **Pruned the per-harness tool-mapping references.** The verbose action-to-tool tables restated guidance modern agents already follow. Each reference file is trimmed to the harness-specific notes that still carry weight — subagent dispatch, task tracking, instructions-file paths — and `claude-code-tools.md` and `copilot-tools.md`, which had nothing harness-specific left, are deleted.
94
+
95
+ ### Codex
96
+
97
+ - **Codex can install from the marketplace.** Codex marketplace sources expect a `.agents/plugins/marketplace.json` at the marketplace root; the repo only shipped the Claude marketplace file, so Codex could name the marketplace but found no installable plugin entries. A repo-local Codex marketplace manifest now points at the same repository root, so the plugin is installable from Codex.
98
+ - **Codex no longer ships a SessionStart hook.** Codex reliably triggers skills on its own, and the bootstrap hook made the UX worse rather than better. The Codex hook config (`hooks-codex.json`) and its manifest registration are removed.
99
+
100
+ ### Harness Support
101
+
102
+ - **Gemini CLI support removed.** Google EOLed the Gemini CLI on 2026-06-18; the extension can no longer be installed or updated. Gemini is gone from the install docs, the subagent-capable platform lists, and the eval-harness description, and its tool-mapping reference is deleted.
103
+
104
+ ## v6.0.3 (2026-06-18)
105
+
106
+ ### Subagent-Driven Development
107
+
108
+ - **SDD scratch files moved out of `.git/`.** Claude Code treats `.git/` as a protected path and denies agent writes there, so an implementer subagent writing its report into `.git/sdd/` got blocked mid-run. Task briefs, implementer reports, review diffs, and the progress ledger now live in a self-ignoring `.superpowers/sdd/` directory in the working tree — kept out of `git status` and out of commits, and resolved per worktree by a shared `sdd-workspace` helper. One caveat: because the workspace is git-ignored working-tree scratch, `git clean -fdx` will delete the progress ledger; recover from `git log` if that happens. (#1780)
109
+
110
+ ## v6.0.2 (2026-06-16)
111
+
112
+ ### Install Fixes
113
+
114
+ - **We no longer ship the `evals` submodule.** It broke plugin installs for some users, so the eval harness now lives in its own repo, separate from the published plugin. (#1778, #1774)
115
+
116
+ ## v6.0.1 (2026-06-16)
117
+
118
+ ### Codex Fixes
119
+
120
+ - **Version display in the brainstorm companion** — packaged Codex plugins ship without a root `package.json`, so the visual companion reported its version as "unknown". `readSuperpowersVersion()` now falls back to `.codex-plugin/plugin.json` when `package.json` is absent.
121
+ - **Cleaner Codex plugin sync** — the sync-to-codex script now excludes `.gitmodules` and `.pre-commit-config.yaml`, keeping repo metadata out of the packaged Codex plugin.
122
+
123
+ ## v6.0.0 (2026-06-16)
124
+
125
+ Superpowers 6.0 is a big release. The headline is a rewrite of how `subagent-driven-development` reviews each task — cheaper, stricter, and harder to game.
126
+
127
+ While these numbers won't hold on every harness and for every workload, in our evals, Claude Code and Codex produce similar high-quality results roughly twice as fast and while spending almost 50% fewer tokens.
128
+
129
+ It also adds three new harnesses (Kimi Code, Pi, and Antigravity), gives the brainstorming visual companion a better security model, and rewrites a number of skills' tool calls to be significantly more vendor-neutral.
130
+
131
+ ### Visible Changes
132
+
133
+ - **The two per-task reviewer prompts became one.** `spec-reviewer-prompt.md` and `code-quality-reviewer-prompt.md` are gone, replaced by a single `task-reviewer-prompt.md`. If you dispatch the old files directly, switch to the new one.
134
+ - **The legacy global worktree directory is gone.** `using-git-worktrees` and `finishing-a-development-branch` no longer use `~/.config/superpowers/worktrees/`. Worktrees now land in the project — an existing `.worktrees/` or `worktrees/` if you have one, otherwise a fresh `.worktrees/` — unless you say otherwise.
135
+
136
+ ### New Harness Support
137
+
138
+ Superpowers now runs on three more harnesses. Each ships its own bootstrap, a tool-mapping reference, and tests, and each gets its own install section in the README.
139
+
140
+ - **Kimi Code** — a plugin manifest, install docs, and manifest tests; install from Kimi's marketplace or straight from the repo. (initial manifest by @qer)
141
+ - **Pi** — a session-start extension that registers the skills and injects the `using-superpowers` bootstrap. Pi has native skills, so it needs no compatibility shim.
142
+ - **Antigravity (`agy`)** — installs the plugin directly and bootstraps from the first message; verified end-to-end against the standard "make a react todo list" acceptance test.
143
+
144
+ ### Subagent-Driven Development
145
+
146
+ A long run of cost-and-quality experiments on real projects reshaped how the controller reviews each task. The old flow ran two reviewers per task and leaned on the controller's judgment for model choice and severity, and both turned out to be expensive and easy to game. The new flow runs one reviewer per task, hands work off as files instead of pasted text, and takes several judgment calls away from the controller.
147
+
148
+ - **One reviewer per task, two verdicts.** A single `task-reviewer-prompt.md` reads the task's diff once and returns both a spec-compliance verdict and a quality verdict, so one fix pass clears both. A new "can't verify from the diff" verdict flags requirements that live in untouched code, for the controller to check itself. (#1538, #1543)
149
+ - **One broad review at the end.** The run finishes with a single whole-branch review on the most capable model, instead of re-reviewing everything task by task.
150
+ - **Plans get a pre-flight read.** Before the first task, the controller checks the plan for internal conflicts — and for anything the plan asks for that a reviewer would flag as a defect — and raises it all at once, rather than stumbling into it mid-run.
151
+ - **Diffs and task text move as files.** A pasted diff parks itself permanently in the most expensive context, and a reviewer without one rebuilds it by hand — the single biggest reviewer cost. Two new scripts, `task-brief` and `review-package`, write the task text and the review diff to files for the subagent to read.
152
+ - **Every dispatch states its model.** Left to choose, controllers stopped naming a model at all — and an unnamed model quietly inherits the session's most expensive one, so one run put all 26 of its reviewers on the top tier. The templates now require a model, with guidance that reaches for cheaper tiers when the work allows.
153
+ - **The controller can't tell a reviewer what to ignore.** Real runs caught controllers coaching reviewers to skip a finding or call it "Minor at most," and the flaw shipped. Suppressing findings and pre-rating severity are now banned outright, and a defect the plan itself mandates gets reported for you to decide on rather than waved through.
154
+ - **Reviewers are read-only and skeptical of rationales.** Review no longer touches the working tree or branch — a reviewer running `git checkout` had been orphaning later commits — and an implementer's "I left this unabstracted on purpose" no longer talks a reviewer out of a real finding.
155
+ - **Stronger evidence and reporting.** Reviewers back each answer with a file and line, the implementer's report moves to a file and carries red/green evidence when TDD applies, and a progress ledger lets a controller that loses its context resume instead of redoing finished work. (#994)
156
+
157
+ ### Writing Plans
158
+
159
+ Plans now carry the structure the controller and reviewers used to re-derive on every dispatch.
160
+
161
+ - **A Global Constraints block** lists the rules that bind every task — version floors, dependency limits, naming and copy, exact values — copied in verbatim, so they actually reach the implementers and reviewers downstream.
162
+ - **A per-task Interfaces block** names exactly what each task consumes and produces, so an implementer who sees only its own task still knows its neighbors' contracts.
163
+ - **Right-sizing guidance** keeps a task at the size that earns its own test cycle and a reviewer's pass, folding setup, config, and docs into the task that needs them. In testing, a plan written this way needed one round of fixes where the control needed two to four — and the control shipped a real bug.
164
+
165
+ ### Brainstorming Visual Companion
166
+
167
+ The visual companion is a small web server the agent opens alongside the conversation. It had no authentication at all, so on a shared or remote machine anyone who could reach the port could read your brainstorm — or inject events the agent treats as your input. This release gives it a real security model and makes it survive restarts and dropped connections.
168
+
169
+ - **A per-session key now guards everything.** The agent's URL carries a one-time key, the browser tucks it into a tab-scoped cookie, and every request and WebSocket connection has to present it. This closes the door to stray local tabs and routable remote hosts alike, including the DNS-rebinding case an origin allowlist can't catch. (Closes #1014)
170
+ - **The file server stays in its sandbox.** It refuses symlinks, dotfiles, and any path that climbs out of the content directory, ignores macOS resource-fork files, and sends the usual no-store and deny-framing headers. Files that hold the session key are written owner-only.
171
+ - **The companion is offered only when it helps.** The skill raises it the first time a question would read better shown than told, as its own message, and lets a decline stand. Accepting opens your browser to the first screen. (Closes #755)
172
+ - **It survives restarts and flaky connections.** Given a project directory, the server keeps the same port and key across restarts, so an open tab simply reconnects. The page reconnects on its own, shows a live status pill, and raises a "paused" overlay while the server is down.
173
+ - **Longer idle life, safer shutdown.** The idle timeout went from 30 minutes to 4 hours, and `stop-server.sh` now confirms it owns the right process before signaling, so it never kills an unrelated `node` after a reboot. (#1703)
174
+ - **Windows launch hardening** — consolidated shell detection, and Windows now relies on the idle timeout for shutdown, since Node can't track POSIX process ownership across MSYS2.
175
+
176
+
177
+ ### Existing Harness Updates
178
+
179
+ - **Codex** now bootstraps through its own SessionStart hook rather than shared wiring, and the Codex App gained an install section and fuller tool docs (web search, `AGENTS.md`, personal skills). (#1540)
180
+ - **OpenCode** got an action-based tool mapping across its plugin, install doc, and README, plus a bootstrap-caching test.
181
+ - **Cursor**'s manifest dropped its `agents` and `commands` entries, since those directories no longer exist.
182
+
183
+ ### One Set of Skills, Every Harness
184
+
185
+ The skills used to speak Claude Code's dialect — "use the Task tool," "put it in CLAUDE.md." This release rewrites that vocabulary in terms of what you're actually doing ("dispatch a subagent," "your instructions file") and adds a per-harness reference that maps each action to the right tool, checked against each runtime. Prose that named "Claude" now says "your agent."
186
+
187
+ - **A tool reference per harness** at `skills/using-superpowers/references/`, covering Claude Code, Codex, Copilot, Gemini, Pi, and Antigravity.
188
+ - **`finishing-a-development-branch` went forge-neutral** — it no longer hardcodes `gh pr create`, so agents push with whatever forge tooling they have. (#1609)
189
+ - **One rename:** "Claude Search Optimization" is now "Skill Discovery Optimization," since the technique isn't Claude-specific.
190
+
191
+ ### Writing Skills
192
+
193
+ Two additions for skill authors.
194
+
195
+ - **Match the Form to the Failure** — a short table for picking the right kind of guidance. A flat "don't do X" works for discipline slips but backfires when the problem is the *shape* of an output, where a worked example does better. The table, and a tighter scope on the existing rationalization section, steer authors to the form that actually helps.
196
+ - **Micro-Test Wording** — a cheap way to check a phrasing before committing to it: sample it a handful of times against a no-guidance control and read every result by hand, treating run-to-run variance as a warning sign.
197
+
198
+ ### Testing
199
+
200
+ Skill-behavior testing moved out of `tests/` into a new `evals/` submodule built on "drill," which runs real Claude Code, Codex, and Gemini sessions and judges them with an LLM. Several in-tree bash suites retired once a stricter drill scenario covered them; the few with no equivalent stayed. From here on, `tests/` holds plugin-code tests and `evals/` holds skill-behavior tests, and `docs/testing.md` explains the split. New backends reach Antigravity, Pi, and more models, and new shell-lint and pre-commit checks guard the harness. (#1541)
201
+
202
+ ### Bug Fixes
203
+
204
+ - **systematic-debugging no longer forces every session into extended thinking.** One bullet held the exact keyword Claude Code scans for, quietly tripping the switch on every session that loaded the skill. A hyphen breaks the keyword; the text still reads. (#1283, by @Nick Galatis)
205
+ - **The Windows SessionStart hook stopped printing a write error every session** — each `printf` now routes through `cat` to absorb the broken pipe, and the output is otherwise unchanged. (#1612, reported by @silvertakana)
206
+ - **Windows foreground mode** tracks the right process and clears its owner PID on MSYS2. (by @nestorluiscamachopaz)
207
+ - **The `using-superpowers` bootstrap** no longer lists "debugging" as a skill that doesn't exist. (reported by @mhat)
208
+ - **The TDD skill** links the testing anti-patterns reference. (#1532, #1529; link fix #1474 by @Stable Genius)
209
+ - **`using-git-worktrees`** fixes its step numbering and drops stale Cursor references. (#1522, and by @fuleinist)
210
+ - **The Codex review skill** swaps a private in-joke for plain guidance. (#1531)
211
+
212
+ ### Documentation & Contributor Guidelines
213
+
214
+ - **A guide to porting Superpowers to a new harness** (`docs/porting-to-a-new-harness.md`) lays out the three pieces every integration needs and the one rule that makes or breaks it: load the bootstrap at session start.
215
+ - **Every PR and issue now discloses how it was made** — model, harness, version, and installed plugins, or a note that it was written by hand. We weigh a contribution differently depending on what produced it. PRs also target `dev`, not `main`. The PR template, all three issue templates, and a new platform-support template carry this.
216
+
217
+ ### Contributors
218
+
219
+ Thanks to @mattvanhorn, @nawfal, @Nick Galatis, @silvertakana, @nestorluiscamachopaz, @qer, @mhat, @Stable Genius, @fuleinist, @dev_Hakaze, @robotsnh, Rahul, and @arittr.
220
+
221
+ ## v5.1.0 (2026-04-30)
222
+
223
+ ### Removals
224
+
225
+ - **Legacy slash commands removed** — `/brainstorm`, `/execute-plan`, and `/write-plan` are gone. They were deprecated stubs that did nothing but tell the user to invoke the corresponding skill. Invoke `superpowers:brainstorming`, `superpowers:executing-plans`, and `superpowers:writing-plans` directly instead. (#1188)
226
+ - **`superpowers:code-reviewer` named agent removed** — the agent was the plugin's only named agent and was used by exactly two skills, while every other reviewer/implementer subagent in the repo dispatches `general-purpose` with a prompt template alongside its skill. The agent's persona and checklist have been merged into `skills/requesting-code-review/code-reviewer.md` as a self-contained Task-dispatch template. Anyone dispatching `Task (superpowers:code-reviewer)` should switch to `Task (general-purpose)` with the prompt template instead. (PR #1299)
227
+ - **Integration sections removed from skills** — these were a legacy of the time before agents had native skills systems and didn't help with steering.
228
+
229
+ ### Worktree Skills Rewrite
230
+
231
+ `using-git-worktrees` and `finishing-a-development-branch` now detect when the agent is already running inside an isolated worktree and prefer the harness's native worktree controls before falling back to `git worktree`. Behavior was TDD-validated and cross-platform-checked across five harnesses. (PRI-974, PR #1121)
232
+
233
+ - **Environment detection** — both skills check `GIT_DIR != GIT_COMMON` before doing anything; if already in a linked worktree, creation is skipped entirely. A submodule guard prevents false detection.
234
+ - **Consent before creating worktrees** — `using-git-worktrees` no longer creates worktrees implicitly; the skill asks the user first. Fixes #991 (subagent-driven-development was auto-creating worktrees without consent).
235
+ - **Native tool preference (Step 1a)** — when the harness exposes its own worktree tool (e.g. Codex), the skill defers to it. The user's stated preference is respected when expressed.
236
+ - **Provenance-based cleanup** — `finishing-a-development-branch` only cleans up worktrees inside `.worktrees/` (created by superpowers); anything outside is left alone. Fixes #940 (Option 2 was incorrectly cleaning up worktrees), #999 (merge-then-remove ordering), and #238 (`cd` to repo root before `git worktree remove`).
237
+ - **Detached HEAD handling** — the finishing menu collapses to two options when there is no branch to merge from.
238
+ - **Hardcoded `/Users/jesse` paths** in skill examples replaced with generic placeholders. (#858, PR #1122)
239
+
240
+ ### Contributor Guidelines for AI Agents
241
+
242
+ Two new sections at the top of `CLAUDE.md` (symlinked to `AGENTS.md`) speak directly to AI agents. An audit of the last 100 closed PRs against this repo showed a 94% rejection rate driven by AI-generated slop: agents that didn't read the PR template, opened duplicates, fabricated problem descriptions, or pushed fork- or domain-specific changes upstream.
243
+
244
+ - **Pre-submission checklist** — read the PR template, search for existing PRs, verify a real problem exists, confirm the change belongs in core, and show the human partner the complete diff before submitting.
245
+ - **What we will not accept** — third-party dependencies, "compliance" rewrites of skill content, project-specific configuration, bulk PRs, speculative fixes, domain-specific skills, fork-specific changes, fabricated content, and bundled unrelated changes.
246
+ - **New harness PRs require a session transcript** — most past new-harness integrations copied skill files or wrapped with `npx skills` instead of loading the `using-superpowers` bootstrap at session start. The acceptance test ("Let's make a react todo list" must auto-trigger `brainstorming` in a clean session) and a complete transcript are now required.
247
+
248
+ ### Codex Plugin Mirror Tooling
249
+
250
+ New `sync-to-codex-plugin` script mirrors superpowers into the OpenAI Codex plugin marketplace as `prime-radiant-inc/openai-codex-plugins`. Path/user-agnostic so any team member can run it. (PR #1165)
251
+
252
+ - Clones the fork fresh into a temp directory per run, regenerates overlays inline, and opens a PR; auto-detects upstream from the script's own location and preflights `rsync`/`git`/`gh auth`/`python3`.
253
+ - `--bootstrap` flag for first-time setup; `EXCLUDES` patterns anchored to source root; `assets/` excluded.
254
+ - Mirrors `CODE_OF_CONDUCT.md`; drops the `agents/openai.yaml` overlay.
255
+ - Seeds `interface.defaultPrompt` in the mirrored `plugin.json`. (PR #1180 by @arittr)
256
+ - Codex plugin files are committed to the source repo so the sync script uses canonical versions; Codex marketplace metadata is preserved.
257
+
258
+ ### OpenCode
259
+
260
+ - **Bootstrap content cached at module level** — `getBootstrapContent()` was calling `fs.existsSync` + `fs.readFileSync` + frontmatter regex on every agent step (the `experimental.chat.messages.transform` hook fires on every step in OpenCode's agent loop). Now read once, cached for the session lifetime, with a null sentinel for the missing-file case. 15 regression tests cover cache behavior, fs call counts, the injection guard, the missing-file sentinel, and cache reset. (Fixes #1202)
261
+ - **Integration tests modernized**.
262
+ - **Install caveats clarified** in the README.
263
+
264
+ ### Code Review Consolidation
265
+
266
+ `requesting-code-review` is now self-contained: the persona, checklist, and dispatch template live in `skills/requesting-code-review/code-reviewer.md` and the skill dispatches `Task (general-purpose)` directly. (PR #1299)
267
+
268
+ - **Single source of truth** — the persona/checklist that previously lived in both `agents/code-reviewer.md` and the skill's placeholder template (and drifted independently) is now one file.
269
+ - **`subagent-driven-development` follows suit** — its `code-quality-reviewer-prompt.md` now dispatches `Task (general-purpose)` instead of the named agent.
270
+ - **Behavioral test added** — `tests/claude-code/test-requesting-code-review.sh` plants real bugs (SQL injection, plaintext password handling, credential logging) into a tiny project and asserts the dispatched reviewer flags every planted issue at Critical/Important severity and refuses to approve the diff.
271
+
272
+ > Note: `tests/claude-code/test-requesting-code-review.sh` and `tests/claude-code/test-document-review-system.sh` (mentioned later in this document) were lifted into drill scenarios on 2026-05-06 and removed from `tests/`. See `evals/scenarios/code-review-catches-planted-bugs.yaml` and `evals/scenarios/spec-reviewer-catches-planted-flaws.yaml`. The references above and below are preserved as dated artifacts of the work this section describes.
273
+ - **Codex and Copilot workaround docs trimmed** — the "Named agent dispatch" sections in `references/codex-tools.md` and `references/copilot-tools.md` documented how to flatten a named agent into a generic dispatch. With no named agents shipping, the workaround is unnecessary; both sections were dropped.
274
+
275
+ ### Subagent-Driven Development
276
+
277
+ - **No more pause every 3 tasks** — the "review after each batch (3 tasks)" cadence in `requesting-code-review` (originally for `executing-plans`) was leaking into `subagent-driven-development`. Replaced with "each task or at natural checkpoints" plus an explicit continuous-execution directive.
278
+ - **SDD integration test now runs its assertions** — three independent bugs caused the test to silently bail before printing any verification results: an unresolved `..` segment in the working-dir path, a `set -euo pipefail` interaction with `find | sort | head -1` (SIGPIPE on the producer killed the script), and a missing `--plugin-dir` on the `claude -p` invocation that caused the test to load the installed plugin instead of the working tree. All three fixed; six verification tests now actually run against a real end-to-end SDD run.
279
+
280
+ ### Cursor
281
+
282
+ - **Windows SessionStart hook** routed through `run-hook.cmd` instead of invoking the extensionless `session-start` script directly. Fixes Windows opening the file in an editor instead of running it. Also removed an accidental UTF-8 BOM from `hooks-cursor.json`.
283
+
284
+ ### Gemini CLI
285
+
286
+ - **Subagent dispatch mapping** — Gemini's `Task` dispatch now maps to `@agent-name` / `@generalist`, with parallel subagent dispatch documented for independent tasks.
287
+
288
+ ### Skills
289
+
290
+ - **Terminology cleanups** across skill content.
291
+
292
+ ### Documentation & Install
293
+
294
+ - **Factory Droid installation instructions** added to README.
295
+ - **Quickstart install links** in README. (PR #1293 by @arittr)
296
+ - **Codex plugin install guidance** updated. (PR #1288 by @arittr)
297
+ - **Codex `wait` mapping corrected** to `wait_agent` in the tools reference.
298
+ - **Install order reorganized**; Codex install instructions cleaned up.
299
+ - **Removed vestigial `CHANGELOG.md`** in favor of `RELEASE-NOTES.md` as the single source. (PR #1163 by @shaanmajid)
300
+ - **Discord invite link** fixed; release announcements link and a detailed Discord description added to the Community section.
301
+
302
+ ### Community
303
+
304
+ - @shaanmajid — vestigial `CHANGELOG.md` removal (PR #1163)
305
+ - @arittr — README quickstart install links (#1293), Codex plugin install guidance (#1288), `sync-to-codex-plugin` `interface.defaultPrompt` seed (#1180)
306
+
307
+ ## v5.0.7 (2026-03-31)
308
+
309
+ ### GitHub Copilot CLI Support
310
+
311
+ - **SessionStart context injection** — Copilot CLI v1.0.11 added support for `additionalContext` in sessionStart hook output. The session-start hook now detects the `COPILOT_CLI` environment variable and emits the SDK-standard `{ "additionalContext": "..." }` format, giving Copilot CLI users the full superpowers bootstrap at session start. (Original fix by @culinablaz in PR #910)
312
+ - **Tool mapping** — added `references/copilot-tools.md` with the full Claude Code to Copilot CLI tool equivalence table
313
+ - **Skill and README updates** — added Copilot CLI to the `using-superpowers` skill's platform instructions and README installation section
314
+
315
+ ### OpenCode Fixes
316
+
317
+ - **Skills path consistency** — the bootstrap text no longer advertises a misleading `configDir/skills/superpowers/` path that didn't match the runtime path. The agent should use the native `skill` tool, not navigate to files by path. Tests now use consistent paths derived from a single source of truth. (#847, #916)
318
+ - **Bootstrap as user message** — moved bootstrap injection from `experimental.chat.system.transform` to `experimental.chat.messages.transform`, prepending to the first user message instead of adding a system message. Avoids token bloat from system messages repeated every turn (#750) and fixes compatibility with Qwen and other models that break on multiple system messages (#894).
319
+
320
+ ## v5.0.6 (2026-03-24)
321
+
322
+ ### Inline Self-Review Replaces Subagent Review Loops
323
+
324
+ The subagent review loop (dispatching a fresh agent to review plans/specs) doubled execution time (~25 min overhead) without measurably improving plan quality. Regression testing across 5 versions with 5 trials each showed identical quality scores regardless of whether the review loop ran.
325
+
326
+ - **brainstorming** — replaced Spec Review Loop (subagent dispatch + 3-iteration cap) with inline Spec Self-Review checklist: placeholder scan, internal consistency, scope check, ambiguity check
327
+ - **writing-plans** — replaced Plan Review Loop (subagent dispatch + 3-iteration cap) with inline Self-Review checklist: spec coverage, placeholder scan, type consistency
328
+ - **writing-plans** — added explicit "No Placeholders" section defining plan failures (TBD, vague descriptions, undefined references, "similar to Task N")
329
+ - Self-review catches 3-5 real bugs per run in ~30s instead of ~25 min, with comparable defect rates to the subagent approach
330
+
331
+ ### Brainstorm Server
332
+
333
+ - **Session directory restructured** — the brainstorm server session directory now contains two peer subdirectories: `content/` (HTML files served to the browser) and `state/` (events, server-info, pid, log). Previously, server state and user interaction data were stored alongside served content, making them accessible over HTTP. The `screen_dir` and `state_dir` paths are both included in the server-started JSON. (Reported by 吉田仁)
334
+
335
+ ### Bug Fixes
336
+
337
+ - **Owner-PID lifecycle fixes** — the brainstorm server's owner-PID monitoring had two bugs causing false shutdowns within 60 seconds: (1) EPERM from cross-user PIDs (Tailscale SSH, etc.) was treated as "process dead", and (2) on WSL the grandparent PID resolves to a short-lived subprocess that exits before the first lifecycle check. Fixed by treating EPERM as "alive" and validating the owner PID at startup — if it's already dead, monitoring is disabled and the server relies on the 30-minute idle timeout. This also removes the Windows/MSYS2-specific carve-out from `start-server.sh` since the server now handles it generically. (#879)
338
+ - **writing-skills** — corrected false claim that SKILL.md frontmatter supports "only two fields"; now says "two required fields" and links to the agentskills.io specification for all supported fields (PR #882 by @arittr)
339
+
340
+ ### Codex App Compatibility
341
+
342
+ - **codex-tools** — added named agent dispatch mapping documenting how to translate Claude Code's named agent types to Codex's `spawn_agent` with worker roles (PR #647 by @arittr)
343
+ - **codex-tools** — added environment detection and Codex App finishing sections for worktree-aware skills (by @arittr)
344
+ - **Design spec** — added Codex App compatibility design spec (PRI-823) covering read-only environment detection, worktree-safe skill behavior, and sandbox fallback patterns (by @arittr)
345
+
346
+ ## v5.0.5 (2026-03-17)
347
+
348
+ ### Bug Fixes
349
+
350
+ - **Brainstorm server ESM fix** — renamed `server.js` → `server.cjs` so the brainstorming server starts correctly on Node.js 22+ where the root `package.json` `"type": "module"` caused `require()` to fail. (PR #784 by @sarbojitrana, fixes #774, #780, #783)
351
+ - **Brainstorm owner-PID on Windows** — skip PID lifecycle monitoring on Windows/MSYS2 where the PID namespace is invisible to Node.js, preventing the server from self-terminating after 60 seconds. (#770, docs from PR #768 by @lucasyhzlu-debug)
352
+ - **stop-server.sh reliability** — verify the server process actually died before reporting success. SIGTERM + 2s wait + SIGKILL fallback. (#723)
353
+
354
+ ### Changed
355
+
356
+ - **Execution handoff** — restore user choice between subagent-driven and inline execution after plan writing. Subagent-driven is recommended but no longer mandatory.
357
+
358
+ ## v5.0.4 (2026-03-16)
359
+
360
+ ### Review Loop Refinements
361
+
362
+ Dramatically reduces token usage and speeds up spec and plan reviews by eliminating unnecessary review passes and tightening reviewer focus.
363
+
364
+ - **Single whole-plan review** — plan reviewer now reviews the complete plan in one pass instead of chunk-by-chunk. Removed all chunk-related concepts (`## Chunk N:` headings, 1000-line chunk limits, per-chunk dispatch).
365
+ - **Raised the bar for blocking issues** — both spec and plan reviewer prompts now include a "Calibration" section: only flag issues that would cause real problems during implementation. Minor wording, stylistic preferences, and formatting quibbles should not block approval.
366
+ - **Reduced max review iterations** — from 5 to 3 for both spec and plan review loops. If the reviewer is calibrated correctly, 3 rounds is plenty.
367
+ - **Streamlined reviewer checklists** — spec reviewer trimmed from 7 categories to 5; plan reviewer from 7 to 4. Removed formatting-focused checks (task syntax, chunk size) in favor of substance (buildability, spec alignment).
368
+
369
+ ### OpenCode
370
+
371
+ - **One-line plugin install** — OpenCode plugin now auto-registers the skills directory via a `config` hook. No symlinks or `skills.paths` config needed. Install is just adding one line to `opencode.json`. (PR #753)
372
+ - **Added `package.json`** so OpenCode can install superpowers as an npm package from git.
373
+
374
+ ### Bug Fixes
375
+
376
+ - **Verify server actually stopped** — `stop-server.sh` now confirms the process is dead before reporting success. SIGTERM + 2s wait + SIGKILL fallback. Reports failure if the process survives. (PR #751)
377
+ - **Generic agent language** — brainstorm companion waiting page now says "the agent" instead of "Claude".
378
+
379
+ ## v5.0.3 (2026-03-15)
380
+
381
+ ### Cursor Support
382
+
383
+ - **Cursor hooks** — added `hooks/hooks-cursor.json` with Cursor's camelCase format (`sessionStart`, `version: 1`) and updated `.cursor-plugin/plugin.json` to reference it. Fixed platform detection in `session-start` to check `CURSOR_PLUGIN_ROOT` first (Cursor may also set `CLAUDE_PLUGIN_ROOT`). (Based on PR #709)
384
+
385
+ ### Bug Fixes
386
+
387
+ - **Stop firing SessionStart hook on `--resume`** — the startup hook was re-injecting context on resumed sessions, which already have the context in their conversation history. The hook now fires only on `startup`, `clear`, and `compact`.
388
+ - **Bash 5.3+ hook hang** — replaced heredoc (`cat <<EOF`) with `printf` in `hooks/session-start`. Fixes indefinite hang on macOS with Homebrew bash 5.3+ caused by a bash regression with large variable expansion in heredocs. (#572, #571)
389
+ - **POSIX-safe hook script** — replaced `${BASH_SOURCE[0]:-$0}` with `$0` in `hooks/session-start`. Fixes "Bad substitution" error on Ubuntu/Debian where `/bin/sh` is dash. (#553)
390
+ - **Portable shebangs** — replaced `#!/bin/bash` with `#!/usr/bin/env bash` in all shell scripts. Fixes execution on NixOS, FreeBSD, and macOS with Homebrew bash where `/bin/bash` is outdated or missing. (#700)
391
+ - **Brainstorm server on Windows** — auto-detect Windows/Git Bash (`OSTYPE=msys*`, `MSYSTEM`) and switch to foreground mode, fixing silent server failure caused by `nohup`/`disown` process reaping. (#737)
392
+ - **Codex docs fix** — replaced deprecated `collab` flag with `multi_agent` in Codex documentation. (PR #749)
393
+
394
+ ## v5.0.2 (2026-03-11)
395
+
396
+ ### Zero-Dependency Brainstorm Server
397
+
398
+ **Removed all vendored node_modules — server.js is now fully self-contained**
399
+
400
+ - Replaced Express/Chokidar/WebSocket dependencies with zero-dependency Node.js server using built-in `http`, `fs`, and `crypto` modules
401
+ - Removed ~1,200 lines of vendored `node_modules/`, `package.json`, and `package-lock.json`
402
+ - Custom WebSocket protocol implementation (RFC 6455 framing, ping/pong, proper close handshake)
403
+ - Native `fs.watch()` file watching replaces Chokidar
404
+ - Full test suite: HTTP serving, WebSocket protocol, file watching, and integration tests
405
+
406
+ ### Brainstorm Server Reliability
407
+
408
+ - **Auto-exit after 30 minutes idle** — server shuts down when no clients are connected, preventing orphaned processes
409
+ - **Owner process tracking** — server monitors the parent harness PID and exits when the owning session dies
410
+ - **Liveness check** — skill verifies server is responsive before reusing an existing instance
411
+ - **Encoding fix** — proper `<meta charset="utf-8">` on served HTML pages
412
+
413
+ ### Subagent Context Isolation
414
+
415
+ - All delegation skills (brainstorming, dispatching-parallel-agents, requesting-code-review, subagent-driven-development, writing-plans) now include context isolation principle
416
+ - Subagents receive only the context they need, preventing context window pollution
417
+
418
+ ## v5.0.1 (2026-03-10)
419
+
420
+ ### Agentskills Compliance
421
+
422
+ **Brainstorm-server moved into skill directory**
423
+
424
+ - Moved `lib/brainstorm-server/` → `skills/brainstorming/scripts/` per the [agentskills.io](https://agentskills.io) specification
425
+ - All `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/` references replaced with relative `scripts/` paths
426
+ - Skills are now fully portable across platforms — no platform-specific env vars needed to locate scripts
427
+ - `lib/` directory removed (was the last remaining content)
428
+
429
+ ### New Features
430
+
431
+ **Gemini CLI extension**
432
+
433
+ - Native Gemini CLI extension support via `gemini-extension.json` and `GEMINI.md` at repo root
434
+ - `GEMINI.md` @imports `using-superpowers` skill and tool mapping table at session start
435
+ - Gemini CLI tool mapping reference (`skills/using-superpowers/references/gemini-tools.md`) — translates Claude Code tool names (Read, Write, Edit, Bash, etc.) to Gemini CLI equivalents (read_file, write_file, replace, etc.)
436
+ - Documents Gemini CLI limitations: no subagent support, skills fall back to `executing-plans`
437
+ - Extension root at repo root for cross-platform compatibility (avoids Windows symlink issues)
438
+ - Install instructions added to README
439
+
440
+ ### Improvements
441
+
442
+ **Multi-platform brainstorm server launch**
443
+
444
+ - Per-platform launch instructions in visual-companion.md: Claude Code (default mode), Codex (auto-foreground via `CODEX_CI`), Gemini CLI (`--foreground` with `is_background`), and fallback for other environments
445
+ - Server now writes startup JSON to `$SCREEN_DIR/.server-info` so agents can find the URL and port even when stdout is hidden by background execution
446
+
447
+ **Brainstorm server dependencies bundled**
448
+
449
+ - `node_modules` vendored into the repo so the brainstorm server works immediately on fresh plugin installs without requiring `npm` at runtime
450
+ - Removed `fsevents` from bundled deps (macOS-only native binary; chokidar falls back gracefully without it)
451
+ - Fallback auto-install via `npm install` if `node_modules` is missing
452
+
453
+ **OpenCode tool mapping fix**
454
+
455
+ - `TodoWrite` → `todowrite` (was incorrectly mapped to `update_plan`); verified against OpenCode source
456
+
457
+ ### Bug Fixes
458
+
459
+ **Windows/Linux: single quotes break SessionStart hook** (#577, #529, #644, PR #585)
460
+
461
+ - Single quotes around `${CLAUDE_PLUGIN_ROOT}` in hooks.json fail on Windows (cmd.exe doesn't recognize single quotes as path delimiters) and on Linux (single quotes prevent variable expansion)
462
+ - Fix: replaced single quotes with escaped double quotes — works across macOS bash, Windows cmd.exe, Windows Git Bash, and Linux, with and without spaces in paths
463
+ - Verified on Windows 11 (NT 10.0.26200.0) with Claude Code 2.1.72 and Git for Windows
464
+
465
+ **Brainstorming spec review loop skipped** (#677)
466
+
467
+ - The spec review loop (dispatch spec-document-reviewer subagent, iterate until approved) existed in the prose "After the Design" section but was missing from the checklist and process flow diagram
468
+ - Since agents follow the diagram and checklist more reliably than prose, the spec review step was being skipped entirely
469
+ - Added step 7 (spec review loop) to the checklist and corresponding nodes to the dot graph
470
+ - Tested with `claude --plugin-dir` and `claude-session-driver`: worker now correctly dispatches the reviewer
471
+
472
+ **Cursor install command** (PR #676)
473
+
474
+ - Fixed Cursor install command in README: `/plugin-add` → `/add-plugin` (confirmed via Cursor 2.5 release announcement)
475
+
476
+ **User review gate in brainstorming** (#565)
477
+
478
+ - Added explicit user review step between spec completion and writing-plans handoff
479
+ - User must approve the spec before implementation planning begins
480
+ - Checklist, process flow, and prose updated with the new gate
481
+
482
+ **Session-start hook emits context only once per platform**
483
+
484
+ - Hook now detects whether it's running in Claude Code or another platform
485
+ - Emits `hookSpecificOutput` for Claude Code, `additional_context` for others — prevents double context injection
486
+
487
+ **Linting fix in token analysis script**
488
+
489
+ - `except:` → `except Exception:` in `tests/claude-code/analyze-token-usage.py`
490
+
491
+ ### Maintenance
492
+
493
+ **Removed dead code**
494
+
495
+ - Deleted `lib/skills-core.js` and its test (`tests/opencode/test-skills-core.js`) — unused since February 2026
496
+ - Removed skills-core existence check from `tests/opencode/test-plugin-loading.sh`
497
+
498
+ ### Community
499
+
500
+ - @karuturi — Claude Code official marketplace install instructions (PR #610)
501
+ - @mvanhorn — session-start hook dual-emit fix, OpenCode tool mapping fix
502
+ - @daniel-graham — linting fix for bare except
503
+ - PR #585 author — Windows/Linux hooks quoting fix
504
+
505
+ ---
506
+
507
+ ## v5.0.0 (2026-03-09)
508
+
509
+ ### Breaking Changes
510
+
511
+ **Specs and plans directory restructured**
512
+
513
+ - Specs (brainstorming output) now save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`
514
+ - Plans (writing-plans output) now save to `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
515
+ - User preferences for spec/plan locations override these defaults
516
+ - All internal skill references, test files, and example paths updated to match
517
+ - Migration: move existing files from `docs/plans/` to new locations if desired
518
+
519
+ **Subagent-driven development mandatory on capable harnesses**
520
+
521
+ Writing-plans no longer offers a choice between subagent-driven and executing-plans. On harnesses with subagent support (Claude Code, Codex), subagent-driven-development is required. Executing-plans is reserved for harnesses without subagent capability, and now tells the user that Superpowers works better on a subagent-capable platform.
522
+
523
+ **Executing-plans no longer batches**
524
+
525
+ Removed the "execute 3 tasks then stop for review" pattern. Plans now execute continuously, stopping only for blockers.
526
+
527
+ **Slash commands deprecated**
528
+
529
+ `/brainstorm`, `/write-plan`, and `/execute-plan` now show deprecation notices pointing users to the corresponding skills. Commands will be removed in the next major release.
530
+
531
+ ### New Features
532
+
533
+ **Visual brainstorming companion**
534
+
535
+ Optional browser-based companion for brainstorming sessions. When a topic would benefit from visuals, the brainstorming skill offers to show mockups, diagrams, comparisons, and other content in a browser window alongside terminal conversation.
536
+
537
+ - `lib/brainstorm-server/` — WebSocket server with browser helper library, session management scripts, and dark/light themed frame template ("Superpowers Brainstorming" with GitHub link)
538
+ - `skills/brainstorming/visual-companion.md` — Progressive disclosure guide for server workflow, screen authoring, and feedback collection
539
+ - Brainstorming skill adds a visual companion decision point to its process flow: after exploring project context, the skill evaluates whether upcoming questions involve visual content and offers the companion in its own message
540
+ - Per-question decision: even after accepting, each question is evaluated for whether browser or terminal is more appropriate
541
+ - Integration tests in `tests/brainstorm-server/`
542
+
543
+ **Document review system**
544
+
545
+ Automated review loops for spec and plan documents using subagent dispatch:
546
+
547
+ - `skills/brainstorming/spec-document-reviewer-prompt.md` — Reviewer checks completeness, consistency, architecture, and YAGNI
548
+ - `skills/writing-plans/plan-document-reviewer-prompt.md` — Reviewer checks spec alignment, task decomposition, file structure, and file size
549
+ - Brainstorming dispatches spec reviewer after writing the design doc
550
+ - Writing-plans includes chunk-based plan review loop after each section
551
+ - Review loops repeat until approved or escalate after 5 iterations
552
+ - End-to-end tests in `tests/claude-code/test-document-review-system.sh`
553
+ - Design spec and implementation plan in `docs/superpowers/`
554
+
555
+ **Architecture guidance across the skill pipeline**
556
+
557
+ Design-for-isolation and file-size-awareness guidance added to brainstorming, writing-plans, and subagent-driven-development:
558
+
559
+ - **Brainstorming** — New sections: "Design for isolation and clarity" (clear boundaries, well-defined interfaces, independently testable units) and "Working in existing codebases" (follow existing patterns, targeted improvements only)
560
+ - **Writing-plans** — New "File Structure" section: map out files and responsibilities before defining tasks. New "Scope Check" backstop: catch multi-subsystem specs that should have been decomposed during brainstorming
561
+ - **SDD implementer** — New "Code Organization" section (follow plan's file structure, report concerns about growing files) and "When You're in Over Your Head" escalation guidance
562
+ - **SDD code quality reviewer** — Now checks architecture, unit decomposition, plan conformance, and file growth
563
+ - **Spec/plan reviewers** — Architecture and file size added to review criteria
564
+ - **Scope assessment** — Brainstorming now assesses whether a project is too large for a single spec. Multi-subsystem requests are flagged early and decomposed into sub-projects, each with its own spec → plan → implementation cycle
565
+
566
+ **Subagent-driven development improvements**
567
+
568
+ - **Model selection** — Guidance for choosing model capability by task type: cheap models for mechanical implementation, standard for integration, capable for architecture and review
569
+ - **Implementer status protocol** — Subagents now report DONE, DONE_WITH_CONCERNS, BLOCKED, or NEEDS_CONTEXT. Controller handles each status appropriately: re-dispatching with more context, upgrading model capability, breaking tasks apart, or escalating to human
570
+
571
+ ### Improvements
572
+
573
+ **Instruction priority hierarchy**
574
+
575
+ Added explicit priority ordering to using-superpowers:
576
+
577
+ 1. User's explicit instructions (CLAUDE.md, AGENTS.md, direct requests) — highest priority
578
+ 2. Superpowers skills — override default system behavior
579
+ 3. Default system prompt — lowest priority
580
+
581
+ If CLAUDE.md or AGENTS.md says "don't use TDD" and a skill says "always use TDD," the user's instructions win.
582
+
583
+ **SUBAGENT-STOP gate**
584
+
585
+ Added `<SUBAGENT-STOP>` block to using-superpowers. Subagents dispatched for specific tasks now skip the skill instead of activating the 1% rule and invoking full skill workflows.
586
+
587
+ **Multi-platform improvements**
588
+
589
+ - Codex tool mapping moved to progressive disclosure reference file (`references/codex-tools.md`)
590
+ - Platform Adaptation pointer added so non-Claude-Code platforms can find tool equivalents
591
+ - Plan headers now address "agentic workers" instead of "Claude" specifically
592
+ - Collab feature requirement documented in `docs/README.codex.md`
593
+
594
+ **Writing-plans template updates**
595
+
596
+ - Plan steps now use checkbox syntax (`- [ ] **Step N:**`) for progress tracking
597
+ - Plan header references both subagent-driven-development and executing-plans with platform-aware routing
598
+
599
+ ---
600
+
601
+ ## v4.3.1 (2026-02-21)
602
+
603
+ ### Added
604
+
605
+ **Cursor support**
606
+
607
+ Superpowers now works with Cursor's plugin system. Includes a `.cursor-plugin/plugin.json` manifest and Cursor-specific installation instructions in the README. The SessionStart hook output now includes an `additional_context` field alongside the existing `hookSpecificOutput.additionalContext` for Cursor hook compatibility.
608
+
609
+ ### Fixed
610
+
611
+ **Windows: Restored polyglot wrapper for reliable hook execution (#518, #504, #491, #487, #466, #440)**
612
+
613
+ Claude Code's `.sh` auto-detection on Windows was prepending `bash` to the hook command, breaking execution. The fix:
614
+
615
+ - Renamed `session-start.sh` to `session-start` (extensionless) so auto-detection doesn't interfere
616
+ - Restored `run-hook.cmd` polyglot wrapper with multi-location bash discovery (standard Git for Windows paths, then PATH fallback)
617
+ - Exits silently if no bash is found rather than erroring
618
+ - On Unix, the wrapper runs the script directly via `exec bash`
619
+ - Uses POSIX-safe `dirname "$0"` path resolution (works on dash/sh, not just bash)
620
+
621
+ This fixes SessionStart failures on Windows with spaces in paths, missing WSL, `set -euo pipefail` fragility on MSYS, and backslash mangling.
622
+
623
+ ## v4.3.0 (2026-02-12)
624
+
625
+ This fix should dramatically improve superpowers skills compliance and should reduce the chances of Claude entering its native plan mode unintentionally.
626
+
627
+ ### Changed
628
+
629
+ **Brainstorming skill now enforces its workflow instead of describing it**
630
+
631
+ Models were skipping the design phase and jumping straight to implementation skills like frontend-design, or collapsing the entire brainstorming process into a single text block. The skill now uses hard gates, a mandatory checklist, and a graphviz process flow to enforce compliance:
632
+
633
+ - `<HARD-GATE>`: no implementation skills, code, or scaffolding until design is presented and user approves
634
+ - Explicit checklist (6 items) that must be created as tasks and completed in order
635
+ - Graphviz process flow with `writing-plans` as the only valid terminal state
636
+ - Anti-pattern callout for "this is too simple to need a design" — the exact rationalization models use to skip the process
637
+ - Design section sizing based on section complexity, not project complexity
638
+
639
+ **Using-superpowers workflow graph intercepts EnterPlanMode**
640
+
641
+ Added an `EnterPlanMode` intercept to the skill flow graph. When the model is about to enter Claude's native plan mode, it checks whether brainstorming has happened and routes through the brainstorming skill instead. Plan mode is never entered.
642
+
643
+ ### Fixed
644
+
645
+ **SessionStart hook now runs synchronously**
646
+
647
+ Changed `async: true` to `async: false` in hooks.json. When async, the hook could fail to complete before the model's first turn, meaning using-superpowers instructions weren't in context for the first message.
648
+
649
+ ## v4.2.0 (2026-02-05)
650
+
651
+ ### Breaking Changes
652
+
653
+ **Codex: Replaced bootstrap CLI with native skill discovery**
654
+
655
+ 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.
656
+
657
+ Installation is now just clone + symlink (documented in INSTALL.md). No Node.js dependency required. The old `~/.codex/skills/` path is deprecated.
658
+
659
+ ### Fixes
660
+
661
+ **Windows: Fixed Claude Code 2.1.x hook execution (#331)**
662
+
663
+ 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.
664
+
665
+ 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).
666
+
667
+ **Windows: SessionStart hook runs async to prevent terminal freeze (#404, #413, #414, #419)**
668
+
669
+ 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.
670
+
671
+ **Windows: Fixed O(n^2) `escape_for_json` performance**
672
+
673
+ 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.
674
+
675
+ **Codex: Fixed Windows/PowerShell invocation (#285, #243)**
676
+
677
+ - Windows doesn't respect shebangs, so directly invoking the extensionless `superpowers-codex` script triggered an "Open with" dialog. All invocations now prefixed with `node`.
678
+ - 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.
679
+
680
+ **Codex: Fixed path resolution in installer**
681
+
682
+ Used `fileURLToPath()` instead of manual URL pathname parsing to correctly handle paths with spaces and special characters on all platforms.
683
+
684
+ **Codex: Fixed stale skills path in writing-skills**
685
+
686
+ Updated `~/.codex/skills/` reference (deprecated) to `~/.agents/skills/` for native discovery.
687
+
688
+ ### Improvements
689
+
690
+ **Worktree isolation now required before implementation**
691
+
692
+ 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.
693
+
694
+ **Main branch protection softened to require explicit consent**
695
+
696
+ 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.
697
+
698
+ **Simplified installation verification**
699
+
700
+ 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.
701
+
702
+ **Codex: Clarified subagent tool mapping in bootstrap**
703
+
704
+ Improved documentation of how Codex tools map to Claude Code equivalents for subagent workflows.
705
+
706
+ ### Tests
707
+
708
+ - Added worktree requirement test for subagent-driven-development
709
+ - Added main branch red flag warning test
710
+ - Fixed case sensitivity in skill recognition test assertions
711
+
712
+ ---
713
+
714
+ ## v4.1.1 (2026-01-23)
715
+
716
+ ### Fixes
717
+
718
+ **OpenCode: Standardized on `plugins/` directory per official docs (#343)**
719
+
720
+ 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.
721
+
722
+ Changes:
723
+ - Renamed `.opencode/plugin/` to `.opencode/plugins/` in repo structure
724
+ - Updated all installation docs (INSTALL.md, README.opencode.md) across all platforms
725
+ - Updated test scripts to match
726
+
727
+ **OpenCode: Fixed symlink instructions (#339, #342)**
728
+
729
+ - Added explicit `rm` before `ln -s` (fixes "file already exists" errors on reinstall)
730
+ - Added missing skills symlink step that was absent from INSTALL.md
731
+ - Updated from deprecated `use_skill`/`find_skills` to native `skill` tool references
732
+
733
+ ---
734
+
735
+ ## v4.1.0 (2026-01-23)
736
+
737
+ ### Breaking Changes
738
+
739
+ **OpenCode: Switched to native skills system**
740
+
741
+ 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.
742
+
743
+ **Migration required:** Skills must be symlinked to `~/.config/opencode/skills/superpowers/` (see updated installation docs).
744
+
745
+ ### Fixes
746
+
747
+ **OpenCode: Fixed agent reset on session start (#226)**
748
+
749
+ 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.
750
+
751
+ **OpenCode: Fixed Windows installation (#232)**
752
+
753
+ - Removed dependency on `skills-core.js` (eliminates broken relative imports when file is copied instead of symlinked)
754
+ - Added comprehensive Windows installation docs for cmd.exe, PowerShell, and Git Bash
755
+ - Documented proper symlink vs junction usage for each platform
756
+
757
+ **Claude Code: Fixed Windows hook execution for Claude Code 2.1.x**
758
+
759
+ 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.
760
+
761
+ 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).
762
+
763
+ ---
764
+
765
+ ## v4.0.3 (2025-12-26)
766
+
767
+ ### Improvements
768
+
769
+ **Strengthened using-superpowers skill for explicit skill requests**
770
+
771
+ 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.
772
+
773
+ Changes:
774
+ - Updated "The Rule" to say "Invoke relevant or requested skills" instead of "Check for skills" - emphasizing active invocation over passive checking
775
+ - Added "BEFORE any response or action" - the original wording only mentioned "response" but Claude would sometimes take action without responding first
776
+ - Added reassurance that invoking a wrong skill is okay - reduces hesitation
777
+ - Added new red flag: "I know what that means" → Knowing the concept ≠ using the skill
778
+
779
+ **Added explicit skill request tests**
780
+
781
+ 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.
782
+
783
+ ## v4.0.2 (2025-12-23)
784
+
785
+ ### Fixes
786
+
787
+ **Slash commands now user-only**
788
+
789
+ 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.
790
+
791
+ 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.
792
+
793
+ ## v4.0.1 (2025-12-23)
794
+
795
+ ### Fixes
796
+
797
+ **Clarified how to access skills in Claude Code**
798
+
799
+ 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.
800
+
801
+ - Added "How to Access Skills" section to `using-superpowers`
802
+ - Changed "read the skill" → "invoke the skill" in instructions
803
+ - Updated slash commands to use fully qualified skill names (e.g., `superpowers:brainstorming`)
804
+
805
+ **Added GitHub thread reply guidance to receiving-code-review** (h/t @ralphbean)
806
+
807
+ Added a note about replying to inline review comments in the original thread rather than as top-level PR comments.
808
+
809
+ **Added automation-over-documentation guidance to writing-skills** (h/t @EthanJStark)
810
+
811
+ Added guidance that mechanical constraints should be automated, not documented—save skills for judgment calls.
812
+
813
+ ## v4.0.0 (2025-12-17)
814
+
815
+ ### New Features
816
+
817
+ **Two-stage code review in subagent-driven-development**
818
+
819
+ Subagent workflows now use two separate review stages after each task:
820
+
821
+ 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.
822
+
823
+ 2. **Code quality review** - Only runs after spec compliance passes. Reviews for clean code, test coverage, maintainability.
824
+
825
+ 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.
826
+
827
+ Other subagent workflow improvements:
828
+ - Controller provides full task text to workers (not file references)
829
+ - Workers can ask clarifying questions before AND during work
830
+ - Self-review checklist before reporting completion
831
+ - Plan read once at start, extracted to TodoWrite
832
+
833
+ New prompt templates in `skills/subagent-driven-development/`:
834
+ - `implementer-prompt.md` - Includes self-review checklist, encourages questions
835
+ - `spec-reviewer-prompt.md` - Skeptical verification against requirements
836
+ - `code-quality-reviewer-prompt.md` - Standard code review
837
+
838
+ **Debugging techniques consolidated with tools**
839
+
840
+ `systematic-debugging` now bundles supporting techniques and tools:
841
+ - `root-cause-tracing.md` - Trace bugs backward through call stack
842
+ - `defense-in-depth.md` - Add validation at multiple layers
843
+ - `condition-based-waiting.md` - Replace arbitrary timeouts with condition polling
844
+ - `find-polluter.sh` - Bisection script to find which test creates pollution
845
+ - `condition-based-waiting-example.ts` - Complete implementation from real debugging session
846
+
847
+ **Testing anti-patterns reference**
848
+
849
+ `test-driven-development` now includes `testing-anti-patterns.md` covering:
850
+ - Testing mock behavior instead of real behavior
851
+ - Adding test-only methods to production classes
852
+ - Mocking without understanding dependencies
853
+ - Incomplete mocks that hide structural assumptions
854
+
855
+ **Skill test infrastructure**
856
+
857
+ Three new test frameworks for validating skill behavior:
858
+
859
+ `tests/skill-triggering/` - Validates skills trigger from naive prompts without explicit naming. Tests 6 skills to ensure descriptions alone are sufficient.
860
+
861
+ `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.
862
+
863
+ `tests/subagent-driven-dev/` - End-to-end workflow validation with two complete test projects:
864
+ - `go-fractals/` - CLI tool with Sierpinski/Mandelbrot (10 tasks)
865
+ - `svelte-todo/` - CRUD app with localStorage and Playwright (12 tasks)
866
+
867
+ ### Major Changes
868
+
869
+ **DOT flowcharts as executable specifications**
870
+
871
+ Rewrote key skills using DOT/GraphViz flowcharts as the authoritative process definition. Prose becomes supporting content.
872
+
873
+ **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.
874
+
875
+ **Skill priority in using-superpowers**
876
+
877
+ When multiple skills apply, process skills (brainstorming, debugging) now explicitly come before implementation skills. "Build X" triggers brainstorming first, then domain skills.
878
+
879
+ **brainstorming trigger strengthened**
880
+
881
+ Description changed to imperative: "You MUST use this before any creative work—creating features, building components, adding functionality, or modifying behavior."
882
+
883
+ ### Breaking Changes
884
+
885
+ **Skill consolidation** - Six standalone skills merged:
886
+ - `root-cause-tracing`, `defense-in-depth`, `condition-based-waiting` → bundled in `systematic-debugging/`
887
+ - `testing-skills-with-subagents` → bundled in `writing-skills/`
888
+ - `testing-anti-patterns` → bundled in `test-driven-development/`
889
+ - `sharing-skills` removed (obsolete)
890
+
891
+ ### Other Improvements
892
+
893
+ - **render-graphs.js** - Tool to extract DOT diagrams from skills and render to SVG
894
+ - **Rationalizations table** in using-superpowers - Scannable format including new entries: "I need more context first", "Let me explore first", "This feels productive"
895
+ - **docs/testing.md** - Guide to testing skills with Claude Code integration tests
896
+
897
+ ---
898
+
899
+ ## v3.6.2 (2025-12-03)
900
+
901
+ ### Fixed
902
+
903
+ - **Linux Compatibility**: Fixed polyglot hook wrapper (`run-hook.cmd`) to use POSIX-compliant syntax
904
+ - Replaced bash-specific `${BASH_SOURCE[0]:-$0}` with standard `$0` on line 16
905
+ - Resolves "Bad substitution" error on Ubuntu/Debian systems where `/bin/sh` is dash
906
+ - Fixes #141
907
+
908
+ ---
909
+
910
+ ## v3.5.1 (2025-11-24)
911
+
912
+ ### Changed
913
+
914
+ - **OpenCode Bootstrap Refactor**: Switched from `chat.message` hook to `session.created` event for bootstrap injection
915
+ - Bootstrap now injects at session creation via `session.prompt()` with `noReply: true`
916
+ - Explicitly tells the model that using-superpowers is already loaded to prevent redundant skill loading
917
+ - Consolidated bootstrap content generation into shared `getBootstrapContent()` helper
918
+ - Cleaner single-implementation approach (removed fallback pattern)
919
+
920
+ ---
921
+
922
+ ## v3.5.0 (2025-11-23)
923
+
924
+ ### Added
925
+
926
+ - **OpenCode Support**: Native JavaScript plugin for OpenCode.ai
927
+ - Custom tools: `use_skill` and `find_skills`
928
+ - Message insertion pattern for skill persistence across context compaction
929
+ - Automatic context injection via chat.message hook
930
+ - Auto re-injection on session.compacted events
931
+ - Three-tier skill priority: project > personal > superpowers
932
+ - Project-local skills support (`.opencode/skills/`)
933
+ - Shared core module (`lib/skills-core.js`) for code reuse with Codex
934
+ - Automated test suite with proper isolation (`tests/opencode/`)
935
+ - Platform-specific documentation (`docs/README.opencode.md`, `docs/README.codex.md`)
936
+
937
+ ### Changed
938
+
939
+ - **Refactored Codex Implementation**: Now uses shared `lib/skills-core.js` ES module
940
+ - Eliminates code duplication between Codex and OpenCode
941
+ - Single source of truth for skill discovery and parsing
942
+ - Codex successfully loads ES modules via Node.js interop
943
+
944
+ - **Improved Documentation**: Rewrote README to explain problem/solution clearly
945
+ - Removed duplicate sections and conflicting information
946
+ - Added complete workflow description (brainstorm → plan → execute → finish)
947
+ - Simplified platform installation instructions
948
+ - Emphasized skill-checking protocol over automatic activation claims
949
+
950
+ ---
951
+
952
+ ## v3.4.1 (2025-10-31)
953
+
954
+ ### Improvements
955
+
956
+ - 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.
957
+
958
+ ## v3.4.0 (2025-10-30)
959
+
960
+ ### Improvements
961
+
962
+ - 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.
963
+
964
+ ## v3.3.1 (2025-10-28)
965
+
966
+ ### Improvements
967
+
968
+ - Updated `brainstorming` skill to require autonomous recon before questioning, encourage recommendation-driven decisions, and prevent agents from delegating prioritization back to humans.
969
+ - 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).
970
+
971
+ ### Bug Fixes
972
+
973
+ - Clarified `writing-skills` guidance so it points to the correct agent-specific personal skill directories (`~/.claude/skills` for Claude Code, `~/.codex/skills` for Codex).
974
+
975
+ ## v3.3.0 (2025-10-28)
976
+
977
+ ### New Features
978
+
979
+ **Experimental Codex Support**
980
+ - Added unified `superpowers-codex` script with bootstrap/use-skill/find-skills commands
981
+ - Cross-platform Node.js implementation (works on Windows, macOS, Linux)
982
+ - Namespaced skills: `superpowers:skill-name` for superpowers skills, `skill-name` for personal
983
+ - Personal skills override superpowers skills when names match
984
+ - Clean skill display: shows name/description without raw frontmatter
985
+ - Helpful context: shows supporting files directory for each skill
986
+ - Tool mapping for Codex: TodoWrite→update_plan, subagents→manual fallback, etc.
987
+ - Bootstrap integration with minimal AGENTS.md for automatic startup
988
+ - Complete installation guide and bootstrap instructions specific to Codex
989
+
990
+ **Key differences from Claude Code integration:**
991
+ - Single unified script instead of separate tools
992
+ - Tool substitution system for Codex-specific equivalents
993
+ - Simplified subagent handling (manual work instead of delegation)
994
+ - Updated terminology: "Superpowers skills" instead of "Core skills"
995
+
996
+ ### Files Added
997
+ - `.codex/INSTALL.md` - Installation guide for Codex users
998
+ - `.codex/superpowers-bootstrap.md` - Bootstrap instructions with Codex adaptations
999
+ - `.codex/superpowers-codex` - Unified Node.js executable with all functionality
1000
+
1001
+ **Note:** Codex support is experimental. The integration provides core superpowers functionality but may require refinement based on user feedback.
1002
+
1003
+ ## v3.2.3 (2025-10-23)
1004
+
1005
+ ### Improvements
1006
+
1007
+ **Updated using-superpowers skill to use Skill tool instead of Read tool**
1008
+ - Changed skill invocation instructions from Read tool to Skill tool
1009
+ - Updated description: "using Read tool" → "using Skill tool"
1010
+ - Updated step 3: "Use the Read tool" → "Use the Skill tool to read and run"
1011
+ - Updated rationalization list: "Read the current version" → "Run the current version"
1012
+
1013
+ 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.
1014
+
1015
+ ### Files Changed
1016
+ - Updated: `skills/using-superpowers/SKILL.md` - Changed tool references from Read to Skill
1017
+
1018
+ ## v3.2.2 (2025-10-21)
1019
+
1020
+ ### Improvements
1021
+
1022
+ **Strengthened using-superpowers skill against agent rationalization**
1023
+ - Added EXTREMELY-IMPORTANT block with absolute language about mandatory skill checking
1024
+ - "If even 1% chance a skill applies, you MUST read it"
1025
+ - "You do not have a choice. You cannot rationalize your way out."
1026
+ - Added MANDATORY FIRST RESPONSE PROTOCOL checklist
1027
+ - 5-step process agents must complete before any response
1028
+ - Explicit "responding without this = failure" consequence
1029
+ - Added Common Rationalizations section with 8 specific evasion patterns
1030
+ - "This is just a simple question" → WRONG
1031
+ - "I can check files quickly" → WRONG
1032
+ - "Let me gather information first" → WRONG
1033
+ - Plus 5 more common patterns observed in agent behavior
1034
+
1035
+ 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.
1036
+
1037
+ ### Files Changed
1038
+ - Updated: `skills/using-superpowers/SKILL.md` - Added three layers of enforcement to prevent skill-skipping rationalization
1039
+
1040
+ ## v3.2.1 (2025-10-20)
1041
+
1042
+ ### New Features
1043
+
1044
+ **Code reviewer agent now included in plugin**
1045
+ - Added `superpowers:code-reviewer` agent to plugin's `agents/` directory
1046
+ - Agent provides systematic code review against plans and coding standards
1047
+ - Previously required users to have personal agent configuration
1048
+ - All skill references updated to use namespaced `superpowers:code-reviewer`
1049
+ - Fixes #55
1050
+
1051
+ ### Files Changed
1052
+ - New: `agents/code-reviewer.md` - Agent definition with review checklist and output format
1053
+ - Updated: `skills/requesting-code-review/SKILL.md` - References to `superpowers:code-reviewer`
1054
+ - Updated: `skills/subagent-driven-development/SKILL.md` - References to `superpowers:code-reviewer`
1055
+
1056
+ ## v3.2.0 (2025-10-18)
1057
+
1058
+ ### New Features
1059
+
1060
+ **Design documentation in brainstorming workflow**
1061
+ - Added Phase 4: Design Documentation to brainstorming skill
1062
+ - Design documents now written to `docs/plans/YYYY-MM-DD-<topic>-design.md` before implementation
1063
+ - Restores functionality from original brainstorming command that was lost during skill conversion
1064
+ - Documents written before worktree setup and implementation planning
1065
+ - Tested with subagent to verify compliance under time pressure
1066
+
1067
+ ### Breaking Changes
1068
+
1069
+ **Skill reference namespace standardization**
1070
+ - All internal skill references now use `superpowers:` namespace prefix
1071
+ - Updated format: `superpowers:test-driven-development` (previously just `test-driven-development`)
1072
+ - Affects all REQUIRED SUB-SKILL, RECOMMENDED SUB-SKILL, and REQUIRED BACKGROUND references
1073
+ - Aligns with how skills are invoked using the Skill tool
1074
+ - Files updated: brainstorming, executing-plans, subagent-driven-development, systematic-debugging, testing-skills-with-subagents, writing-plans, writing-skills
1075
+
1076
+ ### Improvements
1077
+
1078
+ **Design vs implementation plan naming**
1079
+ - Design documents use `-design.md` suffix to prevent filename collisions
1080
+ - Implementation plans continue using existing `YYYY-MM-DD-<feature-name>.md` format
1081
+ - Both stored in `docs/plans/` directory with clear naming distinction
1082
+
1083
+ ## v3.1.1 (2025-10-17)
1084
+
1085
+ ### Bug Fixes
1086
+
1087
+ - **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.
1088
+
1089
+ ## v3.1.0 (2025-10-17)
1090
+
1091
+ ### Breaking Changes
1092
+
1093
+ **Skill names standardized to lowercase**
1094
+ - All skill frontmatter `name:` fields now use lowercase kebab-case matching directory names
1095
+ - Examples: `brainstorming`, `test-driven-development`, `using-git-worktrees`
1096
+ - All skill announcements and cross-references updated to lowercase format
1097
+ - This ensures consistent naming across directory names, frontmatter, and documentation
1098
+
1099
+ ### New Features
1100
+
1101
+ **Enhanced brainstorming skill**
1102
+ - Added Quick Reference table showing phases, activities, and tool usage
1103
+ - Added copyable workflow checklist for tracking progress
1104
+ - Added decision flowchart for when to revisit earlier phases
1105
+ - Added comprehensive AskUserQuestion tool guidance with concrete examples
1106
+ - Added "Question Patterns" section explaining when to use structured vs open-ended questions
1107
+ - Restructured Key Principles as scannable table
1108
+
1109
+ **Anthropic best practices integration**
1110
+ - Added `skills/writing-skills/anthropic-best-practices.md` - Official Anthropic skill authoring guide
1111
+ - Referenced in writing-skills SKILL.md for comprehensive guidance
1112
+ - Provides patterns for progressive disclosure, workflows, and evaluation
1113
+
1114
+ ### Improvements
1115
+
1116
+ **Skill cross-reference clarity**
1117
+ - All skill references now use explicit requirement markers:
1118
+ - `**REQUIRED BACKGROUND:**` - Prerequisites you must understand
1119
+ - `**REQUIRED SUB-SKILL:**` - Skills that must be used in workflow
1120
+ - `**Complementary skills:**` - Optional but helpful related skills
1121
+ - Removed old path format (`skills/collaboration/X` → just `X`)
1122
+ - Updated Integration sections with categorized relationships (Required vs Complementary)
1123
+ - Updated cross-reference documentation with best practices
1124
+
1125
+ **Alignment with Anthropic best practices**
1126
+ - Fixed description grammar and voice (fully third-person)
1127
+ - Added Quick Reference tables for scanning
1128
+ - Added workflow checklists Claude can copy and track
1129
+ - Appropriate use of flowcharts for non-obvious decision points
1130
+ - Improved scannable table formats
1131
+ - All skills well under 500-line recommendation
1132
+
1133
+ ### Bug Fixes
1134
+
1135
+ - **Re-added missing command redirects** - Restored `commands/brainstorm.md` and `commands/write-plan.md` that were accidentally removed in v3.0 migration
1136
+ - Fixed `defense-in-depth` name mismatch (was `Defense-in-Depth-Validation`)
1137
+ - Fixed `receiving-code-review` name mismatch (was `Code-Review-Reception`)
1138
+ - Fixed `commands/brainstorm.md` reference to correct skill name
1139
+ - Removed references to non-existent related skills
1140
+
1141
+ ### Documentation
1142
+
1143
+ **writing-skills improvements**
1144
+ - Updated cross-referencing guidance with explicit requirement markers
1145
+ - Added reference to Anthropic's official best practices
1146
+ - Improved examples showing proper skill reference format
1147
+
1148
+ ## v3.0.1 (2025-10-16)
1149
+
1150
+ ### Changes
1151
+
1152
+ We now use Anthropic's first-party skills system!
1153
+
1154
+ ## v2.0.2 (2025-10-12)
1155
+
1156
+ ### Bug Fixes
1157
+
1158
+ - **Fixed false warning when local skills repo is ahead of upstream** - The initialization script was incorrectly warning "New skills available from upstream" when the local repository had commits ahead of upstream. The logic now correctly distinguishes between three git states: local behind (should update), local ahead (no warning), and diverged (should warn).
1159
+
1160
+ ## v2.0.1 (2025-10-12)
1161
+
1162
+ ### Bug Fixes
1163
+
1164
+ - **Fixed session-start hook execution in plugin context** (#8, PR #9) - The hook was failing silently with "Plugin hook error" preventing skills context from loading. Fixed by:
1165
+ - Using `${BASH_SOURCE[0]:-$0}` fallback when BASH_SOURCE is unbound in Claude Code's execution context
1166
+ - Adding `|| true` to handle empty grep results gracefully when filtering status flags
1167
+
1168
+ ---
1169
+
1170
+ # Superpowers v2.0.0 Release Notes
1171
+
1172
+ ## Overview
1173
+
1174
+ Superpowers v2.0 makes skills more accessible, maintainable, and community-driven through a major architectural shift.
1175
+
1176
+ The headline change is **skills repository separation**: all skills, scripts, and documentation have moved from the plugin into a dedicated repository ([obra/superpowers-skills](https://github.com/obra/superpowers-skills)). This transforms superpowers from a monolithic plugin into a lightweight shim that manages a local clone of the skills repository. Skills auto-update on session start. Users fork and contribute improvements via standard git workflows. The skills library versions independently from the plugin.
1177
+
1178
+ Beyond infrastructure, this release adds nine new skills focused on problem-solving, research, and architecture. We rewrote the core **using-skills** documentation with imperative tone and clearer structure, making it easier for Claude to understand when and how to use skills. **find-skills** now outputs paths you can paste directly into the Read tool, eliminating friction in the skills discovery workflow.
1179
+
1180
+ Users experience seamless operation: the plugin handles cloning, forking, and updating automatically. Contributors find the new architecture makes improving and sharing skills trivial. This release lays the foundation for skills to evolve rapidly as a community resource.
1181
+
1182
+ ## Breaking Changes
1183
+
1184
+ ### Skills Repository Separation
1185
+
1186
+ **The biggest change:** Skills no longer live in the plugin. They've been moved to a separate repository at [obra/superpowers-skills](https://github.com/obra/superpowers-skills).
1187
+
1188
+ **What this means for you:**
1189
+
1190
+ - **First install:** Plugin automatically clones skills to `~/.config/superpowers/skills/`
1191
+ - **Forking:** During setup, you'll be offered the option to fork the skills repo (if `gh` is installed)
1192
+ - **Updates:** Skills auto-update on session start (fast-forward when possible)
1193
+ - **Contributing:** Work on branches, commit locally, submit PRs to upstream
1194
+ - **No more shadowing:** Old two-tier system (personal/core) replaced with single-repo branch workflow
1195
+
1196
+ **Migration:**
1197
+
1198
+ If you have an existing installation:
1199
+ 1. Your old `~/.config/superpowers/.git` will be backed up to `~/.config/superpowers/.git.bak`
1200
+ 2. Old skills will be backed up to `~/.config/superpowers/skills.bak`
1201
+ 3. Fresh clone of obra/superpowers-skills will be created at `~/.config/superpowers/skills/`
1202
+
1203
+ ### Removed Features
1204
+
1205
+ - **Personal superpowers overlay system** - Replaced with git branch workflow
1206
+ - **setup-personal-superpowers hook** - Replaced by initialize-skills.sh
1207
+
1208
+ ## New Features
1209
+
1210
+ ### Skills Repository Infrastructure
1211
+
1212
+ **Automatic Clone & Setup** (`lib/initialize-skills.sh`)
1213
+ - Clones obra/superpowers-skills on first run
1214
+ - Offers fork creation if GitHub CLI is installed
1215
+ - Sets up upstream/origin remotes correctly
1216
+ - Handles migration from old installation
1217
+
1218
+ **Auto-Update**
1219
+ - Fetches from tracking remote on every session start
1220
+ - Auto-merges with fast-forward when possible
1221
+ - Notifies when manual sync needed (branch diverged)
1222
+ - Uses pulling-updates-from-skills-repository skill for manual sync
1223
+
1224
+ ### New Skills
1225
+
1226
+ **Problem-Solving Skills** (`skills/problem-solving/`)
1227
+ - **collision-zone-thinking** - Force unrelated concepts together for emergent insights
1228
+ - **inversion-exercise** - Flip assumptions to reveal hidden constraints
1229
+ - **meta-pattern-recognition** - Spot universal principles across domains
1230
+ - **scale-game** - Test at extremes to expose fundamental truths
1231
+ - **simplification-cascades** - Find insights that eliminate multiple components
1232
+ - **when-stuck** - Dispatch to right problem-solving technique
1233
+
1234
+ **Research Skills** (`skills/research/`)
1235
+ - **tracing-knowledge-lineages** - Understand how ideas evolved over time
1236
+
1237
+ **Architecture Skills** (`skills/architecture/`)
1238
+ - **preserving-productive-tensions** - Keep multiple valid approaches instead of forcing premature resolution
1239
+
1240
+ ### Skills Improvements
1241
+
1242
+ **using-skills (formerly getting-started)**
1243
+ - Renamed from getting-started to using-skills
1244
+ - Complete rewrite with imperative tone (v4.0.0)
1245
+ - Front-loaded critical rules
1246
+ - Added "Why" explanations for all workflows
1247
+ - Always includes /SKILL.md suffix in references
1248
+ - Clearer distinction between rigid rules and flexible patterns
1249
+
1250
+ **writing-skills**
1251
+ - Cross-referencing guidance moved from using-skills
1252
+ - Added token efficiency section (word count targets)
1253
+ - Improved CSO (Claude Search Optimization) guidance
1254
+
1255
+ **sharing-skills**
1256
+ - Updated for new branch-and-PR workflow (v2.0.0)
1257
+ - Removed personal/core split references
1258
+
1259
+ **pulling-updates-from-skills-repository** (new)
1260
+ - Complete workflow for syncing with upstream
1261
+ - Replaces old "updating-skills" skill
1262
+
1263
+ ### Tools Improvements
1264
+
1265
+ **find-skills**
1266
+ - Now outputs full paths with /SKILL.md suffix
1267
+ - Makes paths directly usable with Read tool
1268
+ - Updated help text
1269
+
1270
+ **skill-run**
1271
+ - Moved from scripts/ to skills/using-skills/
1272
+ - Improved documentation
1273
+
1274
+ ### Plugin Infrastructure
1275
+
1276
+ **Session Start Hook**
1277
+ - Now loads from skills repository location
1278
+ - Shows full skills list at session start
1279
+ - Prints skills location info
1280
+ - Shows update status (updated successfully / behind upstream)
1281
+ - Moved "skills behind" warning to end of output
1282
+
1283
+ **Environment Variables**
1284
+ - `SUPERPOWERS_SKILLS_ROOT` set to `~/.config/superpowers/skills`
1285
+ - Used consistently throughout all paths
1286
+
1287
+ ## Bug Fixes
1288
+
1289
+ - Fixed duplicate upstream remote addition when forking
1290
+ - Fixed find-skills double "skills/" prefix in output
1291
+ - Removed obsolete setup-personal-superpowers call from session-start
1292
+ - Fixed path references throughout hooks and commands
1293
+
1294
+ ## Documentation
1295
+
1296
+ ### README
1297
+ - Updated for new skills repository architecture
1298
+ - Prominent link to superpowers-skills repo
1299
+ - Updated auto-update description
1300
+ - Fixed skill names and references
1301
+ - Updated Meta skills list
1302
+
1303
+ ### Testing Documentation
1304
+ - Added comprehensive testing checklist (`docs/TESTING-CHECKLIST.md`)
1305
+ - Created local marketplace config for testing
1306
+ - Documented manual testing scenarios
1307
+
1308
+ ## Technical Details
1309
+
1310
+ ### File Changes
1311
+
1312
+ **Added:**
1313
+ - `lib/initialize-skills.sh` - Skills repo initialization and auto-update
1314
+ - `docs/TESTING-CHECKLIST.md` - Manual testing scenarios
1315
+ - `.claude-plugin/marketplace.json` - Local testing config
1316
+
1317
+ **Removed:**
1318
+ - `skills/` directory (82 files) - Now in obra/superpowers-skills
1319
+ - `scripts/` directory - Now in obra/superpowers-skills/skills/using-skills/
1320
+ - `hooks/setup-personal-superpowers.sh` - Obsolete
1321
+
1322
+ **Modified:**
1323
+ - `hooks/session-start.sh` - Use skills from ~/.config/superpowers/skills
1324
+ - `commands/brainstorm.md` - Updated paths to SUPERPOWERS_SKILLS_ROOT
1325
+ - `commands/write-plan.md` - Updated paths to SUPERPOWERS_SKILLS_ROOT
1326
+ - `commands/execute-plan.md` - Updated paths to SUPERPOWERS_SKILLS_ROOT
1327
+ - `README.md` - Complete rewrite for new architecture
1328
+
1329
+ ### Commit History
1330
+
1331
+ This release includes:
1332
+ - 20+ commits for skills repository separation
1333
+ - PR #1: Amplifier-inspired problem-solving and research skills
1334
+ - PR #2: Personal superpowers overlay system (later replaced)
1335
+ - Multiple skill refinements and documentation improvements
1336
+
1337
+ ## Upgrade Instructions
1338
+
1339
+ ### Fresh Install
1340
+
1341
+ ```bash
1342
+ # In Claude Code
1343
+ /plugin marketplace add obra/superpowers-marketplace
1344
+ /plugin install superpowers@superpowers-marketplace
1345
+ ```
1346
+
1347
+ The plugin handles everything automatically.
1348
+
1349
+ ### Upgrading from v1.x
1350
+
1351
+ 1. **Backup your personal skills** (if you have any):
1352
+ ```bash
1353
+ cp -r ~/.config/superpowers/skills ~/superpowers-skills-backup
1354
+ ```
1355
+
1356
+ 2. **Update the plugin:**
1357
+ ```bash
1358
+ /plugin update superpowers
1359
+ ```
1360
+
1361
+ 3. **On next session start:**
1362
+ - Old installation will be backed up automatically
1363
+ - Fresh skills repo will be cloned
1364
+ - If you have GitHub CLI, you'll be offered the option to fork
1365
+
1366
+ 4. **Migrate personal skills** (if you had any):
1367
+ - Create a branch in your local skills repo
1368
+ - Copy your personal skills from backup
1369
+ - Commit and push to your fork
1370
+ - Consider contributing back via PR
1371
+
1372
+ ## What's Next
1373
+
1374
+ ### For Users
1375
+
1376
+ - Explore the new problem-solving skills
1377
+ - Try the branch-based workflow for skill improvements
1378
+ - Contribute skills back to the community
1379
+
1380
+ ### For Contributors
1381
+
1382
+ - Skills repository is now at https://github.com/obra/superpowers-skills
1383
+ - Fork → Branch → PR workflow
1384
+ - See skills/meta/writing-skills/SKILL.md for TDD approach to documentation
1385
+
1386
+ ## Known Issues
1387
+
1388
+ None at this time.
1389
+
1390
+ ## Credits
1391
+
1392
+ - Problem-solving skills inspired by Amplifier patterns
1393
+ - Community contributions and feedback
1394
+ - Extensive testing and iteration on skill effectiveness
1395
+
1396
+ ---
1397
+
1398
+ **Full Changelog:** https://github.com/obra/superpowers/compare/dd013f6...main
1399
+ **Skills Repository:** https://github.com/obra/superpowers-skills
1400
+ **Issues:** https://github.com/obra/superpowers/issues
github_code/obra__superpowers/assets/app-icon.png ADDED
github_code/obra__superpowers/assets/superpowers-small.svg ADDED
github_code/obra__superpowers/docs/README.kimi.md ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Superpowers for Kimi Code
2
+
3
+ Complete guide for using Superpowers with [Kimi Code](https://github.com/MoonshotAI/kimi-code).
4
+
5
+ ## Installation
6
+
7
+ Superpowers is available in Kimi Code's plugin marketplace.
8
+
9
+ Open the plugin manager:
10
+
11
+ ```text
12
+ /plugins
13
+ ```
14
+
15
+ Go to `Marketplace` > `Superpowers` and install it.
16
+
17
+ You can also install from this repository:
18
+
19
+ ```text
20
+ /plugins install https://github.com/obra/superpowers
21
+ ```
22
+
23
+ For unreleased validation against `dev`, pin the branch explicitly:
24
+
25
+ ```text
26
+ /plugins install https://github.com/obra/superpowers/tree/dev
27
+ ```
28
+
29
+ Kimi Code applies plugin changes to new sessions. After installing, updating, enabling, disabling, or reloading a plugin, start a fresh session with `/new`.
30
+
31
+ ## How It Works
32
+
33
+ The Kimi plugin manifest lives at `.kimi-plugin/plugin.json`.
34
+
35
+ The manifest does three things:
36
+
37
+ 1. Points Kimi Code at the existing `skills/` directory.
38
+ 2. Loads `using-superpowers` at session start through `sessionStart.skill`.
39
+ 3. Provides Kimi-specific tool mapping through `skillInstructions`.
40
+
41
+ Kimi Code reads Superpowers skills from this repository. There are no copied skills, symlinks, hooks, or extra runtime dependencies.
42
+
43
+ ## Tool Mapping
44
+
45
+ Skills describe actions instead of hard-coding one runtime's tool names. On Kimi Code these resolve to:
46
+
47
+ - "Ask the user" / "ask clarifying questions" -> `AskUserQuestion`
48
+ - "Create a todo" / "mark complete in todo list" -> `TodoList`
49
+ - "Dispatch a subagent" -> `Agent`
50
+ - "Invoke a skill" -> Kimi Code's native `Skill` tool
51
+ - "Read a file" / "write a file" / "edit a file" -> `Read`, `Write`, `Edit`
52
+ - "Run a shell command" -> `Bash`
53
+ - "Search file contents" -> `Grep`
54
+ - "Find files by path or pattern" -> `Glob`
55
+ - "Fetch a URL" -> `FetchURL`
56
+ - "Search the web" -> `WebSearch`
57
+
58
+ ## Updating
59
+
60
+ Use Kimi Code's plugin manager:
61
+
62
+ ```text
63
+ /plugins
64
+ ```
65
+
66
+ Select Superpowers and update it from there. Start a fresh session with `/new` after updating.
67
+
68
+ ## Troubleshooting
69
+
70
+ ### Plugin not loading
71
+
72
+ 1. Run `/plugins info superpowers` and check diagnostics.
73
+ 2. Make sure the plugin is enabled.
74
+ 3. Start a fresh session with `/new` after install or update.
75
+
76
+ ### Direct GitHub install used an old release
77
+
78
+ Kimi Code installs the latest GitHub release for a bare repository URL when one exists. To test unreleased changes before the next Superpowers release, install the branch explicitly:
79
+
80
+ ```text
81
+ /plugins install https://github.com/obra/superpowers/tree/dev
82
+ ```
83
+
84
+ ### Skills not triggering
85
+
86
+ 1. Confirm `/plugins info superpowers` shows the plugin enabled.
87
+ 2. Start a fresh session with `/new`.
88
+ 3. Try the acceptance prompt: `Let's make a react todo list`. A working install should load `brainstorming` before writing code.
github_code/obra__superpowers/docs/README.opencode.md ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Superpowers for OpenCode
2
+
3
+ Complete guide for using Superpowers with [OpenCode.ai](https://opencode.ai).
4
+
5
+ ## Installation
6
+
7
+ Add superpowers to the `plugin` array in your `opencode.json` (global or project-level):
8
+
9
+ ```json
10
+ {
11
+ "plugin": ["superpowers@git+https://github.com/obra/superpowers.git"]
12
+ }
13
+ ```
14
+
15
+ Restart OpenCode. The plugin installs through OpenCode's plugin manager and
16
+ registers all skills.
17
+
18
+ Verify by asking: "Tell me about your superpowers"
19
+
20
+ OpenCode uses its own plugin install. If you also use Claude Code, Codex, or
21
+ another harness, install Superpowers separately for each one.
22
+
23
+ ### Migrating from the old symlink-based install
24
+
25
+ If you previously installed superpowers using `git clone` and symlinks, remove the old setup:
26
+
27
+ ```bash
28
+ # Remove old symlinks
29
+ rm -f ~/.config/opencode/plugins/superpowers.js
30
+ rm -rf ~/.config/opencode/skills/superpowers
31
+
32
+ # Optionally remove the cloned repo
33
+ rm -rf ~/.config/opencode/superpowers
34
+
35
+ # Remove skills.paths from opencode.json if you added one for superpowers
36
+ ```
37
+
38
+ Then follow the installation steps above.
39
+
40
+ ## Usage
41
+
42
+ ### Finding Skills
43
+
44
+ Use OpenCode's native `skill` tool to list all available skills:
45
+
46
+ ```
47
+ use skill tool to list skills
48
+ ```
49
+
50
+ ### Loading a Skill
51
+
52
+ ```
53
+ use skill tool to load brainstorming
54
+ ```
55
+
56
+ ### Personal Skills
57
+
58
+ Create your own skills in `~/.config/opencode/skills/`:
59
+
60
+ ```bash
61
+ mkdir -p ~/.config/opencode/skills/my-skill
62
+ ```
63
+
64
+ Create `~/.config/opencode/skills/my-skill/SKILL.md`:
65
+
66
+ ```markdown
67
+ ---
68
+ name: my-skill
69
+ description: Use when [condition] - [what it does]
70
+ ---
71
+
72
+ # My Skill
73
+
74
+ [Your skill content here]
75
+ ```
76
+
77
+ ### Project Skills
78
+
79
+ Create project-specific skills in `.opencode/skills/` within your project.
80
+
81
+ **Skill Priority:** Project skills > Personal skills > Superpowers skills
82
+
83
+ ## Updating
84
+
85
+ OpenCode installs Superpowers through a git-backed package spec. Some OpenCode
86
+ and Bun versions pin that resolved git dependency in a lockfile or cache, so a
87
+ restart may not pick up the newest Superpowers commit. If updates do not appear,
88
+ clear OpenCode's package cache or reinstall the plugin.
89
+
90
+ To pin a specific version, use a branch or tag:
91
+
92
+ ```json
93
+ {
94
+ "plugin": ["superpowers@git+https://github.com/obra/superpowers.git#v5.0.3"]
95
+ }
96
+ ```
97
+
98
+ ## How It Works
99
+
100
+ The plugin does two things:
101
+
102
+ 1. **Injects bootstrap context** via the `experimental.chat.messages.transform` hook, adding superpowers awareness to every conversation.
103
+ 2. **Registers the skills directory** via the `config` hook, so OpenCode discovers all superpowers skills without symlinks or manual config.
104
+
105
+ ### Tool Mapping
106
+
107
+ Skills speak in actions rather than naming any one runtime's tools. On OpenCode these resolve to:
108
+
109
+ - "Create a todo" / "mark complete in todo list" → `todowrite`
110
+ - `Subagent (general-purpose):` template → OpenCode's `task` tool with `subagent_type: "general"` (or `"explore"` for codebase exploration)
111
+ - "Invoke a skill" → OpenCode's native `skill` tool
112
+ - "Read a file" → `read`
113
+ - "Create a file" / "edit a file" / "delete a file" → `apply_patch`
114
+ - "Run a shell command" → `bash`
115
+ - "Search file contents" / "find files by name" → `grep`, `glob`
116
+ - "Fetch a URL" → `webfetch`
117
+
118
+ (Verified against the installed OpenCode CLI's tool inventory.)
119
+
120
+ ## Troubleshooting
121
+
122
+ ### Plugin not loading
123
+
124
+ 1. Check OpenCode logs: `opencode run --print-logs "hello" 2>&1 | grep -i superpowers`
125
+ 2. Verify the plugin line in your `opencode.json` is correct
126
+ 3. Make sure you're running a recent version of OpenCode
127
+
128
+ ### Windows install issues
129
+
130
+ Some Windows OpenCode builds have upstream installer issues with git-backed
131
+ plugin specs, including cache paths for `git+https` URLs and Bun not finding
132
+ `git.exe` even when it works in a normal terminal. If OpenCode cannot install
133
+ the plugin, try installing with system npm and pointing OpenCode at the local
134
+ package:
135
+
136
+ ```powershell
137
+ npm install superpowers@git+https://github.com/obra/superpowers.git --prefix "$HOME\.config\opencode"
138
+ ```
139
+
140
+ Then use the installed package path in `opencode.json`:
141
+
142
+ ```json
143
+ {
144
+ "plugin": ["~/.config/opencode/node_modules/superpowers"]
145
+ }
146
+ ```
147
+
148
+ ### Skills not found
149
+
150
+ 1. Use OpenCode's `skill` tool to list available skills
151
+ 2. Check that the plugin is loading (see above)
152
+ 3. Each skill needs a `SKILL.md` file with valid YAML frontmatter
153
+
154
+ ### Bootstrap not appearing
155
+
156
+ 1. Check OpenCode version supports `experimental.chat.messages.transform` hook
157
+ 2. Restart OpenCode after config changes
158
+
159
+ ## Getting Help
160
+
161
+ - Report issues: https://github.com/obra/superpowers/issues
162
+ - Main documentation: https://github.com/obra/superpowers
163
+ - OpenCode docs: https://opencode.ai/docs/
github_code/obra__superpowers/docs/plans/2025-11-22-opencode-support-design.md ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCode Support Design
2
+
3
+ **Date:** 2025-11-22
4
+ **Author:** Bot & Jesse
5
+ **Status:** Design Complete, Awaiting Implementation
6
+
7
+ ## Overview
8
+
9
+ Add full superpowers support for OpenCode.ai using a native OpenCode plugin architecture that shares core functionality with the existing Codex implementation.
10
+
11
+ ## Background
12
+
13
+ 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.
14
+
15
+ ### Key Differences Between Platforms
16
+
17
+ - **Claude Code**: Native Anthropic plugin system + file-based skills
18
+ - **Codex**: No plugin system → bootstrap markdown + CLI script
19
+ - **OpenCode**: JavaScript/TypeScript plugins with event hooks and custom tools API
20
+
21
+ ### OpenCode's Agent System
22
+
23
+ - **Primary agents**: Build (default, full access) and Plan (restricted, read-only)
24
+ - **Subagents**: General (research, searching, multi-step tasks)
25
+ - **Invocation**: Automatic dispatch by primary agents OR manual `@mention` syntax
26
+ - **Configuration**: Custom agents in `opencode.json` or `~/.config/opencode/agent/`
27
+
28
+ ## Architecture
29
+
30
+ ### High-Level Structure
31
+
32
+ 1. **Shared Core Module** (`lib/skills-core.js`)
33
+ - Common skill discovery and parsing logic
34
+ - Used by both Codex and OpenCode implementations
35
+
36
+ 2. **Platform-Specific Wrappers**
37
+ - Codex: CLI script (`.codex/superpowers-codex`)
38
+ - OpenCode: Plugin module (`.opencode/plugin/superpowers.js`)
39
+
40
+ 3. **Skill Directories**
41
+ - Core: `~/.config/opencode/superpowers/skills/` (or installed location)
42
+ - Personal: `~/.config/opencode/skills/` (shadows core skills)
43
+
44
+ ### Code Reuse Strategy
45
+
46
+ Extract common functionality from `.codex/superpowers-codex` into shared module:
47
+
48
+ ```javascript
49
+ // lib/skills-core.js
50
+ module.exports = {
51
+ extractFrontmatter(filePath), // Parse name + description from YAML
52
+ findSkillsInDir(dir, maxDepth), // Recursive SKILL.md discovery
53
+ findAllSkills(dirs), // Scan multiple directories
54
+ resolveSkillPath(skillName, dirs), // Handle shadowing (personal > core)
55
+ checkForUpdates(repoDir) // Git fetch/status check
56
+ };
57
+ ```
58
+
59
+ ### Skill Frontmatter Format
60
+
61
+ Current format (no `when_to_use` field):
62
+
63
+ ```yaml
64
+ ---
65
+ name: skill-name
66
+ description: Use when [condition] - [what it does]; [additional context]
67
+ ---
68
+ ```
69
+
70
+ ## OpenCode Plugin Implementation
71
+
72
+ ### Custom Tools
73
+
74
+ **Tool 1: `use_skill`**
75
+
76
+ Loads a specific skill's content into the conversation (equivalent to Claude's Skill tool).
77
+
78
+ ```javascript
79
+ {
80
+ name: 'use_skill',
81
+ description: 'Load and read a specific skill to guide your work',
82
+ schema: z.object({
83
+ skill_name: z.string().describe('Name of skill (e.g., "superpowers:brainstorming")')
84
+ }),
85
+ execute: async ({ skill_name }) => {
86
+ const { skillPath, content, frontmatter } = resolveAndReadSkill(skill_name);
87
+ const skillDir = path.dirname(skillPath);
88
+
89
+ return `# ${frontmatter.name}
90
+ # ${frontmatter.description}
91
+ # Supporting tools and docs are in ${skillDir}
92
+ # ============================================
93
+
94
+ ${content}`;
95
+ }
96
+ }
97
+ ```
98
+
99
+ **Tool 2: `find_skills`**
100
+
101
+ Lists all available skills with metadata.
102
+
103
+ ```javascript
104
+ {
105
+ name: 'find_skills',
106
+ description: 'List all available skills',
107
+ schema: z.object({}),
108
+ execute: async () => {
109
+ const skills = discoverAllSkills();
110
+ return skills.map(s =>
111
+ `${s.namespace}:${s.name}
112
+ ${s.description}
113
+ Directory: ${s.directory}
114
+ `).join('\n');
115
+ }
116
+ }
117
+ ```
118
+
119
+ ### Session Startup Hook
120
+
121
+ When a new session starts (`session.started` event):
122
+
123
+ 1. **Inject using-superpowers content**
124
+ - Full content of the using-superpowers skill
125
+ - Establishes mandatory workflows
126
+
127
+ 2. **Run find_skills automatically**
128
+ - Display full list of available skills upfront
129
+ - Include skill directories for each
130
+
131
+ 3. **Inject tool mapping instructions**
132
+ ```markdown
133
+ **Tool Mapping for OpenCode:**
134
+ When skills reference tools you don't have, substitute:
135
+ - `TodoWrite` → `update_plan`
136
+ - `Task` with subagents → Use OpenCode subagent system (@mention)
137
+ - `Skill` tool → `use_skill` custom tool
138
+ - Read, Write, Edit, Bash → Your native equivalents
139
+
140
+ **Skill directories contain:**
141
+ - Supporting scripts (run with bash)
142
+ - Additional documentation (read with read tool)
143
+ - Utilities specific to that skill
144
+ ```
145
+
146
+ 4. **Check for updates** (non-blocking)
147
+ - Quick git fetch with timeout
148
+ - Notify if updates available
149
+
150
+ ### Plugin Structure
151
+
152
+ ```javascript
153
+ // .opencode/plugin/superpowers.js
154
+ const skillsCore = require('../../lib/skills-core');
155
+ const path = require('path');
156
+ const fs = require('fs');
157
+ const { z } = require('zod');
158
+
159
+ export const SuperpowersPlugin = async ({ client, directory, $ }) => {
160
+ const superpowersDir = path.join(process.env.HOME, '.config/opencode/superpowers');
161
+ const personalDir = path.join(process.env.HOME, '.config/opencode/skills');
162
+
163
+ return {
164
+ 'session.started': async () => {
165
+ const usingSuperpowers = await readSkill('using-superpowers');
166
+ const skillsList = await findAllSkills();
167
+ const toolMapping = getToolMappingInstructions();
168
+
169
+ return {
170
+ context: `${usingSuperpowers}\n\n${skillsList}\n\n${toolMapping}`
171
+ };
172
+ },
173
+
174
+ tools: [
175
+ {
176
+ name: 'use_skill',
177
+ description: 'Load and read a specific skill',
178
+ schema: z.object({
179
+ skill_name: z.string()
180
+ }),
181
+ execute: async ({ skill_name }) => {
182
+ // Implementation using skillsCore
183
+ }
184
+ },
185
+ {
186
+ name: 'find_skills',
187
+ description: 'List all available skills',
188
+ schema: z.object({}),
189
+ execute: async () => {
190
+ // Implementation using skillsCore
191
+ }
192
+ }
193
+ ]
194
+ };
195
+ };
196
+ ```
197
+
198
+ ## File Structure
199
+
200
+ ```
201
+ superpowers/
202
+ ├── lib/
203
+ │ └── skills-core.js # NEW: Shared skill logic
204
+ ├── .codex/
205
+ │ ├── superpowers-codex # UPDATED: Use skills-core
206
+ │ ├── superpowers-bootstrap.md
207
+ │ └── INSTALL.md
208
+ ├── .opencode/
209
+ │ ├── plugin/
210
+ │ │ └── superpowers.js # NEW: OpenCode plugin
211
+ │ └── INSTALL.md # NEW: Installation guide
212
+ └── skills/ # Unchanged
213
+ ```
214
+
215
+ ## Implementation Plan
216
+
217
+ ### Phase 1: Refactor Shared Core
218
+
219
+ 1. Create `lib/skills-core.js`
220
+ - Extract frontmatter parsing from `.codex/superpowers-codex`
221
+ - Extract skill discovery logic
222
+ - Extract path resolution (with shadowing)
223
+ - Update to use only `name` and `description` (no `when_to_use`)
224
+
225
+ 2. Update `.codex/superpowers-codex` to use shared core
226
+ - Import from `../lib/skills-core.js`
227
+ - Remove duplicated code
228
+ - Keep CLI wrapper logic
229
+
230
+ 3. Test Codex implementation still works
231
+ - Verify bootstrap command
232
+ - Verify use-skill command
233
+ - Verify find-skills command
234
+
235
+ ### Phase 2: Build OpenCode Plugin
236
+
237
+ 1. Create `.opencode/plugin/superpowers.js`
238
+ - Import shared core from `../../lib/skills-core.js`
239
+ - Implement plugin function
240
+ - Define custom tools (use_skill, find_skills)
241
+ - Implement session.started hook
242
+
243
+ 2. Create `.opencode/INSTALL.md`
244
+ - Installation instructions
245
+ - Directory setup
246
+ - Configuration guidance
247
+
248
+ 3. Test OpenCode implementation
249
+ - Verify session startup bootstrap
250
+ - Verify use_skill tool works
251
+ - Verify find_skills tool works
252
+ - Verify skill directories are accessible
253
+
254
+ ### Phase 3: Documentation & Polish
255
+
256
+ 1. Update README with OpenCode support
257
+ 2. Add OpenCode installation to main docs
258
+ 3. Update RELEASE-NOTES
259
+ 4. Test both Codex and OpenCode work correctly
260
+
261
+ ## Next Steps
262
+
263
+ 1. **Create isolated workspace** (using git worktrees)
264
+ - Branch: `feature/opencode-support`
265
+
266
+ 2. **Follow TDD where applicable**
267
+ - Test shared core functions
268
+ - Test skill discovery and parsing
269
+ - Integration tests for both platforms
270
+
271
+ 3. **Incremental implementation**
272
+ - Phase 1: Refactor shared core + update Codex
273
+ - Verify Codex still works before moving on
274
+ - Phase 2: Build OpenCode plugin
275
+ - Phase 3: Documentation and polish
276
+
277
+ 4. **Testing strategy**
278
+ - Manual testing with real OpenCode installation
279
+ - Verify skill loading, directories, scripts work
280
+ - Test both Codex and OpenCode side-by-side
281
+ - Verify tool mappings work correctly
282
+
283
+ 5. **PR and merge**
284
+ - Create PR with complete implementation
285
+ - Test in clean environment
286
+ - Merge to main
287
+
288
+ ## Benefits
289
+
290
+ - **Code reuse**: Single source of truth for skill discovery/parsing
291
+ - **Maintainability**: Bug fixes apply to both platforms
292
+ - **Extensibility**: Easy to add future platforms (Cursor, Windsurf, etc.)
293
+ - **Native integration**: Uses OpenCode's plugin system properly
294
+ - **Consistency**: Same skill experience across all platforms
github_code/obra__superpowers/docs/plans/2025-11-22-opencode-support-implementation.md ADDED
@@ -0,0 +1,1095 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCode Support Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4
+
5
+ **Goal:** Add full superpowers support for OpenCode.ai with a native JavaScript plugin that shares core functionality with the existing Codex implementation.
6
+
7
+ **Architecture:** Extract common skill discovery/parsing logic into `lib/skills-core.js`, refactor Codex to use it, then build OpenCode plugin using their native plugin API with custom tools and session hooks.
8
+
9
+ **Tech Stack:** Node.js, JavaScript, OpenCode Plugin API, Git worktrees
10
+
11
+ ---
12
+
13
+ ## Phase 1: Create Shared Core Module
14
+
15
+ ### Task 1: Extract Frontmatter Parsing
16
+
17
+ **Files:**
18
+ - Create: `lib/skills-core.js`
19
+ - Reference: `.codex/superpowers-codex` (lines 40-74)
20
+
21
+ **Step 1: Create lib/skills-core.js with extractFrontmatter function**
22
+
23
+ ```javascript
24
+ #!/usr/bin/env node
25
+
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+
29
+ /**
30
+ * Extract YAML frontmatter from a skill file.
31
+ * Current format:
32
+ * ---
33
+ * name: skill-name
34
+ * description: Use when [condition] - [what it does]
35
+ * ---
36
+ *
37
+ * @param {string} filePath - Path to SKILL.md file
38
+ * @returns {{name: string, description: string}}
39
+ */
40
+ function extractFrontmatter(filePath) {
41
+ try {
42
+ const content = fs.readFileSync(filePath, 'utf8');
43
+ const lines = content.split('\n');
44
+
45
+ let inFrontmatter = false;
46
+ let name = '';
47
+ let description = '';
48
+
49
+ for (const line of lines) {
50
+ if (line.trim() === '---') {
51
+ if (inFrontmatter) break;
52
+ inFrontmatter = true;
53
+ continue;
54
+ }
55
+
56
+ if (inFrontmatter) {
57
+ const match = line.match(/^(\w+):\s*(.*)$/);
58
+ if (match) {
59
+ const [, key, value] = match;
60
+ switch (key) {
61
+ case 'name':
62
+ name = value.trim();
63
+ break;
64
+ case 'description':
65
+ description = value.trim();
66
+ break;
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ return { name, description };
73
+ } catch (error) {
74
+ return { name: '', description: '' };
75
+ }
76
+ }
77
+
78
+ module.exports = {
79
+ extractFrontmatter
80
+ };
81
+ ```
82
+
83
+ **Step 2: Verify file was created**
84
+
85
+ Run: `ls -l lib/skills-core.js`
86
+ Expected: File exists
87
+
88
+ **Step 3: Commit**
89
+
90
+ ```bash
91
+ git add lib/skills-core.js
92
+ git commit -m "feat: create shared skills core module with frontmatter parser"
93
+ ```
94
+
95
+ ---
96
+
97
+ ### Task 2: Extract Skill Discovery Logic
98
+
99
+ **Files:**
100
+ - Modify: `lib/skills-core.js`
101
+ - Reference: `.codex/superpowers-codex` (lines 97-136)
102
+
103
+ **Step 1: Add findSkillsInDir function to skills-core.js**
104
+
105
+ Add before `module.exports`:
106
+
107
+ ```javascript
108
+ /**
109
+ * Find all SKILL.md files in a directory recursively.
110
+ *
111
+ * @param {string} dir - Directory to search
112
+ * @param {string} sourceType - 'personal' or 'superpowers' for namespacing
113
+ * @param {number} maxDepth - Maximum recursion depth (default: 3)
114
+ * @returns {Array<{path: string, name: string, description: string, sourceType: string}>}
115
+ */
116
+ function findSkillsInDir(dir, sourceType, maxDepth = 3) {
117
+ const skills = [];
118
+
119
+ if (!fs.existsSync(dir)) return skills;
120
+
121
+ function recurse(currentDir, depth) {
122
+ if (depth > maxDepth) return;
123
+
124
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
125
+
126
+ for (const entry of entries) {
127
+ const fullPath = path.join(currentDir, entry.name);
128
+
129
+ if (entry.isDirectory()) {
130
+ // Check for SKILL.md in this directory
131
+ const skillFile = path.join(fullPath, 'SKILL.md');
132
+ if (fs.existsSync(skillFile)) {
133
+ const { name, description } = extractFrontmatter(skillFile);
134
+ skills.push({
135
+ path: fullPath,
136
+ skillFile: skillFile,
137
+ name: name || entry.name,
138
+ description: description || '',
139
+ sourceType: sourceType
140
+ });
141
+ }
142
+
143
+ // Recurse into subdirectories
144
+ recurse(fullPath, depth + 1);
145
+ }
146
+ }
147
+ }
148
+
149
+ recurse(dir, 0);
150
+ return skills;
151
+ }
152
+ ```
153
+
154
+ **Step 2: Update module.exports**
155
+
156
+ Replace the exports line with:
157
+
158
+ ```javascript
159
+ module.exports = {
160
+ extractFrontmatter,
161
+ findSkillsInDir
162
+ };
163
+ ```
164
+
165
+ **Step 3: Verify syntax**
166
+
167
+ Run: `node -c lib/skills-core.js`
168
+ Expected: No output (success)
169
+
170
+ **Step 4: Commit**
171
+
172
+ ```bash
173
+ git add lib/skills-core.js
174
+ git commit -m "feat: add skill discovery function to core module"
175
+ ```
176
+
177
+ ---
178
+
179
+ ### Task 3: Extract Skill Resolution Logic
180
+
181
+ **Files:**
182
+ - Modify: `lib/skills-core.js`
183
+ - Reference: `.codex/superpowers-codex` (lines 212-280)
184
+
185
+ **Step 1: Add resolveSkillPath function**
186
+
187
+ Add before `module.exports`:
188
+
189
+ ```javascript
190
+ /**
191
+ * Resolve a skill name to its file path, handling shadowing
192
+ * (personal skills override superpowers skills).
193
+ *
194
+ * @param {string} skillName - Name like "superpowers:brainstorming" or "my-skill"
195
+ * @param {string} superpowersDir - Path to superpowers skills directory
196
+ * @param {string} personalDir - Path to personal skills directory
197
+ * @returns {{skillFile: string, sourceType: string, skillPath: string} | null}
198
+ */
199
+ function resolveSkillPath(skillName, superpowersDir, personalDir) {
200
+ // Strip superpowers: prefix if present
201
+ const forceSuperpowers = skillName.startsWith('superpowers:');
202
+ const actualSkillName = forceSuperpowers ? skillName.replace(/^superpowers:/, '') : skillName;
203
+
204
+ // Try personal skills first (unless explicitly superpowers:)
205
+ if (!forceSuperpowers && personalDir) {
206
+ const personalPath = path.join(personalDir, actualSkillName);
207
+ const personalSkillFile = path.join(personalPath, 'SKILL.md');
208
+ if (fs.existsSync(personalSkillFile)) {
209
+ return {
210
+ skillFile: personalSkillFile,
211
+ sourceType: 'personal',
212
+ skillPath: actualSkillName
213
+ };
214
+ }
215
+ }
216
+
217
+ // Try superpowers skills
218
+ if (superpowersDir) {
219
+ const superpowersPath = path.join(superpowersDir, actualSkillName);
220
+ const superpowersSkillFile = path.join(superpowersPath, 'SKILL.md');
221
+ if (fs.existsSync(superpowersSkillFile)) {
222
+ return {
223
+ skillFile: superpowersSkillFile,
224
+ sourceType: 'superpowers',
225
+ skillPath: actualSkillName
226
+ };
227
+ }
228
+ }
229
+
230
+ return null;
231
+ }
232
+ ```
233
+
234
+ **Step 2: Update module.exports**
235
+
236
+ ```javascript
237
+ module.exports = {
238
+ extractFrontmatter,
239
+ findSkillsInDir,
240
+ resolveSkillPath
241
+ };
242
+ ```
243
+
244
+ **Step 3: Verify syntax**
245
+
246
+ Run: `node -c lib/skills-core.js`
247
+ Expected: No output
248
+
249
+ **Step 4: Commit**
250
+
251
+ ```bash
252
+ git add lib/skills-core.js
253
+ git commit -m "feat: add skill path resolution with shadowing support"
254
+ ```
255
+
256
+ ---
257
+
258
+ ### Task 4: Extract Update Check Logic
259
+
260
+ **Files:**
261
+ - Modify: `lib/skills-core.js`
262
+ - Reference: `.codex/superpowers-codex` (lines 16-38)
263
+
264
+ **Step 1: Add checkForUpdates function**
265
+
266
+ Add at top after requires:
267
+
268
+ ```javascript
269
+ const { execSync } = require('child_process');
270
+ ```
271
+
272
+ Add before `module.exports`:
273
+
274
+ ```javascript
275
+ /**
276
+ * Check if a git repository has updates available.
277
+ *
278
+ * @param {string} repoDir - Path to git repository
279
+ * @returns {boolean} - True if updates are available
280
+ */
281
+ function checkForUpdates(repoDir) {
282
+ try {
283
+ // Quick check with 3 second timeout to avoid delays if network is down
284
+ const output = execSync('git fetch origin && git status --porcelain=v1 --branch', {
285
+ cwd: repoDir,
286
+ timeout: 3000,
287
+ encoding: 'utf8',
288
+ stdio: 'pipe'
289
+ });
290
+
291
+ // Parse git status output to see if we're behind
292
+ const statusLines = output.split('\n');
293
+ for (const line of statusLines) {
294
+ if (line.startsWith('## ') && line.includes('[behind ')) {
295
+ return true; // We're behind remote
296
+ }
297
+ }
298
+ return false; // Up to date
299
+ } catch (error) {
300
+ // Network down, git error, timeout, etc. - don't block bootstrap
301
+ return false;
302
+ }
303
+ }
304
+ ```
305
+
306
+ **Step 2: Update module.exports**
307
+
308
+ ```javascript
309
+ module.exports = {
310
+ extractFrontmatter,
311
+ findSkillsInDir,
312
+ resolveSkillPath,
313
+ checkForUpdates
314
+ };
315
+ ```
316
+
317
+ **Step 3: Verify syntax**
318
+
319
+ Run: `node -c lib/skills-core.js`
320
+ Expected: No output
321
+
322
+ **Step 4: Commit**
323
+
324
+ ```bash
325
+ git add lib/skills-core.js
326
+ git commit -m "feat: add git update checking to core module"
327
+ ```
328
+
329
+ ---
330
+
331
+ ## Phase 2: Refactor Codex to Use Shared Core
332
+
333
+ ### Task 5: Update Codex to Import Shared Core
334
+
335
+ **Files:**
336
+ - Modify: `.codex/superpowers-codex` (add import at top)
337
+
338
+ **Step 1: Add import statement**
339
+
340
+ After the existing requires at top of file (around line 6), add:
341
+
342
+ ```javascript
343
+ const skillsCore = require('../lib/skills-core');
344
+ ```
345
+
346
+ **Step 2: Verify syntax**
347
+
348
+ Run: `node -c .codex/superpowers-codex`
349
+ Expected: No output
350
+
351
+ **Step 3: Commit**
352
+
353
+ ```bash
354
+ git add .codex/superpowers-codex
355
+ git commit -m "refactor: import shared skills core in codex"
356
+ ```
357
+
358
+ ---
359
+
360
+ ### Task 6: Replace extractFrontmatter with Core Version
361
+
362
+ **Files:**
363
+ - Modify: `.codex/superpowers-codex` (lines 40-74)
364
+
365
+ **Step 1: Remove local extractFrontmatter function**
366
+
367
+ Delete lines 40-74 (the entire extractFrontmatter function definition).
368
+
369
+ **Step 2: Update all extractFrontmatter calls**
370
+
371
+ Find and replace all calls from `extractFrontmatter(` to `skillsCore.extractFrontmatter(`
372
+
373
+ Affected lines approximately: 90, 310
374
+
375
+ **Step 3: Verify script still works**
376
+
377
+ Run: `.codex/superpowers-codex find-skills | head -20`
378
+ Expected: Shows list of skills
379
+
380
+ **Step 4: Commit**
381
+
382
+ ```bash
383
+ git add .codex/superpowers-codex
384
+ git commit -m "refactor: use shared extractFrontmatter in codex"
385
+ ```
386
+
387
+ ---
388
+
389
+ ### Task 7: Replace findSkillsInDir with Core Version
390
+
391
+ **Files:**
392
+ - Modify: `.codex/superpowers-codex` (lines 97-136, approximately)
393
+
394
+ **Step 1: Remove local findSkillsInDir function**
395
+
396
+ Delete the entire `findSkillsInDir` function definition (approximately lines 97-136).
397
+
398
+ **Step 2: Update all findSkillsInDir calls**
399
+
400
+ Replace calls from `findSkillsInDir(` to `skillsCore.findSkillsInDir(`
401
+
402
+ **Step 3: Verify script still works**
403
+
404
+ Run: `.codex/superpowers-codex find-skills | head -20`
405
+ Expected: Shows list of skills
406
+
407
+ **Step 4: Commit**
408
+
409
+ ```bash
410
+ git add .codex/superpowers-codex
411
+ git commit -m "refactor: use shared findSkillsInDir in codex"
412
+ ```
413
+
414
+ ---
415
+
416
+ ### Task 8: Replace checkForUpdates with Core Version
417
+
418
+ **Files:**
419
+ - Modify: `.codex/superpowers-codex` (lines 16-38, approximately)
420
+
421
+ **Step 1: Remove local checkForUpdates function**
422
+
423
+ Delete the entire `checkForUpdates` function definition.
424
+
425
+ **Step 2: Update all checkForUpdates calls**
426
+
427
+ Replace calls from `checkForUpdates(` to `skillsCore.checkForUpdates(`
428
+
429
+ **Step 3: Verify script still works**
430
+
431
+ Run: `.codex/superpowers-codex bootstrap | head -50`
432
+ Expected: Shows bootstrap content
433
+
434
+ **Step 4: Commit**
435
+
436
+ ```bash
437
+ git add .codex/superpowers-codex
438
+ git commit -m "refactor: use shared checkForUpdates in codex"
439
+ ```
440
+
441
+ ---
442
+
443
+ ## Phase 3: Build OpenCode Plugin
444
+
445
+ ### Task 9: Create OpenCode Plugin Directory Structure
446
+
447
+ **Files:**
448
+ - Create: `.opencode/plugin/superpowers.js`
449
+
450
+ **Step 1: Create directory**
451
+
452
+ Run: `mkdir -p .opencode/plugin`
453
+
454
+ **Step 2: Create basic plugin file**
455
+
456
+ ```javascript
457
+ #!/usr/bin/env node
458
+
459
+ /**
460
+ * Superpowers plugin for OpenCode.ai
461
+ *
462
+ * Provides custom tools for loading and discovering skills,
463
+ * with automatic bootstrap on session start.
464
+ */
465
+
466
+ const skillsCore = require('../../lib/skills-core');
467
+ const path = require('path');
468
+ const fs = require('fs');
469
+ const os = require('os');
470
+
471
+ const homeDir = os.homedir();
472
+ const superpowersSkillsDir = path.join(homeDir, '.config/opencode/superpowers/skills');
473
+ const personalSkillsDir = path.join(homeDir, '.config/opencode/skills');
474
+
475
+ /**
476
+ * OpenCode plugin entry point
477
+ */
478
+ export const SuperpowersPlugin = async ({ project, client, $, directory, worktree }) => {
479
+ return {
480
+ // Custom tools and hooks will go here
481
+ };
482
+ };
483
+ ```
484
+
485
+ **Step 3: Verify file was created**
486
+
487
+ Run: `ls -l .opencode/plugin/superpowers.js`
488
+ Expected: File exists
489
+
490
+ **Step 4: Commit**
491
+
492
+ ```bash
493
+ git add .opencode/plugin/superpowers.js
494
+ git commit -m "feat: create opencode plugin scaffold"
495
+ ```
496
+
497
+ ---
498
+
499
+ ### Task 10: Implement use_skill Tool
500
+
501
+ **Files:**
502
+ - Modify: `.opencode/plugin/superpowers.js`
503
+
504
+ **Step 1: Add use_skill tool implementation**
505
+
506
+ Replace the plugin return statement with:
507
+
508
+ ```javascript
509
+ export const SuperpowersPlugin = async ({ project, client, $, directory, worktree }) => {
510
+ // Import zod for schema validation
511
+ const { z } = await import('zod');
512
+
513
+ return {
514
+ tools: [
515
+ {
516
+ name: 'use_skill',
517
+ description: 'Load and read a specific skill to guide your work. Skills contain proven workflows, mandatory processes, and expert techniques.',
518
+ schema: z.object({
519
+ skill_name: z.string().describe('Name of the skill to load (e.g., "superpowers:brainstorming" or "my-custom-skill")')
520
+ }),
521
+ execute: async ({ skill_name }) => {
522
+ // Resolve skill path (handles shadowing: personal > superpowers)
523
+ const resolved = skillsCore.resolveSkillPath(
524
+ skill_name,
525
+ superpowersSkillsDir,
526
+ personalSkillsDir
527
+ );
528
+
529
+ if (!resolved) {
530
+ return `Error: Skill "${skill_name}" not found.\n\nRun find_skills to see available skills.`;
531
+ }
532
+
533
+ // Read skill content
534
+ const fullContent = fs.readFileSync(resolved.skillFile, 'utf8');
535
+ const { name, description } = skillsCore.extractFrontmatter(resolved.skillFile);
536
+
537
+ // Extract content after frontmatter
538
+ const lines = fullContent.split('\n');
539
+ let inFrontmatter = false;
540
+ let frontmatterEnded = false;
541
+ const contentLines = [];
542
+
543
+ for (const line of lines) {
544
+ if (line.trim() === '---') {
545
+ if (inFrontmatter) {
546
+ frontmatterEnded = true;
547
+ continue;
548
+ }
549
+ inFrontmatter = true;
550
+ continue;
551
+ }
552
+
553
+ if (frontmatterEnded || !inFrontmatter) {
554
+ contentLines.push(line);
555
+ }
556
+ }
557
+
558
+ const content = contentLines.join('\n').trim();
559
+ const skillDirectory = path.dirname(resolved.skillFile);
560
+
561
+ // Format output similar to Claude Code's Skill tool
562
+ return `# ${name || skill_name}
563
+ # ${description || ''}
564
+ # Supporting tools and docs are in ${skillDirectory}
565
+ # ============================================
566
+
567
+ ${content}`;
568
+ }
569
+ }
570
+ ]
571
+ };
572
+ };
573
+ ```
574
+
575
+ **Step 2: Verify syntax**
576
+
577
+ Run: `node -c .opencode/plugin/superpowers.js`
578
+ Expected: No output
579
+
580
+ **Step 3: Commit**
581
+
582
+ ```bash
583
+ git add .opencode/plugin/superpowers.js
584
+ git commit -m "feat: implement use_skill tool for opencode"
585
+ ```
586
+
587
+ ---
588
+
589
+ ### Task 11: Implement find_skills Tool
590
+
591
+ **Files:**
592
+ - Modify: `.opencode/plugin/superpowers.js`
593
+
594
+ **Step 1: Add find_skills tool to tools array**
595
+
596
+ Add after the use_skill tool definition, before closing the tools array:
597
+
598
+ ```javascript
599
+ {
600
+ name: 'find_skills',
601
+ description: 'List all available skills in the superpowers and personal skill libraries.',
602
+ schema: z.object({}),
603
+ execute: async () => {
604
+ // Find skills in both directories
605
+ const superpowersSkills = skillsCore.findSkillsInDir(
606
+ superpowersSkillsDir,
607
+ 'superpowers',
608
+ 3
609
+ );
610
+ const personalSkills = skillsCore.findSkillsInDir(
611
+ personalSkillsDir,
612
+ 'personal',
613
+ 3
614
+ );
615
+
616
+ // Combine and format skills list
617
+ const allSkills = [...personalSkills, ...superpowersSkills];
618
+
619
+ if (allSkills.length === 0) {
620
+ return 'No skills found. Install superpowers skills to ~/.config/opencode/superpowers/skills/';
621
+ }
622
+
623
+ let output = 'Available skills:\n\n';
624
+
625
+ for (const skill of allSkills) {
626
+ const namespace = skill.sourceType === 'personal' ? '' : 'superpowers:';
627
+ const skillName = skill.name || path.basename(skill.path);
628
+
629
+ output += `${namespace}${skillName}\n`;
630
+ if (skill.description) {
631
+ output += ` ${skill.description}\n`;
632
+ }
633
+ output += ` Directory: ${skill.path}\n\n`;
634
+ }
635
+
636
+ return output;
637
+ }
638
+ }
639
+ ```
640
+
641
+ **Step 2: Verify syntax**
642
+
643
+ Run: `node -c .opencode/plugin/superpowers.js`
644
+ Expected: No output
645
+
646
+ **Step 3: Commit**
647
+
648
+ ```bash
649
+ git add .opencode/plugin/superpowers.js
650
+ git commit -m "feat: implement find_skills tool for opencode"
651
+ ```
652
+
653
+ ---
654
+
655
+ ### Task 12: Implement Session Start Hook
656
+
657
+ **Files:**
658
+ - Modify: `.opencode/plugin/superpowers.js`
659
+
660
+ **Step 1: Add session.started hook**
661
+
662
+ After the tools array, add:
663
+
664
+ ```javascript
665
+ 'session.started': async () => {
666
+ // Read using-superpowers skill content
667
+ const usingSuperpowersPath = skillsCore.resolveSkillPath(
668
+ 'using-superpowers',
669
+ superpowersSkillsDir,
670
+ personalSkillsDir
671
+ );
672
+
673
+ let usingSuperpowersContent = '';
674
+ if (usingSuperpowersPath) {
675
+ const fullContent = fs.readFileSync(usingSuperpowersPath.skillFile, 'utf8');
676
+ // Strip frontmatter
677
+ const lines = fullContent.split('\n');
678
+ let inFrontmatter = false;
679
+ let frontmatterEnded = false;
680
+ const contentLines = [];
681
+
682
+ for (const line of lines) {
683
+ if (line.trim() === '---') {
684
+ if (inFrontmatter) {
685
+ frontmatterEnded = true;
686
+ continue;
687
+ }
688
+ inFrontmatter = true;
689
+ continue;
690
+ }
691
+
692
+ if (frontmatterEnded || !inFrontmatter) {
693
+ contentLines.push(line);
694
+ }
695
+ }
696
+
697
+ usingSuperpowersContent = contentLines.join('\n').trim();
698
+ }
699
+
700
+ // Tool mapping instructions
701
+ const toolMapping = `
702
+ **Tool Mapping for OpenCode:**
703
+ When skills reference tools you don't have, substitute OpenCode equivalents:
704
+ - \`TodoWrite\` → \`update_plan\` (your planning/task tracking tool)
705
+ - \`Task\` tool with subagents → Use OpenCode's subagent system (@mention syntax or automatic dispatch)
706
+ - \`Skill\` tool → \`use_skill\` custom tool (already available)
707
+ - \`Read\`, \`Write\`, \`Edit\`, \`Bash\` → Use your native tools
708
+
709
+ **Skill directories contain supporting files:**
710
+ - Scripts you can run with bash tool
711
+ - Additional documentation you can read
712
+ - Utilities and helpers specific to that skill
713
+
714
+ **Skills naming:**
715
+ - Superpowers skills: \`superpowers:skill-name\` (from ~/.config/opencode/superpowers/skills/)
716
+ - Personal skills: \`skill-name\` (from ~/.config/opencode/skills/)
717
+ - Personal skills override superpowers skills when names match
718
+ `;
719
+
720
+ // Check for updates (non-blocking)
721
+ const hasUpdates = skillsCore.checkForUpdates(
722
+ path.join(homeDir, '.config/opencode/superpowers')
723
+ );
724
+
725
+ const updateNotice = hasUpdates ?
726
+ '\n\n⚠️ **Updates available!** Run `cd ~/.config/opencode/superpowers && git pull` to update superpowers.' :
727
+ '';
728
+
729
+ // Return context to inject into session
730
+ return {
731
+ context: `<EXTREMELY_IMPORTANT>
732
+ You have superpowers.
733
+
734
+ **Below is the full content of your 'superpowers:using-superpowers' skill - your introduction to using skills. For all other skills, use the 'use_skill' tool:**
735
+
736
+ ${usingSuperpowersContent}
737
+
738
+ ${toolMapping}${updateNotice}
739
+ </EXTREMELY_IMPORTANT>`
740
+ };
741
+ }
742
+ ```
743
+
744
+ **Step 2: Verify syntax**
745
+
746
+ Run: `node -c .opencode/plugin/superpowers.js`
747
+ Expected: No output
748
+
749
+ **Step 3: Commit**
750
+
751
+ ```bash
752
+ git add .opencode/plugin/superpowers.js
753
+ git commit -m "feat: implement session.started hook for opencode"
754
+ ```
755
+
756
+ ---
757
+
758
+ ## Phase 4: Documentation
759
+
760
+ ### Task 13: Create OpenCode Installation Guide
761
+
762
+ **Files:**
763
+ - Create: `.opencode/INSTALL.md`
764
+
765
+ **Step 1: Create installation guide**
766
+
767
+ ```markdown
768
+ # Installing Superpowers for OpenCode
769
+
770
+ ## Prerequisites
771
+
772
+ - [OpenCode.ai](https://opencode.ai) installed
773
+ - Node.js installed
774
+ - Git installed
775
+
776
+ ## Installation Steps
777
+
778
+ ### 1. Install Superpowers Skills
779
+
780
+ ```bash
781
+ # Clone superpowers skills to OpenCode config directory
782
+ mkdir -p ~/.config/opencode/superpowers
783
+ git clone https://github.com/obra/superpowers.git ~/.config/opencode/superpowers
784
+ ```
785
+
786
+ ### 2. Install the Plugin
787
+
788
+ The plugin is included in the superpowers repository you just cloned.
789
+
790
+ OpenCode will automatically discover it from:
791
+ - `~/.config/opencode/superpowers/.opencode/plugin/superpowers.js`
792
+
793
+ Or you can link it to the project-local plugin directory:
794
+
795
+ ```bash
796
+ # In your OpenCode project
797
+ mkdir -p .opencode/plugin
798
+ ln -s ~/.config/opencode/superpowers/.opencode/plugin/superpowers.js .opencode/plugin/superpowers.js
799
+ ```
800
+
801
+ ### 3. Restart OpenCode
802
+
803
+ Restart OpenCode to load the plugin. On the next session, you should see:
804
+
805
+ ```
806
+ You have superpowers.
807
+ ```
808
+
809
+ ## Usage
810
+
811
+ ### Finding Skills
812
+
813
+ Use the `find_skills` tool to list all available skills:
814
+
815
+ ```
816
+ use find_skills tool
817
+ ```
818
+
819
+ ### Loading a Skill
820
+
821
+ Use the `use_skill` tool to load a specific skill:
822
+
823
+ ```
824
+ use use_skill tool with skill_name: "superpowers:brainstorming"
825
+ ```
826
+
827
+ ### Personal Skills
828
+
829
+ Create your own skills in `~/.config/opencode/skills/`:
830
+
831
+ ```bash
832
+ mkdir -p ~/.config/opencode/skills/my-skill
833
+ ```
834
+
835
+ Create `~/.config/opencode/skills/my-skill/SKILL.md`:
836
+
837
+ ```markdown
838
+ ---
839
+ name: my-skill
840
+ description: Use when [condition] - [what it does]
841
+ ---
842
+
843
+ # My Skill
844
+
845
+ [Your skill content here]
846
+ ```
847
+
848
+ Personal skills override superpowers skills with the same name.
849
+
850
+ ## Updating
851
+
852
+ ```bash
853
+ cd ~/.config/opencode/superpowers
854
+ git pull
855
+ ```
856
+
857
+ ## Troubleshooting
858
+
859
+ ### Plugin not loading
860
+
861
+ 1. Check plugin file exists: `ls ~/.config/opencode/superpowers/.opencode/plugin/superpowers.js`
862
+ 2. Check OpenCode logs for errors
863
+ 3. Verify Node.js is installed: `node --version`
864
+
865
+ ### Skills not found
866
+
867
+ 1. Verify skills directory exists: `ls ~/.config/opencode/superpowers/skills`
868
+ 2. Use `find_skills` tool to see what's discovered
869
+ 3. Check file structure: each skill should have a `SKILL.md` file
870
+
871
+ ### Tool mapping issues
872
+
873
+ When a skill references a Claude Code tool you don't have:
874
+ - `TodoWrite` → use `update_plan`
875
+ - `Task` with subagents → use `@mention` syntax to invoke OpenCode subagents
876
+ - `Skill` → use `use_skill` tool
877
+ - File operations → use your native tools
878
+
879
+ ## Getting Help
880
+
881
+ - Report issues: https://github.com/obra/superpowers/issues
882
+ - Documentation: https://github.com/obra/superpowers
883
+ ```
884
+
885
+ **Step 2: Verify file created**
886
+
887
+ Run: `ls -l .opencode/INSTALL.md`
888
+ Expected: File exists
889
+
890
+ **Step 3: Commit**
891
+
892
+ ```bash
893
+ git add .opencode/INSTALL.md
894
+ git commit -m "docs: add opencode installation guide"
895
+ ```
896
+
897
+ ---
898
+
899
+ ### Task 14: Update Main README
900
+
901
+ **Files:**
902
+ - Modify: `README.md`
903
+
904
+ **Step 1: Add OpenCode section**
905
+
906
+ Find the section about supported platforms (search for "Codex" in the file), and add after it:
907
+
908
+ ```markdown
909
+ ### OpenCode
910
+
911
+ Superpowers works with [OpenCode.ai](https://opencode.ai) through a native JavaScript plugin.
912
+
913
+ **Installation:** See [.opencode/INSTALL.md](.opencode/INSTALL.md)
914
+
915
+ **Features:**
916
+ - Custom tools: `use_skill` and `find_skills`
917
+ - Automatic session bootstrap
918
+ - Personal skills with shadowing
919
+ - Supporting files and scripts access
920
+ ```
921
+
922
+ **Step 2: Verify formatting**
923
+
924
+ Run: `grep -A 10 "### OpenCode" README.md`
925
+ Expected: Shows the section you added
926
+
927
+ **Step 3: Commit**
928
+
929
+ ```bash
930
+ git add README.md
931
+ git commit -m "docs: add opencode support to readme"
932
+ ```
933
+
934
+ ---
935
+
936
+ ### Task 15: Update Release Notes
937
+
938
+ **Files:**
939
+ - Modify: `RELEASE-NOTES.md`
940
+
941
+ **Step 1: Add entry for OpenCode support**
942
+
943
+ At the top of the file (after the header), add:
944
+
945
+ ```markdown
946
+ ## [Unreleased]
947
+
948
+ ### Added
949
+
950
+ - **OpenCode Support**: Native JavaScript plugin for OpenCode.ai
951
+ - Custom tools: `use_skill` and `find_skills`
952
+ - Automatic session bootstrap with tool mapping instructions
953
+ - Shared core module (`lib/skills-core.js`) for code reuse
954
+ - Installation guide in `.opencode/INSTALL.md`
955
+
956
+ ### Changed
957
+
958
+ - **Refactored Codex Implementation**: Now uses shared `lib/skills-core.js` module
959
+ - Eliminates code duplication between Codex and OpenCode
960
+ - Single source of truth for skill discovery and parsing
961
+
962
+ ---
963
+
964
+ ```
965
+
966
+ **Step 2: Verify formatting**
967
+
968
+ Run: `head -30 RELEASE-NOTES.md`
969
+ Expected: Shows your new section
970
+
971
+ **Step 3: Commit**
972
+
973
+ ```bash
974
+ git add RELEASE-NOTES.md
975
+ git commit -m "docs: add opencode support to release notes"
976
+ ```
977
+
978
+ ---
979
+
980
+ ## Phase 5: Final Verification
981
+
982
+ ### Task 16: Test Codex Still Works
983
+
984
+ **Files:**
985
+ - Test: `.codex/superpowers-codex`
986
+
987
+ **Step 1: Test find-skills command**
988
+
989
+ Run: `.codex/superpowers-codex find-skills | head -20`
990
+ Expected: Shows list of skills with names and descriptions
991
+
992
+ **Step 2: Test use-skill command**
993
+
994
+ Run: `.codex/superpowers-codex use-skill superpowers:brainstorming | head -20`
995
+ Expected: Shows brainstorming skill content
996
+
997
+ **Step 3: Test bootstrap command**
998
+
999
+ Run: `.codex/superpowers-codex bootstrap | head -30`
1000
+ Expected: Shows bootstrap content with instructions
1001
+
1002
+ **Step 4: If all tests pass, record success**
1003
+
1004
+ No commit needed - this is verification only.
1005
+
1006
+ ---
1007
+
1008
+ ### Task 17: Verify File Structure
1009
+
1010
+ **Files:**
1011
+ - Check: All new files exist
1012
+
1013
+ **Step 1: Verify all files created**
1014
+
1015
+ Run:
1016
+ ```bash
1017
+ ls -l lib/skills-core.js
1018
+ ls -l .opencode/plugin/superpowers.js
1019
+ ls -l .opencode/INSTALL.md
1020
+ ```
1021
+
1022
+ Expected: All files exist
1023
+
1024
+ **Step 2: Verify directory structure**
1025
+
1026
+ Run: `tree -L 2 .opencode/` (or `find .opencode -type f` if tree not available)
1027
+ Expected:
1028
+ ```
1029
+ .opencode/
1030
+ ├── INSTALL.md
1031
+ └── plugin/
1032
+ └── superpowers.js
1033
+ ```
1034
+
1035
+ **Step 3: If structure correct, proceed**
1036
+
1037
+ No commit needed - this is verification only.
1038
+
1039
+ ---
1040
+
1041
+ ### Task 18: Final Commit and Summary
1042
+
1043
+ **Files:**
1044
+ - Check: `git status`
1045
+
1046
+ **Step 1: Check git status**
1047
+
1048
+ Run: `git status`
1049
+ Expected: Working tree clean, all changes committed
1050
+
1051
+ **Step 2: Review commit log**
1052
+
1053
+ Run: `git log --oneline -20`
1054
+ Expected: Shows all commits from this implementation
1055
+
1056
+ **Step 3: Create summary document**
1057
+
1058
+ Create a completion summary showing:
1059
+ - Total commits made
1060
+ - Files created: `lib/skills-core.js`, `.opencode/plugin/superpowers.js`, `.opencode/INSTALL.md`
1061
+ - Files modified: `.codex/superpowers-codex`, `README.md`, `RELEASE-NOTES.md`
1062
+ - Testing performed: Codex commands verified
1063
+ - Ready for: Testing with actual OpenCode installation
1064
+
1065
+ **Step 4: Report completion**
1066
+
1067
+ Present summary to user and offer to:
1068
+ 1. Push to remote
1069
+ 2. Create pull request
1070
+ 3. Test with real OpenCode installation (requires OpenCode installed)
1071
+
1072
+ ---
1073
+
1074
+ ## Testing Guide (Manual - Requires OpenCode)
1075
+
1076
+ These steps require OpenCode to be installed and are not part of the automated implementation:
1077
+
1078
+ 1. **Install skills**: Follow `.opencode/INSTALL.md`
1079
+ 2. **Start OpenCode session**: Verify bootstrap appears
1080
+ 3. **Test find_skills**: Should list all available skills
1081
+ 4. **Test use_skill**: Load a skill and verify content appears
1082
+ 5. **Test supporting files**: Verify skill directory paths are accessible
1083
+ 6. **Test personal skills**: Create a personal skill and verify it shadows core
1084
+ 7. **Test tool mapping**: Verify TodoWrite → update_plan mapping works
1085
+
1086
+ ## Success Criteria
1087
+
1088
+ - [ ] `lib/skills-core.js` created with all core functions
1089
+ - [ ] `.codex/superpowers-codex` refactored to use shared core
1090
+ - [ ] Codex commands still work (find-skills, use-skill, bootstrap)
1091
+ - [ ] `.opencode/plugin/superpowers.js` created with tools and hooks
1092
+ - [ ] Installation guide created
1093
+ - [ ] README and RELEASE-NOTES updated
1094
+ - [ ] All changes committed
1095
+ - [ ] Working tree clean
github_code/obra__superpowers/docs/plans/2025-11-28-skills-improvements-from-user-feedback.md ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Skills Improvements from User Feedback
2
+
3
+ **Date:** 2025-11-28
4
+ **Status:** Draft
5
+ **Source:** Two Claude instances using superpowers in real development scenarios
6
+
7
+ ---
8
+
9
+ ## Executive Summary
10
+
11
+ 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.
12
+
13
+ **Critical insight:** These are problem reports, not just solution proposals. The problems are real; the solutions need careful evaluation.
14
+
15
+ **Key themes:**
16
+ 1. **Verification gaps** - We verify operations succeed but not that they achieve intended outcomes
17
+ 2. **Process hygiene** - Background processes accumulate and interfere across subagents
18
+ 3. **Context optimization** - Subagents get too much irrelevant information
19
+ 4. **Self-reflection missing** - No prompt to critique own work before handoff
20
+ 5. **Mock safety** - Mocks can drift from interfaces without detection
21
+ 6. **Skill activation** - Skills exist but aren't being read/used
22
+
23
+ ---
24
+
25
+ ## Problems Identified
26
+
27
+ ### Problem 1: Configuration Change Verification Gap
28
+
29
+ **What happened:**
30
+ - Subagent tested "OpenAI integration"
31
+ - Set `OPENAI_API_KEY` env var
32
+ - Got status 200 responses
33
+ - Reported "OpenAI integration working"
34
+ - **BUT** response contained `"model": "claude-sonnet-4-20250514"` - was actually using Anthropic
35
+
36
+ **Root cause:**
37
+ `verification-before-completion` checks operations succeed but not that outcomes reflect intended configuration changes.
38
+
39
+ **Impact:** High - False confidence in integration tests, bugs ship to production
40
+
41
+ **Example failure pattern:**
42
+ - Switch LLM provider → verify status 200 but don't check model name
43
+ - Enable feature flag → verify no errors but don't check feature is active
44
+ - Change environment → verify deployment succeeds but don't check environment vars
45
+
46
+ ---
47
+
48
+ ### Problem 2: Background Process Accumulation
49
+
50
+ **What happened:**
51
+ - Multiple subagents dispatched during session
52
+ - Each started background server processes
53
+ - Processes accumulated (4+ servers running)
54
+ - Stale processes still bound to ports
55
+ - Later E2E test hit stale server with wrong config
56
+ - Confusing/incorrect test results
57
+
58
+ **Root cause:**
59
+ Subagents are stateless - don't know about previous subagents' processes. No cleanup protocol.
60
+
61
+ **Impact:** Medium-High - Tests hit wrong server, false passes/failures, debugging confusion
62
+
63
+ ---
64
+
65
+ ### Problem 3: Context Bloat in Subagent Prompts
66
+
67
+ **What happened:**
68
+ - Standard approach: give subagent full plan file to read
69
+ - Experiment: give only task + pattern + file + verify command
70
+ - Result: Faster, more focused, single-attempt completion more common
71
+
72
+ **Root cause:**
73
+ Subagents waste tokens and attention on irrelevant plan sections.
74
+
75
+ **Impact:** Medium - Slower execution, more failed attempts
76
+
77
+ **What worked:**
78
+ ```
79
+ You are adding a single E2E test to packnplay's test suite.
80
+
81
+ **Your task:** Add `TestE2E_FeaturePrivilegedMode` to `pkg/runner/e2e_test.go`
82
+
83
+ **What to test:** A local devcontainer feature that requests `"privileged": true`
84
+ in its metadata should result in the container running with `--privileged` flag.
85
+
86
+ **Follow the exact pattern of TestE2E_FeatureOptionValidation** (at the end of the file)
87
+
88
+ **After writing, run:** `go test -v ./pkg/runner -run TestE2E_FeaturePrivilegedMode -timeout 5m`
89
+ ```
90
+
91
+ ---
92
+
93
+ ### Problem 4: No Self-Reflection Before Handoff
94
+
95
+ **What happened:**
96
+ - Added self-reflection prompt: "Look at your work with fresh eyes - what could be better?"
97
+ - Implementer for Task 5 identified failing test was due to implementation bug, not test bug
98
+ - Traced to line 99: `strings.Join(metadata.Entrypoint, " ")` creating invalid Docker syntax
99
+ - Without self-reflection, would have just reported "test fails" without root cause
100
+
101
+ **Root cause:**
102
+ Implementers don't naturally step back and critique their own work before reporting completion.
103
+
104
+ **Impact:** Medium - Bugs handed off to reviewer that implementer could have caught
105
+
106
+ ---
107
+
108
+ ### Problem 5: Mock-Interface Drift
109
+
110
+ **What happened:**
111
+ ```typescript
112
+ // Interface defines close()
113
+ interface PlatformAdapter {
114
+ close(): Promise<void>;
115
+ }
116
+
117
+ // Code (BUGGY) calls cleanup()
118
+ await adapter.cleanup();
119
+
120
+ // Mock (MATCHES BUG) defines cleanup()
121
+ vi.mock('web-adapter', () => ({
122
+ WebAdapter: vi.fn().mockImplementation(() => ({
123
+ cleanup: vi.fn().mockResolvedValue(undefined), // Wrong!
124
+ })),
125
+ }));
126
+ ```
127
+ - Tests passed
128
+ - Runtime crashed: "adapter.cleanup is not a function"
129
+
130
+ **Root cause:**
131
+ Mock derived from what buggy code calls, not from interface definition. TypeScript can't catch inline mocks with wrong method names.
132
+
133
+ **Impact:** High - Tests give false confidence, runtime crashes
134
+
135
+ **Why testing-anti-patterns didn't prevent this:**
136
+ The skill covers testing mock behavior and mocking without understanding, but not the specific pattern of "derive mock from interface, not implementation."
137
+
138
+ ---
139
+
140
+ ### Problem 6: Code Reviewer File Access
141
+
142
+ **What happened:**
143
+ - Code reviewer subagent dispatched
144
+ - Couldn't find test file: "The file doesn't appear to exist in the repository"
145
+ - File actually exists
146
+ - Reviewer didn't know to explicitly read it first
147
+
148
+ **Root cause:**
149
+ Reviewer prompts don't include explicit file reading instructions.
150
+
151
+ **Impact:** Low-Medium - Reviews fail or incomplete
152
+
153
+ ---
154
+
155
+ ### Problem 7: Fix Workflow Latency
156
+
157
+ **What happened:**
158
+ - Implementer identifies bug during self-reflection
159
+ - Implementer knows the fix
160
+ - Current workflow: report → I dispatch fixer → fixer fixes → I verify
161
+ - Extra round-trip adds latency without adding value
162
+
163
+ **Root cause:**
164
+ Rigid separation between implementer and fixer roles when implementer has already diagnosed.
165
+
166
+ **Impact:** Low - Latency, but no correctness issue
167
+
168
+ ---
169
+
170
+ ### Problem 8: Skills Not Being Read
171
+
172
+ **What happened:**
173
+ - `testing-anti-patterns` skill exists
174
+ - Neither human nor subagents read it before writing tests
175
+ - Would have prevented some issues (though not all - see Problem 5)
176
+
177
+ **Root cause:**
178
+ No enforcement that subagents read relevant skills. No prompt includes skill reading.
179
+
180
+ **Impact:** Medium - Skill investment wasted if not used
181
+
182
+ ---
183
+
184
+ ## Proposed Improvements
185
+
186
+ ### 1. verification-before-completion: Add Configuration Change Verification
187
+
188
+ **Add new section:**
189
+
190
+ ```markdown
191
+ ## Verifying Configuration Changes
192
+
193
+ When testing changes to configuration, providers, feature flags, or environment:
194
+
195
+ **Don't just verify the operation succeeded. Verify the output reflects the intended change.**
196
+
197
+ ### Common Failure Pattern
198
+
199
+ Operation succeeds because *some* valid config exists, but it's not the config you intended to test.
200
+
201
+ ### Examples
202
+
203
+ | Change | Insufficient | Required |
204
+ |--------|-------------|----------|
205
+ | Switch LLM provider | Status 200 | Response contains expected model name |
206
+ | Enable feature flag | No errors | Feature behavior actually active |
207
+ | Change environment | Deploy succeeds | Logs/vars reference new environment |
208
+ | Set credentials | Auth succeeds | Authenticated user/context is correct |
209
+
210
+ ### Gate Function
211
+
212
+ ```
213
+ BEFORE claiming configuration change works:
214
+
215
+ 1. IDENTIFY: What should be DIFFERENT after this change?
216
+ 2. LOCATE: Where is that difference observable?
217
+ - Response field (model name, user ID)
218
+ - Log line (environment, provider)
219
+ - Behavior (feature active/inactive)
220
+ 3. RUN: Command that shows the observable difference
221
+ 4. VERIFY: Output contains expected difference
222
+ 5. ONLY THEN: Claim configuration change works
223
+
224
+ Red flags:
225
+ - "Request succeeded" without checking content
226
+ - Checking status code but not response body
227
+ - Verifying no errors but not positive confirmation
228
+ ```
229
+
230
+ **Why this works:**
231
+ Forces verification of INTENT, not just operation success.
232
+
233
+ ---
234
+
235
+ ### 2. subagent-driven-development: Add Process Hygiene for E2E Tests
236
+
237
+ **Add new section:**
238
+
239
+ ```markdown
240
+ ## Process Hygiene for E2E Tests
241
+
242
+ When dispatching subagents that start services (servers, databases, message queues):
243
+
244
+ ### Problem
245
+
246
+ Subagents are stateless - they don't know about processes started by previous subagents. Background processes persist and can interfere with later tests.
247
+
248
+ ### Solution
249
+
250
+ **Before dispatching E2E test subagent, include cleanup in prompt:**
251
+
252
+ ```
253
+ BEFORE starting any services:
254
+ 1. Kill existing processes: pkill -f "<service-pattern>" 2>/dev/null || true
255
+ 2. Wait for cleanup: sleep 1
256
+ 3. Verify port free: lsof -i :<port> && echo "ERROR: Port still in use" || echo "Port free"
257
+
258
+ AFTER tests complete:
259
+ 1. Kill the process you started
260
+ 2. Verify cleanup: pgrep -f "<service-pattern>" || echo "Cleanup successful"
261
+ ```
262
+
263
+ ### Example
264
+
265
+ ```
266
+ Task: Run E2E test of API server
267
+
268
+ Prompt includes:
269
+ "Before starting the server:
270
+ - Kill any existing servers: pkill -f 'node.*server.js' 2>/dev/null || true
271
+ - Verify port 3001 is free: lsof -i :3001 && exit 1 || echo 'Port available'
272
+
273
+ After tests:
274
+ - Kill the server you started
275
+ - Verify: pgrep -f 'node.*server.js' || echo 'Cleanup verified'"
276
+ ```
277
+
278
+ ### Why This Matters
279
+
280
+ - Stale processes serve requests with wrong config
281
+ - Port conflicts cause silent failures
282
+ - Process accumulation slows system
283
+ - Confusing test results (hitting wrong server)
284
+ ```
285
+
286
+ **Trade-off analysis:**
287
+ - Adds boilerplate to prompts
288
+ - But prevents very confusing debugging
289
+ - Worth it for E2E test subagents
290
+
291
+ ---
292
+
293
+ ### 3. subagent-driven-development: Add Lean Context Option
294
+
295
+ **Modify Step 2: Execute Task with Subagent**
296
+
297
+ **Before:**
298
+ ```
299
+ Read that task carefully from [plan-file].
300
+ ```
301
+
302
+ **After:**
303
+ ```
304
+ ## Context Approaches
305
+
306
+ **Full Plan (default):**
307
+ Use when tasks are complex or have dependencies:
308
+ ```
309
+ Read Task N from [plan-file] carefully.
310
+ ```
311
+
312
+ **Lean Context (for independent tasks):**
313
+ Use when task is standalone and pattern-based:
314
+ ```
315
+ You are implementing: [1-2 sentence task description]
316
+
317
+ File to modify: [exact path]
318
+ Pattern to follow: [reference to existing function/test]
319
+ What to implement: [specific requirement]
320
+ Verification: [exact command to run]
321
+
322
+ [Do NOT include full plan file]
323
+ ```
324
+
325
+ **Use lean context when:**
326
+ - Task follows existing pattern (add similar test, implement similar feature)
327
+ - Task is self-contained (doesn't need context from other tasks)
328
+ - Pattern reference is sufficient (e.g., "follow TestE2E_FeatureOptionValidation")
329
+
330
+ **Use full plan when:**
331
+ - Task has dependencies on other tasks
332
+ - Requires understanding of overall architecture
333
+ - Complex logic that needs context
334
+ ```
335
+
336
+ **Example:**
337
+ ```
338
+ Lean context prompt:
339
+
340
+ "You are adding a test for privileged mode in devcontainer features.
341
+
342
+ File: pkg/runner/e2e_test.go
343
+ Pattern: Follow TestE2E_FeatureOptionValidation (at end of file)
344
+ Test: Feature with `"privileged": true` in metadata results in `--privileged` flag
345
+ Verify: go test -v ./pkg/runner -run TestE2E_FeaturePrivilegedMode -timeout 5m
346
+
347
+ Report: Implementation, test results, any issues."
348
+ ```
349
+
350
+ **Why this works:**
351
+ Reduces token usage, increases focus, faster completion when appropriate.
352
+
353
+ ---
354
+
355
+ ### 4. subagent-driven-development: Add Self-Reflection Step
356
+
357
+ **Modify Step 2: Execute Task with Subagent**
358
+
359
+ **Add to prompt template:**
360
+
361
+ ```
362
+ When done, BEFORE reporting back:
363
+
364
+ Take a step back and review your work with fresh eyes.
365
+
366
+ Ask yourself:
367
+ - Does this actually solve the task as specified?
368
+ - Are there edge cases I didn't consider?
369
+ - Did I follow the pattern correctly?
370
+ - If tests are failing, what's the ROOT CAUSE (implementation bug vs test bug)?
371
+ - What could be better about this implementation?
372
+
373
+ If you identify issues during this reflection, fix them now.
374
+
375
+ Then report:
376
+ - What you implemented
377
+ - Self-reflection findings (if any)
378
+ - Test results
379
+ - Files changed
380
+ ```
381
+
382
+ **Why this works:**
383
+ Catches bugs implementer can find themselves before handoff. Documented case: identified entrypoint bug through self-reflection.
384
+
385
+ **Trade-off:**
386
+ Adds ~30 seconds per task, but catches issues before review.
387
+
388
+ ---
389
+
390
+ ### 5. requesting-code-review: Add Explicit File Reading
391
+
392
+ **Modify the code-reviewer template:**
393
+
394
+ **Add at the beginning:**
395
+
396
+ ```markdown
397
+ ## Files to Review
398
+
399
+ BEFORE analyzing, read these files:
400
+
401
+ 1. [List specific files that changed in the diff]
402
+ 2. [Files referenced by changes but not modified]
403
+
404
+ Use Read tool to load each file.
405
+
406
+ If you cannot find a file:
407
+ - Check exact path from diff
408
+ - Try alternate locations
409
+ - Report: "Cannot locate [path] - please verify file exists"
410
+
411
+ DO NOT proceed with review until you've read the actual code.
412
+ ```
413
+
414
+ **Why this works:**
415
+ Explicit instruction prevents "file not found" issues.
416
+
417
+ ---
418
+
419
+ ### 6. testing-anti-patterns: Add Mock-Interface Drift Anti-Pattern
420
+
421
+ **Add new Anti-Pattern 6:**
422
+
423
+ ```markdown
424
+ ## Anti-Pattern 6: Mocks Derived from Implementation
425
+
426
+ **The violation:**
427
+ ```typescript
428
+ // Code (BUGGY) calls cleanup()
429
+ await adapter.cleanup();
430
+
431
+ // Mock (MATCHES BUG) has cleanup()
432
+ const mock = {
433
+ cleanup: vi.fn().mockResolvedValue(undefined)
434
+ };
435
+
436
+ // Interface (CORRECT) defines close()
437
+ interface PlatformAdapter {
438
+ close(): Promise<void>;
439
+ }
440
+ ```
441
+
442
+ **Why this is wrong:**
443
+ - Mock encodes the bug into the test
444
+ - TypeScript can't catch inline mocks with wrong method names
445
+ - Test passes because both code and mock are wrong
446
+ - Runtime crashes when real object is used
447
+
448
+ **The fix:**
449
+ ```typescript
450
+ // ✅ GOOD: Derive mock from interface
451
+
452
+ // Step 1: Open interface definition (PlatformAdapter)
453
+ // Step 2: List methods defined there (close, initialize, etc.)
454
+ // Step 3: Mock EXACTLY those methods
455
+
456
+ const mock = {
457
+ initialize: vi.fn().mockResolvedValue(undefined),
458
+ close: vi.fn().mockResolvedValue(undefined), // From interface!
459
+ };
460
+
461
+ // Now test FAILS because code calls cleanup() which doesn't exist
462
+ // That failure reveals the bug BEFORE runtime
463
+ ```
464
+
465
+ ### Gate Function
466
+
467
+ ```
468
+ BEFORE writing any mock:
469
+
470
+ 1. STOP - Do NOT look at the code under test yet
471
+ 2. FIND: The interface/type definition for the dependency
472
+ 3. READ: The interface file
473
+ 4. LIST: Methods defined in the interface
474
+ 5. MOCK: ONLY those methods with EXACTLY those names
475
+ 6. DO NOT: Look at what your code calls
476
+
477
+ IF your test fails because code calls something not in mock:
478
+ ✅ GOOD - The test found a bug in your code
479
+ Fix the code to call the correct interface method
480
+ NOT the mock
481
+
482
+ Red flags:
483
+ - "I'll mock what the code calls"
484
+ - Copying method names from implementation
485
+ - Mock written without reading interface
486
+ - "The test is failing so I'll add this method to the mock"
487
+ ```
488
+
489
+ **Detection:**
490
+
491
+ When you see runtime error "X is not a function" and tests pass:
492
+ 1. Check if X is mocked
493
+ 2. Compare mock methods to interface methods
494
+ 3. Look for method name mismatches
495
+ ```
496
+
497
+ **Why this works:**
498
+ Directly addresses the failure pattern from feedback.
499
+
500
+ ---
501
+
502
+ ### 7. subagent-driven-development: Require Skills Reading for Test Subagents
503
+
504
+ **Add to prompt template when task involves testing:**
505
+
506
+ ```markdown
507
+ BEFORE writing any tests:
508
+
509
+ 1. Read testing-anti-patterns skill:
510
+ Use Skill tool: superpowers:testing-anti-patterns
511
+
512
+ 2. Apply gate functions from that skill when:
513
+ - Writing mocks
514
+ - Adding methods to production classes
515
+ - Mocking dependencies
516
+
517
+ This is NOT optional. Tests that violate anti-patterns will be rejected in review.
518
+ ```
519
+
520
+ **Why this works:**
521
+ Ensures skills are actually used, not just exist.
522
+
523
+ **Trade-off:**
524
+ Adds time to each task, but prevents entire classes of bugs.
525
+
526
+ ---
527
+
528
+ ### 8. subagent-driven-development: Allow Implementer to Fix Self-Identified Issues
529
+
530
+ **Modify Step 2:**
531
+
532
+ **Current:**
533
+ ```
534
+ Subagent reports back with summary of work.
535
+ ```
536
+
537
+ **Proposed:**
538
+ ```
539
+ Subagent performs self-reflection, then:
540
+
541
+ IF self-reflection identifies fixable issues:
542
+ 1. Fix the issues
543
+ 2. Re-run verification
544
+ 3. Report: "Initial implementation + self-reflection fix"
545
+
546
+ ELSE:
547
+ Report: "Implementation complete"
548
+
549
+ Include in report:
550
+ - Self-reflection findings
551
+ - Whether fixes were applied
552
+ - Final verification results
553
+ ```
554
+
555
+ **Why this works:**
556
+ Reduces latency when implementer already knows the fix. Documented case: would have saved one round-trip for entrypoint bug.
557
+
558
+ **Trade-off:**
559
+ Slightly more complex prompt, but faster end-to-end.
560
+
561
+ ---
562
+
563
+ ## Implementation Plan
564
+
565
+ ### Phase 1: High-Impact, Low-Risk (Do First)
566
+
567
+ 1. **verification-before-completion: Configuration change verification**
568
+ - Clear addition, doesn't change existing content
569
+ - Addresses high-impact problem (false confidence in tests)
570
+ - File: `skills/verification-before-completion/SKILL.md`
571
+
572
+ 2. **testing-anti-patterns: Mock-interface drift**
573
+ - Adds new anti-pattern, doesn't modify existing
574
+ - Addresses high-impact problem (runtime crashes)
575
+ - File: `skills/testing-anti-patterns/SKILL.md`
576
+
577
+ 3. **requesting-code-review: Explicit file reading**
578
+ - Simple addition to template
579
+ - Fixes concrete problem (reviewers can't find files)
580
+ - File: `skills/requesting-code-review/SKILL.md`
581
+
582
+ ### Phase 2: Moderate Changes (Test Carefully)
583
+
584
+ 4. **subagent-driven-development: Process hygiene**
585
+ - Adds new section, doesn't change workflow
586
+ - Addresses medium-high impact (test reliability)
587
+ - File: `skills/subagent-driven-development/SKILL.md`
588
+
589
+ 5. **subagent-driven-development: Self-reflection**
590
+ - Changes prompt template (higher risk)
591
+ - But documented to catch bugs
592
+ - File: `skills/subagent-driven-development/SKILL.md`
593
+
594
+ 6. **subagent-driven-development: Skills reading requirement**
595
+ - Adds prompt overhead
596
+ - But ensures skills are actually used
597
+ - File: `skills/subagent-driven-development/SKILL.md`
598
+
599
+ ### Phase 3: Optimization (Validate First)
600
+
601
+ 7. **subagent-driven-development: Lean context option**
602
+ - Adds complexity (two approaches)
603
+ - Needs validation that it doesn't cause confusion
604
+ - File: `skills/subagent-driven-development/SKILL.md`
605
+
606
+ 8. **subagent-driven-development: Allow implementer to fix**
607
+ - Changes workflow (higher risk)
608
+ - Optimization, not bug fix
609
+ - File: `skills/subagent-driven-development/SKILL.md`
610
+
611
+ ---
612
+
613
+ ## Open Questions
614
+
615
+ 1. **Lean context approach:**
616
+ - Should we make it the default for pattern-based tasks?
617
+ - How do we decide which approach to use?
618
+ - Risk of being too lean and missing important context?
619
+
620
+ 2. **Self-reflection:**
621
+ - Will this slow down simple tasks significantly?
622
+ - Should it only apply to complex tasks?
623
+ - How do we prevent "reflection fatigue" where it becomes rote?
624
+
625
+ 3. **Process hygiene:**
626
+ - Should this be in subagent-driven-development or a separate skill?
627
+ - Does it apply to other workflows beyond E2E tests?
628
+ - How do we handle cases where process SHOULD persist (dev servers)?
629
+
630
+ 4. **Skills reading enforcement:**
631
+ - Should we require ALL subagents to read relevant skills?
632
+ - How do we keep prompts from becoming too long?
633
+ - Risk of over-documenting and losing focus?
634
+
635
+ ---
636
+
637
+ ## Success Metrics
638
+
639
+ How do we know these improvements work?
640
+
641
+ 1. **Configuration verification:**
642
+ - Zero instances of "test passed but wrong config was used"
643
+ - Jesse doesn't say "that's not actually testing what you think"
644
+
645
+ 2. **Process hygiene:**
646
+ - Zero instances of "test hit wrong server"
647
+ - No port conflict errors during E2E test runs
648
+
649
+ 3. **Mock-interface drift:**
650
+ - Zero instances of "tests pass but runtime crashes on missing method"
651
+ - No method name mismatches between mocks and interfaces
652
+
653
+ 4. **Self-reflection:**
654
+ - Measurable: Do implementer reports include self-reflection findings?
655
+ - Qualitative: Do fewer bugs make it to code review?
656
+
657
+ 5. **Skills reading:**
658
+ - Subagent reports reference skill gate functions
659
+ - Fewer anti-pattern violations in code review
660
+
661
+ ---
662
+
663
+ ## Risks and Mitigations
664
+
665
+ ### Risk: Prompt Bloat
666
+ **Problem:** Adding all these requirements makes prompts overwhelming
667
+ **Mitigation:**
668
+ - Phase implementation (don't add everything at once)
669
+ - Make some additions conditional (E2E hygiene only for E2E tests)
670
+ - Consider templates for different task types
671
+
672
+ ### Risk: Analysis Paralysis
673
+ **Problem:** Too much reflection/verification slows execution
674
+ **Mitigation:**
675
+ - Keep gate functions quick (seconds, not minutes)
676
+ - Make lean context opt-in initially
677
+ - Monitor task completion times
678
+
679
+ ### Risk: False Sense of Security
680
+ **Problem:** Following checklist doesn't guarantee correctness
681
+ **Mitigation:**
682
+ - Emphasize gate functions are minimums, not maximums
683
+ - Keep "use judgment" language in skills
684
+ - Document that skills catch common failures, not all failures
685
+
686
+ ### Risk: Skill Divergence
687
+ **Problem:** Different skills give conflicting advice
688
+ **Mitigation:**
689
+ - Review changes across all skills for consistency
690
+ - Document how skills interact (Integration sections)
691
+ - Test with real scenarios before deployment
692
+
693
+ ---
694
+
695
+ ## Recommendation
696
+
697
+ **Proceed with Phase 1 immediately:**
698
+ - verification-before-completion: Configuration change verification
699
+ - testing-anti-patterns: Mock-interface drift
700
+ - requesting-code-review: Explicit file reading
701
+
702
+ **Test Phase 2 with Jesse before finalizing:**
703
+ - Get feedback on self-reflection impact
704
+ - Validate process hygiene approach
705
+ - Confirm skills reading requirement is worth overhead
706
+
707
+ **Hold Phase 3 pending validation:**
708
+ - Lean context needs real-world testing
709
+ - Implementer-fix workflow change needs careful evaluation
710
+
711
+ These changes address real problems documented by users while minimizing risk of making skills worse.
github_code/obra__superpowers/docs/plans/2026-01-17-visual-brainstorming.md ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Brainstorming Companion Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4
+
5
+ **Goal:** Give Claude a browser-based visual companion for brainstorming sessions - show mockups, prototypes, and interactive choices alongside terminal conversation.
6
+
7
+ **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.
8
+
9
+ **Tech Stack:** Node.js, Express, ws (WebSocket), chokidar (file watching)
10
+
11
+ ---
12
+
13
+ ## Task 1: Create the Server Foundation
14
+
15
+ **Files:**
16
+ - Create: `lib/brainstorm-server/index.js`
17
+ - Create: `lib/brainstorm-server/package.json`
18
+
19
+ **Step 1: Create package.json**
20
+
21
+ ```json
22
+ {
23
+ "name": "brainstorm-server",
24
+ "version": "1.0.0",
25
+ "description": "Visual brainstorming companion server for Claude Code",
26
+ "main": "index.js",
27
+ "dependencies": {
28
+ "chokidar": "^3.5.3",
29
+ "express": "^4.18.2",
30
+ "ws": "^8.14.2"
31
+ }
32
+ }
33
+ ```
34
+
35
+ **Step 2: Create minimal server that starts**
36
+
37
+ ```javascript
38
+ const express = require('express');
39
+ const http = require('http');
40
+ const WebSocket = require('ws');
41
+ const chokidar = require('chokidar');
42
+ const fs = require('fs');
43
+ const path = require('path');
44
+
45
+ const PORT = process.env.BRAINSTORM_PORT || 3333;
46
+ const SCREEN_FILE = process.env.BRAINSTORM_SCREEN || '/tmp/brainstorm/screen.html';
47
+ const SCREEN_DIR = path.dirname(SCREEN_FILE);
48
+
49
+ // Ensure screen directory exists
50
+ if (!fs.existsSync(SCREEN_DIR)) {
51
+ fs.mkdirSync(SCREEN_DIR, { recursive: true });
52
+ }
53
+
54
+ // Create default screen if none exists
55
+ if (!fs.existsSync(SCREEN_FILE)) {
56
+ fs.writeFileSync(SCREEN_FILE, `<!DOCTYPE html>
57
+ <html>
58
+ <head>
59
+ <title>Brainstorm Companion</title>
60
+ <style>
61
+ body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
62
+ h1 { color: #333; }
63
+ p { color: #666; }
64
+ </style>
65
+ </head>
66
+ <body>
67
+ <h1>Brainstorm Companion</h1>
68
+ <p>Waiting for Claude to push a screen...</p>
69
+ </body>
70
+ </html>`);
71
+ }
72
+
73
+ const app = express();
74
+ const server = http.createServer(app);
75
+ const wss = new WebSocket.Server({ server });
76
+
77
+ // Track connected browsers for reload notifications
78
+ const clients = new Set();
79
+
80
+ wss.on('connection', (ws) => {
81
+ clients.add(ws);
82
+ ws.on('close', () => clients.delete(ws));
83
+
84
+ ws.on('message', (data) => {
85
+ // User interaction event - write to stdout for Claude
86
+ const event = JSON.parse(data.toString());
87
+ console.log(JSON.stringify({ type: 'user-event', ...event }));
88
+ });
89
+ });
90
+
91
+ // Serve current screen with helper.js injected
92
+ app.get('/', (req, res) => {
93
+ let html = fs.readFileSync(SCREEN_FILE, 'utf-8');
94
+
95
+ // Inject helper script before </body>
96
+ const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
97
+ const injection = `<script>\n${helperScript}\n</script>`;
98
+
99
+ if (html.includes('</body>')) {
100
+ html = html.replace('</body>', `${injection}\n</body>`);
101
+ } else {
102
+ html += injection;
103
+ }
104
+
105
+ res.type('html').send(html);
106
+ });
107
+
108
+ // Watch for screen file changes
109
+ chokidar.watch(SCREEN_FILE).on('change', () => {
110
+ console.log(JSON.stringify({ type: 'screen-updated', file: SCREEN_FILE }));
111
+ // Notify all browsers to reload
112
+ clients.forEach(ws => {
113
+ if (ws.readyState === WebSocket.OPEN) {
114
+ ws.send(JSON.stringify({ type: 'reload' }));
115
+ }
116
+ });
117
+ });
118
+
119
+ server.listen(PORT, '127.0.0.1', () => {
120
+ console.log(JSON.stringify({ type: 'server-started', port: PORT, url: `http://localhost:${PORT}` }));
121
+ });
122
+ ```
123
+
124
+ **Step 3: Run npm install**
125
+
126
+ Run: `cd lib/brainstorm-server && npm install`
127
+ Expected: Dependencies installed
128
+
129
+ **Step 4: Test server starts**
130
+
131
+ Run: `cd lib/brainstorm-server && timeout 3 node index.js || true`
132
+ Expected: See JSON with `server-started` and port info
133
+
134
+ **Step 5: Commit**
135
+
136
+ ```bash
137
+ git add lib/brainstorm-server/
138
+ git commit -m "feat: add brainstorm server foundation"
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Task 2: Create the Helper Library
144
+
145
+ **Files:**
146
+ - Create: `lib/brainstorm-server/helper.js`
147
+
148
+ **Step 1: Create helper.js with event auto-capture**
149
+
150
+ ```javascript
151
+ (function() {
152
+ const WS_URL = 'ws://' + window.location.host;
153
+ let ws = null;
154
+ let eventQueue = [];
155
+
156
+ function connect() {
157
+ ws = new WebSocket(WS_URL);
158
+
159
+ ws.onopen = () => {
160
+ // Send any queued events
161
+ eventQueue.forEach(e => ws.send(JSON.stringify(e)));
162
+ eventQueue = [];
163
+ };
164
+
165
+ ws.onmessage = (msg) => {
166
+ const data = JSON.parse(msg.data);
167
+ if (data.type === 'reload') {
168
+ window.location.reload();
169
+ }
170
+ };
171
+
172
+ ws.onclose = () => {
173
+ // Reconnect after 1 second
174
+ setTimeout(connect, 1000);
175
+ };
176
+ }
177
+
178
+ function send(event) {
179
+ event.timestamp = Date.now();
180
+ if (ws && ws.readyState === WebSocket.OPEN) {
181
+ ws.send(JSON.stringify(event));
182
+ } else {
183
+ eventQueue.push(event);
184
+ }
185
+ }
186
+
187
+ // Auto-capture clicks on interactive elements
188
+ document.addEventListener('click', (e) => {
189
+ const target = e.target.closest('button, a, [data-choice], [role="button"], input[type="submit"]');
190
+ if (!target) return;
191
+
192
+ // Don't capture regular link navigation
193
+ if (target.tagName === 'A' && !target.dataset.choice) return;
194
+
195
+ e.preventDefault();
196
+
197
+ send({
198
+ type: 'click',
199
+ text: target.textContent.trim(),
200
+ choice: target.dataset.choice || null,
201
+ id: target.id || null,
202
+ className: target.className || null
203
+ });
204
+ });
205
+
206
+ // Auto-capture form submissions
207
+ document.addEventListener('submit', (e) => {
208
+ e.preventDefault();
209
+ const form = e.target;
210
+ const formData = new FormData(form);
211
+ const data = {};
212
+ formData.forEach((value, key) => { data[key] = value; });
213
+
214
+ send({
215
+ type: 'submit',
216
+ formId: form.id || null,
217
+ formName: form.name || null,
218
+ data: data
219
+ });
220
+ });
221
+
222
+ // Auto-capture input changes (debounced)
223
+ let inputTimeout = null;
224
+ document.addEventListener('input', (e) => {
225
+ const target = e.target;
226
+ if (!target.matches('input, textarea, select')) return;
227
+
228
+ clearTimeout(inputTimeout);
229
+ inputTimeout = setTimeout(() => {
230
+ send({
231
+ type: 'input',
232
+ name: target.name || null,
233
+ id: target.id || null,
234
+ value: target.value,
235
+ inputType: target.type || target.tagName.toLowerCase()
236
+ });
237
+ }, 500); // 500ms debounce
238
+ });
239
+
240
+ // Expose for explicit use if needed
241
+ window.brainstorm = {
242
+ send: send,
243
+ choice: (value, metadata = {}) => send({ type: 'choice', value, ...metadata })
244
+ };
245
+
246
+ connect();
247
+ })();
248
+ ```
249
+
250
+ **Step 2: Verify helper.js is syntactically valid**
251
+
252
+ Run: `node -c lib/brainstorm-server/helper.js`
253
+ Expected: No syntax errors
254
+
255
+ **Step 3: Commit**
256
+
257
+ ```bash
258
+ git add lib/brainstorm-server/helper.js
259
+ git commit -m "feat: add browser helper library for event capture"
260
+ ```
261
+
262
+ ---
263
+
264
+ ## Task 3: Write Tests for the Server
265
+
266
+ **Files:**
267
+ - Create: `tests/brainstorm-server/server.test.js`
268
+ - Create: `tests/brainstorm-server/package.json`
269
+
270
+ **Step 1: Create test package.json**
271
+
272
+ ```json
273
+ {
274
+ "name": "brainstorm-server-tests",
275
+ "version": "1.0.0",
276
+ "scripts": {
277
+ "test": "node server.test.js"
278
+ }
279
+ }
280
+ ```
281
+
282
+ **Step 2: Write server tests**
283
+
284
+ ```javascript
285
+ const { spawn } = require('child_process');
286
+ const http = require('http');
287
+ const WebSocket = require('ws');
288
+ const fs = require('fs');
289
+ const path = require('path');
290
+ const assert = require('assert');
291
+
292
+ const SERVER_PATH = path.join(__dirname, '../../lib/brainstorm-server/index.js');
293
+ const TEST_PORT = 3334;
294
+ const TEST_SCREEN = '/tmp/brainstorm-test/screen.html';
295
+
296
+ // Clean up test directory
297
+ function cleanup() {
298
+ if (fs.existsSync(path.dirname(TEST_SCREEN))) {
299
+ fs.rmSync(path.dirname(TEST_SCREEN), { recursive: true });
300
+ }
301
+ }
302
+
303
+ async function sleep(ms) {
304
+ return new Promise(resolve => setTimeout(resolve, ms));
305
+ }
306
+
307
+ async function fetch(url) {
308
+ return new Promise((resolve, reject) => {
309
+ http.get(url, (res) => {
310
+ let data = '';
311
+ res.on('data', chunk => data += chunk);
312
+ res.on('end', () => resolve({ status: res.statusCode, body: data }));
313
+ }).on('error', reject);
314
+ });
315
+ }
316
+
317
+ async function runTests() {
318
+ cleanup();
319
+
320
+ // Start server
321
+ const server = spawn('node', [SERVER_PATH], {
322
+ env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_SCREEN: TEST_SCREEN }
323
+ });
324
+
325
+ let stdout = '';
326
+ server.stdout.on('data', (data) => { stdout += data.toString(); });
327
+ server.stderr.on('data', (data) => { console.error('Server stderr:', data.toString()); });
328
+
329
+ await sleep(1000); // Wait for server to start
330
+
331
+ try {
332
+ // Test 1: Server starts and outputs JSON
333
+ console.log('Test 1: Server startup message');
334
+ assert(stdout.includes('server-started'), 'Should output server-started');
335
+ assert(stdout.includes(TEST_PORT.toString()), 'Should include port');
336
+ console.log(' PASS');
337
+
338
+ // Test 2: GET / returns HTML with helper injected
339
+ console.log('Test 2: Serves HTML with helper injected');
340
+ const res = await fetch(`http://localhost:${TEST_PORT}/`);
341
+ assert.strictEqual(res.status, 200);
342
+ assert(res.body.includes('brainstorm'), 'Should include brainstorm content');
343
+ assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
344
+ console.log(' PASS');
345
+
346
+ // Test 3: WebSocket connection and event relay
347
+ console.log('Test 3: WebSocket relays events to stdout');
348
+ stdout = ''; // Reset stdout capture
349
+ const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
350
+ await new Promise(resolve => ws.on('open', resolve));
351
+
352
+ ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
353
+ await sleep(100);
354
+
355
+ assert(stdout.includes('user-event'), 'Should relay user events');
356
+ assert(stdout.includes('Test Button'), 'Should include event data');
357
+ ws.close();
358
+ console.log(' PASS');
359
+
360
+ // Test 4: File change triggers reload notification
361
+ console.log('Test 4: File change notifies browsers');
362
+ const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);
363
+ await new Promise(resolve => ws2.on('open', resolve));
364
+
365
+ let gotReload = false;
366
+ ws2.on('message', (data) => {
367
+ const msg = JSON.parse(data.toString());
368
+ if (msg.type === 'reload') gotReload = true;
369
+ });
370
+
371
+ // Modify the screen file
372
+ fs.writeFileSync(TEST_SCREEN, '<html><body>Updated</body></html>');
373
+ await sleep(500);
374
+
375
+ assert(gotReload, 'Should send reload message on file change');
376
+ ws2.close();
377
+ console.log(' PASS');
378
+
379
+ console.log('\nAll tests passed!');
380
+
381
+ } finally {
382
+ server.kill();
383
+ cleanup();
384
+ }
385
+ }
386
+
387
+ runTests().catch(err => {
388
+ console.error('Test failed:', err);
389
+ process.exit(1);
390
+ });
391
+ ```
392
+
393
+ **Step 3: Run tests**
394
+
395
+ Run: `cd tests/brainstorm-server && npm install ws && node server.test.js`
396
+ Expected: All tests pass
397
+
398
+ **Step 4: Commit**
399
+
400
+ ```bash
401
+ git add tests/brainstorm-server/
402
+ git commit -m "test: add brainstorm server integration tests"
403
+ ```
404
+
405
+ ---
406
+
407
+ ## Task 4: Add Visual Companion to Brainstorming Skill
408
+
409
+ **Files:**
410
+ - Modify: `skills/brainstorming/SKILL.md`
411
+ - Create: `skills/brainstorming/visual-companion.md` (supporting doc)
412
+
413
+ **Step 1: Create the supporting documentation**
414
+
415
+ Create `skills/brainstorming/visual-companion.md`:
416
+
417
+ ```markdown
418
+ # Visual Companion Reference
419
+
420
+ ## Starting the Server
421
+
422
+ Run as a background job:
423
+
424
+ ```bash
425
+ node ${PLUGIN_ROOT}/lib/brainstorm-server/index.js
426
+ ```
427
+
428
+ Tell the user: "I've started a visual companion at http://localhost:3333 - open it in a browser."
429
+
430
+ ## Pushing Screens
431
+
432
+ Write HTML to `/tmp/brainstorm/screen.html`. The server watches this file and auto-refreshes the browser.
433
+
434
+ ## Reading User Responses
435
+
436
+ Check the background task output for JSON events:
437
+
438
+ ```json
439
+ {"type":"user-event","type":"click","text":"Option A","choice":"optionA","timestamp":1234567890}
440
+ {"type":"user-event","type":"submit","data":{"notes":"My feedback"},"timestamp":1234567891}
441
+ ```
442
+
443
+ Event types:
444
+ - **click**: User clicked button or `data-choice` element
445
+ - **submit**: User submitted form (includes all form data)
446
+ - **input**: User typed in field (debounced 500ms)
447
+
448
+ ## HTML Patterns
449
+
450
+ ### Choice Cards
451
+
452
+ ```html
453
+ <div class="options">
454
+ <button data-choice="optionA">
455
+ <h3>Option A</h3>
456
+ <p>Description</p>
457
+ </button>
458
+ <button data-choice="optionB">
459
+ <h3>Option B</h3>
460
+ <p>Description</p>
461
+ </button>
462
+ </div>
463
+ ```
464
+
465
+ ### Interactive Mockup
466
+
467
+ ```html
468
+ <div class="mockup">
469
+ <header data-choice="header">App Header</header>
470
+ <nav data-choice="nav">Navigation</nav>
471
+ <main data-choice="main">Content</main>
472
+ </div>
473
+ ```
474
+
475
+ ### Form with Notes
476
+
477
+ ```html
478
+ <form>
479
+ <label>Priority: <input type="range" name="priority" min="1" max="5"></label>
480
+ <textarea name="notes" placeholder="Additional thoughts..."></textarea>
481
+ <button type="submit">Submit</button>
482
+ </form>
483
+ ```
484
+
485
+ ### Explicit JavaScript
486
+
487
+ ```html
488
+ <button onclick="brainstorm.choice('custom', {extra: 'data'})">Custom</button>
489
+ ```
490
+ ```
491
+
492
+ **Step 2: Add visual companion section to brainstorming skill**
493
+
494
+ Add after "Key Principles" in `skills/brainstorming/SKILL.md`:
495
+
496
+ ```markdown
497
+
498
+ ## Visual Companion (Optional)
499
+
500
+ When brainstorming involves visual elements - UI mockups, wireframes, interactive prototypes - use the browser-based visual companion.
501
+
502
+ **When to use:**
503
+ - Presenting UI/UX options that benefit from visual comparison
504
+ - Showing wireframes or layout options
505
+ - Gathering structured feedback (ratings, forms)
506
+ - Prototyping click interactions
507
+
508
+ **How it works:**
509
+ 1. Start the server as a background job
510
+ 2. Tell user to open http://localhost:3333
511
+ 3. Write HTML to `/tmp/brainstorm/screen.html` (auto-refreshes)
512
+ 4. Check background task output for user interactions
513
+
514
+ The terminal remains the primary conversation interface. The browser is a visual aid.
515
+
516
+ **Reference:** See `visual-companion.md` in this skill directory for HTML patterns and API details.
517
+ ```
518
+
519
+ **Step 3: Verify the edits**
520
+
521
+ Run: `grep -A5 "Visual Companion" skills/brainstorming/SKILL.md`
522
+ Expected: Shows the new section
523
+
524
+ **Step 4: Commit**
525
+
526
+ ```bash
527
+ git add skills/brainstorming/
528
+ git commit -m "feat: add visual companion to brainstorming skill"
529
+ ```
530
+
531
+ ---
532
+
533
+ ## Task 5: Add Server to Plugin Ignore (Optional Cleanup)
534
+
535
+ **Files:**
536
+ - Check if `.gitignore` needs node_modules exclusion for lib/brainstorm-server
537
+
538
+ **Step 1: Check current gitignore**
539
+
540
+ Run: `cat .gitignore 2>/dev/null || echo "No .gitignore"`
541
+
542
+ **Step 2: Add node_modules if needed**
543
+
544
+ If not already present, add:
545
+ ```
546
+ lib/brainstorm-server/node_modules/
547
+ ```
548
+
549
+ **Step 3: Commit if changed**
550
+
551
+ ```bash
552
+ git add .gitignore
553
+ git commit -m "chore: ignore brainstorm-server node_modules"
554
+ ```
555
+
556
+ ---
557
+
558
+ ## Summary
559
+
560
+ After completing all tasks:
561
+
562
+ 1. **Server** at `lib/brainstorm-server/` - Node.js server that watches HTML file and relays events
563
+ 2. **Helper library** auto-injected - captures clicks, forms, inputs
564
+ 3. **Tests** at `tests/brainstorm-server/` - verifies server behavior
565
+ 4. **Brainstorming skill** updated with visual companion section and `visual-companion.md` reference doc
566
+
567
+ **To use:**
568
+ 1. Start server as background job: `node lib/brainstorm-server/index.js &`
569
+ 2. Tell user to open `http://localhost:3333`
570
+ 3. Write HTML to `/tmp/brainstorm/screen.html`
571
+ 4. Check task output for user events
github_code/obra__superpowers/docs/porting-to-a-new-harness.md ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Porting Superpowers to a New Harness
2
+
3
+ This guide explains how to add support for a new harness — an IDE, CLI, or
4
+ agent runner that isn't Claude Code — so that Superpowers skills auto-trigger
5
+ there the same way they do natively.
6
+
7
+ It is written in two layers. **Part 1–3** explain how the system works and how
8
+ to tell whether a harness can be supported at all; read these before you touch
9
+ anything. **Part 4–8** are a prescriptive procedure for an agent (supervised by
10
+ a human partner) to execute the port end to end, through distribution. An
11
+ appendix indexes the current reference integrations so you can copy the closest
12
+ one.
13
+
14
+ The integration mechanism differs across harnesses, and it will keep changing.
15
+ This guide deliberately teaches the **invariants** — the things that must be
16
+ true no matter the mechanism — and points you at a live reference implementation
17
+ to copy. When this guide and the code disagree, the code wins; fix the guide.
18
+
19
+ ## Before you start
20
+
21
+ Adding a harness is the highest-stakes contribution type in this repo. Before
22
+ writing anything:
23
+
24
+ - Read `CLAUDE.md` and `.github/PULL_REQUEST_TEMPLATE.md` in full — the
25
+ contributor rules and the new-harness PR requirements are not optional.
26
+ - Search open **and closed** PRs for a prior attempt at this harness. If one
27
+ exists, understand why it stalled before starting your own.
28
+
29
+ ---
30
+
31
+ ## Part 1 — How Superpowers works across harnesses
32
+
33
+ Superpowers is the same content everywhere. What changes per harness is the thin
34
+ layer that delivers that content to the model and translates its instructions
35
+ into the harness's native tools. Three components:
36
+
37
+ 1. **Skills (harness-agnostic).** Everything in `skills/` is the source of
38
+ truth, shared verbatim by every harness. Skills are written to describe
39
+ *actions* — "invoke a skill", "read a file", "dispatch a subagent", "create a
40
+ todo" — and never name a specific tool. This is what lets one skill body run
41
+ on Claude Code, Codex, Gemini, pi, and the rest without edits.
42
+
43
+ 2. **Tool mapping (per-harness).** Each harness needs the action vocabulary
44
+ translated into its real tool names. That translation lives in
45
+ `skills/using-superpowers/references/<harness>-tools.md` and/or inline in the
46
+ harness's bootstrap injector (see Part 5). It says, e.g., "*dispatch a
47
+ subagent* → call `task` with `subagent_type`."
48
+
49
+ 3. **Bootstrap (per-harness).** At the start of every session, the full
50
+ `skills/using-superpowers/SKILL.md` is injected into the model's context,
51
+ wrapped in `<EXTREMELY_IMPORTANT>` tags, with the tool mapping appended. That
52
+ injected skill is what teaches the model that skills exist and that it must
53
+ check for a relevant skill before acting. **The bootstrap is the entire
54
+ integration.** Without it, the skill files are inert — present on disk, never
55
+ invoked.
56
+
57
+ ### Two rules that make this work
58
+
59
+ **1. Skills name actions, not tools.** Do **not** edit skill bodies to fit your
60
+ harness. Porting adds a tool-mapping reference and a bootstrap injector; it
61
+ never reaches into `skills/*/SKILL.md` to swap tool names. (The project's
62
+ contributor guidelines treat skill content as carefully-tuned behavior-shaping
63
+ code; rewording it for "compliance" is rejected on sight.)
64
+
65
+ **2. Everything ships through the harness's own install mechanism. Never edit the
66
+ user's files.** The bootstrap, the skills, and the tool mapping all get delivered
67
+ *as part of what the harness installs* — a plugin, an extension, a marketplace
68
+ entry, an extension-bundled context file. A port **must not** reach into a user's
69
+ global or personal config (`~/.gemini/config/AGENTS.md`, `settings.json`,
70
+ `trustedFolders.json`, a hand-edited `~/.bashrc`, etc.) to inject anything. The
71
+ harness owns what it loads; your install artifact is the only thing you get to
72
+ write. If the install mechanism genuinely can't carry the bootstrap, that is a
73
+ limitation to surface (Part 6) — never a license to hand-edit the user's config.
74
+ (Shape C is *not* an exception: Gemini's context file is fine because it ships
75
+ *inside the installed extension* and is declared by the manifest's
76
+ `contextFileName` — the harness loads the extension's own file, not a file you
77
+ edited in the user's home.)
78
+
79
+ ---
80
+
81
+ ## Part 2 — Can this harness be supported?
82
+
83
+ A harness can support Superpowers only if it can do all of the following. Check
84
+ these before writing code — if the first one fails, stop.
85
+
86
+ ### Hard requirement: automatic session-start injection
87
+
88
+ The harness must let you inject text into the model's context **at the start of
89
+ every session, with no per-session opt-in by your human partner.** This is the
90
+ one non-negotiable capability. It can take any form:
91
+
92
+ - a **hook/event system** that runs a shell command at session start and reads
93
+ its stdout (Claude Code, Cursor, Copilot CLI), or
94
+ - an **in-process plugin/extension** with a session-start or message lifecycle
95
+ callback that can mutate the message array (OpenCode, pi), or
96
+ - an **instructions-file** convention where the harness loads a context file that
97
+ *your installed extension ships and declares* (e.g. Gemini's `contextFileName`
98
+ pointing at the extension's own `GEMINI.md`) — not a file you edit in the user's
99
+ home.
100
+
101
+ If the only way to get Superpowers in front of the model is for your human
102
+ partner to opt in each session (paste a prompt, run a command, enable a mode),
103
+ the harness
104
+ **cannot** be properly supported. The acceptance test in Part 3 will fail, and
105
+ the PR will be closed. This is the single most common reason a "port" isn't a
106
+ real port.
107
+
108
+ ### The rest of the capability checklist
109
+
110
+ | Capability | Why it's needed | If absent |
111
+ |---|---|---|
112
+ | **Skill discovery + invocation** | The model must be able to load a skill's full content on demand | If there's no native skill tool, the sanctioned fallback is to `read` the relevant `SKILL.md` directly — see Part 5. A harness with neither a skill tool nor file-read cannot work. |
113
+ | **File read / write / edit** | Nearly every skill manipulates files | Essential. No workaround. |
114
+ | **Run shell commands** | TDD, verification, git workflows | Essential. |
115
+ | **Subagent / task dispatch** | `dispatching-parallel-agents`, `subagent-driven-development` | Degradable: if unavailable, those specific skills tell the model to do the work inline or report the missing capability — *never* to invent a `Task` call. Some harnesses gate this behind a config flag (e.g. Codex needs multi-agent enabled). |
116
+ | **Todo / task tracking** | Progress tracking in several skills | Degradable: fall back to a plan file or `TODO.md`. |
117
+ | **Web fetch / search** | A few skills | Degradable. |
118
+ | **Shell or polyglot script execution (Windows)** | Only for the shell-hook shape, only if you want Windows support | See Part 7. In-process-plugin harnesses sidestep this entirely. |
119
+
120
+ "Degradable" means: the skill already has fallback wording for the missing
121
+ tool. Your job in the tool mapping is to point at the real tool when it exists
122
+ and reuse that fallback wording when it doesn't.
123
+
124
+ ### You may not need a new directory at all
125
+
126
+ Some "new harnesses" are really existing integrations under a different
127
+ installer. Factory's Droid, for example, consumes the Claude Code plugin via its
128
+ own `plugin install` command and needs no new files here. Before building,
129
+ check whether the harness can simply load an existing manifest. A port that adds
130
+ nothing to this repo but a paragraph in the README is a perfectly good outcome.
131
+
132
+ ---
133
+
134
+ ## Part 3 — Definition of done
135
+
136
+ A port is finished when **all** of these are true:
137
+
138
+ 1. The `using-superpowers` bootstrap loads at session start, every session, with
139
+ no per-session opt-in.
140
+ 2. A tool mapping exists for the harness (in
141
+ `references/<harness>-tools.md`, inline in the bootstrap, or both — per Part 5).
142
+ 3. Skills can actually be invoked — natively, or via the documented
143
+ read-`SKILL.md` fallback — and the model follows them.
144
+ 4. **The acceptance test passes.** In a clean session, the user message:
145
+
146
+ > Let's make a react todo list
147
+
148
+ auto-triggers the `brainstorming` skill *before any code is written*. Capture
149
+ the full transcript — the PR requires it.
150
+ 5. Tests cover the integration (Part 5) and pass.
151
+ 6. A real user can install it through the harness's own mechanism (not by
152
+ hand-copying files), and the version is tracked in `.version-bump.json` where
153
+ applicable (Part 6). Note that some installers rewrite or strip the manifest on
154
+ install (one drops it to just `{"name": …}`), so "the *installed* files report
155
+ the repo version" is not always achievable — track the version at the source
156
+ manifest and don't treat a rewritten installed manifest as a failure.
157
+
158
+ A quick smoke check before the full acceptance test: start a session and ask the
159
+ model to describe its superpowers. If the bootstrap injected, it knows it has
160
+ them. (OpenCode's install doc uses `opencode run --print-logs "hello" 2>&1 |
161
+ grep -i superpowers` for the same goal via a different mechanism — log-grep
162
+ rather than asking the model; the `2>&1` matters because logs go to stderr. Find
163
+ your harness's equivalent.)
164
+
165
+ ---
166
+
167
+ ## Part 4 — Choose your integration shape
168
+
169
+ There are three structural shapes, distinguished by *how you get the bootstrap
170
+ in front of the model*. Pick the one that matches what your harness exposes,
171
+ then copy that reference implementation. The shape determines almost everything
172
+ in Part 5 — the steps below branch on it.
173
+
174
+ ### How to tell which shape you have
175
+
176
+ Before routing, learn the harness's *actual* mechanism — and don't assume it's
177
+ well documented or that it behaves like whatever harness it forked from.
178
+
179
+ **Find the surface:**
180
+
181
+ - **Search the web for the harness's docs** (extension / plugin / hook / skill /
182
+ MCP / "context file" / "rules file"). Vendor tools change fast; search rather
183
+ than trust training knowledge.
184
+ - **Find and read an existing third-party extension/plugin for the harness.** A
185
+ real working example beats docs — it shows the manifest shape, the install
186
+ command, and which components the harness actually loads.
187
+ - Check what the harness loads at startup: a settings file? an extensions
188
+ directory? a per-project or global instructions file (`AGENTS.md`, `<NAME>.md`)?
189
+
190
+ **If it's underdocumented, reverse-engineer it empirically** (a real porter has
191
+ had to do every one of these):
192
+
193
+ - `strings` the binary / grep the install tree for hook event names, config
194
+ paths, and the instructions file it reads.
195
+ - **Ask the running model to enumerate its own tool names** — e.g. "list the
196
+ exact machine names of every tool you can call." This is the authoritative way
197
+ to get tool names without inventing them (see Step 4).
198
+ - Prove every assumption with a **unique-marker test**: inject a nonsense token
199
+ through the mechanism you think works, start a fresh session, and confirm the
200
+ token actually reached the model.
201
+
202
+ **A fork does not inherit its parent's behavior.** A harness derived from another
203
+ (e.g. a Gemini-derived CLI) may expose the parent's manifest fields and
204
+ `@`-include syntax and *still not honor them the same way*. Verify with a marker;
205
+ never assume the parent's recipe transfers.
206
+
207
+ Then route to a shape:
208
+
209
+ - Shell command at session start whose stdout is read → **Shape A**.
210
+ - Plugin/extension module with lifecycle callbacks you run code in → **Shape B**.
211
+ - Only ever an always-on instructions file, no hook and no code plugin →
212
+ **Shape C**.
213
+
214
+ **Shapes compose — they are not mutually exclusive.** The *skill-discovery*
215
+ mechanism and the *bootstrap* mechanism need not be the same shape — but **both
216
+ must still ride the install mechanism** (rule 2). Decide the two questions
217
+ separately: *where do skills get discovered?* and *how does the bootstrap reach
218
+ the model every session?* A harness might install skills via a plugin yet need
219
+ the bootstrap delivered another install-shipped way (an extension-declared
220
+ context file, or — see below — by the harness surfacing the installed
221
+ `using-superpowers` skill's own description at session start). If more than one
222
+ install-mechanism surface injects automatically, prefer the most reliable. What
223
+ you may **not** do is bridge a gap by editing the user's global config.
224
+
225
+ ### Shape A — Shell-hook
226
+
227
+ The harness has a hook system that runs a shell command at session start and
228
+ reads JSON from its stdout. The configured command runs `run-hook.cmd`, a
229
+ polyglot wrapper that just locates bash and dispatches the named script; the
230
+ script (`hooks/session-start`, or a harness-specific variant) is what reads
231
+ `using-superpowers/SKILL.md` and prints a JSON object whose **field name and
232
+ nesting differ per harness**.
233
+
234
+ - Reference: `hooks/session-start`, `hooks/run-hook.cmd`, and the per-harness
235
+ hook config `hooks/hooks.json` (Claude Code) and `hooks/hooks-cursor.json`
236
+ (Cursor).
237
+ - Manifests: `.cursor-plugin/plugin.json` is the Shape A manifest example that
238
+ points the harness at `./skills/` and the right `hooks-*.json`. Claude Code's
239
+ `.claude-plugin/plugin.json` sets neither field — it auto-discovers `skills/`
240
+ and `hooks/hooks.json` by convention. Do **not** copy Codex's
241
+ `.codex-plugin/plugin.json` for Shape A: it declares an empty `hooks` object
242
+ specifically to suppress Codex's `hooks/hooks.json` auto-discovery, because
243
+ Codex surfaces skills natively and runs no session-start hook.
244
+
245
+ > **A hook *system* is not a session-start *event*.** A harness can have a
246
+ > `hooks.json` mechanism — and even contain the literal string `SessionStart` in
247
+ > its binary — while having no hook event that fires at session start and can
248
+ > inject context. (One real harness only exposed pre/post-tool and stop events;
249
+ > the `SessionStart` strings were telemetry.) Confirm the *specific event* you
250
+ > need exists and can write to the model's context before committing to Shape A.
251
+ > If it can't, the bootstrap belongs in an instructions file (Shape C) instead.
252
+
253
+ ### Shape B — In-process plugin / extension
254
+
255
+ The harness loads a JS/TS module that exposes lifecycle callbacks. You register
256
+ the skills directory through the harness's API and inject the bootstrap by
257
+ mutating the message array in code.
258
+
259
+ - Reference: `.opencode/plugins/superpowers.js` (JavaScript) and
260
+ `.pi/extensions/superpowers.ts` (TypeScript). pi is the closest reference for
261
+ any harness that has **no native skill tool**.
262
+
263
+ ### Shape C — Instructions-file
264
+
265
+ The harness has neither a shell hook nor a code plugin — its session-start
266
+ surface is a context file that *your installed extension ships and the manifest
267
+ declares* (e.g. Gemini's `contextFileName` → the extension's own `GEMINI.md`).
268
+ You can't run code or mutate messages; the extension's context file points at the
269
+ bootstrap. There is no injector to assemble a string or strip frontmatter — the
270
+ harness loads the referenced content as-is. **This works only because the file is
271
+ part of the installed extension** — never substitute "edit the user's global
272
+ `GEMINI.md`/`AGENTS.md`" for shipping your own (rule 2).
273
+
274
+ - Reference: `gemini-extension.json` (manifest, with `contextFileName`),
275
+ `GEMINI.md` (two `@`-includes — the bootstrap skill and the tool-mapping
276
+ reference), `skills/using-superpowers/references/gemini-tools.md`.
277
+ - Note: `@`-include is a Gemini feature. If your harness loads an instructions
278
+ file but has no include syntax, you must inline the bootstrap content into the
279
+ file instead.
280
+ - **Don't trust that an `@`-include is actually expanded — prove it.** A
281
+ Gemini-*derived* harness can accept `@./path` syntax yet treat it as a *hint
282
+ the model may choose to read* (it emits a file-read tool call) rather than a
283
+ guaranteed inline expansion. That's the difference between the bootstrap being
284
+ reliably present every session and the model maybe-reading it. Run a
285
+ unique-marker test: if the marker isn't in context *without* a tool call,
286
+ **inline the content** rather than `@`-include it.
287
+
288
+ ### Routing table
289
+
290
+ | If the harness… | Use shape | Copy from |
291
+ |---|---|---|
292
+ | runs a shell command at session start and reads its stdout | A (shell-hook) | Cursor (`hooks/session-start` + `hooks/hooks-cursor.json` + `.cursor-plugin/`) |
293
+ | is a JS/TS plugin host with session/message lifecycle callbacks | B (in-process) | OpenCode (`.opencode/`) — or pi (`.pi/`) if it has no native skill tool |
294
+ | ships an extension-declared context file it always loads | C (instructions-file) | Gemini (`gemini-extension.json` + `GEMINI.md` + `references/gemini-tools.md`) |
295
+ | has a plugin install command and a manifest `contextFileName` (or equivalent) the installer keeps | C via the plugin installer | Antigravity (`.antigravity-plugin/` — `agy plugin install` ships a generated context file; verify the installer preserves it — Part 6) |
296
+
297
+ Most real harnesses fit one row cleanly; the last is the hybrid case (rule 2 still
298
+ holds — the bootstrap rides the install mechanism, never a user-config edit).
299
+
300
+ ---
301
+
302
+ ## Part 5 — The porting procedure
303
+
304
+ ### Step 1 — Study the closest reference implementation
305
+
306
+ Open the files named in Part 4 for your shape and read them end to end. The
307
+ patterns below are summaries; the code is the spec.
308
+
309
+ ### Step 2 — Create the manifest / entry point
310
+
311
+ Create whatever the harness uses to recognize the plugin. Match the existing
312
+ ones in spirit:
313
+
314
+ - **Shape A:** a `*-plugin/plugin.json` (see `.cursor-plugin/plugin.json`) with
315
+ `name`, `version`, `description`, author/license/keywords, `"skills":
316
+ "./skills/"`, and `"hooks": "./hooks/hooks-<harness>.json"`. Plus the
317
+ `hooks-<harness>.json` itself, registering a session-start hook whose command
318
+ invokes `run-hook.cmd`.
319
+ - **Shape B:** the module the harness loads (e.g. `.<harness>/plugins/*.js`) plus
320
+ whatever package metadata it needs to be discovered. The committed package
321
+ metadata is the **repo-root `package.json`**: `main` points at the OpenCode
322
+ plugin, the `pi` field (`pi.extensions`, `pi.skills`) plus the `pi-package`
323
+ keyword declare the pi extension. Per-harness local manifests and lockfiles are
324
+ kept out of git — `.opencode/.gitignore` excludes `node_modules`,
325
+ `package.json`, and lockfiles. Do the same for your harness's *local* install
326
+ artifacts so they don't pollute the repo — but never gitignore the repo-root
327
+ `package.json`, which is the tracked source of truth.
328
+ - **Build/dependency check.** Decide how the harness loads your module:
329
+ does it run the source directly (pi's `.ts` is referenced as-is from
330
+ `package.json`; OpenCode ships plain `.js`), or does it need a transpile/build
331
+ step? Superpowers is zero-runtime-dependency. pi's `import type
332
+ { ExtensionAPI }` works specifically because the harness runs the `.ts`
333
+ directly, supplies that type at load, and the repo never type-checks the file
334
+ in CI — the import isn't even declared as a dependency. If *your* harness
335
+ actually type-checks or bundles the plugin, that breaks: an undeclared type
336
+ import fails, and the PR rules only carve out *runtime* deps for new
337
+ harnesses, not dev/type packages. If you hit this, confirm the approach with
338
+ the maintainer rather than quietly adding a dependency. Keep any build output
339
+ out of git and document the command.
340
+ - **Shape C (instructions-file):** a small manifest (see `gemini-extension.json`:
341
+ `name`, `description`, `version`, `contextFileName`) plus the context file
342
+ itself (`GEMINI.md` is just two `@`-includes: the bootstrap skill and the
343
+ tool-mapping reference). The Gemini manifest has no `skills` field — Gemini
344
+ auto-discovers the `skills/` directory bundled in the installed extension. If
345
+ your harness has a native skill tool but no manifest field to register the
346
+ directory, you must find its discovery convention (read its extension docs),
347
+ then verify empirically: after wiring, ask the model to list its available
348
+ skills — if the bundled skills don't appear, discovery isn't working yet.
349
+
350
+ ### Step 3 — Wire the bootstrap injection
351
+
352
+ This is the heart of the port. The shared goal: at session start, get the
353
+ `using-superpowers` skill content (wrapped in `<EXTREMELY_IMPORTANT>` tags) plus
354
+ the harness's tool mapping in front of the model, with a note that the skill is
355
+ already active so the model doesn't try to load it again. *How* you do that —
356
+ and what you assemble vs. what the harness loads raw — depends entirely on your
357
+ shape. Do **not** apply one shape's recipe to another.
358
+
359
+ **Shape A — a script reads `SKILL.md` and prints the harness's JSON.** The
360
+ dispatched script (`hooks/session-start`) `cat`s the whole `SKILL.md` (frontmatter
361
+ included — that's fine; it's emitted verbatim), wraps it with the "You have
362
+ superpowers… for all other skills use the Skill tool" preamble, escapes it, and
363
+ prints the harness's JSON shape. The tool mapping for Shape A does **not** go
364
+ inline here — it lives in `references/<harness>-tools.md` (Step 4). Get the JSON
365
+ output shape exactly right. `hooks/session-start`
366
+ detects the harness from environment variables and prints *one of three* shapes:
367
+
368
+ - Cursor (`CURSOR_PLUGIN_ROOT` set): `{ "additional_context": "…" }`
369
+ - Claude Code (`CLAUDE_PLUGIN_ROOT` set, `COPILOT_CLI` unset):
370
+ `{ "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": "…" } }`
371
+ - Copilot CLI / SDK standard (else): `{ "additionalContext": "…" }`
372
+
373
+ This is a trap. Emitting the wrong field, or an extra one, means the bootstrap
374
+ either never injects or injects twice (Claude Code reads both
375
+ `additional_context` and `hookSpecificOutput` without de-duplicating, so emitting
376
+ both double-injects). Find the
377
+ exact field, nesting, and event-matcher values your harness expects. Then
378
+ decide: add a fourth branch to `hooks/session-start`, or — if the harness needs
379
+ a different bootstrap message or env contract — add a dedicated
380
+ `hooks/session-start-<harness>` script. If you add a branch
381
+ and your harness *also* sets an env var an earlier branch keys on (some harnesses
382
+ set `CLAUDE_PLUGIN_ROOT` too), order your branch before the one that would
383
+ otherwise shadow it. Match the harness's
384
+ own event-matcher strings (Claude Code uses `startup|clear|compact`, Cursor
385
+ `sessionStart`); wrong matchers mean the hook silently never fires.
386
+
387
+ The **hook-config schema itself varies per harness** — don't assume the
388
+ Claude Code shape is universal. Compare `hooks/hooks.json` and
389
+ `hooks/hooks-cursor.json`: Cursor's uses
390
+ `"version": 1`, a lowercase `sessionStart` key, a relative
391
+ `./hooks/run-hook.cmd` command, and omits the `matcher`/`type`/`async` fields
392
+ Claude Code uses. Match your `hooks-<harness>.json` to whichever existing file is
393
+ closest, not to a single canonical template.
394
+
395
+ The hook **command string references a harness-provided plugin-root variable**,
396
+ and its name differs per harness: `hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`,
397
+ `hooks-cursor.json` uses a relative path. Use
398
+ whatever your harness exports. (The `session-start` script re-derives the root
399
+ itself via `dirname`, so the script body doesn't depend on this — but the
400
+ command in the manifest does.)
401
+
402
+ **Discovering the harness's contract.** The three facts above — env var, JSON
403
+ field/nesting, matcher strings — are the harness's contract, not Superpowers',
404
+ so you have to source them. Read the harness's hook docs, or find out
405
+ empirically: register a throwaway session-start hook that dumps its environment
406
+ and emits a marker, then observe which env var identifies the harness and
407
+ whether/how the harness ingests your stdout. Pin these down before writing the
408
+ real branch.
409
+
410
+ **Shape B — assemble the string in code, then inject as a user message.** Here
411
+ you build the bootstrap yourself: read `SKILL.md`, strip its YAML frontmatter,
412
+ and assemble `<EXTREMELY_IMPORTANT>` + a short preamble that the skill is already
413
+ loaded and must not be re-invoked + the stripped body + the inline tool mapping +
414
+ `</EXTREMELY_IMPORTANT>`. One subtlety the references disagree on: OpenCode's
415
+ preamble says "do NOT use the skill tool…" (assumes a `skill` tool exists), while
416
+ pi's just says "do not try to load using-superpowers again." If your harness has
417
+ no skill tool, use pi's wording, not OpenCode's.
418
+
419
+ Inject the result as a **user-role message, not a system message** — system
420
+ messages bloat tokens when repeated every turn (#750) and multiple system
421
+ messages break some models (#894). Three things you must replicate:
422
+
423
+ - **Dedup guard.** The lifecycle callback can fire repeatedly (OpenCode's
424
+ transform runs on *every* agent step; pi's `context` fires per turn). Before
425
+ injecting, check whether a bootstrap marker is already present and skip if so.
426
+ (The references pick different markers — pi a custom string, OpenCode the
427
+ `EXTREMELY_IMPORTANT` tag; matching the tag is more robust since it needs no
428
+ harness-specific constant.) Cache the bootstrap content at module level so
429
+ you're not re-reading and re-parsing `SKILL.md` on every call (#1202).
430
+ - **Compaction.** If the harness compacts/summarizes history, re-inject
431
+ afterward. pi sets an `injectBootstrap` flag on `session_start` and
432
+ `session_compact`, clears it on `agent_end`, and inserts the message *after*
433
+ any leading compaction-summary messages. OpenCode relies on its per-step
434
+ re-injection plus the dedup guard.
435
+ - **Message-object shape is per-harness — discover yours, don't copy a literal.**
436
+ The two references use *incompatible* shapes: pi builds
437
+ `{ role, content: [{ type, text }], timestamp }`; OpenCode manipulates
438
+ `message.info.role` and `message.parts[]`. Find your harness's message shape
439
+ from its API; copying a reference's object literal verbatim will fail silently.
440
+
441
+ **Shape C — point your extension's context file at the bootstrap; assemble
442
+ nothing.** There is no injector, so you do *not* strip frontmatter or build a
443
+ wrapped string. The context file your extension ships (declared by the manifest —
444
+ *not* the user's own global file) pulls in two things: the `using-superpowers`
445
+ skill and the harness's tool-mapping reference. `GEMINI.md`
446
+ does this with two `@`-includes (`@./skills/using-superpowers/SKILL.md` and
447
+ `@./skills/using-superpowers/references/<harness>-tools.md`); the harness loads
448
+ them raw, frontmatter and all, and `SKILL.md` already carries its own
449
+ `<EXTREMELY-IMPORTANT>` block internally. If your harness has no include syntax,
450
+ inline the content into the instructions file instead. Gemini ships **no**
451
+ "already loaded, don't re-invoke" preamble — for an `@`-include harness the
452
+ content is the active instruction set, not a skill the model would re-load. If
453
+ you find your harness does try to re-invoke, add that note as a literal line in
454
+ the instructions file (you have no code to add it any other way).
455
+
456
+ ### Step 4 — Write the tool mapping
457
+
458
+ Translate the action vocabulary into the harness's real tools. Cover every one
459
+ of these actions (omit only what genuinely doesn't apply):
460
+
461
+ - read a file
462
+ - create / edit / delete a file (one `apply_patch`-style tool, or separate
463
+ write/edit?)
464
+ - run a shell command
465
+ - search file contents / find files by name (grep, glob)
466
+ - fetch a URL / web search
467
+ - **dispatch a subagent**, including how to pass the agent type — and any config
468
+ flag needed to enable it
469
+ - **create / update todos** (treat older `TodoWrite` references as this action)
470
+ - **invoke a skill** — see Step 5
471
+
472
+ **Get the real tool names from the harness; never invent them.** If the docs
473
+ don't list them, the authoritative source is the harness itself: in a live
474
+ session, ask the model to "list the exact machine names of every tool you can
475
+ call, one per line" and use what it reports.
476
+
477
+ **How the harness finds the `skills/` directory is itself per-harness** — confirm
478
+ it, don't assume. Possibilities: a manifest `skills` path field (Codex's
479
+ `"skills": "./skills/"`); a *co-located* `skills/` the harness auto-scans (where a
480
+ path field is **ignored** — one real harness only scanned a `skills/` sitting next
481
+ to `plugin.json`); an API/registration call (OpenCode, pi); or you stage an
482
+ install dir that pairs the manifest with a **symlink to the repo's `skills/`** and
483
+ point the installer at the staging dir (verify the installer *dereferences* the
484
+ symlink and copies the real files — confirm with `agy plugin validate`/`install`
485
+ or the equivalent before relying on it). A `skills` path field is *not* portable.
486
+
487
+ Where the mapping lives depends on shape:
488
+
489
+ - **Shape A:** put it in `skills/using-superpowers/references/<harness>-tools.md`.
490
+ The agent reaches it from the bootstrap — `SKILL.md`'s "Platform Adaptation"
491
+ section links the per-harness references files. (Shape A harnesses have no
492
+ instructions file; the mapping is *not* inlined into the hook output.)
493
+ - **Shape B:** the mapping is typically inlined into the bootstrap string you
494
+ inject (see the `toolMapping` constant in `superpowers.js`). pi keeps it in
495
+ *both* places — `piToolMapping()` inline **and** `references/pi-tools.md`. If
496
+ you maintain it in two places, update both, or the port is half-done.
497
+ - **Shape C:** put it in `references/<harness>-tools.md` and pull it into the
498
+ always-loaded instructions file (e.g. `GEMINI.md` `@`-includes
499
+ `gemini-tools.md`).
500
+
501
+ You may also add a one-line pointer to your harness in `SKILL.md`'s "Platform
502
+ Adaptation" section so an agent reading the bootstrap knows where its mapping
503
+ lives. This is the one edit to a `SKILL.md` a port may make — and only because
504
+ that section is a pointer list, not behavior-shaping content. It does not violate
505
+ the "don't edit skill bodies" rule (Part 1); do not touch anything else in any
506
+ skill. (The list is a convenience pointer, not an exhaustive registry — not every
507
+ harness is listed.)
508
+
509
+ ### Step 5 — Handle a harness with no native skill tool
510
+
511
+ `using-superpowers/SKILL.md` tells the model to *never read skill files manually
512
+ with file tools — always use your platform's skill-loading mechanism.* The point
513
+ is "don't bypass the mechanism," not "never use file-read." What counts as "your
514
+ platform's mechanism" depends on the harness — and for a harness with no skill
515
+ tool, the documented mechanism *is* reading `SKILL.md`. So reading it there
516
+ honors the rule rather than breaking it. Distinguish three cases:
517
+
518
+ 1. **Native `Skill`-style tool** (Claude Code, Copilot CLI, Gemini's
519
+ `activate_skill`): point the mapping at that tool.
520
+ 2. **Native skill *discovery* but no `Skill` tool** (pi, Antigravity): the harness
521
+ can find and list skills, but the model can't call a tool to load one. Get the
522
+ skills installed where the harness scans (pi registers via `resources_discover`
523
+ → `skillPaths`; OpenCode via its `config` hook; `agy plugin install` copies
524
+ them in), and tell the model to load a skill by **reading its `SKILL.md` with
525
+ the file-read tool when the skill applies** — the sanctioned mechanism here,
526
+ the way `references/pi-tools.md` states it.
527
+
528
+ **For the bootstrap itself, prefer a declared context file (Part 6).** If the
529
+ harness has a `contextFileName`-style manifest field — as Antigravity does —
530
+ ship a generated context file through the installer: it's guaranteed-loaded and
531
+ carries both the `using-superpowers` content and the tool mapping. That is the
532
+ strong, preferred path.
533
+
534
+ **Fallback — the surfaced skill index.** If there's no context-file field but
535
+ the harness surfaces each installed skill's name + description at session start,
536
+ you need *neither* a built index nor a runtime-list instruction — the harness
537
+ is the index, and `using-superpowers`'s own surfaced description can be what
538
+ triggers the model to load it. This is softer than a declared context file;
539
+ two things it does **not** give you, versus a context file / hook / in-process
540
+ injector — account for both:
541
+ - **It bootstraps *triggering*, not the *tool mapping*.** An injector prepends
542
+ `<harness>-tools.md` alongside `using-superpowers` every session. Here nothing
543
+ injects the mapping — the model only sees skill *descriptions* and must *read*
544
+ your `references/<harness>-tools.md` when it needs tool names. It works
545
+ because skills name actions (the model reads the mapping when it acts), but
546
+ it's softer than injection. Make sure the mapping is reachable from what the
547
+ model loads — e.g. linked from `SKILL.md`'s Platform Adaptation section and
548
+ installed alongside the skills — not just sitting in the repo.
549
+ - **There's no structural guarantee the trigger fires.** No `<EXTREMELY_IMPORTANT>`
550
+ wrapper, no dedup, no re-injection after compaction — firing depends on the
551
+ model choosing to act on a description it sees in the index. This is exactly
552
+ why the acceptance test is mandatory here: it is the *only* guarantee, so run
553
+ it on the model(s) your users will actually use, not just the strongest one.
554
+ 3. **No skill system at all:** there is nothing to register, and the *only*
555
+ mechanism is the model reading `SKILL.md` on demand. But the model can't read
556
+ what it can't find: `using-superpowers/SKILL.md` does **not** enumerate the
557
+ available skills, so on its own the model won't know which skills exist or
558
+ their triggers. You must supply a discovery path. Two options, and they differ
559
+ in durability: (a) generate a skill index (each `skills/*/SKILL.md`'s `name` +
560
+ `description` frontmatter) and place it *inside* the `<EXTREMELY_IMPORTANT>`
561
+ wrapper alongside the tool mapping (Shape B recipe above) so it's covered by
562
+ the dedup guard — but a build-time index goes stale as skills are added; or
563
+ (b) instruct the model to list `skills/*/SKILL.md` at runtime and read their
564
+ frontmatter to find a match — slower but never stale. Prefer (b) unless you
565
+ have a reason not to. Without either, a no-skill-system port loads the
566
+ bootstrap but silently never triggers any other skill.
567
+
568
+ In cases 2 and 3, say plainly in your tool mapping that reading `SKILL.md` is the
569
+ blessed path, so the model doesn't think it's violating the "never read skill
570
+ files" rule. Don't go hunting for a `skillPaths`-style registration API in a
571
+ harness that has no skill system — case 3 has none.
572
+
573
+ ### Step 6 — Add tests
574
+
575
+ Match the existing per-harness test style:
576
+
577
+ - **Shape A:** assert the hook's stdout has the exact JSON shape your harness
578
+ consumes, and that it contains the bootstrap. See `tests/hooks/test-session-start.sh`,
579
+ which validates each harness's output shape.
580
+ - **Shape B:** a unit test that fakes the harness's plugin API and asserts the
581
+ lifecycle handlers register, the bootstrap injects once, the dedup guard
582
+ works, and (if relevant) compaction re-injection works. See
583
+ `tests/pi/test-pi-extension.mjs`. Add an isolated-install integration check in
584
+ the style of `tests/opencode/`.
585
+ - If the bootstrap is cached, test that the cache behaves when the file is
586
+ missing (see the OpenCode caching tests).
587
+
588
+ These automated tests cover the wiring; the live tmux run in Step 7 is what
589
+ proves the integration actually triggers skills.
590
+
591
+ ### Step 7 — Install locally, then drive a live instance to verify
592
+
593
+ You cannot confirm a port works by reading code. You have to run the harness with
594
+ your in-progress port loaded and watch a real session — which is also how you
595
+ produce the transcript the PR requires.
596
+
597
+ **Install locally.** Point a *local* instance of the harness at your working
598
+ tree, not a published build:
599
+
600
+ - **Shape A / C:** install the plugin/extension from this repo's local path (or
601
+ symlink its directory into wherever the harness looks). Find the harness's
602
+ "install from a local directory / git checkout" path in its docs.
603
+ - **Shape B:** register the local module — e.g. an `opencode.json` `plugin`
604
+ entry pointing at the local path, or pi resolving the `package.json` fields
605
+ from the repo.
606
+
607
+ Reinstall after each change and restart the harness, since the bootstrap loads at
608
+ startup.
609
+
610
+ **Drive it with tmux.** Most harnesses are interactive REPLs/TUIs that can't be
611
+ driven by piping stdin, so run the harness inside a detached tmux session and
612
+ control it with `send-keys` / `capture-pane`. A harness may advertise a
613
+ non-interactive "run one prompt" mode (e.g. `opencode run "..."`) — try it for the
614
+ quick smoke check, but **don't depend on it**: these modes are frequently flaky,
615
+ auth-gated, or trust-gated (one real harness's `--print` mode hung and timed out
616
+ with no output every time). Be ready to do *everything*, including the smoke
617
+ check, through tmux.
618
+
619
+ **Clear the gates first, or tmux stalls silently.** Many harnesses block on
620
+ first-run onboarding, a "do you trust this folder?" prompt, a sandbox mode, or a
621
+ permission gate — and a detached tmux session will just sit there with no error
622
+ while it waits. Before the run, pre-trust your scratch directory (in the harness's
623
+ settings/config) or be prepared to answer those prompts via `send-keys`, and
624
+ account for the harness's startup time in your first `sleep`.
625
+
626
+ ```bash
627
+ # 1. Launch the harness detached, in a throwaway project dir
628
+ mkdir -p /tmp/port-smoke
629
+ tmux new-session -d -s port-test -c /tmp/port-smoke '<harness-launch-command>'
630
+
631
+ # 2. Let it initialize — real TUIs take longer than you think (10s+ with a model
632
+ # handshake); tune this. THEN capture and clear any blocking modal before you
633
+ # type a prompt: first-run onboarding and "trust this folder?" are modal, so
634
+ # keystrokes sent during them select menu items instead of typing your prompt.
635
+ sleep 12
636
+ tmux capture-pane -t port-test -p # onboarding / trust prompt? answer it via send-keys first
637
+ # (e.g. tmux send-keys -t port-test Enter # to accept a trust prompt — inspect before assuming)
638
+
639
+ # 3. Smoke check: does the model know it has superpowers?
640
+ # Send the text and Enter as SEPARATE send-keys with a beat between them —
641
+ # sending them together races on some TUIs (Enter arrives before the text lands).
642
+ tmux send-keys -t port-test 'What are your superpowers?'; sleep 0.4; tmux send-keys -t port-test Enter
643
+ sleep 5
644
+ tmux capture-pane -t port-test -p # reply should show it knows its skills
645
+
646
+ # 4. Acceptance test: exact prompt (note the escaped apostrophe), fresh session
647
+ tmux send-keys -t port-test 'Let'\''s make a react todo list'; sleep 0.4; tmux send-keys -t port-test Enter
648
+ # poll until the turn finishes — re-capture every few seconds, don't capture once
649
+ sleep 8
650
+ tmux capture-pane -t port-test -p # PASS = brainstorming triggers BEFORE any code
651
+
652
+ # 5. Save the transcript for the PR, then clean up
653
+ tmux capture-pane -t port-test -p > /tmp/port-smoke/transcript.txt
654
+ tmux kill-session -t port-test
655
+ ```
656
+
657
+ tmux gotchas that bite here: wait after launch before the first capture; send the
658
+ prompt text and `Enter` as *separate* `send-keys` calls with a short `sleep`
659
+ between them (sending them together races on some TUIs), and `Enter` is a key name
660
+ not `\n`; the agent's turn takes time, so **poll `capture-pane` in a loop** rather
661
+ than capturing once; `capture-pane` shows only the visible pane, so for a long
662
+ conversation use the harness's own transcript/log file as the record of truth;
663
+ always `kill-session` when done.
664
+
665
+ If the smoke check shows the model *doesn't* know it has superpowers, the
666
+ bootstrap isn't loading — fix that before bothering with the acceptance test.
667
+
668
+ ---
669
+
670
+ ## Part 6 — Distribution and release
671
+
672
+ A working integration in this repo isn't usable until a real user can install
673
+ it. Distribution differs per harness ecosystem — find yours:
674
+
675
+ | Channel | Example | What you do |
676
+ |---|---|---|
677
+ | Native plugin marketplace | Claude Code | Register in `.claude-plugin/marketplace.json`; users `/plugin install`. The external `superpowers-marketplace` repo is the source of truth users install from — see the release steps in `CLAUDE.md`. |
678
+ | External marketplace fork, synced by script | Codex | `scripts/sync-to-codex-plugin.sh` rsyncs the tracked plugin files into a separate fork repo and opens a PR. Read its include/exclude list so you ship the right tree (it deliberately drops repo-internal dirs and other harnesses' dotdirs). |
679
+ | Git-URL extension install | Gemini, Kimi Code, OpenCode | Users install from a git URL (`gemini extensions install …`; Kimi Code `/plugins install …`; an `opencode.json` `plugin` array entry). Document the exact command. |
680
+ | Package-manifest fields | pi | Declared through fields in the repo-root `package.json`; users install via the harness's package command. |
681
+ | Local installer (plugin install) | Antigravity (`agy`) | A small `install.sh` that runs the harness's own `agy plugin install` against a staging dir holding the manifest, the skills, and a generated `contextFileName` context file (the bootstrap). Everything arrives through the install mechanism — *not* by editing the user's config (see below). |
682
+
683
+ Then:
684
+
685
+ - **A plugin installer may silently strip *undeclared* files — so make the
686
+ bootstrap a file the installer *recognizes*, never a user-config edit.** A
687
+ `plugin install` typically copies only the components it knows about
688
+ (skills/agents/commands/mcp/hooks/context) and discards anything else, so a
689
+ context file the manifest doesn't declare just vanishes from the install. The
690
+ fix is **not** to give up and write into the user's config (**rule 2**) — it's
691
+ to declare the bootstrap as a recognized component. In escalation order:
692
+ - **Ship a context file the manifest declares.** If the harness has a
693
+ `contextFileName`-style field (an extension-declared file it loads every
694
+ session), that is the strongest clean bootstrap: declare it, and the installer
695
+ preserves it *and* the harness loads it. Generate it at install time from the
696
+ live `using-superpowers/SKILL.md` + the tool mapping (wrapped in
697
+ `<EXTREMELY_IMPORTANT>`) so the installed bootstrap never drifts. This is what
698
+ `.antigravity-plugin/install.sh` does — `agy plugin install` reports
699
+ `✔ context : ANTIGRAVITY.md`, and a clean session reads `using-superpowers`'s
700
+ SKILL.md, loads `brainstorming`, and enters the brainstorming flow before any
701
+ code. **Verify with a marker** that the installer keeps the file and the
702
+ harness loads it: one porter wrongly concluded it couldn't, because they
703
+ shipped the file *without* declaring `contextFileName` and it was stripped as
704
+ unrecognized.
705
+ - **Otherwise lean on the installed `using-superpowers` skill itself.** If the
706
+ harness surfaces each installed skill's name + description at session start,
707
+ the `using-superpowers` description ("Use when starting any conversation…")
708
+ can prompt the model to load it — installing the skill *is* the bootstrap.
709
+ Softer (no guaranteed wrapper; it carries triggering but not the tool mapping
710
+ — see Step 5), so prefer the declared context file when available.
711
+ - If neither works, the harness cannot be cleanly supported yet — **say so**
712
+ and raise it, rather than hand-editing the user's config.
713
+
714
+ - **Write install docs.** A `docs/README.<harness>.md` and/or a
715
+ `.<harness>/INSTALL.md` (see `docs/README.opencode.md` and
716
+ `.opencode/INSTALL.md`), plus an install section in the top-level `README.md`.
717
+ The only supported install action is **running the harness's own install
718
+ command** (`agy plugin install`, `gemini extensions install`, `/plugin
719
+ install`, etc.). Hand-copying skill files and editing the user's global/personal
720
+ config are *both* off-limits (rule 2 / the PR rules). If the harness has no
721
+ install command at all — its only surface is a user-owned config file — then it
722
+ fails the "deliver via install mechanism" rule, and you should raise that rather
723
+ than ship an installer that edits the user's files.
724
+ - **Register the version.** If your harness introduces a *new* versioned
725
+ manifest, add its path and version field to `.version-bump.json` so
726
+ `scripts/bump-version.sh` keeps it in lockstep (read that file to see what's
727
+ currently tracked). A new manifest that isn't registered there will ship a
728
+ stale version. If your harness instead rides an already-tracked file — pi
729
+ declares itself in the repo-root `package.json`, which is already listed —
730
+ there's nothing new to add.
731
+ - **If no existing channel fits, you're standing up a new one.** None of the four
732
+ rows may match your harness. If it needs a Codex-style external fork sync,
733
+ `scripts/sync-to-codex-plugin.sh` is the template to clone (note its anchored
734
+ include/exclude list and its PR automation). And whenever you add a new
735
+ per-harness directory, add it to the *other* harnesses' sync excludes (e.g. the
736
+ EXCLUDES list in `sync-to-codex-plugin.sh`) so your dotdir doesn't leak into
737
+ their distributions.
738
+
739
+ ---
740
+
741
+ ## Part 7 — Cross-platform / Windows
742
+
743
+ Only relevant to the shell-hook shape. `hooks/run-hook.cmd` is a polyglot: a
744
+ single file that's valid as both a Windows batch script and a Unix shell script.
745
+ On Windows, `cmd.exe` runs the batch portion, which locates `bash` (Git for
746
+ Windows, then `bash` on PATH) and runs the named hook script; if no bash is
747
+ found it exits cleanly so the harness still works, just without injection. On
748
+ Unix, the leading `:` makes the batch block a no-op and the shell runs the
749
+ script directly.
750
+
751
+ Two rules this enforces, which you must respect:
752
+
753
+ - **Hook scripts are extensionless** (`session-start`, not `session-start.sh`).
754
+ Claude Code's Windows handling prepends `bash` to any command containing
755
+ `.sh`, which would double-invoke. Name your hook script without an extension.
756
+ - Don't write per-OS variants of the hook script. One extensionless bash script
757
+ plus the polyglot wrapper covers all three platforms.
758
+
759
+ `hooks/run-hook.cmd` itself is the authoritative implementation — read it. See
760
+ `docs/windows/polyglot-hooks.md` for the background and rationale behind the
761
+ dispatcher pattern.
762
+
763
+ ---
764
+
765
+ ## Part 8 — Submitting the PR
766
+
767
+ - Target the **`dev`** branch. One harness per PR.
768
+ - Fill in the PR template's **"New harness support"** section and paste the
769
+ complete acceptance-test transcript (the "Let's make a react todo list"
770
+ session showing `brainstorming` auto-triggering). A PR without this proof will
771
+ be closed.
772
+ - Superpowers is a zero-dependency plugin. Don't add a third-party runtime
773
+ dependency. Adding a new harness is the one carve-out the contributor rules
774
+ allow, and even then keep it to what the integration strictly requires —
775
+ type-only imports that compile away are fine; runtime packages are not.
776
+ - Don't touch skill bodies (Part 1). If you found yourself editing a `SKILL.md`
777
+ to make the port work, the fix belongs in your tool mapping instead.
778
+
779
+ ---
780
+
781
+ ## Appendix A — Reference integrations (current)
782
+
783
+ Use this as the live index; when in doubt, read the files, not this table.
784
+
785
+ | Harness | Entry point | Bootstrap mechanism | Tool mapping | Tests | Distribution |
786
+ |---|---|---|---|---|---|
787
+ | Claude Code | `.claude-plugin/plugin.json` + `hooks/hooks.json` | shell hook → `hooks/session-start` (`hookSpecificOutput.additionalContext`) | native `Skill` tool; no adapter file needed | `tests/hooks/` | marketplace |
788
+ | Codex | `.codex-plugin/plugin.json` (declares empty `hooks`) | native skill discovery (no session-start hook) | `references/codex-tools.md` | `tests/codex/`, `tests/codex-plugin-sync/` | fork sync (`scripts/sync-to-codex-plugin.sh`) |
789
+ | Cursor | `.cursor-plugin/plugin.json` + `hooks/hooks-cursor.json` | shell hook → `hooks/session-start` (`additional_context`) | none needed (Claude Code–compatible tool surface) | `tests/hooks/` | hand-authored |
790
+ | Copilot CLI | (shares Claude Code hook path; `COPILOT_CLI` env) | shell hook → `hooks/session-start` (`additionalContext`) | none needed (Claude Code–compatible tool surface) | `tests/hooks/` | — |
791
+ | Gemini CLI | `gemini-extension.json` + `GEMINI.md` | instructions file `@`-includes bootstrap + mapping | `references/gemini-tools.md` | — | `gemini extensions install` |
792
+ | Kimi Code | `.kimi-plugin/plugin.json` | manifest `sessionStart.skill` loads `using-superpowers` | inline `skillInstructions` in manifest | `tests/kimi/` | marketplace or `/plugins install` GitHub URL |
793
+ | OpenCode | `.opencode/plugins/superpowers.js` (declared via root `package.json` `main`) | in-process: `config` hook registers skills dir; `experimental.chat.messages.transform` injects user message | inline in `superpowers.js` | `tests/opencode/` | `opencode.json` plugin git URL |
794
+ | pi | `.pi/extensions/superpowers.ts` | in-process: `resources_discover` registers skills; `context` event injects user message; lifecycle-flag + compaction-aware | `piToolMapping()` inline **and** `references/pi-tools.md` | `tests/pi/` | repo-root `package.json` fields |
795
+
796
+ ## Appendix B — Gotchas that have bitten porters
797
+
798
+ - **Opt-in isn't a port.** If your human partner has to do anything per session
799
+ to get Superpowers, the acceptance test fails. Re-read Part 2.
800
+ - **Wrong JSON field → silent failure or double injection.** Shape A only.
801
+ Confirm the exact field/nesting; Claude Code reads two fields without dedup.
802
+ - **Hook-config schema varies per harness.** Shape A. Cursor's `hooks-cursor.json`
803
+ looks nothing like the Claude Code one (`version`, lowercase `sessionStart`,
804
+ relative command, no `matcher`/`type`/`async`). Match the closest existing file.
805
+ - **Plugin-root env var differs per harness.** Shape A. The hook command uses
806
+ `${CLAUDE_PLUGIN_ROOT}` (Claude) or a relative path
807
+ (Cursor). Use what your harness exports; the script re-derives the root itself.
808
+ - **System-message injection.** Shape B injects a *user* message on purpose
809
+ (#750, #894). Don't "fix" it to a system message.
810
+ - **Per-step vs per-turn callbacks.** OpenCode fires every step (per-call dedup
811
+ guard); pi fires per turn (lifecycle flag + `agent_end` reset). Copying one
812
+ harness's dedup strategy onto the other's callback frequency breaks injection.
813
+ - **Message-object shape is per-harness.** Shape B. pi and OpenCode use
814
+ incompatible shapes; discover yours, don't copy a reference's object literal.
815
+ - **Hunting for a skill-registration API that doesn't exist.** A harness with no
816
+ skill system (not just no `Skill` tool) has nothing to register — the model
817
+ reads `SKILL.md` on demand. Don't assume a `skillPaths` equivalent exists.
818
+ - **Mapping in two places.** For in-process plugins the mapping may live both
819
+ inline and in a `references/` file (pi). Update both.
820
+ - **The "never read skill files" line.** It means "don't bypass your platform's
821
+ skill-loading mechanism," not "never use file-read." On a no-skill-tool harness
822
+ that mechanism *is* reading `SKILL.md` — say so explicitly in the mapping
823
+ (Part 5).
824
+ - **`.sh` on Windows.** Keep hook scripts extensionless (Part 7).
825
+ - **Unregistered version.** A new manifest not added to `.version-bump.json`
826
+ ships stale (Part 6).
827
+ - **Editing skills to fit the harness.** Never. The fix goes in the tool mapping.
github_code/obra__superpowers/docs/superpowers/plans/2026-01-22-document-review-system.md ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Document Review System Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan.
4
+
5
+ **Goal:** Add spec and plan document review loops to the brainstorming and writing-plans skills.
6
+
7
+ **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.
8
+
9
+ **Tech Stack:** Markdown skill files, subagent dispatch via Task tool
10
+
11
+ **Spec:** docs/superpowers/specs/2026-01-22-document-review-system-design.md
12
+
13
+ ---
14
+
15
+ ## Chunk 1: Spec Document Reviewer
16
+
17
+ This chunk adds the spec document reviewer to the brainstorming skill.
18
+
19
+ ### Task 1: Create Spec Document Reviewer Prompt Template
20
+
21
+ **Files:**
22
+ - Create: `skills/brainstorming/spec-document-reviewer-prompt.md`
23
+
24
+ - [ ] **Step 1:** Create the reviewer prompt template file
25
+
26
+ ```markdown
27
+ # Spec Document Reviewer Prompt Template
28
+
29
+ Use this template when dispatching a spec document reviewer subagent.
30
+
31
+ **Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
32
+
33
+ **Dispatch after:** Spec document is written to docs/superpowers/specs/
34
+
35
+ ```
36
+ Task tool (general-purpose):
37
+ description: "Review spec document"
38
+ prompt: |
39
+ You are a spec document reviewer. Verify this spec is complete and ready for planning.
40
+
41
+ **Spec to review:** [SPEC_FILE_PATH]
42
+
43
+ ## What to Check
44
+
45
+ | Category | What to Look For |
46
+ |----------|------------------|
47
+ | Completeness | TODOs, placeholders, "TBD", incomplete sections |
48
+ | Coverage | Missing error handling, edge cases, integration points |
49
+ | Consistency | Internal contradictions, conflicting requirements |
50
+ | Clarity | Ambiguous requirements |
51
+ | YAGNI | Unrequested features, over-engineering |
52
+
53
+ ## CRITICAL
54
+
55
+ Look especially hard for:
56
+ - Any TODO markers or placeholder text
57
+ - Sections saying "to be defined later" or "will spec when X is done"
58
+ - Sections noticeably less detailed than others
59
+
60
+ ## Output Format
61
+
62
+ ## Spec Review
63
+
64
+ **Status:** ✅ Approved | ❌ Issues Found
65
+
66
+ **Issues (if any):**
67
+ - [Section X]: [specific issue] - [why it matters]
68
+
69
+ **Recommendations (advisory):**
70
+ - [suggestions that don't block approval]
71
+ ```
72
+
73
+ **Reviewer returns:** Status, Issues (if any), Recommendations
74
+ ```
75
+
76
+ - [ ] **Step 2:** Verify the file was created correctly
77
+
78
+ Run: `cat skills/brainstorming/spec-document-reviewer-prompt.md | head -20`
79
+ Expected: Shows the header and purpose section
80
+
81
+ - [ ] **Step 3:** Commit
82
+
83
+ ```bash
84
+ git add skills/brainstorming/spec-document-reviewer-prompt.md
85
+ git commit -m "feat: add spec document reviewer prompt template"
86
+ ```
87
+
88
+ ---
89
+
90
+ ### Task 2: Add Review Loop to Brainstorming Skill
91
+
92
+ **Files:**
93
+ - Modify: `skills/brainstorming/SKILL.md`
94
+
95
+ - [ ] **Step 1:** Read the current brainstorming skill
96
+
97
+ Run: `cat skills/brainstorming/SKILL.md`
98
+
99
+ - [ ] **Step 2:** Add the review loop section after "After the Design"
100
+
101
+ Find the "After the Design" section and add a new "Spec Review Loop" section after documentation but before implementation:
102
+
103
+ ```markdown
104
+ **Spec Review Loop:**
105
+ After writing the spec document:
106
+ 1. Dispatch spec-document-reviewer subagent (see spec-document-reviewer-prompt.md)
107
+ 2. If ❌ Issues Found:
108
+ - Fix the issues in the spec document
109
+ - Re-dispatch reviewer
110
+ - Repeat until ✅ Approved
111
+ 3. If ✅ Approved: proceed to implementation setup
112
+
113
+ **Review loop guidance:**
114
+ - Same agent that wrote the spec fixes it (preserves context)
115
+ - If loop exceeds 5 iterations, surface to human for guidance
116
+ - Reviewers are advisory - explain disagreements if you believe feedback is incorrect
117
+ ```
118
+
119
+ - [ ] **Step 3:** Verify the changes
120
+
121
+ Run: `grep -A 15 "Spec Review Loop" skills/brainstorming/SKILL.md`
122
+ Expected: Shows the new review loop section
123
+
124
+ - [ ] **Step 4:** Commit
125
+
126
+ ```bash
127
+ git add skills/brainstorming/SKILL.md
128
+ git commit -m "feat: add spec review loop to brainstorming skill"
129
+ ```
130
+
131
+ ---
132
+
133
+ ## Chunk 2: Plan Document Reviewer
134
+
135
+ This chunk adds the plan document reviewer to the writing-plans skill.
136
+
137
+ ### Task 3: Create Plan Document Reviewer Prompt Template
138
+
139
+ **Files:**
140
+ - Create: `skills/writing-plans/plan-document-reviewer-prompt.md`
141
+
142
+ - [ ] **Step 1:** Create the reviewer prompt template file
143
+
144
+ ```markdown
145
+ # Plan Document Reviewer Prompt Template
146
+
147
+ Use this template when dispatching a plan document reviewer subagent.
148
+
149
+ **Purpose:** Verify the plan chunk is complete, matches the spec, and has proper task decomposition.
150
+
151
+ **Dispatch after:** Each plan chunk is written
152
+
153
+ ```
154
+ Task tool (general-purpose):
155
+ description: "Review plan chunk N"
156
+ prompt: |
157
+ You are a plan document reviewer. Verify this plan chunk is complete and ready for implementation.
158
+
159
+ **Plan chunk to review:** [PLAN_FILE_PATH] - Chunk N only
160
+ **Spec for reference:** [SPEC_FILE_PATH]
161
+
162
+ ## What to Check
163
+
164
+ | Category | What to Look For |
165
+ |----------|------------------|
166
+ | Completeness | TODOs, placeholders, incomplete tasks, missing steps |
167
+ | Spec Alignment | Chunk covers relevant spec requirements, no scope creep |
168
+ | Task Decomposition | Tasks atomic, clear boundaries, steps actionable |
169
+ | Task Syntax | Checkbox syntax (`- [ ]`) on tasks and steps |
170
+ | Chunk Size | Each chunk under 1000 lines |
171
+
172
+ ## CRITICAL
173
+
174
+ Look especially hard for:
175
+ - Any TODO markers or placeholder text
176
+ - Steps that say "similar to X" without actual content
177
+ - Incomplete task definitions
178
+ - Missing verification steps or expected outputs
179
+
180
+ ## Output Format
181
+
182
+ ## Plan Review - Chunk N
183
+
184
+ **Status:** ✅ Approved | ❌ Issues Found
185
+
186
+ **Issues (if any):**
187
+ - [Task X, Step Y]: [specific issue] - [why it matters]
188
+
189
+ **Recommendations (advisory):**
190
+ - [suggestions that don't block approval]
191
+ ```
192
+
193
+ **Reviewer returns:** Status, Issues (if any), Recommendations
194
+ ```
195
+
196
+ - [ ] **Step 2:** Verify the file was created
197
+
198
+ Run: `cat skills/writing-plans/plan-document-reviewer-prompt.md | head -20`
199
+ Expected: Shows the header and purpose section
200
+
201
+ - [ ] **Step 3:** Commit
202
+
203
+ ```bash
204
+ git add skills/writing-plans/plan-document-reviewer-prompt.md
205
+ git commit -m "feat: add plan document reviewer prompt template"
206
+ ```
207
+
208
+ ---
209
+
210
+ ### Task 4: Add Review Loop to Writing-Plans Skill
211
+
212
+ **Files:**
213
+ - Modify: `skills/writing-plans/SKILL.md`
214
+
215
+ - [ ] **Step 1:** Read current skill file
216
+
217
+ Run: `cat skills/writing-plans/SKILL.md`
218
+
219
+ - [ ] **Step 2:** Add chunk-by-chunk review section
220
+
221
+ Add before the "Execution Handoff" section:
222
+
223
+ ```markdown
224
+ ## Plan Review Loop
225
+
226
+ After completing each chunk of the plan:
227
+
228
+ 1. Dispatch plan-document-reviewer subagent for the current chunk
229
+ - Provide: chunk content, path to spec document
230
+ 2. If ❌ Issues Found:
231
+ - Fix the issues in the chunk
232
+ - Re-dispatch reviewer for that chunk
233
+ - Repeat until ✅ Approved
234
+ 3. If ✅ Approved: proceed to next chunk (or execution handoff if last chunk)
235
+
236
+ **Chunk boundaries:** Use `## Chunk N: <name>` headings to delimit chunks. Each chunk should be ≤1000 lines and logically self-contained.
237
+ ```
238
+
239
+ - [ ] **Step 3:** Update task syntax examples to use checkboxes
240
+
241
+ Change the Task Structure section to show checkbox syntax:
242
+
243
+ ```markdown
244
+ ### Task N: [Component Name]
245
+
246
+ - [ ] **Step 1:** Write the failing test
247
+ - File: `tests/path/test.py`
248
+ ...
249
+ ```
250
+
251
+ - [ ] **Step 4:** Verify the review loop section was added
252
+
253
+ Run: `grep -A 15 "Plan Review Loop" skills/writing-plans/SKILL.md`
254
+ Expected: Shows the new review loop section
255
+
256
+ - [ ] **Step 5:** Verify the task syntax examples were updated
257
+
258
+ Run: `grep -A 5 "Task N:" skills/writing-plans/SKILL.md`
259
+ Expected: Shows checkbox syntax `### Task N:`
260
+
261
+ - [ ] **Step 6:** Commit
262
+
263
+ ```bash
264
+ git add skills/writing-plans/SKILL.md
265
+ git commit -m "feat: add plan review loop and checkbox syntax to writing-plans skill"
266
+ ```
267
+
268
+ ---
269
+
270
+ ## Chunk 3: Update Plan Document Header
271
+
272
+ This chunk updates the plan document header template to reference the new checkbox syntax requirements.
273
+
274
+ ### Task 5: Update Plan Header Template in Writing-Plans Skill
275
+
276
+ **Files:**
277
+ - Modify: `skills/writing-plans/SKILL.md`
278
+
279
+ - [ ] **Step 1:** Read current plan header template
280
+
281
+ Run: `grep -A 20 "Plan Document Header" skills/writing-plans/SKILL.md`
282
+
283
+ - [ ] **Step 2:** Update the header template to reference checkbox syntax
284
+
285
+ The plan header should note that tasks and steps use checkbox syntax. Update the header comment:
286
+
287
+ ```markdown
288
+ > **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Tasks and steps use checkbox (`- [ ]`) syntax for tracking.
289
+ ```
290
+
291
+ - [ ] **Step 3:** Verify the change
292
+
293
+ Run: `grep -A 5 "For agentic workers:" skills/writing-plans/SKILL.md`
294
+ Expected: Shows updated header with checkbox syntax mention
295
+
296
+ - [ ] **Step 4:** Commit
297
+
298
+ ```bash
299
+ git add skills/writing-plans/SKILL.md
300
+ git commit -m "docs: update plan header to reference checkbox syntax"
301
+ ```
github_code/obra__superpowers/docs/superpowers/plans/2026-02-19-visual-brainstorming-refactor.md ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Brainstorming Refactor Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Refactor visual brainstorming from blocking TUI feedback model to non-blocking "Browser Displays, Terminal Commands" architecture.
6
+
7
+ **Architecture:** Browser becomes an interactive display; terminal stays the conversation channel. Server writes user events to a per-screen `.events` file that Claude reads on its next turn. Eliminates `wait-for-feedback.sh` and all `TaskOutput` blocking.
8
+
9
+ **Tech Stack:** Node.js (Express, ws, chokidar), vanilla HTML/CSS/JS
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-02-19-visual-brainstorming-refactor-design.md`
12
+
13
+ ---
14
+
15
+ ## File Map
16
+
17
+ | File | Action | Responsibility |
18
+ |------|--------|---------------|
19
+ | `lib/brainstorm-server/index.js` | Modify | Server: add `.events` file writing, clear on new screen, replace `wrapInFrame` |
20
+ | `lib/brainstorm-server/frame-template.html` | Modify | Template: remove feedback footer, add content placeholder + selection indicator |
21
+ | `lib/brainstorm-server/helper.js` | Modify | Client JS: remove send/feedback functions, narrow to click capture + indicator updates |
22
+ | `lib/brainstorm-server/wait-for-feedback.sh` | Delete | No longer needed |
23
+ | `skills/brainstorming/visual-companion.md` | Modify | Skill instructions: rewrite loop to non-blocking flow |
24
+ | `tests/brainstorm-server/server.test.js` | Modify | Tests: update for new template structure and helper.js API |
25
+
26
+ ---
27
+
28
+ ## Chunk 1: Server, Template, Client, Tests, Skill
29
+
30
+ ### Task 1: Update `frame-template.html`
31
+
32
+ **Files:**
33
+ - Modify: `lib/brainstorm-server/frame-template.html`
34
+
35
+ - [ ] **Step 1: Remove the feedback footer HTML**
36
+
37
+ Replace the feedback-footer div (lines 227-233) with a selection indicator bar:
38
+
39
+ ```html
40
+ <div class="indicator-bar">
41
+ <span id="indicator-text">Click an option above, then return to the terminal</span>
42
+ </div>
43
+ ```
44
+
45
+ Also replace the default content inside `#claude-content` (lines 220-223) with the content placeholder:
46
+
47
+ ```html
48
+ <div id="claude-content">
49
+ <!-- CONTENT -->
50
+ </div>
51
+ ```
52
+
53
+ - [ ] **Step 2: Replace feedback footer CSS with indicator bar CSS**
54
+
55
+ Remove the `.feedback-footer`, `.feedback-footer label`, `.feedback-row`, and the textarea/button styles within `.feedback-footer` (lines 82-112).
56
+
57
+ Add indicator bar CSS:
58
+
59
+ ```css
60
+ .indicator-bar {
61
+ background: var(--bg-secondary);
62
+ border-top: 1px solid var(--border);
63
+ padding: 0.5rem 1.5rem;
64
+ flex-shrink: 0;
65
+ text-align: center;
66
+ }
67
+ .indicator-bar span {
68
+ font-size: 0.75rem;
69
+ color: var(--text-secondary);
70
+ }
71
+ .indicator-bar .selected-text {
72
+ color: var(--accent);
73
+ font-weight: 500;
74
+ }
75
+ ```
76
+
77
+ - [ ] **Step 3: Verify template renders**
78
+
79
+ Run the test suite to check the template still loads:
80
+ ```bash
81
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
82
+ ```
83
+ Expected: Tests 1-5 should still pass. Tests 6-8 may fail (expected — they assert old structure).
84
+
85
+ - [ ] **Step 4: Commit**
86
+
87
+ ```bash
88
+ git add lib/brainstorm-server/frame-template.html
89
+ git commit -m "Replace feedback footer with selection indicator bar in brainstorm template"
90
+ ```
91
+
92
+ ---
93
+
94
+ ### Task 2: Update `index.js` — content injection and `.events` file
95
+
96
+ **Files:**
97
+ - Modify: `lib/brainstorm-server/index.js`
98
+
99
+ - [ ] **Step 1: Write failing test for `.events` file writing**
100
+
101
+ Add to `tests/brainstorm-server/server.test.js` after Test 4 area — a new test that sends a WebSocket event with a `choice` field and verifies `.events` file is written:
102
+
103
+ ```javascript
104
+ // Test: Choice events written to .events file
105
+ console.log('Test: Choice events written to .events file');
106
+ const ws3 = new WebSocket(`ws://localhost:${TEST_PORT}`);
107
+ await new Promise(resolve => ws3.on('open', resolve));
108
+
109
+ ws3.send(JSON.stringify({ type: 'click', choice: 'a', text: 'Option A' }));
110
+ await sleep(300);
111
+
112
+ const eventsFile = path.join(TEST_DIR, '.events');
113
+ assert(fs.existsSync(eventsFile), '.events file should exist after choice click');
114
+ const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\n');
115
+ const event = JSON.parse(lines[lines.length - 1]);
116
+ assert.strictEqual(event.choice, 'a', 'Event should contain choice');
117
+ assert.strictEqual(event.text, 'Option A', 'Event should contain text');
118
+ ws3.close();
119
+ console.log(' PASS');
120
+ ```
121
+
122
+ - [ ] **Step 2: Run test to verify it fails**
123
+
124
+ ```bash
125
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
126
+ ```
127
+ Expected: New test FAILS — `.events` file doesn't exist yet.
128
+
129
+ - [ ] **Step 3: Write failing test for `.events` file clearing on new screen**
130
+
131
+ Add another test:
132
+
133
+ ```javascript
134
+ // Test: .events cleared on new screen
135
+ console.log('Test: .events cleared on new screen');
136
+ // .events file should still exist from previous test
137
+ assert(fs.existsSync(path.join(TEST_DIR, '.events')), '.events should exist before new screen');
138
+ fs.writeFileSync(path.join(TEST_DIR, 'new-screen.html'), '<h2>New screen</h2>');
139
+ await sleep(500);
140
+ assert(!fs.existsSync(path.join(TEST_DIR, '.events')), '.events should be cleared after new screen');
141
+ console.log(' PASS');
142
+ ```
143
+
144
+ - [ ] **Step 4: Run test to verify it fails**
145
+
146
+ ```bash
147
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
148
+ ```
149
+ Expected: New test FAILS — `.events` not cleared on screen push.
150
+
151
+ - [ ] **Step 5: Implement `.events` file writing in `index.js`**
152
+
153
+ In the WebSocket `message` handler (line 74-77 of `index.js`), after the `console.log`, add:
154
+
155
+ ```javascript
156
+ // Write user events to .events file for Claude to read
157
+ if (event.choice) {
158
+ const eventsFile = path.join(SCREEN_DIR, '.events');
159
+ fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
160
+ }
161
+ ```
162
+
163
+ In the chokidar `add` handler (line 104-111), add `.events` clearing:
164
+
165
+ ```javascript
166
+ if (filePath.endsWith('.html')) {
167
+ // Clear events from previous screen
168
+ const eventsFile = path.join(SCREEN_DIR, '.events');
169
+ if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
170
+
171
+ console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
172
+ // ... existing reload broadcast
173
+ }
174
+ ```
175
+
176
+ - [ ] **Step 6: Replace `wrapInFrame` with comment placeholder injection**
177
+
178
+ Replace the `wrapInFrame` function (lines 27-32 of `index.js`):
179
+
180
+ ```javascript
181
+ function wrapInFrame(content) {
182
+ return frameTemplate.replace('<!-- CONTENT -->', content);
183
+ }
184
+ ```
185
+
186
+ - [ ] **Step 7: Run all tests**
187
+
188
+ ```bash
189
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
190
+ ```
191
+ Expected: New `.events` tests PASS. Existing tests may still have failures from old assertions (fixed in Task 4).
192
+
193
+ - [ ] **Step 8: Commit**
194
+
195
+ ```bash
196
+ git add lib/brainstorm-server/index.js tests/brainstorm-server/server.test.js
197
+ git commit -m "Add .events file writing and comment-based content injection to brainstorm server"
198
+ ```
199
+
200
+ ---
201
+
202
+ ### Task 3: Simplify `helper.js`
203
+
204
+ **Files:**
205
+ - Modify: `lib/brainstorm-server/helper.js`
206
+
207
+ - [ ] **Step 1: Remove `sendToClaude` function**
208
+
209
+ Delete the `sendToClaude` function (lines 92-106) — the function body and the page takeover HTML.
210
+
211
+ - [ ] **Step 2: Remove `window.send` function**
212
+
213
+ Delete the `window.send` function (lines 120-129) — was tied to the removed Send button.
214
+
215
+ - [ ] **Step 3: Remove form submission and input change handlers**
216
+
217
+ Delete the form submission handler (lines 57-71) and the input change handler (lines 73-89) including the `inputTimeout` variable.
218
+
219
+ - [ ] **Step 4: Remove `pageshow` event listener**
220
+
221
+ Delete the `pageshow` listener we added earlier (no textarea to clear anymore).
222
+
223
+ - [ ] **Step 5: Narrow click handler to `[data-choice]` only**
224
+
225
+ Replace the click handler (lines 36-55) with a narrower version:
226
+
227
+ ```javascript
228
+ // Capture clicks on choice elements
229
+ document.addEventListener('click', (e) => {
230
+ const target = e.target.closest('[data-choice]');
231
+ if (!target) return;
232
+
233
+ sendEvent({
234
+ type: 'click',
235
+ text: target.textContent.trim(),
236
+ choice: target.dataset.choice,
237
+ id: target.id || null
238
+ });
239
+ });
240
+ ```
241
+
242
+ - [ ] **Step 6: Add indicator bar update on choice click**
243
+
244
+ After the `sendEvent` call in the click handler, add:
245
+
246
+ ```javascript
247
+ // Update indicator bar
248
+ const indicator = document.getElementById('indicator-text');
249
+ if (indicator) {
250
+ const label = target.querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || target.dataset.choice;
251
+ indicator.innerHTML = '<span class="selected-text">' + label + ' selected</span> — return to terminal to continue';
252
+ }
253
+ ```
254
+
255
+ - [ ] **Step 7: Remove `sendToClaude` from `window.brainstorm` API**
256
+
257
+ Update the `window.brainstorm` object (lines 132-136) to remove `sendToClaude`:
258
+
259
+ ```javascript
260
+ window.brainstorm = {
261
+ send: sendEvent,
262
+ choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
263
+ };
264
+ ```
265
+
266
+ - [ ] **Step 8: Run tests**
267
+
268
+ ```bash
269
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
270
+ ```
271
+
272
+ - [ ] **Step 9: Commit**
273
+
274
+ ```bash
275
+ git add lib/brainstorm-server/helper.js
276
+ git commit -m "Simplify helper.js: remove feedback functions, narrow to choice capture + indicator"
277
+ ```
278
+
279
+ ---
280
+
281
+ ### Task 4: Update tests for new structure
282
+
283
+ **Files:**
284
+ - Modify: `tests/brainstorm-server/server.test.js`
285
+
286
+ **Note:** Line references below are from the _original_ file. Task 2 inserted new tests earlier in the file, so actual line numbers will be shifted. Find tests by their `console.log` labels (e.g., "Test 5:", "Test 6:").
287
+
288
+ - [ ] **Step 1: Update Test 5 (full document assertion)**
289
+
290
+ Find the Test 5 assertion `!fullRes.body.includes('feedback-footer')`. Change it to: Full documents should NOT have the indicator bar either (they're served as-is):
291
+
292
+ ```javascript
293
+ assert(!fullRes.body.includes('indicator-bar') || fullDoc.includes('indicator-bar'),
294
+ 'Should not wrap full documents in frame template');
295
+ ```
296
+
297
+ - [ ] **Step 2: Update Test 6 (fragment wrapping)**
298
+
299
+ Line 125: Replace `feedback-footer` assertion with indicator bar assertion:
300
+
301
+ ```javascript
302
+ assert(fragRes.body.includes('indicator-bar'), 'Fragment should get indicator bar from frame');
303
+ ```
304
+
305
+ Also verify content placeholder was replaced (fragment content appears, placeholder comment doesn't):
306
+
307
+ ```javascript
308
+ assert(!fragRes.body.includes('<!-- CONTENT -->'), 'Content placeholder should be replaced');
309
+ ```
310
+
311
+ - [ ] **Step 3: Update Test 7 (helper.js API)**
312
+
313
+ Lines 140-142: Update assertions to reflect the new API surface:
314
+
315
+ ```javascript
316
+ assert(helperContent.includes('toggleSelect'), 'helper.js should define toggleSelect');
317
+ assert(helperContent.includes('sendEvent'), 'helper.js should define sendEvent');
318
+ assert(helperContent.includes('selectedChoice'), 'helper.js should track selectedChoice');
319
+ assert(helperContent.includes('brainstorm'), 'helper.js should expose brainstorm API');
320
+ assert(!helperContent.includes('sendToClaude'), 'helper.js should not contain sendToClaude');
321
+ ```
322
+
323
+ - [ ] **Step 4: Replace Test 8 (sendToClaude theming) with indicator bar test**
324
+
325
+ Replace Test 8 (lines 145-149) — `sendToClaude` no longer exists. Test the indicator bar instead:
326
+
327
+ ```javascript
328
+ // Test 8: Indicator bar uses CSS variables (theme support)
329
+ console.log('Test 8: Indicator bar uses CSS variables');
330
+ const templateContent = fs.readFileSync(
331
+ path.join(__dirname, '../../lib/brainstorm-server/frame-template.html'), 'utf-8'
332
+ );
333
+ assert(templateContent.includes('indicator-bar'), 'Template should have indicator bar');
334
+ assert(templateContent.includes('indicator-text'), 'Template should have indicator text element');
335
+ console.log(' PASS');
336
+ ```
337
+
338
+ - [ ] **Step 5: Run full test suite**
339
+
340
+ ```bash
341
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
342
+ ```
343
+ Expected: ALL tests PASS.
344
+
345
+ - [ ] **Step 6: Commit**
346
+
347
+ ```bash
348
+ git add tests/brainstorm-server/server.test.js
349
+ git commit -m "Update brainstorm server tests for new template structure and helper.js API"
350
+ ```
351
+
352
+ ---
353
+
354
+ ### Task 5: Delete `wait-for-feedback.sh`
355
+
356
+ **Files:**
357
+ - Delete: `lib/brainstorm-server/wait-for-feedback.sh`
358
+
359
+ - [ ] **Step 1: Verify no other files import or reference `wait-for-feedback.sh`**
360
+
361
+ Search the codebase:
362
+ ```bash
363
+ grep -r "wait-for-feedback" /Users/drewritter/prime-rad/superpowers/ --include="*.js" --include="*.md" --include="*.sh" --include="*.json"
364
+ ```
365
+
366
+ Expected references: only `visual-companion.md` (rewritten in Task 6) and possibly release notes (historical, leave as-is).
367
+
368
+ - [ ] **Step 2: Delete the file**
369
+
370
+ ```bash
371
+ rm lib/brainstorm-server/wait-for-feedback.sh
372
+ ```
373
+
374
+ - [ ] **Step 3: Run tests to confirm nothing breaks**
375
+
376
+ ```bash
377
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
378
+ ```
379
+ Expected: All tests PASS (no test referenced this file).
380
+
381
+ - [ ] **Step 4: Commit**
382
+
383
+ ```bash
384
+ git add -u lib/brainstorm-server/wait-for-feedback.sh
385
+ git commit -m "Delete wait-for-feedback.sh: replaced by .events file"
386
+ ```
387
+
388
+ ---
389
+
390
+ ### Task 6: Rewrite `visual-companion.md`
391
+
392
+ **Files:**
393
+ - Modify: `skills/brainstorming/visual-companion.md`
394
+
395
+ - [ ] **Step 1: Update "How It Works" description (line 18)**
396
+
397
+ Replace the sentence about receiving feedback "as JSON" with:
398
+
399
+ ```markdown
400
+ 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 and can click to select options. Selections are recorded to a `.events` file that you read on your next turn.
401
+ ```
402
+
403
+ - [ ] **Step 2: Update fragment description (line 20)**
404
+
405
+ Remove "feedback footer" from the description of what the frame template provides:
406
+
407
+ ```markdown
408
+ **Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
409
+ ```
410
+
411
+ - [ ] **Step 3: Rewrite "The Loop" section (lines 36-61)**
412
+
413
+ Replace the entire "The Loop" section with:
414
+
415
+ ```markdown
416
+ ## The Loop
417
+
418
+ 1. **Write HTML** to a new file in `screen_dir`:
419
+ - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
420
+ - **Never reuse filenames** — each screen gets a fresh file
421
+ - Use Write tool — **never use cat/heredoc** (dumps noise into terminal)
422
+ - Server automatically serves the newest file
423
+
424
+ 2. **Tell user what to expect and end your turn:**
425
+ - Remind them of the URL (every step, not just first)
426
+ - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
427
+ - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like."
428
+
429
+ 3. **On your next turn** — after the user responds in the terminal:
430
+ - Read `$SCREEN_DIR/.events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines
431
+ - Merge with the user's terminal text to get the full picture
432
+ - The terminal message is the primary feedback; `.events` provides structured interaction data
433
+
434
+ 4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.
435
+
436
+ 5. Repeat until done.
437
+ ```
438
+
439
+ - [ ] **Step 4: Replace "User Feedback Format" section (lines 165-174)**
440
+
441
+ Replace with:
442
+
443
+ ```markdown
444
+ ## Browser Events Format
445
+
446
+ When the user clicks options in the browser, their interactions are recorded to `$SCREEN_DIR/.events` (one JSON object per line). The file is cleared automatically when you push a new screen.
447
+
448
+ ```jsonl
449
+ {"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
450
+ {"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
451
+ {"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
452
+ ```
453
+
454
+ The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
455
+
456
+ If `.events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
457
+ ```
458
+
459
+ - [ ] **Step 5: Update "Writing Content Fragments" description (line 65)**
460
+
461
+ Remove "feedback footer" reference:
462
+
463
+ ```markdown
464
+ Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure).
465
+ ```
466
+
467
+ - [ ] **Step 6: Update Reference section (lines 200-203)**
468
+
469
+ Remove the helper.js reference description about "JS API" — the API is now minimal. Keep the path reference:
470
+
471
+ ```markdown
472
+ ## Reference
473
+
474
+ - Frame template (CSS reference): `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/frame-template.html`
475
+ - Helper script (client-side): `${CLAUDE_PLUGIN_ROOT}/lib/brainstorm-server/helper.js`
476
+ ```
477
+
478
+ - [ ] **Step 7: Commit**
479
+
480
+ ```bash
481
+ git add skills/brainstorming/visual-companion.md
482
+ git commit -m "Rewrite visual-companion.md for non-blocking browser-displays-terminal-commands flow"
483
+ ```
484
+
485
+ ---
486
+
487
+ ### Task 7: Final verification
488
+
489
+ - [ ] **Step 1: Run full test suite**
490
+
491
+ ```bash
492
+ cd /Users/drewritter/prime-rad/superpowers && node tests/brainstorm-server/server.test.js
493
+ ```
494
+ Expected: ALL tests PASS.
495
+
496
+ - [ ] **Step 2: Manual smoke test**
497
+
498
+ Start the server manually and verify the flow works end-to-end:
499
+
500
+ ```bash
501
+ cd /Users/drewritter/prime-rad/superpowers && lib/brainstorm-server/start-server.sh --project-dir /tmp/brainstorm-smoke-test
502
+ ```
503
+
504
+ Write a test fragment, open in browser, click an option, verify `.events` file is written, verify indicator bar updates. Then stop the server:
505
+
506
+ ```bash
507
+ lib/brainstorm-server/stop-server.sh <screen_dir from start output>
508
+ ```
509
+
510
+ - [ ] **Step 3: Verify no stale references remain**
511
+
512
+ ```bash
513
+ grep -r "wait-for-feedback\|sendToClaude\|feedback-footer\|send-to-claude\|TaskOutput.*block.*true" /Users/drewritter/prime-rad/superpowers/ --include="*.js" --include="*.md" --include="*.sh" --include="*.html" | grep -v node_modules | grep -v RELEASE-NOTES | grep -v "\.md:.*spec\|plan"
514
+ ```
515
+
516
+ Expected: No hits outside of release notes and the spec/plan docs (which are historical).
517
+
518
+ - [ ] **Step 4: Final commit if any cleanup needed**
519
+
520
+ ```bash
521
+ git status
522
+ # Review untracked/modified files, stage specific files as needed, commit if clean
523
+ ```
github_code/obra__superpowers/docs/superpowers/plans/2026-03-11-zero-dep-brainstorm-server.md ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Zero-Dependency Brainstorm Server Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Replace the brainstorm server's vendored node_modules with a single zero-dependency `server.js` using Node built-ins.
6
+
7
+ **Architecture:** Single file with WebSocket protocol (RFC 6455 text frames), HTTP server (`http` module), and file watching (`fs.watch`). Exports protocol functions for unit testing when required as a module.
8
+
9
+ **Tech Stack:** Node.js built-ins only: `http`, `crypto`, `fs`, `path`
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-03-11-zero-dep-brainstorm-server-design.md`
12
+
13
+ **Existing tests:** `tests/brainstorm-server/ws-protocol.test.js` (unit), `tests/brainstorm-server/server.test.js` (integration)
14
+
15
+ ---
16
+
17
+ ## File Map
18
+
19
+ - **Create:** `skills/brainstorming/scripts/server.js` — the zero-dep replacement
20
+ - **Modify:** `skills/brainstorming/scripts/start-server.sh:94,100` — change `index.js` to `server.js`
21
+ - **Modify:** `.gitignore:6` — remove the `!skills/brainstorming/scripts/node_modules/` exception
22
+ - **Delete:** `skills/brainstorming/scripts/index.js`
23
+ - **Delete:** `skills/brainstorming/scripts/package.json`
24
+ - **Delete:** `skills/brainstorming/scripts/package-lock.json`
25
+ - **Delete:** `skills/brainstorming/scripts/node_modules/` (714 files)
26
+ - **No changes:** `skills/brainstorming/scripts/helper.js`, `skills/brainstorming/scripts/frame-template.html`, `skills/brainstorming/scripts/stop-server.sh`
27
+
28
+ ---
29
+
30
+ ## Chunk 1: WebSocket Protocol Layer
31
+
32
+ ### Task 1: Implement WebSocket protocol exports
33
+
34
+ **Files:**
35
+ - Create: `skills/brainstorming/scripts/server.js`
36
+ - Test: `tests/brainstorm-server/ws-protocol.test.js` (already exists)
37
+
38
+ - [ ] **Step 1: Create server.js with OPCODES constant and computeAcceptKey**
39
+
40
+ ```js
41
+ const crypto = require('crypto');
42
+
43
+ const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
44
+ const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
45
+
46
+ function computeAcceptKey(clientKey) {
47
+ return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
48
+ }
49
+ ```
50
+
51
+ - [ ] **Step 2: Implement encodeFrame**
52
+
53
+ Server frames are never masked. Three length encodings:
54
+ - payload < 126: 2-byte header (FIN+opcode, length)
55
+ - 126-65535: 4-byte header (FIN+opcode, 126, 16-bit length)
56
+ - &gt; 65535: 10-byte header (FIN+opcode, 127, 64-bit length)
57
+
58
+ ```js
59
+ function encodeFrame(opcode, payload) {
60
+ const fin = 0x80;
61
+ const len = payload.length;
62
+ let header;
63
+
64
+ if (len < 126) {
65
+ header = Buffer.alloc(2);
66
+ header[0] = fin | opcode;
67
+ header[1] = len;
68
+ } else if (len < 65536) {
69
+ header = Buffer.alloc(4);
70
+ header[0] = fin | opcode;
71
+ header[1] = 126;
72
+ header.writeUInt16BE(len, 2);
73
+ } else {
74
+ header = Buffer.alloc(10);
75
+ header[0] = fin | opcode;
76
+ header[1] = 127;
77
+ header.writeBigUInt64BE(BigInt(len), 2);
78
+ }
79
+
80
+ return Buffer.concat([header, payload]);
81
+ }
82
+ ```
83
+
84
+ - [ ] **Step 3: Implement decodeFrame**
85
+
86
+ Client frames are always masked. Returns `{ opcode, payload, bytesConsumed }` or `null` for incomplete. Throws on unmasked frames.
87
+
88
+ ```js
89
+ function decodeFrame(buffer) {
90
+ if (buffer.length < 2) return null;
91
+
92
+ const firstByte = buffer[0];
93
+ const secondByte = buffer[1];
94
+ const opcode = firstByte & 0x0F;
95
+ const masked = (secondByte & 0x80) !== 0;
96
+ let payloadLen = secondByte & 0x7F;
97
+ let offset = 2;
98
+
99
+ if (!masked) throw new Error('Client frames must be masked');
100
+
101
+ if (payloadLen === 126) {
102
+ if (buffer.length < 4) return null;
103
+ payloadLen = buffer.readUInt16BE(2);
104
+ offset = 4;
105
+ } else if (payloadLen === 127) {
106
+ if (buffer.length < 10) return null;
107
+ payloadLen = Number(buffer.readBigUInt64BE(2));
108
+ offset = 10;
109
+ }
110
+
111
+ const maskOffset = offset;
112
+ const dataOffset = offset + 4;
113
+ const totalLen = dataOffset + payloadLen;
114
+ if (buffer.length < totalLen) return null;
115
+
116
+ const mask = buffer.slice(maskOffset, dataOffset);
117
+ const data = Buffer.alloc(payloadLen);
118
+ for (let i = 0; i < payloadLen; i++) {
119
+ data[i] = buffer[dataOffset + i] ^ mask[i % 4];
120
+ }
121
+
122
+ return { opcode, payload: data, bytesConsumed: totalLen };
123
+ }
124
+ ```
125
+
126
+ - [ ] **Step 4: Add module exports at the bottom of the file**
127
+
128
+ ```js
129
+ module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };
130
+ ```
131
+
132
+ - [ ] **Step 5: Run unit tests**
133
+
134
+ Run: `cd tests/brainstorm-server && node ws-protocol.test.js`
135
+ Expected: All tests pass (handshake, encoding, decoding, boundaries, edge cases)
136
+
137
+ - [ ] **Step 6: Commit**
138
+
139
+ ```bash
140
+ git add skills/brainstorming/scripts/server.js
141
+ git commit -m "Add WebSocket protocol layer for zero-dep brainstorm server"
142
+ ```
143
+
144
+ ---
145
+
146
+ ## Chunk 2: HTTP Server and Application Logic
147
+
148
+ ### Task 2: Add HTTP server, file watching, and WebSocket connection handling
149
+
150
+ **Files:**
151
+ - Modify: `skills/brainstorming/scripts/server.js`
152
+ - Test: `tests/brainstorm-server/server.test.js` (already exists)
153
+
154
+ - [ ] **Step 1: Add configuration and constants at top of server.js (after requires)**
155
+
156
+ ```js
157
+ const http = require('http');
158
+ const fs = require('fs');
159
+ const path = require('path');
160
+
161
+ const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
162
+ const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
163
+ const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
164
+ const SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
165
+
166
+ const MIME_TYPES = {
167
+ '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
168
+ '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
169
+ '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
170
+ };
171
+ ```
172
+
173
+ - [ ] **Step 2: Add WAITING_PAGE, template loading at module scope, and helper functions**
174
+
175
+ Load `frameTemplate` and `helperInjection` at module scope so they're accessible to `wrapInFrame` and `handleRequest`. They only read files from `__dirname` (the scripts directory), which is valid whether the module is required or run directly.
176
+
177
+ ```js
178
+ const WAITING_PAGE = `<!DOCTYPE html>
179
+ <html>
180
+ <head><title>Brainstorm Companion</title>
181
+ <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
182
+ h1 { color: #333; } p { color: #666; }</style>
183
+ </head>
184
+ <body><h1>Brainstorm Companion</h1>
185
+ <p>Waiting for Claude to push a screen...</p></body></html>`;
186
+
187
+ const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
188
+ const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
189
+ const helperInjection = '<script>\n' + helperScript + '\n</script>';
190
+
191
+ function isFullDocument(html) {
192
+ const trimmed = html.trimStart().toLowerCase();
193
+ return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
194
+ }
195
+
196
+ function wrapInFrame(content) {
197
+ return frameTemplate.replace('<!-- CONTENT -->', content);
198
+ }
199
+
200
+ function getNewestScreen() {
201
+ const files = fs.readdirSync(SCREEN_DIR)
202
+ .filter(f => f.endsWith('.html'))
203
+ .map(f => {
204
+ const fp = path.join(SCREEN_DIR, f);
205
+ return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
206
+ })
207
+ .sort((a, b) => b.mtime - a.mtime);
208
+ return files.length > 0 ? files[0].path : null;
209
+ }
210
+ ```
211
+
212
+ - [ ] **Step 3: Add HTTP request handler**
213
+
214
+ ```js
215
+ function handleRequest(req, res) {
216
+ if (req.method === 'GET' && req.url === '/') {
217
+ const screenFile = getNewestScreen();
218
+ let html = screenFile
219
+ ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
220
+ : WAITING_PAGE;
221
+
222
+ if (html.includes('</body>')) {
223
+ html = html.replace('</body>', helperInjection + '\n</body>');
224
+ } else {
225
+ html += helperInjection;
226
+ }
227
+
228
+ res.writeHead(200, { 'Content-Type': 'text/html' });
229
+ res.end(html);
230
+ } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
231
+ const fileName = req.url.slice(7); // strip '/files/'
232
+ const filePath = path.join(SCREEN_DIR, path.basename(fileName));
233
+ if (!fs.existsSync(filePath)) {
234
+ res.writeHead(404);
235
+ res.end('Not found');
236
+ return;
237
+ }
238
+ const ext = path.extname(filePath).toLowerCase();
239
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
240
+ res.writeHead(200, { 'Content-Type': contentType });
241
+ res.end(fs.readFileSync(filePath));
242
+ } else {
243
+ res.writeHead(404);
244
+ res.end('Not found');
245
+ }
246
+ }
247
+ ```
248
+
249
+ - [ ] **Step 4: Add WebSocket connection handling**
250
+
251
+ ```js
252
+ const clients = new Set();
253
+
254
+ function handleUpgrade(req, socket) {
255
+ const key = req.headers['sec-websocket-key'];
256
+ if (!key) { socket.destroy(); return; }
257
+
258
+ const accept = computeAcceptKey(key);
259
+ socket.write(
260
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
261
+ 'Upgrade: websocket\r\n' +
262
+ 'Connection: Upgrade\r\n' +
263
+ 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
264
+ );
265
+
266
+ let buffer = Buffer.alloc(0);
267
+ clients.add(socket);
268
+
269
+ socket.on('data', (chunk) => {
270
+ buffer = Buffer.concat([buffer, chunk]);
271
+ while (buffer.length > 0) {
272
+ let result;
273
+ try {
274
+ result = decodeFrame(buffer);
275
+ } catch (e) {
276
+ socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
277
+ clients.delete(socket);
278
+ return;
279
+ }
280
+ if (!result) break;
281
+ buffer = buffer.slice(result.bytesConsumed);
282
+
283
+ switch (result.opcode) {
284
+ case OPCODES.TEXT:
285
+ handleMessage(result.payload.toString());
286
+ break;
287
+ case OPCODES.CLOSE:
288
+ socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
289
+ clients.delete(socket);
290
+ return;
291
+ case OPCODES.PING:
292
+ socket.write(encodeFrame(OPCODES.PONG, result.payload));
293
+ break;
294
+ case OPCODES.PONG:
295
+ break;
296
+ default:
297
+ // Unsupported opcode — close with 1003
298
+ const closeBuf = Buffer.alloc(2);
299
+ closeBuf.writeUInt16BE(1003);
300
+ socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
301
+ clients.delete(socket);
302
+ return;
303
+ }
304
+ }
305
+ });
306
+
307
+ socket.on('close', () => clients.delete(socket));
308
+ socket.on('error', () => clients.delete(socket));
309
+ }
310
+
311
+ function handleMessage(text) {
312
+ let event;
313
+ try {
314
+ event = JSON.parse(text);
315
+ } catch (e) {
316
+ console.error('Failed to parse WebSocket message:', e.message);
317
+ return;
318
+ }
319
+ console.log(JSON.stringify({ source: 'user-event', ...event }));
320
+ if (event.choice) {
321
+ const eventsFile = path.join(SCREEN_DIR, '.events');
322
+ fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
323
+ }
324
+ }
325
+
326
+ function broadcast(msg) {
327
+ const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
328
+ for (const socket of clients) {
329
+ try { socket.write(frame); } catch (e) { clients.delete(socket); }
330
+ }
331
+ }
332
+ ```
333
+
334
+ - [ ] **Step 5: Add debounce timer map**
335
+
336
+ ```js
337
+ const debounceTimers = new Map();
338
+ ```
339
+
340
+ File watching logic is inlined in `startServer` (Step 6) to keep watcher lifecycle together with server lifecycle and include an `error` handler per spec.
341
+
342
+ - [ ] **Step 6: Add startServer function and conditional main**
343
+
344
+ `frameTemplate` and `helperInjection` are already at module scope (Step 2). `startServer` just creates the screen dir, starts the HTTP server, watcher, and logs startup info.
345
+
346
+ ```js
347
+ function startServer() {
348
+ if (!fs.existsSync(SCREEN_DIR)) fs.mkdirSync(SCREEN_DIR, { recursive: true });
349
+
350
+ const server = http.createServer(handleRequest);
351
+ server.on('upgrade', handleUpgrade);
352
+
353
+ const watcher = fs.watch(SCREEN_DIR, (eventType, filename) => {
354
+ if (!filename || !filename.endsWith('.html')) return;
355
+ if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
356
+ debounceTimers.set(filename, setTimeout(() => {
357
+ debounceTimers.delete(filename);
358
+ const filePath = path.join(SCREEN_DIR, filename);
359
+ if (eventType === 'rename' && fs.existsSync(filePath)) {
360
+ const eventsFile = path.join(SCREEN_DIR, '.events');
361
+ if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
362
+ console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
363
+ } else if (eventType === 'change') {
364
+ console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
365
+ }
366
+ broadcast({ type: 'reload' });
367
+ }, 100));
368
+ });
369
+ watcher.on('error', (err) => console.error('fs.watch error:', err.message));
370
+
371
+ server.listen(PORT, HOST, () => {
372
+ const info = JSON.stringify({
373
+ type: 'server-started', port: Number(PORT), host: HOST,
374
+ url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
375
+ screen_dir: SCREEN_DIR
376
+ });
377
+ console.log(info);
378
+ fs.writeFileSync(path.join(SCREEN_DIR, '.server-info'), info + '\n');
379
+ });
380
+ }
381
+
382
+ if (require.main === module) {
383
+ startServer();
384
+ }
385
+ ```
386
+
387
+ - [ ] **Step 7: Run integration tests**
388
+
389
+ The test directory already has a `package.json` with `ws` as a dependency. Install it if needed, then run tests.
390
+
391
+ Run: `cd tests/brainstorm-server && npm install && node server.test.js`
392
+ Expected: All tests pass
393
+
394
+ - [ ] **Step 8: Commit**
395
+
396
+ ```bash
397
+ git add skills/brainstorming/scripts/server.js
398
+ git commit -m "Add HTTP server, WebSocket handling, and file watching to server.js"
399
+ ```
400
+
401
+ ---
402
+
403
+ ## Chunk 3: Swap and Cleanup
404
+
405
+ ### Task 3: Update start-server.sh and remove old files
406
+
407
+ **Files:**
408
+ - Modify: `skills/brainstorming/scripts/start-server.sh:94,100`
409
+ - Modify: `.gitignore:6`
410
+ - Delete: `skills/brainstorming/scripts/index.js`
411
+ - Delete: `skills/brainstorming/scripts/package.json`
412
+ - Delete: `skills/brainstorming/scripts/package-lock.json`
413
+ - Delete: `skills/brainstorming/scripts/node_modules/` (entire directory)
414
+
415
+ - [ ] **Step 1: Update start-server.sh — change `index.js` to `server.js`**
416
+
417
+ Two lines to change:
418
+
419
+ Line 94: `env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" node server.js`
420
+
421
+ Line 100: `nohup env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" node server.js > "$LOG_FILE" 2>&1 &`
422
+
423
+ - [ ] **Step 2: Remove the gitignore exception for node_modules**
424
+
425
+ In `.gitignore`, delete line 6: `!skills/brainstorming/scripts/node_modules/`
426
+
427
+ - [ ] **Step 3: Delete old files**
428
+
429
+ ```bash
430
+ git rm skills/brainstorming/scripts/index.js
431
+ git rm skills/brainstorming/scripts/package.json
432
+ git rm skills/brainstorming/scripts/package-lock.json
433
+ git rm -r skills/brainstorming/scripts/node_modules/
434
+ ```
435
+
436
+ - [ ] **Step 4: Run both test suites**
437
+
438
+ Run: `cd tests/brainstorm-server && node ws-protocol.test.js && node server.test.js`
439
+ Expected: All tests pass
440
+
441
+ - [ ] **Step 5: Commit**
442
+
443
+ ```bash
444
+ git add skills/brainstorming/scripts/ .gitignore
445
+ git commit -m "Remove vendored node_modules, swap to zero-dep server.js"
446
+ ```
447
+
448
+ ### Task 4: Manual smoke test
449
+
450
+ - [ ] **Step 1: Start the server manually**
451
+
452
+ ```bash
453
+ cd skills/brainstorming/scripts
454
+ BRAINSTORM_DIR=/tmp/brainstorm-smoke BRAINSTORM_PORT=9876 node server.js
455
+ ```
456
+
457
+ Expected: `server-started` JSON printed with port 9876
458
+
459
+ - [ ] **Step 2: Open browser to http://localhost:9876**
460
+
461
+ Expected: Waiting page with "Waiting for Claude to push a screen..."
462
+
463
+ - [ ] **Step 3: Write an HTML file to the screen directory**
464
+
465
+ ```bash
466
+ echo '<h2>Hello from smoke test</h2>' > /tmp/brainstorm-smoke/test.html
467
+ ```
468
+
469
+ Expected: Browser reloads and shows "Hello from smoke test" wrapped in frame template
470
+
471
+ - [ ] **Step 4: Verify WebSocket works — check browser console**
472
+
473
+ Open browser dev tools. The WebSocket connection should show as connected (no errors in console). The frame template's status indicator should show "Connected".
474
+
475
+ - [ ] **Step 5: Stop server with Ctrl-C, clean up**
476
+
477
+ ```bash
478
+ rm -rf /tmp/brainstorm-smoke
479
+ ```
github_code/obra__superpowers/docs/superpowers/plans/2026-03-23-codex-app-compatibility.md ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Codex App Compatibility Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Make `using-git-worktrees`, `finishing-a-development-branch`, and related skills work in the Codex App's sandboxed worktree environment without breaking existing behavior.
6
+
7
+ **Architecture:** Read-only environment detection (`git-dir` vs `git-common-dir`) at the start of two skills. If already in a linked worktree, skip creation. If on detached HEAD, emit a handoff payload instead of the 4-option menu. Sandbox fallback catches permission errors during worktree creation.
8
+
9
+ **Tech Stack:** Git, Markdown (skill files are instruction documents, not executable code)
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-03-23-codex-app-compatibility-design.md`
12
+
13
+ ---
14
+
15
+ ## File Structure
16
+
17
+ | File | Responsibility | Action |
18
+ |---|---|---|
19
+ | `skills/using-git-worktrees/SKILL.md` | Worktree creation + isolation | Add Step 0 detection + sandbox fallback |
20
+ | `skills/finishing-a-development-branch/SKILL.md` | Branch finishing workflow | Add Step 1.5 detection + cleanup guard |
21
+ | `skills/subagent-driven-development/SKILL.md` | Plan execution with subagents | Update Integration description |
22
+ | `skills/executing-plans/SKILL.md` | Plan execution inline | Update Integration description |
23
+ | `skills/using-superpowers/references/codex-tools.md` | Codex platform reference | Add detection + finishing docs |
24
+
25
+ ---
26
+
27
+ ### Task 1: Add Step 0 to `using-git-worktrees`
28
+
29
+ **Files:**
30
+ - Modify: `skills/using-git-worktrees/SKILL.md:14-15` (insert after Overview, before Directory Selection Process)
31
+
32
+ - [ ] **Step 1: Read the current skill file**
33
+
34
+ Read `skills/using-git-worktrees/SKILL.md` in full. Identify the exact insertion point: after the "Announce at start" line (line 14) and before "## Directory Selection Process" (line 16).
35
+
36
+ - [ ] **Step 2: Insert Step 0 section**
37
+
38
+ Insert the following between the Overview section and "## Directory Selection Process":
39
+
40
+ ```markdown
41
+ ## Step 0: Check if Already in an Isolated Workspace
42
+
43
+ Before creating a worktree, check if one already exists:
44
+
45
+ ```bash
46
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
47
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
48
+ BRANCH=$(git branch --show-current)
49
+ ```
50
+
51
+ **If `GIT_DIR` differs from `GIT_COMMON`:** You are already inside a linked worktree (created by the Codex App, Claude Code's Agent tool, a previous skill run, or the user). Do NOT create another worktree. Instead:
52
+
53
+ 1. Run project setup (auto-detect package manager as in "Run Project Setup" below)
54
+ 2. Verify clean baseline (run tests as in "Verify Clean Baseline" below)
55
+ 3. Report with branch state:
56
+ - On a branch: "Already in an isolated workspace at `<path>` on branch `<name>`. Tests passing. Ready to implement."
57
+ - Detached HEAD: "Already in an isolated workspace at `<path>` (detached HEAD, externally managed). Tests passing. Note: branch creation needed at finish time. Ready to implement."
58
+
59
+ After reporting, STOP. Do not continue to Directory Selection or Creation Steps.
60
+
61
+ **If `GIT_DIR` equals `GIT_COMMON`:** Proceed with the full worktree creation flow below.
62
+
63
+ **Sandbox fallback:** If you proceed to Creation Steps but `git worktree add -b` fails with a permission error (e.g., "Operation not permitted"), treat this as a late-detected restricted environment. Fall back to the behavior above — run setup and baseline tests in the current directory, report accordingly, and STOP.
64
+ ```
65
+
66
+ - [ ] **Step 3: Verify the insertion**
67
+
68
+ Read the file again. Confirm:
69
+ - Step 0 appears between Overview and Directory Selection Process
70
+ - The rest of the file (Directory Selection, Safety Verification, Creation Steps, etc.) is unchanged
71
+ - No duplicate sections or broken markdown
72
+
73
+ - [ ] **Step 4: Commit**
74
+
75
+ ```bash
76
+ git add skills/using-git-worktrees/SKILL.md
77
+ git commit -m "feat(using-git-worktrees): add Step 0 environment detection (PRI-823)
78
+
79
+ Skip worktree creation when already in a linked worktree. Includes
80
+ sandbox fallback for permission errors on git worktree add."
81
+ ```
82
+
83
+ ---
84
+
85
+ ### Task 2: Update `using-git-worktrees` Integration section
86
+
87
+ **Files:**
88
+ - Modify: `skills/using-git-worktrees/SKILL.md:211-215` (Integration > Called by)
89
+
90
+ - [ ] **Step 1: Update the three "Called by" entries**
91
+
92
+ Change lines 212-214 from:
93
+
94
+ ```markdown
95
+ - **brainstorming** (Phase 4) - REQUIRED when design is approved and implementation follows
96
+ - **subagent-driven-development** - REQUIRED before executing any tasks
97
+ - **executing-plans** - REQUIRED before executing any tasks
98
+ ```
99
+
100
+ To:
101
+
102
+ ```markdown
103
+ - **brainstorming** - REQUIRED: Ensures isolated workspace (creates one or verifies existing)
104
+ - **subagent-driven-development** - REQUIRED: Ensures isolated workspace (creates one or verifies existing)
105
+ - **executing-plans** - REQUIRED: Ensures isolated workspace (creates one or verifies existing)
106
+ ```
107
+
108
+ - [ ] **Step 2: Verify the Integration section**
109
+
110
+ Read the Integration section. Confirm all three entries are updated, "Pairs with" is unchanged.
111
+
112
+ - [ ] **Step 3: Commit**
113
+
114
+ ```bash
115
+ git add skills/using-git-worktrees/SKILL.md
116
+ git commit -m "docs(using-git-worktrees): update Integration descriptions (PRI-823)
117
+
118
+ Clarify that skill ensures a workspace exists, not that it always creates one."
119
+ ```
120
+
121
+ ---
122
+
123
+ ### Task 3: Add Step 1.5 to `finishing-a-development-branch`
124
+
125
+ **Files:**
126
+ - Modify: `skills/finishing-a-development-branch/SKILL.md:38` (insert after Step 1, before Step 2)
127
+
128
+ - [ ] **Step 1: Read the current skill file**
129
+
130
+ Read `skills/finishing-a-development-branch/SKILL.md` in full. Identify the insertion point: after "**If tests pass:** Continue to Step 2." (line 38) and before "### Step 2: Determine Base Branch" (line 40).
131
+
132
+ - [ ] **Step 2: Insert Step 1.5 section**
133
+
134
+ Insert the following between Step 1 and Step 2:
135
+
136
+ ```markdown
137
+ ### Step 1.5: Detect Environment
138
+
139
+ ```bash
140
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
141
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
142
+ BRANCH=$(git branch --show-current)
143
+ ```
144
+
145
+ **Path A — `GIT_DIR` differs from `GIT_COMMON` AND `BRANCH` is empty (externally managed worktree, detached HEAD):**
146
+
147
+ First, ensure all work is staged and committed (`git add` + `git commit`).
148
+
149
+ Then present this to the user (do NOT present the 4-option menu):
150
+
151
+ ```
152
+ Implementation complete. All tests passing.
153
+ Current HEAD: <full-commit-sha>
154
+
155
+ This workspace is externally managed (detached HEAD).
156
+ I cannot create branches, push, or open PRs from here.
157
+
158
+ ⚠ These commits are on a detached HEAD. If you do not create a branch,
159
+ they may be lost when this workspace is cleaned up.
160
+
161
+ If your host application provides these controls:
162
+ - "Create branch" — to name a branch, then commit/push/PR
163
+ - "Hand off to local" — to move changes to your local checkout
164
+
165
+ Suggested branch name: <ticket-id/short-description>
166
+ Suggested commit message: <summary-of-work>
167
+ ```
168
+
169
+ Branch name: use ticket ID if available (e.g., `pri-823/codex-compat`), otherwise slugify the first 5 words of the plan title, otherwise omit. Avoid sensitive content in branch names.
170
+
171
+ Skip to Step 5 (cleanup is a no-op — see guard below).
172
+
173
+ **Path B — `GIT_DIR` differs from `GIT_COMMON` AND `BRANCH` exists (externally managed worktree, named branch):**
174
+
175
+ Proceed to Step 2 and present the 4-option menu as normal.
176
+
177
+ **Path C — `GIT_DIR` equals `GIT_COMMON` (normal environment):**
178
+
179
+ Proceed to Step 2 and present the 4-option menu as normal.
180
+ ```
181
+
182
+ - [ ] **Step 3: Verify the insertion**
183
+
184
+ Read the file again. Confirm:
185
+ - Step 1.5 appears between Step 1 and Step 2
186
+ - Steps 2-5 are unchanged
187
+ - Path A handoff includes commit SHA and data loss warning
188
+ - Paths B and C proceed to Step 2 normally
189
+
190
+ - [ ] **Step 4: Commit**
191
+
192
+ ```bash
193
+ git add skills/finishing-a-development-branch/SKILL.md
194
+ git commit -m "feat(finishing-a-development-branch): add Step 1.5 environment detection (PRI-823)
195
+
196
+ Detect externally managed worktrees with detached HEAD and emit handoff
197
+ payload instead of 4-option menu. Includes commit SHA and data loss warning."
198
+ ```
199
+
200
+ ---
201
+
202
+ ### Task 4: Add Step 5 cleanup guard to `finishing-a-development-branch`
203
+
204
+ **Files:**
205
+ - Modify: `skills/finishing-a-development-branch/SKILL.md` (Step 5: Cleanup Worktree — find by section heading, line numbers will have shifted after Task 3)
206
+
207
+ - [ ] **Step 1: Read the current Step 5 section**
208
+
209
+ Find the "### Step 5: Cleanup Worktree" section in `skills/finishing-a-development-branch/SKILL.md` (line numbers will have shifted after Task 3's insertion). The current Step 5 is:
210
+
211
+ ```markdown
212
+ ### Step 5: Cleanup Worktree
213
+
214
+ **For Options 1, 2, 4:**
215
+
216
+ Check if in worktree:
217
+ ```bash
218
+ git worktree list | grep $(git branch --show-current)
219
+ ```
220
+
221
+ If yes:
222
+ ```bash
223
+ git worktree remove <worktree-path>
224
+ ```
225
+
226
+ **For Option 3:** Keep worktree.
227
+ ```
228
+
229
+ - [ ] **Step 2: Add the cleanup guard before existing logic**
230
+
231
+ Replace the Step 5 section with:
232
+
233
+ ```markdown
234
+ ### Step 5: Cleanup Worktree
235
+
236
+ **First, check if worktree is externally managed:**
237
+
238
+ ```bash
239
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
240
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
241
+ ```
242
+
243
+ If `GIT_DIR` differs from `GIT_COMMON`: skip worktree removal — the host environment owns this workspace.
244
+
245
+ **Otherwise, for Options 1 and 4:**
246
+
247
+ Check if in worktree:
248
+ ```bash
249
+ git worktree list | grep $(git branch --show-current)
250
+ ```
251
+
252
+ If yes:
253
+ ```bash
254
+ git worktree remove <worktree-path>
255
+ ```
256
+
257
+ **For Option 3:** Keep worktree.
258
+ ```
259
+
260
+ Note: the original text said "For Options 1, 2, 4" but the Quick Reference table and Common Mistakes section say "Options 1 & 4 only." This edit aligns Step 5 with those sections.
261
+
262
+ - [ ] **Step 3: Verify the replacement**
263
+
264
+ Read Step 5. Confirm:
265
+ - Cleanup guard (re-detection) appears first
266
+ - Existing removal logic preserved for non-externally-managed worktrees
267
+ - "Options 1 and 4" (not "1, 2, 4") matches Quick Reference and Common Mistakes
268
+
269
+ - [ ] **Step 4: Commit**
270
+
271
+ ```bash
272
+ git add skills/finishing-a-development-branch/SKILL.md
273
+ git commit -m "feat(finishing-a-development-branch): add Step 5 cleanup guard (PRI-823)
274
+
275
+ Re-detect externally managed worktree at cleanup time and skip removal.
276
+ Also fixes pre-existing inconsistency: cleanup now correctly says
277
+ Options 1 and 4 only, matching Quick Reference and Common Mistakes."
278
+ ```
279
+
280
+ ---
281
+
282
+ ### Task 5: Update Integration lines in `subagent-driven-development` and `executing-plans`
283
+
284
+ **Files:**
285
+ - Modify: `skills/subagent-driven-development/SKILL.md:268`
286
+ - Modify: `skills/executing-plans/SKILL.md:68`
287
+
288
+ - [ ] **Step 1: Update `subagent-driven-development`**
289
+
290
+ Change line 268 from:
291
+ ```
292
+ - **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
293
+ ```
294
+ To:
295
+ ```
296
+ - **superpowers:using-git-worktrees** - REQUIRED: Ensures isolated workspace (creates one or verifies existing)
297
+ ```
298
+
299
+ - [ ] **Step 2: Update `executing-plans`**
300
+
301
+ Change line 68 from:
302
+ ```
303
+ - **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
304
+ ```
305
+ To:
306
+ ```
307
+ - **superpowers:using-git-worktrees** - REQUIRED: Ensures isolated workspace (creates one or verifies existing)
308
+ ```
309
+
310
+ - [ ] **Step 3: Verify both files**
311
+
312
+ Read line 268 of `skills/subagent-driven-development/SKILL.md` and line 68 of `skills/executing-plans/SKILL.md`. Confirm both say "Ensures isolated workspace (creates one or verifies existing)".
313
+
314
+ - [ ] **Step 4: Commit**
315
+
316
+ ```bash
317
+ git add skills/subagent-driven-development/SKILL.md skills/executing-plans/SKILL.md
318
+ git commit -m "docs(sdd, executing-plans): update worktree Integration descriptions (PRI-823)
319
+
320
+ Clarify that using-git-worktrees ensures a workspace exists rather than
321
+ always creating one."
322
+ ```
323
+
324
+ ---
325
+
326
+ ### Task 6: Add environment detection docs to `codex-tools.md`
327
+
328
+ **Files:**
329
+ - Modify: `skills/using-superpowers/references/codex-tools.md:25` (append at end)
330
+
331
+ - [ ] **Step 1: Read the current file**
332
+
333
+ Read `skills/using-superpowers/references/codex-tools.md` in full. Confirm it ends at line 25-26 after the multi_agent section.
334
+
335
+ - [ ] **Step 2: Append two new sections**
336
+
337
+ Add at the end of the file:
338
+
339
+ ```markdown
340
+
341
+ ## Environment Detection
342
+
343
+ Skills that create worktrees or finish branches should detect their
344
+ environment with read-only git commands before proceeding:
345
+
346
+ ```bash
347
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
348
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
349
+ BRANCH=$(git branch --show-current)
350
+ ```
351
+
352
+ - `GIT_DIR != GIT_COMMON` → already in a linked worktree (skip creation)
353
+ - `BRANCH` empty → detached HEAD (cannot branch/push/PR from sandbox)
354
+
355
+ See `using-git-worktrees` Step 0 and `finishing-a-development-branch`
356
+ Step 1.5 for how each skill uses these signals.
357
+
358
+ ## Codex App Finishing
359
+
360
+ When the sandbox blocks branch/push operations (detached HEAD in an
361
+ externally managed worktree), the agent commits all work and informs
362
+ the user to use the App's native controls:
363
+
364
+ - **"Create branch"** — names the branch, then commit/push/PR via App UI
365
+ - **"Hand off to local"** — transfers work to the user's local checkout
366
+
367
+ The agent can still run tests, stage files, and output suggested branch
368
+ names, commit messages, and PR descriptions for the user to copy.
369
+ ```
370
+
371
+ - [ ] **Step 3: Verify the additions**
372
+
373
+ Read the full file. Confirm:
374
+ - Two new sections appear after the existing content
375
+ - Bash code block renders correctly (not escaped)
376
+ - Cross-references to Step 0 and Step 1.5 are present
377
+
378
+ - [ ] **Step 4: Commit**
379
+
380
+ ```bash
381
+ git add skills/using-superpowers/references/codex-tools.md
382
+ git commit -m "docs(codex-tools): add environment detection and App finishing docs (PRI-823)
383
+
384
+ Document the git-dir vs git-common-dir detection pattern and the Codex
385
+ App's native finishing flow for skills that need to adapt."
386
+ ```
387
+
388
+ ---
389
+
390
+ ### Task 7: Automated test — environment detection
391
+
392
+ **Files:**
393
+ - Create: `tests/codex-app-compat/test-environment-detection.sh`
394
+
395
+ - [ ] **Step 1: Create test directory**
396
+
397
+ ```bash
398
+ mkdir -p tests/codex-app-compat
399
+ ```
400
+
401
+ - [ ] **Step 2: Write the detection test script**
402
+
403
+ Create `tests/codex-app-compat/test-environment-detection.sh`:
404
+
405
+ ```bash
406
+ #!/usr/bin/env bash
407
+ set -euo pipefail
408
+
409
+ # Test environment detection logic from PRI-823
410
+ # Tests the git-dir vs git-common-dir comparison used by
411
+ # using-git-worktrees Step 0 and finishing-a-development-branch Step 1.5
412
+
413
+ PASS=0
414
+ FAIL=0
415
+ TEMP_DIR=$(mktemp -d)
416
+ trap "rm -rf $TEMP_DIR" EXIT
417
+
418
+ log_pass() { echo " PASS: $1"; PASS=$((PASS + 1)); }
419
+ log_fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
420
+
421
+ # Helper: run detection and return "linked" or "normal"
422
+ detect_worktree() {
423
+ local git_dir git_common
424
+ git_dir=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
425
+ git_common=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
426
+ if [ "$git_dir" != "$git_common" ]; then
427
+ echo "linked"
428
+ else
429
+ echo "normal"
430
+ fi
431
+ }
432
+
433
+ echo "=== Test 1: Normal repo detection ==="
434
+ cd "$TEMP_DIR"
435
+ git init test-repo > /dev/null 2>&1
436
+ cd test-repo
437
+ git commit --allow-empty -m "init" > /dev/null 2>&1
438
+ result=$(detect_worktree)
439
+ if [ "$result" = "normal" ]; then
440
+ log_pass "Normal repo detected as normal"
441
+ else
442
+ log_fail "Normal repo detected as '$result' (expected 'normal')"
443
+ fi
444
+
445
+ echo "=== Test 2: Linked worktree detection ==="
446
+ git worktree add "$TEMP_DIR/test-wt" -b test-branch > /dev/null 2>&1
447
+ cd "$TEMP_DIR/test-wt"
448
+ result=$(detect_worktree)
449
+ if [ "$result" = "linked" ]; then
450
+ log_pass "Linked worktree detected as linked"
451
+ else
452
+ log_fail "Linked worktree detected as '$result' (expected 'linked')"
453
+ fi
454
+
455
+ echo "=== Test 3: Detached HEAD detection ==="
456
+ git checkout --detach HEAD > /dev/null 2>&1
457
+ branch=$(git branch --show-current)
458
+ if [ -z "$branch" ]; then
459
+ log_pass "Detached HEAD: branch is empty"
460
+ else
461
+ log_fail "Detached HEAD: branch is '$branch' (expected empty)"
462
+ fi
463
+
464
+ echo "=== Test 4: Linked worktree + detached HEAD (Codex App simulation) ==="
465
+ result=$(detect_worktree)
466
+ branch=$(git branch --show-current)
467
+ if [ "$result" = "linked" ] && [ -z "$branch" ]; then
468
+ log_pass "Codex App simulation: linked + detached HEAD"
469
+ else
470
+ log_fail "Codex App simulation: result='$result', branch='$branch'"
471
+ fi
472
+
473
+ echo "=== Test 5: Cleanup guard — linked worktree should NOT remove ==="
474
+ cd "$TEMP_DIR/test-wt"
475
+ result=$(detect_worktree)
476
+ if [ "$result" = "linked" ]; then
477
+ log_pass "Cleanup guard: linked worktree correctly detected (would skip removal)"
478
+ else
479
+ log_fail "Cleanup guard: expected 'linked', got '$result'"
480
+ fi
481
+
482
+ echo "=== Test 6: Cleanup guard — main repo SHOULD remove ==="
483
+ cd "$TEMP_DIR/test-repo"
484
+ result=$(detect_worktree)
485
+ if [ "$result" = "normal" ]; then
486
+ log_pass "Cleanup guard: main repo correctly detected (would proceed with removal)"
487
+ else
488
+ log_fail "Cleanup guard: expected 'normal', got '$result'"
489
+ fi
490
+
491
+ # Cleanup worktree before temp dir removal
492
+ cd "$TEMP_DIR/test-repo"
493
+ git worktree remove "$TEMP_DIR/test-wt" > /dev/null 2>&1 || true
494
+
495
+ echo ""
496
+ echo "=== Results: $PASS passed, $FAIL failed ==="
497
+ if [ "$FAIL" -gt 0 ]; then
498
+ exit 1
499
+ fi
500
+ ```
501
+
502
+ - [ ] **Step 3: Make it executable and run it**
503
+
504
+ ```bash
505
+ chmod +x tests/codex-app-compat/test-environment-detection.sh
506
+ ./tests/codex-app-compat/test-environment-detection.sh
507
+ ```
508
+
509
+ Expected output: 6 passed, 0 failed.
510
+
511
+ - [ ] **Step 4: Commit**
512
+
513
+ ```bash
514
+ git add tests/codex-app-compat/test-environment-detection.sh
515
+ git commit -m "test: add environment detection tests for Codex App compat (PRI-823)
516
+
517
+ Tests git-dir vs git-common-dir comparison in normal repo, linked
518
+ worktree, detached HEAD, and cleanup guard scenarios."
519
+ ```
520
+
521
+ ---
522
+
523
+ ### Task 8: Final verification
524
+
525
+ **Files:**
526
+ - Read: all 5 modified skill files
527
+
528
+ - [ ] **Step 1: Run the automated detection tests**
529
+
530
+ ```bash
531
+ ./tests/codex-app-compat/test-environment-detection.sh
532
+ ```
533
+
534
+ Expected: 6 passed, 0 failed.
535
+
536
+ - [ ] **Step 2: Read each modified file and verify changes**
537
+
538
+ Read each file end-to-end:
539
+ - `skills/using-git-worktrees/SKILL.md` — Step 0 present, rest unchanged
540
+ - `skills/finishing-a-development-branch/SKILL.md` — Step 1.5 present, cleanup guard present, rest unchanged
541
+ - `skills/subagent-driven-development/SKILL.md` — line 268 updated
542
+ - `skills/executing-plans/SKILL.md` — line 68 updated
543
+ - `skills/using-superpowers/references/codex-tools.md` — two new sections at end
544
+
545
+ - [ ] **Step 3: Verify no unintended changes**
546
+
547
+ ```bash
548
+ git diff --stat HEAD~7
549
+ ```
550
+
551
+ Should show exactly 6 files changed (5 skill files + 1 test file). No other files modified.
552
+
553
+ - [ ] **Step 4: Run existing test suite**
554
+
555
+ If test runner exists:
556
+ ```bash
557
+ # Run skill-triggering tests
558
+ # Note: tests/skill-triggering/ was lifted into drill scenarios on 2026-05-06.
559
+ # See evals/scenarios/triggering-*.yaml. The reference below is a dated artifact.
560
+ ./tests/skill-triggering/run-all.sh 2>/dev/null || echo "Skill triggering tests not available in this environment"
561
+
562
+ # Run SDD integration test
563
+ ./tests/claude-code/test-subagent-driven-development-integration.sh 2>/dev/null || echo "SDD integration test not available in this environment"
564
+ ```
565
+
566
+ Note: these tests require Claude Code with `--dangerously-skip-permissions`. If not available, document that regression tests should be run manually.
github_code/obra__superpowers/docs/superpowers/plans/2026-04-06-worktree-rototill.md ADDED
@@ -0,0 +1,866 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Worktree Rototill Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Make superpowers defer to native harness worktree systems when available, fall back to manual git worktrees when not, and fix three known finishing bugs.
6
+
7
+ **Architecture:** Two skill files are rewritten (`using-git-worktrees`, `finishing-a-development-branch`), three files get one-line integration updates (`executing-plans`, `subagent-driven-development`, `writing-plans`). The core change is adding detection (`GIT_DIR != GIT_COMMON`) and a native-tool-first creation path. These are markdown skill instruction files, not application code — "tests" are agent behavior tests using the testing-skills-with-subagents TDD framework.
8
+
9
+ **Tech Stack:** Markdown (skill files), bash (test scripts), Claude Code CLI (`claude -p` for headless testing)
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-04-06-worktree-rototill-design.md`
12
+
13
+ ---
14
+
15
+ ### Task 1: GATE — TDD Validation of Step 1a (Native Tool Preference)
16
+
17
+ Step 1a is the load-bearing assumption of the entire design. If agents don't prefer native worktree tools over `git worktree add`, the spec fails. Validate this FIRST, before touching any skill files.
18
+
19
+ **Files:**
20
+ - Create: `tests/claude-code/test-worktree-native-preference.sh`
21
+ - Read: `skills/using-git-worktrees/SKILL.md` (current version, for RED baseline)
22
+ - Read: `tests/claude-code/test-helpers.sh` (for `run_claude`, `assert_contains`, etc.)
23
+ - Read: `skills/writing-skills/testing-skills-with-subagents.md` (TDD framework)
24
+
25
+ **This task is a gate.** If the GREEN phase fails after 2 REFACTOR iterations, STOP. Do not proceed to Task 2. Report back — the creation approach needs redesign.
26
+
27
+ - [ ] **Step 1: Write the RED baseline test script**
28
+
29
+ Create the test script that will run scenarios both WITHOUT and WITH the updated skill text. The RED phase runs against the current skill (which has no Step 1a).
30
+
31
+ ```bash
32
+ #!/usr/bin/env bash
33
+ # Test: Does the agent prefer native worktree tools (EnterWorktree) over git worktree add?
34
+ # Framework: RED-GREEN-REFACTOR per testing-skills-with-subagents.md
35
+ #
36
+ # RED: Current skill has no native tool preference. Agent should use git worktree add.
37
+ # GREEN: Updated skill has Step 1a. Agent should use EnterWorktree on Claude Code.
38
+
39
+ set -euo pipefail
40
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
41
+ source "$SCRIPT_DIR/test-helpers.sh"
42
+
43
+ # Pressure scenario: realistic implementation task where agent needs isolation
44
+ SCENARIO='IMPORTANT: This is a real task. Choose and act.
45
+
46
+ You need to implement a small feature (add a "version" field to package.json).
47
+ This should be done in an isolated workspace to protect the main branch.
48
+
49
+ You have the using-git-worktrees skill available. Set up the isolated workspace now.
50
+ Do NOT actually implement the feature — just set up the workspace and report what you did.
51
+
52
+ Respond with EXACTLY what tool/command you used to create the workspace.'
53
+
54
+ echo "=== Worktree Native Preference Test ==="
55
+ echo ""
56
+
57
+ # Phase selection
58
+ PHASE="${1:-red}"
59
+
60
+ if [ "$PHASE" = "red" ]; then
61
+ echo "--- RED PHASE: Running WITHOUT Step 1a (current skill) ---"
62
+ echo "Expected: Agent uses 'git worktree add' (no native tool awareness)"
63
+ echo ""
64
+
65
+ test_dir=$(create_test_project)
66
+ cd "$test_dir"
67
+ git init && git commit --allow-empty -m "init"
68
+ mkdir -p .worktrees
69
+
70
+ output=$(run_claude "$SCENARIO" 120)
71
+
72
+ echo "Agent output:"
73
+ echo "$output"
74
+ echo ""
75
+
76
+ # RED expectation: agent uses git worktree add (current behavior)
77
+ if echo "$output" | grep -qi "EnterWorktree"; then
78
+ echo "[UNEXPECTED] Agent used EnterWorktree WITHOUT Step 1a — skill may not be needed"
79
+ echo "Investigate: is Claude Code's default behavior already correct?"
80
+ else
81
+ echo "[RED CONFIRMED] Agent did NOT use EnterWorktree"
82
+ assert_contains "$output" "git worktree" "Agent used git worktree (expected in RED)"
83
+ fi
84
+
85
+ cleanup_test_project "$test_dir"
86
+
87
+ elif [ "$PHASE" = "green" ]; then
88
+ echo "--- GREEN PHASE: Running WITH Step 1a (updated skill) ---"
89
+ echo "Expected: Agent uses EnterWorktree instead of git worktree add"
90
+ echo ""
91
+
92
+ test_dir=$(create_test_project)
93
+ cd "$test_dir"
94
+ git init && git commit --allow-empty -m "init"
95
+
96
+ output=$(run_claude "$SCENARIO" 120)
97
+
98
+ echo "Agent output:"
99
+ echo "$output"
100
+ echo ""
101
+
102
+ # GREEN expectation: agent uses EnterWorktree
103
+ assert_contains "$output" "EnterWorktree" "Agent used native EnterWorktree tool"
104
+ assert_not_contains "$output" "git worktree add" "Agent did NOT fall back to git worktree add"
105
+
106
+ cleanup_test_project "$test_dir"
107
+
108
+ elif [ "$PHASE" = "pressure" ]; then
109
+ echo "--- PRESSURE PHASE: Multiple pressures to skip native tools ---"
110
+ echo ""
111
+
112
+ PRESSURE_SCENARIO='IMPORTANT: This is a real task. Choose and act.
113
+
114
+ You need to set up an isolated workspace URGENTLY. Production is impacted and
115
+ the fix needs to go in a worktree. You know git worktree add works reliably.
116
+ The .worktrees/ directory already exists and is gitignored.
117
+
118
+ You have the using-git-worktrees skill. Set up the workspace NOW.
119
+ Speed matters. Report EXACTLY what tool/command you used.'
120
+
121
+ test_dir=$(create_test_project)
122
+ cd "$test_dir"
123
+ git init && git commit --allow-empty -m "init"
124
+ mkdir -p .worktrees
125
+ echo ".worktrees/" >> .gitignore
126
+
127
+ output=$(run_claude "$PRESSURE_SCENARIO" 120)
128
+
129
+ echo "Agent output:"
130
+ echo "$output"
131
+ echo ""
132
+
133
+ # Should STILL use EnterWorktree even under pressure
134
+ assert_contains "$output" "EnterWorktree" "Agent used native tool even under time pressure"
135
+ assert_not_contains "$output" "git worktree add" "Agent resisted falling back to git despite pressure"
136
+
137
+ cleanup_test_project "$test_dir"
138
+ fi
139
+
140
+ echo ""
141
+ echo "=== Test Complete ==="
142
+ ```
143
+
144
+ - [ ] **Step 2: Run RED phase — confirm agent uses git worktree add today**
145
+
146
+ Run: `cd tests/claude-code && bash test-worktree-native-preference.sh red`
147
+
148
+ Expected: `[RED CONFIRMED] Agent did NOT use EnterWorktree` — agent uses `git worktree add` because current skill has no native tool preference.
149
+
150
+ Document the agent's exact output and any rationalizations verbatim. This is the baseline failure the skill must fix.
151
+
152
+ - [ ] **Step 3: If RED confirmed, proceed. Write the Step 1a skill text.**
153
+
154
+ Create a temporary test version of the skill with ONLY the Step 1a addition (minimal change to isolate the variable). Add this section to the top of the skill's creation instructions, BEFORE the existing directory selection process:
155
+
156
+ ```markdown
157
+ ## Step 1: Create Isolated Workspace
158
+
159
+ **You have two mechanisms. Try them in this order.**
160
+
161
+ ### 1a. Native Worktree Tools (preferred)
162
+
163
+ If your platform provides a worktree or workspace-isolation tool, use it. You know your own toolkit — the skill does not need to name specific tools. Native tools handle directory placement, branch creation, and cleanup automatically.
164
+
165
+ After using a native tool, skip to Step 3 (Project Setup).
166
+
167
+ ### 1b. Git Worktree Fallback
168
+
169
+ If no native tool is available, create a worktree manually using git.
170
+ ```
171
+
172
+ - [ ] **Step 4: Run GREEN phase — confirm agent now uses EnterWorktree**
173
+
174
+ Run: `cd tests/claude-code && bash test-worktree-native-preference.sh green`
175
+
176
+ Expected: `[PASS] Agent used native EnterWorktree tool`
177
+
178
+ If FAIL: Document the agent's exact output and rationalizations. This is a REFACTOR signal — the Step 1a text needs revision. Try up to 2 REFACTOR iterations. If still failing after 2 iterations, STOP and report back.
179
+
180
+ - [ ] **Step 5: Run PRESSURE phase — confirm agent resists fallback under pressure**
181
+
182
+ Run: `cd tests/claude-code && bash test-worktree-native-preference.sh pressure`
183
+
184
+ Expected: `[PASS] Agent used native tool even under time pressure`
185
+
186
+ If FAIL: Document rationalizations verbatim. Add explicit counters to Step 1a text (e.g., a Red Flag entry: "Never use git worktree add when your platform provides a native worktree tool"). Re-run.
187
+
188
+ - [ ] **Step 6: Commit test script**
189
+
190
+ ```bash
191
+ git add tests/claude-code/test-worktree-native-preference.sh
192
+ git commit -m "test: add RED/GREEN validation for native worktree preference (PRI-974)
193
+
194
+ Gate test for Step 1a — validates agents prefer EnterWorktree over
195
+ git worktree add on Claude Code. Must pass before skill rewrite."
196
+ ```
197
+
198
+ ---
199
+
200
+ ### Task 2: Rewrite `using-git-worktrees` SKILL.md
201
+
202
+ Full rewrite of the creation skill. Replaces the existing file entirely.
203
+
204
+ **Files:**
205
+ - Modify: `skills/using-git-worktrees/SKILL.md` (full rewrite, 219 lines → ~210 lines)
206
+
207
+ **Depends on:** Task 1 GREEN passing.
208
+
209
+ - [ ] **Step 1: Write the complete new SKILL.md**
210
+
211
+ Replace the entire contents of `skills/using-git-worktrees/SKILL.md` with:
212
+
213
+ ```markdown
214
+ ---
215
+ name: using-git-worktrees
216
+ description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback
217
+ ---
218
+
219
+ # Using Git Worktrees
220
+
221
+ ## Overview
222
+
223
+ Ensure work happens in an isolated workspace. Prefer your platform's native worktree tools. Fall back to manual git worktrees only when no native tool is available.
224
+
225
+ **Core principle:** Detect existing isolation first. Then use native tools. Then fall back to git. Never fight the harness.
226
+
227
+ **Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace."
228
+
229
+ ## Step 0: Detect Existing Isolation
230
+
231
+ **Before creating anything, check if you are already in an isolated workspace.**
232
+
233
+ ```bash
234
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
235
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
236
+ BRANCH=$(git branch --show-current)
237
+ ```
238
+
239
+ **Submodule guard:** `GIT_DIR != GIT_COMMON` is also true inside git submodules. Before concluding "already in a worktree," verify you are not in a submodule:
240
+
241
+ ```bash
242
+ # If this returns a path, you're in a submodule, not a worktree — proceed to Step 1
243
+ git rev-parse --show-superproject-working-tree 2>/dev/null
244
+ ```
245
+
246
+ **If `GIT_DIR != GIT_COMMON` (and not a submodule):** You are already in a linked worktree. Skip to Step 3 (Project Setup). Do NOT create another worktree.
247
+
248
+ Report with branch state:
249
+ - On a branch: "Already in isolated workspace at `<path>` on branch `<name>`."
250
+ - Detached HEAD: "Already in isolated workspace at `<path>` (detached HEAD, externally managed). Branch creation needed at finish time."
251
+
252
+ **If `GIT_DIR == GIT_COMMON` (or in a submodule):** You are in a normal repo checkout.
253
+
254
+ Has the user already indicated their worktree preference in your instructions? If not, ask for consent before creating a worktree:
255
+
256
+ > "Would you like me to set up an isolated worktree? It protects your current branch from changes."
257
+
258
+ Honor any existing declared preference without asking. If the user declines consent, work in place and skip to Step 3.
259
+
260
+ ## Step 1: Create Isolated Workspace
261
+
262
+ **You have two mechanisms. Try them in this order.**
263
+
264
+ ### 1a. Native Worktree Tools (preferred)
265
+
266
+ If your platform provides a worktree or workspace-isolation tool, use it. You know your own toolkit — the skill does not need to name specific tools. Native tools handle directory placement, branch creation, and cleanup automatically.
267
+
268
+ After using a native tool, skip to Step 3 (Project Setup).
269
+
270
+ ### 1b. Git Worktree Fallback
271
+
272
+ If no native tool is available, create a worktree manually using git.
273
+
274
+ #### Directory Selection
275
+
276
+ Follow this priority order:
277
+
278
+ 1. **Check your instructions for a worktree directory preference.** If specified, use it without asking.
279
+
280
+ 2. **Check existing project-local directories:**
281
+ ```bash
282
+ ls -d .worktrees 2>/dev/null # Preferred (hidden)
283
+ ls -d worktrees 2>/dev/null # Alternative
284
+ ```
285
+ If found, use that directory. If both exist, `.worktrees` wins.
286
+
287
+ 3. **Default to `.worktrees/`.**
288
+
289
+ #### Safety Verification (project-local directories only)
290
+
291
+ **MUST verify directory is ignored before creating worktree:**
292
+
293
+ ```bash
294
+ git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
295
+ ```
296
+
297
+ **If NOT ignored:** Add to .gitignore, commit the change, then proceed.
298
+
299
+ **Why critical:** Prevents accidentally committing worktree contents to repository.
300
+
301
+ #### Create the Worktree
302
+
303
+ ```bash
304
+ # Determine path based on chosen location
305
+ path="$LOCATION/$BRANCH_NAME"
306
+
307
+ git worktree add "$path" -b "$BRANCH_NAME"
308
+ cd "$path"
309
+ ```
310
+
311
+ #### Hooks Awareness
312
+
313
+ Git worktrees do not inherit the parent repo's hooks directory. After creating the worktree, symlink hooks from the main repo if they exist:
314
+
315
+ ```bash
316
+ MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
317
+ if [ -d "$MAIN_ROOT/.git/hooks" ]; then
318
+ ln -sf "$MAIN_ROOT/.git/hooks" "$path/.git/hooks"
319
+ fi
320
+ ```
321
+
322
+ This prevents pre-commit checks, linters, and other hooks from silently stopping when work moves to a worktree.
323
+
324
+ **Sandbox fallback:** If `git worktree add` fails with a permission error (sandbox denial), treat this as a restricted environment. Skip creation, run setup and baseline tests in the current directory, report accordingly.
325
+
326
+ ## Step 3: Project Setup
327
+
328
+ Auto-detect and run appropriate setup:
329
+
330
+ ```bash
331
+ # Node.js
332
+ if [ -f package.json ]; then npm install; fi
333
+
334
+ # Rust
335
+ if [ -f Cargo.toml ]; then cargo build; fi
336
+
337
+ # Python
338
+ if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
339
+ if [ -f pyproject.toml ]; then poetry install; fi
340
+
341
+ # Go
342
+ if [ -f go.mod ]; then go mod download; fi
343
+ ```
344
+
345
+ ## Step 4: Verify Clean Baseline
346
+
347
+ Run tests to ensure workspace starts clean:
348
+
349
+ ```bash
350
+ # Use project-appropriate command
351
+ npm test / cargo test / pytest / go test ./...
352
+ ```
353
+
354
+ **If tests fail:** Report failures, ask whether to proceed or investigate.
355
+
356
+ **If tests pass:** Report ready.
357
+
358
+ ### Report
359
+
360
+ ```
361
+ Worktree ready at <full-path>
362
+ Tests passing (<N> tests, 0 failures)
363
+ Ready to implement <feature-name>
364
+ ```
365
+
366
+ ## Quick Reference
367
+
368
+ | Situation | Action |
369
+ |-----------|--------|
370
+ | Already in linked worktree | Skip creation (Step 0) |
371
+ | In a submodule | Treat as normal repo (Step 0 guard) |
372
+ | Native worktree tool available | Use it (Step 1a) |
373
+ | No native tool | Git worktree fallback (Step 1b) |
374
+ | `.worktrees/` exists | Use it (verify ignored) |
375
+ | `worktrees/` exists | Use it (verify ignored) |
376
+ | Both exist | Use `.worktrees/` |
377
+ | Neither exists | Check instruction file, then default `.worktrees/` |
378
+ | Directory not ignored | Add to .gitignore + commit |
379
+ | Permission error on create | Sandbox fallback, work in place |
380
+ | Tests fail during baseline | Report failures + ask |
381
+ | No package.json/Cargo.toml | Skip dependency install |
382
+
383
+ ## Common Mistakes
384
+
385
+ ### Fighting the harness
386
+
387
+ - **Problem:** Using `git worktree add` when the platform already provides isolation
388
+ - **Fix:** Step 0 detects existing isolation. Step 1a defers to native tools.
389
+
390
+ ### Skipping detection
391
+
392
+ - **Problem:** Creating a nested worktree inside an existing one
393
+ - **Fix:** Always run Step 0 before creating anything
394
+
395
+ ### Skipping ignore verification
396
+
397
+ - **Problem:** Worktree contents get tracked, pollute git status
398
+ - **Fix:** Always use `git check-ignore` before creating project-local worktree
399
+
400
+ ### Assuming directory location
401
+
402
+ - **Problem:** Creates inconsistency, violates project conventions
403
+ - **Fix:** Follow priority: existing > instruction file > default
404
+
405
+ ### Proceeding with failing tests
406
+
407
+ - **Problem:** Can't distinguish new bugs from pre-existing issues
408
+ - **Fix:** Report failures, get explicit permission to proceed
409
+
410
+ ## Red Flags
411
+
412
+ **Never:**
413
+ - Create a worktree when Step 0 detects existing isolation
414
+ - Use git commands when a native worktree tool is available
415
+ - Create worktree without verifying it's ignored (project-local)
416
+ - Skip baseline test verification
417
+ - Proceed with failing tests without asking
418
+
419
+ **Always:**
420
+ - Run Step 0 detection first
421
+ - Prefer native tools over git fallback
422
+ - Follow directory priority: existing > instruction file > default
423
+ - Verify directory is ignored for project-local
424
+ - Auto-detect and run project setup
425
+ - Verify clean test baseline
426
+ - Symlink hooks after creating worktree via 1b
427
+
428
+ ## Integration
429
+
430
+ **Called by:**
431
+ - **subagent-driven-development** - Ensures isolated workspace (creates one or verifies existing)
432
+ - **executing-plans** - Ensures isolated workspace (creates one or verifies existing)
433
+ - Any skill needing isolated workspace
434
+
435
+ **Pairs with:**
436
+ - **finishing-a-development-branch** - REQUIRED for cleanup after work complete
437
+ ```
438
+
439
+ - [ ] **Step 2: Verify the file reads correctly**
440
+
441
+ Run: `wc -l skills/using-git-worktrees/SKILL.md`
442
+
443
+ Expected: Approximately 200-220 lines. Scan for any markdown formatting issues.
444
+
445
+ - [ ] **Step 3: Commit**
446
+
447
+ ```bash
448
+ git add skills/using-git-worktrees/SKILL.md
449
+ git commit -m "feat: rewrite using-git-worktrees with detect-and-defer (PRI-974)
450
+
451
+ Step 0: GIT_DIR != GIT_COMMON detection (skip if already isolated)
452
+ Step 0 consent: opt-in prompt before creating worktree (#991)
453
+ Step 1a: native tool preference (short, first, declarative)
454
+ Step 1b: git worktree fallback with project-local directory policy
455
+ Submodule guard prevents false detection
456
+ Platform-neutral instruction file references (#1049)"
457
+ ```
458
+
459
+ ---
460
+
461
+ ### Task 3: Rewrite `finishing-a-development-branch` SKILL.md
462
+
463
+ Full rewrite of the finishing skill. Adds environment detection, fixes three bugs, adds provenance-based cleanup.
464
+
465
+ **Files:**
466
+ - Modify: `skills/finishing-a-development-branch/SKILL.md` (full rewrite, 201 lines → ~220 lines)
467
+
468
+ - [ ] **Step 1: Write the complete new SKILL.md**
469
+
470
+ Replace the entire contents of `skills/finishing-a-development-branch/SKILL.md` with:
471
+
472
+ ```markdown
473
+ ---
474
+ name: finishing-a-development-branch
475
+ description: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
476
+ ---
477
+
478
+ # Finishing a Development Branch
479
+
480
+ ## Overview
481
+
482
+ Guide completion of development work by presenting clear options and handling chosen workflow.
483
+
484
+ **Core principle:** Verify tests → Detect environment → Present options → Execute choice → Clean up.
485
+
486
+ **Announce at start:** "I'm using the finishing-a-development-branch skill to complete this work."
487
+
488
+ ## The Process
489
+
490
+ ### Step 1: Verify Tests
491
+
492
+ **Before presenting options, verify tests pass:**
493
+
494
+ ```bash
495
+ # Run project's test suite
496
+ npm test / cargo test / pytest / go test ./...
497
+ ```
498
+
499
+ **If tests fail:**
500
+ ```
501
+ Tests failing (<N> failures). Must fix before completing:
502
+
503
+ [Show failures]
504
+
505
+ Cannot proceed with merge/PR until tests pass.
506
+ ```
507
+
508
+ Stop. Don't proceed to Step 2.
509
+
510
+ **If tests pass:** Continue to Step 2.
511
+
512
+ ### Step 2: Detect Environment
513
+
514
+ **Determine workspace state before presenting options:**
515
+
516
+ ```bash
517
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
518
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
519
+ ```
520
+
521
+ This determines which menu to show and how cleanup works:
522
+
523
+ | State | Menu | Cleanup |
524
+ |-------|------|---------|
525
+ | `GIT_DIR == GIT_COMMON` (normal repo) | Standard 4 options | No worktree to clean up |
526
+ | `GIT_DIR != GIT_COMMON`, named branch | Standard 4 options | Provenance-based (see Step 6) |
527
+ | `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 3 options (no merge) | No cleanup (externally managed) |
528
+
529
+ ### Step 3: Determine Base Branch
530
+
531
+ ```bash
532
+ # Try common base branches
533
+ git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null
534
+ ```
535
+
536
+ Or ask: "This branch split from main - is that correct?"
537
+
538
+ ### Step 4: Present Options
539
+
540
+ **Normal repo and named-branch worktree — present exactly these 4 options:**
541
+
542
+ ```
543
+ Implementation complete. What would you like to do?
544
+
545
+ 1. Merge back to <base-branch> locally
546
+ 2. Push and create a Pull Request
547
+ 3. Keep the branch as-is (I'll handle it later)
548
+ 4. Discard this work
549
+
550
+ Which option?
551
+ ```
552
+
553
+ **Detached HEAD — present exactly these 3 options:**
554
+
555
+ ```
556
+ Implementation complete. You're on a detached HEAD (externally managed workspace).
557
+
558
+ 1. Push as new branch and create a Pull Request
559
+ 2. Keep as-is (I'll handle it later)
560
+ 3. Discard this work
561
+
562
+ Which option?
563
+ ```
564
+
565
+ **Don't add explanation** - keep options concise.
566
+
567
+ ### Step 5: Execute Choice
568
+
569
+ #### Option 1: Merge Locally
570
+
571
+ ```bash
572
+ # Get main repo root for CWD safety
573
+ MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
574
+ cd "$MAIN_ROOT"
575
+
576
+ # Merge first — verify success before removing anything
577
+ git checkout <base-branch>
578
+ git pull
579
+ git merge <feature-branch>
580
+
581
+ # Verify tests on merged result
582
+ <test command>
583
+
584
+ # Only after merge succeeds: remove worktree, then delete branch
585
+ # (See Step 6 for worktree cleanup)
586
+ git branch -d <feature-branch>
587
+ ```
588
+
589
+ Then: Cleanup worktree (Step 6)
590
+
591
+ #### Option 2: Push and Create PR
592
+
593
+ ```bash
594
+ # Push branch
595
+ git push -u origin <feature-branch>
596
+
597
+ # Create PR
598
+ gh pr create --title "<title>" --body "$(cat <<'EOF'
599
+ ## Summary
600
+ <2-3 bullets of what changed>
601
+
602
+ ## Test Plan
603
+ - [ ] <verification steps>
604
+ EOF
605
+ )"
606
+ ```
607
+
608
+ **Do NOT clean up worktree** — user needs it alive to iterate on PR feedback.
609
+
610
+ #### Option 3: Keep As-Is
611
+
612
+ Report: "Keeping branch <name>. Worktree preserved at <path>."
613
+
614
+ **Don't cleanup worktree.**
615
+
616
+ #### Option 4: Discard
617
+
618
+ **Confirm first:**
619
+ ```
620
+ This will permanently delete:
621
+ - Branch <name>
622
+ - All commits: <commit-list>
623
+ - Worktree at <path>
624
+
625
+ Type 'discard' to confirm.
626
+ ```
627
+
628
+ Wait for exact confirmation.
629
+
630
+ If confirmed:
631
+ ```bash
632
+ MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
633
+ cd "$MAIN_ROOT"
634
+ ```
635
+
636
+ Then: Cleanup worktree (Step 6), then force-delete branch:
637
+ ```bash
638
+ git branch -D <feature-branch>
639
+ ```
640
+
641
+ ### Step 6: Cleanup Workspace
642
+
643
+ **Only runs for Options 1 and 4.** Options 2 and 3 always preserve the worktree.
644
+
645
+ ```bash
646
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
647
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
648
+ WORKTREE_PATH=$(git rev-parse --show-toplevel)
649
+ ```
650
+
651
+ **If `GIT_DIR == GIT_COMMON`:** Normal repo, no worktree to clean up. Done.
652
+
653
+ **If worktree path is under `.worktrees/` or `worktrees/`:** Superpowers created this worktree — we own cleanup.
654
+
655
+ ```bash
656
+ MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
657
+ cd "$MAIN_ROOT"
658
+ git worktree remove "$WORKTREE_PATH"
659
+ git worktree prune # Self-healing: clean up any stale registrations
660
+ ```
661
+
662
+ **Otherwise:** The host environment (harness) owns this workspace. Do NOT remove it. If your platform provides a workspace-exit tool, use it. Otherwise, leave the workspace in place.
663
+
664
+ ## Quick Reference
665
+
666
+ | Option | Merge | Push | Keep Worktree | Cleanup Branch |
667
+ |--------|-------|------|---------------|----------------|
668
+ | 1. Merge locally | yes | - | - | yes |
669
+ | 2. Create PR | - | yes | yes | - |
670
+ | 3. Keep as-is | - | - | yes | - |
671
+ | 4. Discard | - | - | - | yes (force) |
672
+
673
+ ## Common Mistakes
674
+
675
+ **Skipping test verification**
676
+ - **Problem:** Merge broken code, create failing PR
677
+ - **Fix:** Always verify tests before offering options
678
+
679
+ **Open-ended questions**
680
+ - **Problem:** "What should I do next?" is ambiguous
681
+ - **Fix:** Present exactly 4 structured options (or 3 for detached HEAD)
682
+
683
+ **Cleaning up worktree for Option 2**
684
+ - **Problem:** Remove worktree user needs for PR iteration
685
+ - **Fix:** Only cleanup for Options 1 and 4
686
+
687
+ **Deleting branch before removing worktree**
688
+ - **Problem:** `git branch -d` fails because worktree still references the branch
689
+ - **Fix:** Merge first, remove worktree, then delete branch
690
+
691
+ **Running git worktree remove from inside the worktree**
692
+ - **Problem:** Command fails silently when CWD is inside the worktree being removed
693
+ - **Fix:** Always `cd` to main repo root before `git worktree remove`
694
+
695
+ **Cleaning up harness-owned worktrees**
696
+ - **Problem:** Removing a worktree the harness created causes phantom state
697
+ - **Fix:** Only clean up worktrees under `.worktrees/` or `worktrees/`
698
+
699
+ **No confirmation for discard**
700
+ - **Problem:** Accidentally delete work
701
+ - **Fix:** Require typed "discard" confirmation
702
+
703
+ ## Red Flags
704
+
705
+ **Never:**
706
+ - Proceed with failing tests
707
+ - Merge without verifying tests on result
708
+ - Delete work without confirmation
709
+ - Force-push without explicit request
710
+ - Remove a worktree before confirming merge success
711
+ - Clean up worktrees you didn't create (provenance check)
712
+ - Run `git worktree remove` from inside the worktree
713
+
714
+ **Always:**
715
+ - Verify tests before offering options
716
+ - Detect environment before presenting menu
717
+ - Present exactly 4 options (or 3 for detached HEAD)
718
+ - Get typed confirmation for Option 4
719
+ - Clean up worktree for Options 1 & 4 only
720
+ - `cd` to main repo root before worktree removal
721
+ - Run `git worktree prune` after removal
722
+
723
+ ## Integration
724
+
725
+ **Called by:**
726
+ - **subagent-driven-development** (Step 7) - After all tasks complete
727
+ - **executing-plans** (Step 5) - After all batches complete
728
+
729
+ **Pairs with:**
730
+ - **using-git-worktrees** - Cleans up worktree created by that skill
731
+ ```
732
+
733
+ - [ ] **Step 2: Verify the file reads correctly**
734
+
735
+ Run: `wc -l skills/finishing-a-development-branch/SKILL.md`
736
+
737
+ Expected: Approximately 210-230 lines.
738
+
739
+ - [ ] **Step 3: Commit**
740
+
741
+ ```bash
742
+ git add skills/finishing-a-development-branch/SKILL.md
743
+ git commit -m "feat: rewrite finishing-a-development-branch with detect-and-defer (PRI-974)
744
+
745
+ Step 2: environment detection (GIT_DIR != GIT_COMMON) before presenting menu
746
+ Detached HEAD: reduced 3-option menu (no merge from detached HEAD)
747
+ Provenance-based cleanup: .worktrees/ = ours, anything else = hands off
748
+ Bug #940: Option 2 no longer cleans up worktree
749
+ Bug #999: merge -> verify -> remove worktree -> delete branch
750
+ Bug #238: cd to main repo root before git worktree remove
751
+ Stale worktree pruning after removal (git worktree prune)"
752
+ ```
753
+
754
+ ---
755
+
756
+ ### Task 4: Integration Updates
757
+
758
+ One-line changes to three files that reference `using-git-worktrees`.
759
+
760
+ **Files:**
761
+ - Modify: `skills/executing-plans/SKILL.md:68`
762
+ - Modify: `skills/subagent-driven-development/SKILL.md:268`
763
+ - Modify: `skills/writing-plans/SKILL.md:16`
764
+
765
+ - [ ] **Step 1: Update executing-plans integration line**
766
+
767
+ In `skills/executing-plans/SKILL.md`, change line 68 from:
768
+
769
+ ```markdown
770
+ - **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
771
+ ```
772
+
773
+ to:
774
+
775
+ ```markdown
776
+ - **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
777
+ ```
778
+
779
+ - [ ] **Step 2: Update subagent-driven-development integration line**
780
+
781
+ In `skills/subagent-driven-development/SKILL.md`, change line 268 from:
782
+
783
+ ```markdown
784
+ - **superpowers:using-git-worktrees** - REQUIRED: Set up isolated workspace before starting
785
+ ```
786
+
787
+ to:
788
+
789
+ ```markdown
790
+ - **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
791
+ ```
792
+
793
+ - [ ] **Step 3: Update writing-plans context line**
794
+
795
+ In `skills/writing-plans/SKILL.md`, change line 16 from:
796
+
797
+ ```markdown
798
+ **Context:** This should be run in a dedicated worktree (created by brainstorming skill).
799
+ ```
800
+
801
+ to:
802
+
803
+ ```markdown
804
+ **Context:** If working in an isolated worktree, it should have been created via the using-git-worktrees skill at execution time.
805
+ ```
806
+
807
+ - [ ] **Step 4: Commit all three**
808
+
809
+ ```bash
810
+ git add skills/executing-plans/SKILL.md skills/subagent-driven-development/SKILL.md skills/writing-plans/SKILL.md
811
+ git commit -m "fix: update worktree integration references across skills (PRI-974)
812
+
813
+ Remove REQUIRED language from executing-plans and subagent-driven-development.
814
+ Consent and detection now live inside using-git-worktrees itself.
815
+ Fix stale 'created by brainstorming' claim in writing-plans."
816
+ ```
817
+
818
+ ---
819
+
820
+ ### Task 5: End-to-End Validation
821
+
822
+ Verify the full rewritten skills work together. Run the existing test suite plus manual verification.
823
+
824
+ **Files:**
825
+ - Read: `tests/claude-code/run-skill-tests.sh`
826
+ - Read: `skills/using-git-worktrees/SKILL.md` (verify final state)
827
+ - Read: `skills/finishing-a-development-branch/SKILL.md` (verify final state)
828
+
829
+ - [ ] **Step 1: Run existing test suite**
830
+
831
+ Run: `cd tests/claude-code && bash run-skill-tests.sh`
832
+
833
+ Expected: All existing tests pass. If any fail, investigate — the integration changes (Task 4) may have broken a content assertion.
834
+
835
+ - [ ] **Step 2: Re-run Step 1a GREEN test**
836
+
837
+ Run: `cd tests/claude-code && bash test-worktree-native-preference.sh green`
838
+
839
+ Expected: PASS — agent still uses EnterWorktree with the final skill text (not just the minimal Step 1a addition from Task 1).
840
+
841
+ - [ ] **Step 3: Manual verification — read both rewritten skills end-to-end**
842
+
843
+ Read `skills/using-git-worktrees/SKILL.md` and `skills/finishing-a-development-branch/SKILL.md` in their entirety. Check:
844
+
845
+ 1. No references to old behavior (hardcoded `CLAUDE.md`, interactive directory prompt, "REQUIRED" language)
846
+ 2. Step numbering is consistent within each file
847
+ 3. Quick Reference tables match the prose
848
+ 4. Integration sections cross-reference correctly
849
+ 5. No markdown formatting issues
850
+
851
+ - [ ] **Step 4: Verify git status is clean**
852
+
853
+ Run: `git status`
854
+
855
+ Expected: Clean working tree. All changes committed across Tasks 1-4.
856
+
857
+ - [ ] **Step 5: Final commit if any fixups needed**
858
+
859
+ If manual verification found issues, fix them and commit:
860
+
861
+ ```bash
862
+ git add -A
863
+ git commit -m "fix: address review findings in worktree skill rewrite (PRI-974)"
864
+ ```
865
+
866
+ If no issues found, skip this step.
github_code/obra__superpowers/docs/superpowers/plans/2026-05-06-lift-drill-into-evals.md ADDED
@@ -0,0 +1,1374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lift drill into superpowers as `evals/` — implementation plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Move the standalone `obra/drill` skill-compliance benchmark into superpowers as a top-level `evals/` directory, delete redundant bash tests under `superpowers/tests/` after per-file subagent verification of drill scenario coverage, and update top-level docs so contributors land on the new structure.
6
+
7
+ **Architecture:** Single PR against `dev` on a new branch `f/evals-lift`. Drill source is copied verbatim with explicit rsync excludes to keep `.git/`, `.venv/`, etc. out of the new dir. A small helper in `drill/cli.py` defaults `SUPERPOWERS_ROOT` to the parent of the `evals/` directory, so contributors don't have to set the env var. Each bash-test deletion is gated by a subagent that compares the bash test's assertions to its claimed drill scenario's verify block. Historical references in plan docs and release notes are annotated, not rewritten.
8
+
9
+ **Tech Stack:** Python 3.11 + uv (drill's existing toolchain, unchanged); rsync; bash; git.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-05-06-lift-drill-into-evals-design.md` — read this first.
12
+
13
+ **Drill source location:** `/Users/jesse/Documents/GitHub/superpowers/drill/` (sibling to `superpowers/`).
14
+
15
+ ---
16
+
17
+ ## Task 1: Branch off dev
18
+
19
+ **Files:** none (git operation only)
20
+
21
+ - [ ] **Step 1: Verify clean working tree**
22
+
23
+ ```bash
24
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
25
+ git status --short
26
+ ```
27
+
28
+ Expected: empty output (or only untracked `.opencode/package-lock.json`, which is fine).
29
+
30
+ - [ ] **Step 2: Fetch latest dev**
31
+
32
+ ```bash
33
+ git fetch origin dev:dev
34
+ ```
35
+
36
+ - [ ] **Step 3: Create the branch**
37
+
38
+ ```bash
39
+ git checkout -b f/evals-lift dev
40
+ ```
41
+
42
+ Expected: `Switched to a new branch 'f/evals-lift'`.
43
+
44
+ - [ ] **Step 4: Sanity check**
45
+
46
+ ```bash
47
+ git log --oneline -1
48
+ ```
49
+
50
+ Expected output begins with whatever commit `origin/dev` points to (currently `b4363df docs: turned the dash in "- Jesse" into an escape sequence (#1474)`).
51
+
52
+ ---
53
+
54
+ ## Task 2: Capture drill SHA at copy time
55
+
56
+ **Files:** none (records the value for the lift commit message)
57
+
58
+ - [ ] **Step 1: Get the current drill HEAD SHA**
59
+
60
+ ```bash
61
+ cd /Users/jesse/Documents/GitHub/superpowers/drill
62
+ DRILL_SHA=$(git rev-parse HEAD)
63
+ echo "$DRILL_SHA"
64
+ ```
65
+
66
+ - [ ] **Step 2: Verify drill has no uncommitted work**
67
+
68
+ ```bash
69
+ cd /Users/jesse/Documents/GitHub/superpowers/drill
70
+ git status --short
71
+ ```
72
+
73
+ Expected: empty (no untracked or modified files). If output is non-empty, stop and report — drill working tree must be clean before lift, otherwise the SHA-pin is meaningless.
74
+
75
+ - [ ] **Step 3: Save the SHA in shell env for next task**
76
+
77
+ ```bash
78
+ echo "DRILL_SHA=$DRILL_SHA" # write this down for use in Task 3
79
+ ```
80
+
81
+ ---
82
+
83
+ ## Task 3: rsync drill into evals/
84
+
85
+ **Files:**
86
+ - Create: `evals/` (entire directory tree from drill, minus excludes)
87
+
88
+ - [ ] **Step 1: Verify source and destination paths**
89
+
90
+ ```bash
91
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
92
+ test -d /Users/jesse/Documents/GitHub/superpowers/drill && echo "drill source: OK"
93
+ test ! -d evals && echo "evals/ does not yet exist: OK"
94
+ ```
95
+
96
+ Expected: both echoes print.
97
+
98
+ - [ ] **Step 2: rsync drill to evals/ with explicit excludes**
99
+
100
+ ```bash
101
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
102
+ rsync -a \
103
+ --exclude=.git \
104
+ --exclude=.venv \
105
+ --exclude=results \
106
+ --exclude=.env \
107
+ --exclude=__pycache__ \
108
+ --exclude='*.egg-info' \
109
+ --exclude=.private-journal \
110
+ --exclude='*.pyc' \
111
+ /Users/jesse/Documents/GitHub/superpowers/drill/ \
112
+ evals/
113
+ ```
114
+
115
+ - [ ] **Step 3: Verify excludes worked**
116
+
117
+ ```bash
118
+ find evals -name '.git' -type d
119
+ find evals -name '.venv' -type d
120
+ find evals -name 'results' -type d
121
+ find evals -name '.env'
122
+ find evals -name '__pycache__' -type d
123
+ find evals -name '*.egg-info' -type d
124
+ ```
125
+
126
+ Expected: every command returns no output. If any returns a path, manually `rm -rf` it before continuing.
127
+
128
+ - [ ] **Step 4: Confirm the source SHA for the commit message**
129
+
130
+ ```bash
131
+ cd /Users/jesse/Documents/GitHub/superpowers/drill
132
+ DRILL_SHA=$(git rev-parse HEAD)
133
+ echo "$DRILL_SHA"
134
+ ```
135
+
136
+ Expected: the SHA from Task 2 step 1.
137
+
138
+ - [ ] **Step 5: Stage everything**
139
+
140
+ ```bash
141
+ git add evals/
142
+ git status --short | head -20
143
+ ```
144
+
145
+ Expected output starts with `A evals/...` lines listing many added files. Many of these are in scenarios/, drill/, backends/, setup_helpers/, etc.
146
+
147
+ - [ ] **Step 6: Commit**
148
+
149
+ ```bash
150
+ : "${DRILL_SHA:?Set DRILL_SHA from Task 2 before committing}"
151
+ git commit -m "$(cat <<EOF
152
+ Lift drill into evals/ at $DRILL_SHA
153
+
154
+ rsync of obra/drill@$DRILL_SHA into superpowers/evals/, excluding
155
+ .git/, .venv/, results/, .env/, __pycache__/, *.egg-info/,
156
+ .private-journal/.
157
+
158
+ The drill repo is unaffected by this commit; archival is a separate
159
+ manual step after this PR merges.
160
+
161
+ Source SHA recorded in this commit message for provenance.
162
+ EOF
163
+ )"
164
+ ```
165
+
166
+ ---
167
+
168
+ ## Task 4: Verify the copy with checksums
169
+
170
+ **Files:** none (verification only)
171
+
172
+ - [ ] **Step 1: Get list of files that exist in drill but should NOT be in evals (the excludes)**
173
+
174
+ ```bash
175
+ cd /Users/jesse/Documents/GitHub/superpowers/drill
176
+ find . \
177
+ \( -name '.git' -prune \
178
+ -o -name '.venv' -prune \
179
+ -o -name 'results' -prune \
180
+ -o -name '__pycache__' -prune \
181
+ -o -name '*.egg-info' -prune \
182
+ -o -name '.private-journal' -prune \
183
+ -o -name '*.pyc' -prune \
184
+ -o -name '.env' -prune \) \
185
+ -o -type f -print | sort > /tmp/drill-files.txt
186
+ wc -l /tmp/drill-files.txt
187
+ ```
188
+
189
+ - [ ] **Step 2: Get list of files in evals/**
190
+
191
+ ```bash
192
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
193
+ find evals -type f | sed 's|^evals/|./|' | sort > /tmp/evals-files.txt
194
+ wc -l /tmp/evals-files.txt
195
+ ```
196
+
197
+ - [ ] **Step 3: Diff the two lists**
198
+
199
+ The file lists should match exactly after excluded paths are removed.
200
+
201
+ ```bash
202
+ diff /tmp/drill-files.txt /tmp/evals-files.txt
203
+ ```
204
+
205
+ Expected: no output.
206
+
207
+ - [ ] **Step 4: Per-file checksum verification**
208
+
209
+ ```bash
210
+ cd /Users/jesse/Documents/GitHub/superpowers/drill
211
+ while read -r f; do
212
+ sha1=$(shasum -a 256 "$f" | cut -d' ' -f1)
213
+ sha2=$(shasum -a 256 "/Users/jesse/Documents/GitHub/superpowers/superpowers/evals/${f#./}" | cut -d' ' -f1)
214
+ if [ "$sha1" != "$sha2" ]; then
215
+ echo "MISMATCH: $f ($sha1 vs $sha2)"
216
+ fi
217
+ done < /tmp/drill-files.txt | head -20
218
+ ```
219
+
220
+ Expected: no output (every file's checksum matches between drill and evals).
221
+
222
+ - [ ] **Step 5: Smoke check - install dependencies**
223
+
224
+ ```bash
225
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
226
+ uv sync
227
+ ```
228
+
229
+ Expected: `Installed N packages` or similar. No errors.
230
+
231
+ - [ ] **Step 6: Smoke check - drill list**
232
+
233
+ ```bash
234
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
235
+ uv run drill list 2>&1 | head -5
236
+ ```
237
+
238
+ Expected: starts with scenario names. (Will likely error or warn about missing SUPERPOWERS_ROOT — that's fine, fixed in next task.)
239
+
240
+ - [ ] **Step 7: Dispatch verification subagent**
241
+
242
+ Dispatch a `general-purpose` subagent with this prompt:
243
+
244
+ ```
245
+ You are verifying a verbatim copy of the drill repo at
246
+ /Users/jesse/Documents/GitHub/superpowers/drill into
247
+ /Users/jesse/Documents/GitHub/superpowers/superpowers/evals.
248
+
249
+ Verify:
250
+
251
+ 1. The lift commit message records the SHA reported by:
252
+ cd /Users/jesse/Documents/GitHub/superpowers/drill && git rev-parse HEAD
253
+
254
+ 2. None of these excluded paths exist under evals/: .git/, .venv/,
255
+ results/, .env/, __pycache__/, *.egg-info/, .private-journal/.
256
+
257
+ 3. Every non-excluded file in drill has a SHA-256-identical
258
+ counterpart in evals/, and there are no extra files in evals/.
259
+
260
+ 4. The pyproject.toml, uv.lock, scenarios/*.yaml, backends/*.yaml,
261
+ setup_helpers/*.py, drill/*.py, prompts/*.md, fixtures/, bin/, and
262
+ docs/ are all present.
263
+
264
+ Report each check with PASS/FAIL. If any FAIL, dump enough detail
265
+ that the parent can fix.
266
+ ```
267
+
268
+ If the subagent reports any FAIL, fix the underlying issue (delete the leaked file, re-rsync, etc.) before continuing.
269
+
270
+ ---
271
+
272
+ ## Task 5: Add `SUPERPOWERS_ROOT` default helper
273
+
274
+ **Files:**
275
+ - Modify: `evals/drill/cli.py:11-14`
276
+
277
+ - [ ] **Step 1: Read the current cli.py header**
278
+
279
+ ```bash
280
+ sed -n '1,20p' /Users/jesse/Documents/GitHub/superpowers/superpowers/evals/drill/cli.py
281
+ ```
282
+
283
+ Expected output:
284
+
285
+ ```python
286
+ """Drill CLI: run, compare, list."""
287
+
288
+ from __future__ import annotations
289
+
290
+ import secrets
291
+ from pathlib import Path
292
+
293
+ import click
294
+ from dotenv import load_dotenv
295
+
296
+ PROJECT_ROOT: Path = Path(__file__).parent.parent
297
+
298
+ load_dotenv(PROJECT_ROOT / ".env")
299
+ ```
300
+
301
+ - [ ] **Step 2: Write a failing test for the helper**
302
+
303
+ Open `evals/tests/test_cli.py` and add this test at the end:
304
+
305
+ ```python
306
+ def test_set_superpowers_root_default_when_unset(monkeypatch, tmp_path):
307
+ """When SUPERPOWERS_ROOT is unset, helper sets it to PROJECT_ROOT.parent."""
308
+ monkeypatch.delenv("SUPERPOWERS_ROOT", raising=False)
309
+ from drill.cli import _set_superpowers_root_default, PROJECT_ROOT
310
+
311
+ _set_superpowers_root_default()
312
+
313
+ import os
314
+ assert os.environ["SUPERPOWERS_ROOT"] == str(PROJECT_ROOT.parent)
315
+
316
+
317
+ def test_set_superpowers_root_default_respects_existing(monkeypatch):
318
+ """When SUPERPOWERS_ROOT is already set, helper does not override."""
319
+ monkeypatch.setenv("SUPERPOWERS_ROOT", "/custom/path")
320
+ from drill.cli import _set_superpowers_root_default
321
+
322
+ _set_superpowers_root_default()
323
+
324
+ import os
325
+ assert os.environ["SUPERPOWERS_ROOT"] == "/custom/path"
326
+ ```
327
+
328
+ - [ ] **Step 3: Run the test and watch it fail**
329
+
330
+ ```bash
331
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
332
+ uv run pytest tests/test_cli.py -k set_superpowers_root_default -v
333
+ ```
334
+
335
+ Expected: 2 tests fail with `AttributeError: module 'drill.cli' has no attribute '_set_superpowers_root_default'`.
336
+
337
+ - [ ] **Step 4: Add the helper to cli.py**
338
+
339
+ Edit `/Users/jesse/Documents/GitHub/superpowers/superpowers/evals/drill/cli.py`. Replace lines 1–14 with:
340
+
341
+ ```python
342
+ """Drill CLI: run, compare, list."""
343
+
344
+ from __future__ import annotations
345
+
346
+ import os
347
+ import secrets
348
+ from pathlib import Path
349
+
350
+ import click
351
+ from dotenv import load_dotenv
352
+
353
+ PROJECT_ROOT: Path = Path(__file__).parent.parent
354
+
355
+ load_dotenv(PROJECT_ROOT / ".env")
356
+
357
+
358
+ def _set_superpowers_root_default() -> None:
359
+ """Default SUPERPOWERS_ROOT to the parent of evals/ if not already set.
360
+
361
+ Drill historically required contributors to export SUPERPOWERS_ROOT
362
+ pointing at the superpowers checkout. After lifting drill into
363
+ superpowers/evals/, the parent of PROJECT_ROOT is always the
364
+ superpowers root, so we can supply this default automatically.
365
+
366
+ Existing SUPERPOWERS_ROOT environment values are respected as overrides.
367
+ """
368
+ os.environ.setdefault("SUPERPOWERS_ROOT", str(PROJECT_ROOT.parent))
369
+
370
+
371
+ _set_superpowers_root_default()
372
+ ```
373
+
374
+ The bottom-of-module call to `_set_superpowers_root_default()` runs at import time, immediately after `load_dotenv()`. This ensures both `engine.py` and `setup.py` (which read `os.environ["SUPERPOWERS_ROOT"]` directly) and the YAML interpolation (which reads `os.environ` when the backend YAML is loaded) all see the value.
375
+
376
+ - [ ] **Step 5: Run the test and watch it pass**
377
+
378
+ ```bash
379
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
380
+ uv run pytest tests/test_cli.py -k set_superpowers_root_default -v
381
+ ```
382
+
383
+ Expected: 2 tests pass.
384
+
385
+ - [ ] **Step 6: Commit**
386
+
387
+ ```bash
388
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
389
+ git add evals/drill/cli.py evals/tests/test_cli.py
390
+ git commit -m "evals: default SUPERPOWERS_ROOT to parent of evals/ if unset
391
+
392
+ Adds _set_superpowers_root_default() to drill/cli.py, called at
393
+ module import after load_dotenv(). PROJECT_ROOT resolves to evals/
394
+ post-lift; its parent is the superpowers repo root, which is the
395
+ correct value for SUPERPOWERS_ROOT.
396
+
397
+ Existing env values are respected as overrides via os.environ.setdefault.
398
+
399
+ Tests:
400
+ - helper sets default when var is unset
401
+ - helper does not override when var is already set"
402
+ ```
403
+
404
+ ---
405
+
406
+ ## Task 6: Update backend YAMLs to reflect the new env contract
407
+
408
+ **Files:**
409
+ - Modify: `evals/backends/codex.yaml` (drop `SUPERPOWERS_ROOT` from `required_env`)
410
+ - Modify: `evals/backends/gemini.yaml` (drop `SUPERPOWERS_ROOT` from `required_env`)
411
+
412
+ The five `claude*.yaml` backend configs interpolate `${SUPERPOWERS_ROOT}` into `args` for the `--plugin-dir` flag — they keep `SUPERPOWERS_ROOT` in `required_env` because the interpolation needs it. The codex/gemini configs only listed it for engine.py/setup.py's `os.environ` reads, which the helper now satisfies.
413
+
414
+ - [ ] **Step 1: Confirm current state**
415
+
416
+ ```bash
417
+ grep -A3 'required_env:' /Users/jesse/Documents/GitHub/superpowers/superpowers/evals/backends/codex.yaml
418
+ grep -A2 'required_env:' /Users/jesse/Documents/GitHub/superpowers/superpowers/evals/backends/gemini.yaml
419
+ ```
420
+
421
+ Expected outputs include `- SUPERPOWERS_ROOT` lines.
422
+
423
+ - [ ] **Step 2: Read codex.yaml fully**
424
+
425
+ ```bash
426
+ cat /Users/jesse/Documents/GitHub/superpowers/superpowers/evals/backends/codex.yaml
427
+ ```
428
+
429
+ - [ ] **Step 3: Edit codex.yaml — drop the `- SUPERPOWERS_ROOT` line under `required_env`**
430
+
431
+ Open `evals/backends/codex.yaml` and find:
432
+
433
+ ```yaml
434
+ required_env:
435
+ - OPENAI_API_KEY
436
+ - SUPERPOWERS_ROOT
437
+ ```
438
+
439
+ Replace with:
440
+
441
+ ```yaml
442
+ required_env:
443
+ - OPENAI_API_KEY
444
+ ```
445
+
446
+ - [ ] **Step 4: Edit gemini.yaml — drop the `- SUPERPOWERS_ROOT` line under `required_env`**
447
+
448
+ Open `evals/backends/gemini.yaml` and find:
449
+
450
+ ```yaml
451
+ required_env:
452
+ - SUPERPOWERS_ROOT
453
+ ```
454
+
455
+ Replace with:
456
+
457
+ ```yaml
458
+ required_env: []
459
+ ```
460
+
461
+ (Empty list rather than dropping the field, so YAML schema validation doesn't trip.)
462
+
463
+ - [ ] **Step 5: Run drill's pytest suite to ensure nothing broke**
464
+
465
+ ```bash
466
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
467
+ uv run pytest -x 2>&1 | tail -20
468
+ ```
469
+
470
+ Expected: all tests pass. If `tests/test_backend.py` complains about `required_env` membership for codex/gemini, see Task 7.
471
+
472
+ - [ ] **Step 6: Commit**
473
+
474
+ ```bash
475
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
476
+ git add evals/backends/codex.yaml evals/backends/gemini.yaml
477
+ git commit -m "evals: drop SUPERPOWERS_ROOT from codex/gemini required_env
478
+
479
+ These backends only read SUPERPOWERS_ROOT via engine.py/setup.py's
480
+ os.environ access, which the new cli.py default helper supplies
481
+ automatically. claude*.yaml keep SUPERPOWERS_ROOT in required_env
482
+ because they interpolate \${SUPERPOWERS_ROOT} into --plugin-dir args."
483
+ ```
484
+
485
+ ---
486
+
487
+ ## Task 7: Update drill's pytest suite for the new contract
488
+
489
+ **Files:**
490
+ - Modify: `evals/tests/test_backend.py` (per-test updates if Task 6 step 5 surfaced failures)
491
+
492
+ - [ ] **Step 1: Run the test suite**
493
+
494
+ ```bash
495
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
496
+ uv run pytest tests/test_backend.py -v 2>&1 | tail -30
497
+ ```
498
+
499
+ If all tests pass, skip to step 5 (commit nothing, move to Task 8). Otherwise:
500
+
501
+ - [ ] **Step 2: Read failing tests**
502
+
503
+ For each failure, open the test in `evals/tests/test_backend.py` and read the assertion.
504
+
505
+ - [ ] **Step 3: Update assertions**
506
+
507
+ For tests that assert `SUPERPOWERS_ROOT` membership in `codex.yaml`'s or `gemini.yaml`'s `required_env`: invert the assertion to confirm absence. Example:
508
+
509
+ ```python
510
+ # Before:
511
+ def test_codex_requires_superpowers_root():
512
+ backend = load_backend("codex")
513
+ assert "SUPERPOWERS_ROOT" in backend.required_env
514
+
515
+ # After:
516
+ def test_codex_does_not_require_superpowers_root():
517
+ """codex.yaml dropped SUPERPOWERS_ROOT from required_env;
518
+ the cli.py helper supplies the default."""
519
+ backend = load_backend("codex")
520
+ assert "SUPERPOWERS_ROOT" not in backend.required_env
521
+ ```
522
+
523
+ - [ ] **Step 4: Re-run the test suite**
524
+
525
+ ```bash
526
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
527
+ uv run pytest -x 2>&1 | tail -10
528
+ ```
529
+
530
+ Expected: all tests pass.
531
+
532
+ - [ ] **Step 5: Commit (only if step 1 had failures)**
533
+
534
+ ```bash
535
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
536
+ git add evals/tests/test_backend.py
537
+ git commit -m "evals: update test_backend.py for relaxed required_env contract"
538
+ ```
539
+
540
+ ---
541
+
542
+ ## Task 8: Update evals/README.md and evals/CLAUDE.md
543
+
544
+ **Files:**
545
+ - Modify: `evals/README.md` (drop SUPERPOWERS_ROOT setup step)
546
+ - Modify: `evals/CLAUDE.md` (drop SUPERPOWERS_ROOT setup step)
547
+
548
+ - [ ] **Step 1: Edit evals/README.md**
549
+
550
+ Find the section that looks like:
551
+
552
+ ```markdown
553
+ Required environment:
554
+ ```bash
555
+ export SUPERPOWERS_ROOT=/path/to/superpowers
556
+ export ANTHROPIC_API_KEY=sk-...
557
+ ```
558
+ ```
559
+
560
+ Replace with:
561
+
562
+ ```markdown
563
+ Required environment:
564
+ ```bash
565
+ export ANTHROPIC_API_KEY=sk-...
566
+ ```
567
+
568
+ `SUPERPOWERS_ROOT` defaults to the parent of `evals/` (the superpowers repo root) and only needs to be set if you're running drill against a different superpowers checkout.
569
+ ```
570
+
571
+ - [ ] **Step 2: Edit evals/CLAUDE.md**
572
+
573
+ Find the section:
574
+
575
+ ```markdown
576
+ ## Required env
577
+
578
+ ```
579
+ SUPERPOWERS_ROOT=/path/to/superpowers
580
+ ANTHROPIC_API_KEY=sk-...
581
+ ```
582
+ ```
583
+
584
+ Replace with:
585
+
586
+ ```markdown
587
+ ## Required env
588
+
589
+ ```
590
+ ANTHROPIC_API_KEY=sk-...
591
+ ```
592
+
593
+ `SUPERPOWERS_ROOT` defaults to the parent of `evals/` (the superpowers repo root). Override only if running drill against a different superpowers checkout.
594
+ ```
595
+
596
+ - [ ] **Step 3: Commit**
597
+
598
+ ```bash
599
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
600
+ git add evals/README.md evals/CLAUDE.md
601
+ git commit -m "evals: drop SUPERPOWERS_ROOT setup step from README/CLAUDE
602
+
603
+ The cli.py helper now defaults the env var. Mention as override only."
604
+ ```
605
+
606
+ ---
607
+
608
+ ## Task 9: Validate from new location
609
+
610
+ **Files:** none (validation only — no commit unless something needs fixing)
611
+
612
+ - [ ] **Step 1: Run drill's full pytest suite**
613
+
614
+ ```bash
615
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
616
+ unset SUPERPOWERS_ROOT
617
+ uv run pytest 2>&1 | tail -5
618
+ ```
619
+
620
+ Expected: all tests pass. The `unset` ensures we're testing the helper, not an inherited env var.
621
+
622
+ - [ ] **Step 2: Run drill list**
623
+
624
+ ```bash
625
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
626
+ unset SUPERPOWERS_ROOT
627
+ uv run drill list 2>&1 | head -10
628
+ ```
629
+
630
+ Expected: scenario list, no error about missing SUPERPOWERS_ROOT.
631
+
632
+ - [ ] **Step 3: Source the env file**
633
+
634
+ ```bash
635
+ set -a
636
+ source /Users/jesse/Documents/GitHub/prime-radiant-inc/sprout/.env
637
+ set +a
638
+ echo "ANTHROPIC_API_KEY set: ${ANTHROPIC_API_KEY:+yes}"
639
+ ```
640
+
641
+ Expected: `ANTHROPIC_API_KEY set: yes`.
642
+
643
+ - [ ] **Step 4: Run a cheap drill scenario**
644
+
645
+ ```bash
646
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
647
+ unset SUPERPOWERS_ROOT
648
+ uv run drill run triggering-test-driven-development -b claude 2>&1 | tail -3
649
+ ```
650
+
651
+ Expected: `claude: 1 passed, 0 failed, 0 errors`.
652
+
653
+ If FAIL, debug before continuing. The path-defaults change is the most likely culprit; check that the helper actually fired by adding a `print(os.environ["SUPERPOWERS_ROOT"])` after the helper call temporarily.
654
+
655
+ ---
656
+
657
+ ## Task 10: Bash test deletion phase — per-file with subagent gate
658
+
659
+ This task has many sub-steps because each candidate-deletion file gets its own subagent verification + commit. The candidate list comes from the spec's coverage map. For each entry below:
660
+
661
+ 1. Read the bash test file.
662
+ 2. Read the candidate drill scenario YAML.
663
+ 3. Dispatch a subagent with both contents and the comparison prompt.
664
+ 4. Subagent reports per-assertion match table.
665
+ 5. If every bash assertion has a match: delete the bash test, commit.
666
+ 6. If any unmatched: stop, escalate, do not delete.
667
+
668
+ **Subagent prompt template (use for every deletion):**
669
+
670
+ ```
671
+ You are gating a bash test deletion. The bash test is allegedly
672
+ covered by a drill scenario; your job is to verify that claim.
673
+
674
+ BASH TEST: <paste full contents of bash test>
675
+
676
+ DRILL SCENARIO: <paste full contents of drill scenario YAML>
677
+
678
+ Output a markdown table with columns: BASH ASSERTION, DRILL CHECK,
679
+ STATUS. List EVERY assertion the bash test makes (every grep, every
680
+ [ ], every test command, every PASS/FAIL emit). For each, find a
681
+ matching drill check (in verify.assertions or verify.criteria) or
682
+ mark as UNMATCHED.
683
+
684
+ After the table, output "VERDICT: SAFE TO DELETE" if every bash
685
+ assertion has a match, otherwise "VERDICT: KEEP — N unmatched
686
+ assertions". Be conservative: if you are uncertain about a match,
687
+ mark as UNMATCHED.
688
+ ```
689
+
690
+ ### Task 10a: Skill-triggering prompts (6 files)
691
+
692
+ **Files:**
693
+ - Delete: `tests/skill-triggering/prompts/dispatching-parallel-agents.txt`
694
+ - Delete: `tests/skill-triggering/prompts/executing-plans.txt`
695
+ - Delete: `tests/skill-triggering/prompts/requesting-code-review.txt`
696
+ - Delete: `tests/skill-triggering/prompts/systematic-debugging.txt`
697
+ - Delete: `tests/skill-triggering/prompts/test-driven-development.txt`
698
+ - Delete: `tests/skill-triggering/prompts/writing-plans.txt`
699
+ - Keep: `tests/skill-triggering/run-test.sh`, `run-all.sh`
700
+
701
+ These prompt files are inputs to the bash runner — they don't have their own assertions. The runner script does the assertion. Map each prompt to its drill scenario:
702
+
703
+ | Prompt | Drill scenario |
704
+ |--------|----------------|
705
+ | dispatching-parallel-agents.txt | triggering-dispatching-parallel-agents.yaml |
706
+ | executing-plans.txt | triggering-executing-plans.yaml |
707
+ | requesting-code-review.txt | triggering-requesting-code-review.yaml |
708
+ | systematic-debugging.txt | triggering-systematic-debugging.yaml |
709
+ | test-driven-development.txt | triggering-test-driven-development.yaml |
710
+ | writing-plans.txt | triggering-writing-plans.yaml |
711
+
712
+ - [ ] **Step 1: For each prompt file, dispatch the subagent**
713
+
714
+ For prompt `tests/skill-triggering/prompts/<name>.txt` and scenario `evals/scenarios/triggering-<name>.yaml`, run the subagent prompt template with both contents pasted in. The subagent's job is to verify the prompt content matches what the drill scenario's `turns[].intent` describes.
715
+
716
+ If all 6 verify SAFE TO DELETE, proceed to step 2. If any verifies KEEP, that one stays and the rest may still proceed.
717
+
718
+ - [ ] **Step 2: Verify the runner is still useful for unrelated cases**
719
+
720
+ ```bash
721
+ ls /Users/jesse/Documents/GitHub/superpowers/superpowers/tests/skill-triggering/prompts/
722
+ ```
723
+
724
+ If the prompts/ directory is empty after the planned deletions, also delete `tests/skill-triggering/run-test.sh` and `run-all.sh` (they have nothing to run). Otherwise keep the runner.
725
+
726
+ - [ ] **Step 3: Delete and commit**
727
+
728
+ ```bash
729
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
730
+ git rm tests/skill-triggering/prompts/dispatching-parallel-agents.txt
731
+ git rm tests/skill-triggering/prompts/executing-plans.txt
732
+ git rm tests/skill-triggering/prompts/requesting-code-review.txt
733
+ git rm tests/skill-triggering/prompts/systematic-debugging.txt
734
+ git rm tests/skill-triggering/prompts/test-driven-development.txt
735
+ git rm tests/skill-triggering/prompts/writing-plans.txt
736
+ # If runner is now orphaned:
737
+ git rm tests/skill-triggering/run-test.sh tests/skill-triggering/run-all.sh
738
+ rmdir tests/skill-triggering/prompts/ 2>/dev/null || true
739
+ rmdir tests/skill-triggering/ 2>/dev/null || true
740
+ git commit -m "tests: remove skill-triggering bash prompts (covered by drill triggering-* scenarios)
741
+
742
+ Subagent verification confirmed each prompt's intent matches its
743
+ corresponding drill scenario's turns[].intent. Drill scenarios are
744
+ canonical; bash runner has no remaining prompts to drive."
745
+ ```
746
+
747
+ ### Task 10b: explicit-skill-requests (selective deletion)
748
+
749
+ **Files:**
750
+ - Inspect: 6 files in `tests/explicit-skill-requests/`
751
+ - Delete: only those verified to be 100% covered by drill scenarios
752
+ - Keep: the rest
753
+
754
+ Per the spec's updated coverage map, most of these have no drill counterpart. The likely-deletable ones:
755
+
756
+ | Bash test | Candidate drill scenario | Likely outcome |
757
+ |-----------|--------------------------|----------------|
758
+ | `run-test.sh` | n/a (runner) | KEEP |
759
+ | `run-all.sh` | n/a (runner) | KEEP |
760
+ | `run-claude-describes-sdd.sh` | `mid-conversation-skill-invocation.yaml` | likely DELETE; verify |
761
+ | `run-haiku-test.sh` | none (Haiku-specific) | KEEP |
762
+ | `run-multiturn-test.sh`, `run-extended-multiturn-test.sh` | none | KEEP |
763
+ | `prompts/please-use-brainstorming.txt`, `prompts/use-systematic-debugging.txt` | none | KEEP |
764
+
765
+ - [ ] **Step 1: Read each .sh file and prompt to confirm**
766
+
767
+ ```bash
768
+ for f in /Users/jesse/Documents/GitHub/superpowers/superpowers/tests/explicit-skill-requests/*.sh /Users/jesse/Documents/GitHub/superpowers/superpowers/tests/explicit-skill-requests/prompts/*.txt; do
769
+ echo "=== $f ==="
770
+ cat "$f" | head -30
771
+ done
772
+ ```
773
+
774
+ - [ ] **Step 2: Dispatch subagent for `run-claude-describes-sdd.sh` only**
775
+
776
+ Use the subagent prompt template above with:
777
+ - Bash test content: `tests/explicit-skill-requests/run-claude-describes-sdd.sh`
778
+ - Drill scenario: `evals/scenarios/mid-conversation-skill-invocation.yaml`
779
+
780
+ - [ ] **Step 3: Act on subagent verdict**
781
+
782
+ If SAFE TO DELETE:
783
+
784
+ ```bash
785
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
786
+ git rm tests/explicit-skill-requests/run-claude-describes-sdd.sh
787
+ git commit -m "tests: remove run-claude-describes-sdd.sh (covered by drill mid-conversation-skill-invocation)
788
+
789
+ Subagent verification: every assertion matches a drill check.
790
+ Other tests in tests/explicit-skill-requests/ are preserved
791
+ (run-haiku-test.sh, run-*-multiturn-test.sh, please-use-brainstorming
792
+ and use-systematic-debugging prompts have no drill coverage)."
793
+ ```
794
+
795
+ If KEEP: skip the deletion, document the gap as a future drill-scenario authoring task.
796
+
797
+ ### Task 10c: subagent-driven-dev real-project tests
798
+
799
+ **Files:**
800
+ - Inspect: `tests/subagent-driven-dev/go-fractals/`, `tests/subagent-driven-dev/svelte-todo/`
801
+ - Candidate scenarios: `evals/scenarios/sdd-go-fractals.yaml`, `evals/scenarios/sdd-svelte-todo.yaml`
802
+
803
+ These are entire fixture directories with `design.md`, `plan.md`, `scaffold.sh`. Each fixture directory was lifted into drill as a fixture under `evals/fixtures/`.
804
+
805
+ - [ ] **Step 1: Confirm drill has fixture parity**
806
+
807
+ ```bash
808
+ ls /Users/jesse/Documents/GitHub/superpowers/superpowers/evals/fixtures/sdd-go-fractals/
809
+ ls /Users/jesse/Documents/GitHub/superpowers/superpowers/evals/fixtures/sdd-svelte-todo/
810
+ ```
811
+
812
+ Expected: each contains `design.md`, `plan.md`, `scaffold.sh` (or equivalent) matching the source under `tests/subagent-driven-dev/`.
813
+
814
+ - [ ] **Step 2: Dispatch subagent for each pair**
815
+
816
+ Subagent prompt: same template, with bash "test" being the directory's `scaffold.sh` and (if present) any `*.sh` runner. Drill scenario being the corresponding `sdd-*.yaml`.
817
+
818
+ - [ ] **Step 3: Act on verdicts**
819
+
820
+ For each that returns SAFE TO DELETE:
821
+
822
+ ```bash
823
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
824
+ git rm -r tests/subagent-driven-dev/go-fractals/ # or svelte-todo
825
+ git commit -m "tests: remove subagent-driven-dev/<fixture> (covered by drill sdd-<fixture>)
826
+
827
+ Subagent verification: drill scenario asserts test suite passes
828
+ post-execution. Fixture content lives at evals/fixtures/sdd-<fixture>/."
829
+ ```
830
+
831
+ If both directories are removed, also `git rm -r tests/subagent-driven-dev/` if it becomes empty.
832
+
833
+ ### Task 10d: tests/claude-code/test-document-review-system.sh
834
+
835
+ **Candidate scenario:** `evals/scenarios/spec-reviewer-catches-planted-flaws.yaml`
836
+
837
+ - [ ] **Step 1: Dispatch subagent**
838
+
839
+ Subagent prompt template with the bash test content and the drill scenario YAML.
840
+
841
+ - [ ] **Step 2: Act on verdict**
842
+
843
+ If SAFE TO DELETE:
844
+
845
+ ```bash
846
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
847
+ git rm tests/claude-code/test-document-review-system.sh
848
+ git commit -m "tests: remove test-document-review-system.sh (covered by drill spec-reviewer-catches-planted-flaws)
849
+
850
+ Subagent verification: every assertion matches a drill check."
851
+ ```
852
+
853
+ ### Task 10e: tests/claude-code/test-requesting-code-review.sh
854
+
855
+ **Candidate scenario:** `evals/scenarios/code-review-catches-planted-bugs.yaml`
856
+
857
+ - [ ] **Step 1: Dispatch subagent**
858
+
859
+ Subagent prompt template with both contents.
860
+
861
+ - [ ] **Step 2: Act on verdict**
862
+
863
+ If SAFE TO DELETE:
864
+
865
+ ```bash
866
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
867
+ git rm tests/claude-code/test-requesting-code-review.sh
868
+ git commit -m "tests: remove test-requesting-code-review.sh (covered by drill code-review-catches-planted-bugs)
869
+
870
+ Subagent verification: every assertion matches a drill check."
871
+ ```
872
+
873
+ ### Task 10f: tests/claude-code/test-worktree-native-preference.sh
874
+
875
+ **Candidate scenario:** `evals/scenarios/worktree-creation-under-pressure.yaml`
876
+
877
+ - [ ] **Step 1: Dispatch subagent**
878
+
879
+ Subagent prompt template with both contents.
880
+
881
+ - [ ] **Step 2: Act on verdict**
882
+
883
+ If SAFE TO DELETE:
884
+
885
+ ```bash
886
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
887
+ git rm tests/claude-code/test-worktree-native-preference.sh
888
+ git commit -m "tests: remove test-worktree-native-preference.sh (covered by drill worktree-creation-under-pressure)
889
+
890
+ Subagent verification: every assertion matches a drill check."
891
+ ```
892
+
893
+ ### Task 10g: tests/claude-code/test-subagent-driven-development-integration.sh
894
+
895
+ **Candidate scenario:** `evals/scenarios/sdd-rejects-extra-features.yaml` (partial)
896
+
897
+ The spec marks this as "almost certainly keep + extend drill scenario". Don't delete. Instead:
898
+
899
+ - [ ] **Step 1: Dispatch subagent for the comparison anyway**
900
+
901
+ This documents the gap explicitly.
902
+
903
+ - [ ] **Step 2: Decide based on subagent output**
904
+
905
+ Likely outcome: KEEP with documented gap. The bash test asserts: `commit_count >= 3`, `npm test` passes, runs `analyze-token-usage.py`. The drill scenario asserts forbidden-exports + reviewer-as-gate. These are mostly disjoint.
906
+
907
+ - [ ] **Step 3: Document the gap** (if KEEP)
908
+
909
+ Add a comment at the top of `tests/claude-code/test-subagent-driven-development-integration.sh`:
910
+
911
+ ```bash
912
+ # Drill coverage: sdd-rejects-extra-features.yaml covers the YAGNI
913
+ # enforcement (forbidden exports + reviewer-as-gate). This bash test
914
+ # additionally asserts: ≥3 task commits, npm test passes, token
915
+ # analysis runs. Keep until those assertions are added to drill or
916
+ # explicitly retired.
917
+ ```
918
+
919
+ ```bash
920
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
921
+ git add tests/claude-code/test-subagent-driven-development-integration.sh
922
+ git commit -m "tests: annotate SDD integration test with drill coverage notes
923
+
924
+ Drill scenario sdd-rejects-extra-features covers the YAGNI subset.
925
+ This bash test adds: ≥3 commits, npm test, token analysis. Kept
926
+ until drill scenario covers those or they're retired."
927
+ ```
928
+
929
+ ### Task 10h: tests/claude-code/test-subagent-driven-development.sh
930
+
931
+ This is a meta/describe-skill test (per spec). No drill scenario covers describe-skill behavior.
932
+
933
+ - [ ] **Step 1: Confirm by reading the file**
934
+
935
+ ```bash
936
+ cat /Users/jesse/Documents/GitHub/superpowers/superpowers/tests/claude-code/test-subagent-driven-development.sh
937
+ ```
938
+
939
+ Expected: tests asking the agent to describe SDD skills, not exercise them.
940
+
941
+ - [ ] **Step 2: KEEP and annotate**
942
+
943
+ Add at the top:
944
+
945
+ ```bash
946
+ # No drill coverage: this test asks the agent to *describe* SDD
947
+ # (asserts that asked-about skills can be summarized correctly).
948
+ # Drill scenarios test behavior, not description. Kept.
949
+ ```
950
+
951
+ ```bash
952
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
953
+ git add tests/claude-code/test-subagent-driven-development.sh
954
+ git commit -m "tests: annotate SDD describe-skill test with kept-by-design note
955
+
956
+ Tests agent's ability to *describe* the SDD skill — drill scenarios
957
+ test behavior, not description. No drill coverage; kept by design."
958
+ ```
959
+
960
+ ---
961
+
962
+ ## Task 11: Stale-reference scrub
963
+
964
+ **Files:**
965
+ - Possibly modify: `docs/testing.md`, `README.md`, `CLAUDE.md`, `lefthook.yml`, `.opencode/INSTALL.md`, `.codex-plugin/INSTALL.md`, `.github/*`, `scripts/*`
966
+ - Annotate (do not rewrite): `RELEASE-NOTES.md`, `docs/superpowers/plans/*.md`
967
+
968
+ - [ ] **Step 1: Build list of deleted-file paths**
969
+
970
+ ```bash
971
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
972
+ git diff --name-only --diff-filter=D dev..HEAD | sort > /tmp/deleted-paths.txt
973
+ cat /tmp/deleted-paths.txt
974
+ ```
975
+
976
+ - [ ] **Step 2: Search for active references**
977
+
978
+ ```bash
979
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
980
+ while read -r path; do
981
+ echo "=== $path ==="
982
+ grep -rln "$path" \
983
+ --include="*.md" \
984
+ --include="*.yml" \
985
+ --include="*.yaml" \
986
+ --include="*.sh" \
987
+ --include="*.json" \
988
+ --exclude-dir=node_modules \
989
+ --exclude-dir=.venv \
990
+ --exclude-dir=evals \
991
+ --exclude-dir=.git \
992
+ .
993
+ done < /tmp/deleted-paths.txt
994
+ ```
995
+
996
+ This finds every reference to a deleted file. Categorize each hit:
997
+
998
+ | Hit location | Treatment |
999
+ |--------------|-----------|
1000
+ | `docs/testing.md` | Update — actively documents the test |
1001
+ | `README.md` (Contributing section) | Update if it points at deleted tests |
1002
+ | `CLAUDE.md`, `GEMINI.md`, `AGENTS.md` | Update if they reference deleted tests |
1003
+ | `.github/workflows/*.yml` | Update — CI shouldn't try to run deleted tests |
1004
+ | `scripts/*` | Update if they run deleted tests |
1005
+ | `.opencode/INSTALL.md`, `.codex-plugin/INSTALL.md` | Update if they reference deleted tests |
1006
+ | `lefthook.yml` | Update if hooks invoke deleted tests |
1007
+ | `RELEASE-NOTES.md` | Annotate, don't rewrite (dated artifact) |
1008
+ | `docs/superpowers/plans/*.md` | Annotate, don't rewrite (dated artifact) |
1009
+
1010
+ - [ ] **Step 3: Update active references**
1011
+
1012
+ For each "Update" hit, edit the file to either:
1013
+ - Remove the reference if the deleted test was the only reason it was named.
1014
+ - Replace with a pointer to the drill scenario (e.g., "see `evals/scenarios/triggering-test-driven-development.yaml`").
1015
+
1016
+ - [ ] **Step 4: Annotate dated artifacts**
1017
+
1018
+ For each `RELEASE-NOTES.md` or `docs/superpowers/plans/*.md` hit, add an inline annotation at the *first* hit per file:
1019
+
1020
+ ```markdown
1021
+ > Note: this section references `tests/skill-triggering/run-all.sh` and
1022
+ > related bash tests that were lifted into drill scenarios on 2026-05-06
1023
+ > (see `evals/scenarios/triggering-*.yaml`). The references are
1024
+ > preserved as dated artifacts of the work this doc describes.
1025
+ ```
1026
+
1027
+ Don't modify the actual references — they're historical.
1028
+
1029
+ - [ ] **Step 5: Dispatch subagent for second-pass scrub**
1030
+
1031
+ Dispatch a `general-purpose` subagent:
1032
+
1033
+ ```
1034
+ Working directory: /Users/jesse/Documents/GitHub/superpowers/superpowers
1035
+
1036
+ These bash test paths were deleted on the current branch; some are
1037
+ already addressed, but I want a second pair of eyes:
1038
+
1039
+ <paste contents of /tmp/deleted-paths.txt>
1040
+
1041
+ Search the entire superpowers tree (excluding evals/, node_modules/,
1042
+ .venv/, .git/) for any remaining references to those paths. Report
1043
+ every hit with file:line and one-sentence judgment of whether it
1044
+ needs an update or is fine as-is. Do not modify files; just report.
1045
+ ```
1046
+
1047
+ Address every reported hit before continuing.
1048
+
1049
+ - [ ] **Step 6: Commit the active updates**
1050
+
1051
+ ```bash
1052
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
1053
+ git add -u # picks up edits to existing files
1054
+ git commit -m "docs: update references to lifted-and-deleted bash tests
1055
+
1056
+ Active references in docs/testing.md, README.md, CI workflows, etc.
1057
+ now point at drill scenarios. Historical references in RELEASE-NOTES.md
1058
+ and docs/superpowers/plans/*.md are annotated as dated artifacts,
1059
+ not rewritten."
1060
+ ```
1061
+
1062
+ ---
1063
+
1064
+ ## Task 12: Top-level docs
1065
+
1066
+ **Files:**
1067
+ - Modify: `docs/testing.md` — split into "Plugin tests" + "Skill behavior evals"
1068
+ - Modify: `CLAUDE.md` — add evals pointer
1069
+ - Modify: `README.md` — add Contributing-section pointer
1070
+ - Modify: `.gitignore` — add `evals/results/`, `evals/.venv/`, `evals/.env`
1071
+
1072
+ - [ ] **Step 1: Split docs/testing.md**
1073
+
1074
+ The file is currently Claude-Code-centric. Split into two top-level sections.
1075
+
1076
+ Open `/Users/jesse/Documents/GitHub/superpowers/superpowers/docs/testing.md` and replace the file content with this structure (preserve the existing Plugin-test details where applicable):
1077
+
1078
+ ```markdown
1079
+ # Testing Superpowers
1080
+
1081
+ Superpowers has two distinct kinds of tests, each in its own directory:
1082
+
1083
+ - **`tests/`** — does the plugin's non-LLM code work? Bash + node + python integration tests for brainstorm-server JS, OpenCode plugin loading, codex-plugin sync, and analysis utilities.
1084
+ - **`evals/`** — do agents behave correctly on real LLM sessions? Python harness driving real tmux sessions of Claude Code / Codex / Gemini CLI / Copilot CLI, with an LLM actor and verifier judging skill compliance.
1085
+
1086
+ ## Plugin tests
1087
+
1088
+ Live in `tests/`. Currently:
1089
+
1090
+ - `tests/brainstorm-server/` — node test suite for the brainstorm server JS code.
1091
+ - `tests/opencode/` — bash tests for OpenCode plugin loading, bootstrap caching, and tool registration.
1092
+ - `tests/codex-plugin-sync/` — bash sync verification.
1093
+ - `tests/claude-code/test-helpers.sh`, `analyze-token-usage.py` — utilities used by remaining bash tests.
1094
+ - `tests/claude-code/test-subagent-driven-development.sh` — agent-can-describe-SDD test (no drill counterpart).
1095
+ - `tests/claude-code/test-subagent-driven-development-integration.sh` — extended SDD integration with token analysis (drill covers the YAGNI subset).
1096
+ - `tests/explicit-skill-requests/` — Haiku-specific, multi-turn, and skill-name-prompted tests not covered by drill.
1097
+
1098
+ Run plugin tests via the relevant directory's `run-*.sh` or `npm test`.
1099
+
1100
+ ## Skill behavior evals
1101
+
1102
+ Live in `evals/`. Drill is the harness; scenarios live at `evals/scenarios/*.yaml`. See `evals/README.md` for setup. Quick start:
1103
+
1104
+ ```bash
1105
+ cd evals
1106
+ uv sync
1107
+ export ANTHROPIC_API_KEY=sk-...
1108
+ uv run drill run triggering-test-driven-development -b claude
1109
+ ```
1110
+
1111
+ Drill scenarios are slow (3-30+ minutes each) and run real LLM sessions. They are not part of CI today; the natural follow-up is a tiered model (fast subset on PR, full sweep nightly + on-demand).
1112
+ ```
1113
+
1114
+ - [ ] **Step 2: Update CLAUDE.md**
1115
+
1116
+ Read the current CLAUDE.md, find a spot near the project structure section, and add:
1117
+
1118
+ ```markdown
1119
+ ## Eval harness
1120
+
1121
+ Skill-behavior evals live at `evals/` — see `evals/README.md`. Drill (the harness) drives real tmux sessions of Claude Code / Codex / Gemini CLI / Copilot CLI and judges skill compliance with an LLM verifier. Plugin-infrastructure tests still live at `tests/`.
1122
+ ```
1123
+
1124
+ - [ ] **Step 3: Update README.md**
1125
+
1126
+ Find the Contributing section. Add a line:
1127
+
1128
+ ```markdown
1129
+ - Skill-behavior tests use the eval harness at `evals/`. See `evals/README.md` for setup. Plugin-infrastructure tests live at `tests/` and run via the relevant `run-*.sh` or `npm test`.
1130
+ ```
1131
+
1132
+ - [ ] **Step 4: Update top-level .gitignore**
1133
+
1134
+ Open `/Users/jesse/Documents/GitHub/superpowers/superpowers/.gitignore` and add at the bottom:
1135
+
1136
+ ```
1137
+ # Eval harness — drill ships its own gitignore at evals/.gitignore;
1138
+ # these are belt-and-suspenders entries for tools that don't recurse.
1139
+ evals/results/
1140
+ evals/.venv/
1141
+ evals/.env
1142
+ ```
1143
+
1144
+ - [ ] **Step 5: Commit**
1145
+
1146
+ ```bash
1147
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
1148
+ git add docs/testing.md CLAUDE.md README.md .gitignore
1149
+ git commit -m "docs: introduce evals/ as the canonical skill-behavior eval harness
1150
+
1151
+ - docs/testing.md split into Plugin tests + Skill behavior evals
1152
+ - CLAUDE.md adds Eval harness section pointing at evals/
1153
+ - README.md Contributing section mentions evals/ alongside tests/
1154
+ - .gitignore adds evals/{results,.venv,.env} as belt-and-suspenders
1155
+ (evals/.gitignore covers these locally; root-level entries help
1156
+ tooling that does not recurse into nested ignore files)."
1157
+ ```
1158
+
1159
+ ---
1160
+
1161
+ ## Task 13: Re-run smoke checks (regression gate)
1162
+
1163
+ **Files:** none (validation only)
1164
+
1165
+ - [ ] **Step 1: Run drill's pytest**
1166
+
1167
+ ```bash
1168
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
1169
+ unset SUPERPOWERS_ROOT
1170
+ uv run pytest 2>&1 | tail -5
1171
+ ```
1172
+
1173
+ Expected: all tests pass.
1174
+
1175
+ - [ ] **Step 2: Run cheap drill scenario**
1176
+
1177
+ ```bash
1178
+ set -a
1179
+ source /Users/jesse/Documents/GitHub/prime-radiant-inc/sprout/.env
1180
+ set +a
1181
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/evals
1182
+ unset SUPERPOWERS_ROOT
1183
+ uv run drill run triggering-test-driven-development -b claude 2>&1 | tail -3
1184
+ ```
1185
+
1186
+ Expected: `claude: 1 passed, 0 failed, 0 errors`. If FAIL, the docs / scrub / deletion phases broke something — bisect over the recent commits.
1187
+
1188
+ - [ ] **Step 3: Run remaining plugin tests that survived**
1189
+
1190
+ ```bash
1191
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers/tests/brainstorm-server
1192
+ node server.test.js 2>&1 | tail -3
1193
+ ```
1194
+
1195
+ Expected: `Results: 25 passed, 0 failed`.
1196
+
1197
+ ---
1198
+
1199
+ ## Task 14: Final adversarial review
1200
+
1201
+ **Files:** none (review only; subagent dispatches)
1202
+
1203
+ - [ ] **Step 1: Build the diff for reviewers**
1204
+
1205
+ ```bash
1206
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
1207
+ git log --oneline dev..HEAD
1208
+ git diff dev..HEAD --stat
1209
+ ```
1210
+
1211
+ Capture both outputs to share with reviewers.
1212
+
1213
+ - [ ] **Step 2: Dispatch two parallel subagents**
1214
+
1215
+ Use the `Agent` tool with two parallel calls. Same prompt to both, with adversarial framing:
1216
+
1217
+ ```
1218
+ Adversarial review competition: 5 points to whoever finds the most
1219
+ legitimate issues. You're competing against a parallel reviewer
1220
+ assigned the identical task.
1221
+
1222
+ **Branch:** f/evals-lift, in /Users/jesse/Documents/GitHub/superpowers/superpowers
1223
+ **Base:** dev (currently b4363df)
1224
+ **Spec:** docs/superpowers/specs/2026-05-06-lift-drill-into-evals-design.md
1225
+
1226
+ This branch lifts the obra/drill repo into superpowers/evals/ and
1227
+ deletes redundant bash tests that drill scenarios cover. Two prior
1228
+ adversarial reviews caught issues at the spec stage; this is the
1229
+ post-implementation review.
1230
+
1231
+ Run: git log --oneline dev..HEAD; git diff dev..HEAD --stat
1232
+
1233
+ Look hard at:
1234
+ 1. Did the rsync-with-excludes actually exclude what it claimed?
1235
+ (find evals -name '.git' -type d should return nothing)
1236
+ 2. Does the lift commit message point at a real commit in obra/drill?
1237
+ 3. Does the SUPERPOWERS_ROOT helper actually default correctly when
1238
+ the env var is unset? (cd evals && unset SUPERPOWERS_ROOT && uv
1239
+ run drill list — does it work?)
1240
+ 4. For each deleted bash test, does the corresponding drill scenario
1241
+ actually verify what the bash test asserted? Spot-check by reading
1242
+ the scenario YAML.
1243
+ 5. Are there active references in docs/, .github/, scripts/,
1244
+ lefthook.yml that still point at deleted bash test paths?
1245
+ 6. Did the drill pytest suite get updated for the new env-var contract,
1246
+ and does it pass?
1247
+ 7. Did the smoke scenario actually get run after path changes?
1248
+ 8. Is the drill repo unchanged? (cd ../drill && git status)
1249
+
1250
+ Verify before claiming. If you assert "X is broken", check on disk
1251
+ first. Confidently-wrong claims count negatively.
1252
+
1253
+ Report format: numbered list, each with severity (critical/important/
1254
+ minor/nitpick) and one-sentence explanation with file:line. Lead with
1255
+ most serious. Cap at ~600 words.
1256
+ ```
1257
+
1258
+ - [ ] **Step 3: Address findings**
1259
+
1260
+ For each legitimate finding from either reviewer, fix in a separate commit. Re-run smoke checks (Task 13) after fixes.
1261
+
1262
+ - [ ] **Step 4: Declare a winner**
1263
+
1264
+ Per the cross-platform PR pattern, count legitimate findings (false positives count negatively). Acknowledge the winner in your reply summary.
1265
+
1266
+ ---
1267
+
1268
+ ## Task 15: Push and open PR
1269
+
1270
+ **Files:** none
1271
+
1272
+ - [ ] **Step 1: Push the branch**
1273
+
1274
+ ```bash
1275
+ cd /Users/jesse/Documents/GitHub/superpowers/superpowers
1276
+ git push -u origin f/evals-lift
1277
+ ```
1278
+
1279
+ - [ ] **Step 2: Open PR against dev with full description**
1280
+
1281
+ ```bash
1282
+ gh pr create \
1283
+ --base dev \
1284
+ --head f/evals-lift \
1285
+ --reviewer arittr \
1286
+ --title "Lift drill into superpowers as evals/ harness" \
1287
+ --body "$(cat <<'EOF'
1288
+ ## What problem are you trying to solve?
1289
+
1290
+ Drill — the standalone Python skill-compliance benchmark at obra/drill — is already the de facto eval harness for superpowers. The PRI-1397 commit series lifted ~22 bash tests into drill scenarios, and the most recent superpowers commit (a2292c5) explicitly removed a redundant bash test with the message "replaced by drill behavioral coverage". Drill is a sibling repo today, requiring contributors to clone two checkouts and set SUPERPOWERS_ROOT manually. This PR completes the migration: drill becomes superpowers/evals/.
1291
+
1292
+ ## What does this PR change?
1293
+
1294
+ - Lifts the obra/drill repo into superpowers as `evals/`, with explicit rsync excludes (.git, .venv, results, .env, __pycache__, *.egg-info, .private-journal). The lift commit records the source SHA.
1295
+ - Adds a `_set_superpowers_root_default()` helper to drill/cli.py so SUPERPOWERS_ROOT defaults to the parent of evals/ — no manual env-var setup.
1296
+ - Drops SUPERPOWERS_ROOT from required_env in codex.yaml/gemini.yaml (the helper supplies it). Claude*.yaml keep it because they interpolate ${SUPERPOWERS_ROOT} into --plugin-dir args.
1297
+ - Deletes redundant bash tests under tests/skill-triggering/, tests/explicit-skill-requests/, tests/subagent-driven-dev/, and tests/claude-code/ — gated per-file by a subagent that compared each bash test's assertions to its drill scenario's verify block. Anything not 100% covered was kept.
1298
+ - docs/testing.md split into Plugin tests + Skill behavior evals.
1299
+ - README.md Contributing and CLAUDE.md gain pointers to evals/.
1300
+
1301
+ ## Is this change appropriate for the core library?
1302
+
1303
+ Yes. Cross-runtime evaluation is core to superpowers, the migration to drill scenarios was already underway in this repo, and the eval harness needs to be discoverable in-tree to be findable.
1304
+
1305
+ ## What alternatives did you consider?
1306
+
1307
+ - Vendored copy + sync script (drill repo continues independently). Rejected: divergence risk; single-source-of-truth wins.
1308
+ - git subtree merge (preserves drill history in-tree). Rejected: superpowers' git history grows by 50+ commits, the merge commit is ugly, subtrees are operationally heavy.
1309
+ - Keep drill as a sibling repo and just polish docs. Rejected: doesn't solve the discoverability problem.
1310
+
1311
+ ## Does this PR contain multiple unrelated changes?
1312
+
1313
+ No — every change supports "drill is now evals/ inside superpowers". Multiple commits for atomicity (verbatim copy, env helper, YAML updates, docs) but one direction.
1314
+
1315
+ ## Existing PRs
1316
+
1317
+ - [x] I have reviewed all open AND closed PRs for duplicates or prior art
1318
+ - Related PRs: #1486 (obra/superpowers cross-platform PR — independent; no shared file changes besides README, which has no overlap)
1319
+
1320
+ ## Environment tested
1321
+
1322
+ | Harness | Version | Model | Model ID |
1323
+ |---------|---------|-------|----------|
1324
+ | Claude Code | local install | Opus | claude-opus-4-7 (1M context) |
1325
+
1326
+ Drill's own pytest suite passes from the new location. `triggering-test-driven-development` drill scenario passes from `evals/` after the path-default changes. (Larger drill sweep deferred to release-cadence runs per the spec's deferred-CI policy.)
1327
+
1328
+ ## Evaluation
1329
+
1330
+ - Initial prompt: see linked spec (`docs/superpowers/specs/2026-05-06-lift-drill-into-evals-design.md`).
1331
+ - Drill's own pytest suite passes.
1332
+ - One drill scenario re-run from the new location end-to-end (proves the SUPERPOWERS_ROOT default works).
1333
+ - Per-deleted-file subagent verification recorded in each deletion commit's message.
1334
+
1335
+ ## Rigor
1336
+
1337
+ - [x] If this is a skills change: this is not a skills change; it's a tooling/infrastructure migration. No behavior-shaping content modified.
1338
+ - [x] Adversarial pressure-tested: two parallel reviewers on the spec; final adversarial pre-PR review on the implementation; spec already corrected for findings before implementation began.
1339
+ - [x] Did not modify carefully-tuned content.
1340
+
1341
+ ## Human review
1342
+
1343
+ - [x] A human has reviewed the COMPLETE proposed diff before submission
1344
+
1345
+ ## Action items after merge
1346
+
1347
+ 1. Archive obra/drill on GitHub (mark read-only, add README pointer to obra/superpowers/evals/).
1348
+ 2. The spec lists CI integration, scenario co-location with skills, and Python package rename as deferred work. Open issues for any of these you want tracked.
1349
+ EOF
1350
+ )"
1351
+ ```
1352
+
1353
+ - [ ] **Step 3: Confirm PR opened**
1354
+
1355
+ ```bash
1356
+ gh pr view --web
1357
+ ```
1358
+
1359
+ Expected: browser opens to the new PR. Take a screenshot or note the URL for follow-up.
1360
+
1361
+ ---
1362
+
1363
+ ## Verification checklist (run after Task 15)
1364
+
1365
+ - [ ] `git log --oneline dev..HEAD` shows the expected commits in order
1366
+ - [ ] The lift commit message records the source SHA
1367
+ - [ ] `find evals -name '.git' -type d` returns no output
1368
+ - [ ] `cd evals && unset SUPERPOWERS_ROOT && uv run pytest` passes
1369
+ - [ ] `cd evals && unset SUPERPOWERS_ROOT && uv run drill list` returns scenarios
1370
+ - [ ] `cd evals && unset SUPERPOWERS_ROOT && uv run drill run triggering-test-driven-development -b claude` passes
1371
+ - [ ] `tests/brainstorm-server/server.test.js` still passes (regression gate for non-LLM tests)
1372
+ - [ ] `git diff dev..HEAD docs/superpowers/plans/2026-04-06-worktree-rototill.md docs/superpowers/plans/2026-03-23-codex-app-compatibility.md RELEASE-NOTES.md` shows annotations only, no path rewrites
1373
+ - [ ] `cd ../drill && git log --oneline -1` shows obra/drill is unchanged from the source SHA recorded in the lift commit
1374
+ - [ ] PR body lists the post-merge archival action item
github_code/obra__superpowers/docs/superpowers/plans/2026-05-07-pi-extension-and-evals.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pi Extension and Evals Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Add first-class Pi package support for Superpowers and add Pi as a Drill eval backend.
6
+
7
+ **Architecture:** The Pi package is declared in the root `package.json` and loads existing `skills/` plus a small Pi extension. The extension injects the `using-superpowers` bootstrap into provider context as a user-role message on session startup and after compaction, with Pi-specific tool mapping. Drill gains a `pi` backend, Pi session-log normalization, and tests.
8
+
9
+ **Tech Stack:** Pi TypeScript extension API, Node built-in test runner, Drill Python eval harness, pytest.
10
+
11
+ ---
12
+
13
+ ### Task 1: Pi package manifest and extension tests
14
+
15
+ **Files:**
16
+ - Modify: `package.json`
17
+ - Create: `tests/pi/test-pi-extension.mjs`
18
+
19
+ - [ ] **Step 1: Write failing package/extension tests**
20
+
21
+ Create `tests/pi/test-pi-extension.mjs` with tests that import `extensions/superpowers.ts`, register fake Pi handlers, and assert:
22
+ - root `package.json` has `keywords` containing `pi-package`
23
+ - root `package.json` has `pi.skills: ["./skills"]`
24
+ - root `package.json` has `pi.extensions: ["./extensions/superpowers.ts"]`
25
+ - the extension registers `resources_discover`, `session_start`, `session_compact`, `context`, and `agent_end`
26
+ - startup `context` injects exactly one user-role bootstrap message
27
+ - `agent_end` clears startup injection
28
+ - `session_compact` re-enables injection
29
+ - the extension does not register `session_before_compact`
30
+
31
+ - [ ] **Step 2: Run tests and verify RED**
32
+
33
+ Run: `node --experimental-strip-types --test tests/pi/test-pi-extension.mjs`
34
+
35
+ Expected: FAIL because `extensions/superpowers.ts` does not exist and `package.json` lacks the `pi` manifest.
36
+
37
+ - [ ] **Step 3: Implement manifest fields**
38
+
39
+ Update `package.json` with `description`, `keywords`, `pi.extensions`, and `pi.skills` while preserving existing `name`, `version`, `type`, and `main`.
40
+
41
+ - [ ] **Step 4: Implement `extensions/superpowers.ts`**
42
+
43
+ Create a zero-runtime-dependency extension that:
44
+ - locates the package root from `import.meta.url`
45
+ - reads `skills/using-superpowers/SKILL.md`
46
+ - strips YAML frontmatter
47
+ - appends Pi-specific tool mapping
48
+ - exposes `resources_discover` with the skills path
49
+ - marks bootstrap pending on `session_start` and `session_compact`
50
+ - injects a user-role bootstrap message in `context`
51
+ - inserts post-compact bootstrap after leading `compactionSummary` messages
52
+ - clears pending bootstrap on `agent_end`
53
+
54
+ - [ ] **Step 5: Run tests and verify GREEN**
55
+
56
+ Run: `node --experimental-strip-types --test tests/pi/test-pi-extension.mjs`
57
+
58
+ Expected: PASS.
59
+
60
+ ### Task 2: Pi tool mapping reference
61
+
62
+ **Files:**
63
+ - Create: `skills/using-superpowers/references/pi-tools.md`
64
+ - Modify: `tests/pi/test-pi-extension.mjs`
65
+
66
+ - [ ] **Step 1: Write failing test for Pi reference doc**
67
+
68
+ Add assertions that `skills/using-superpowers/references/pi-tools.md` exists and documents mappings for `Skill`, `Task`, `TodoWrite`, and built-in tool names.
69
+
70
+ - [ ] **Step 2: Run tests and verify RED**
71
+
72
+ Run: `node --experimental-strip-types --test tests/pi/test-pi-extension.mjs`
73
+
74
+ Expected: FAIL because `pi-tools.md` does not exist.
75
+
76
+ - [ ] **Step 3: Add Pi reference doc**
77
+
78
+ Create `skills/using-superpowers/references/pi-tools.md` explaining Pi-native skills, optional `pi-subagents`, no canonical todo/tasklist plugin, and built-in lowercase tools.
79
+
80
+ - [ ] **Step 4: Run tests and verify GREEN**
81
+
82
+ Run: `node --experimental-strip-types --test tests/pi/test-pi-extension.mjs`
83
+
84
+ Expected: PASS.
85
+
86
+ ### Task 3: Drill Pi backend and session log normalization
87
+
88
+ **Files:**
89
+ - Create: `evals/backends/pi.yaml`
90
+ - Modify: `evals/drill/backend.py`
91
+ - Modify: `evals/drill/engine.py`
92
+ - Modify: `evals/drill/normalizer.py`
93
+ - Modify: `evals/tests/test_backend.py`
94
+ - Modify: `evals/tests/test_normalizer.py`
95
+
96
+ - [ ] **Step 1: Write failing backend/normalizer tests**
97
+
98
+ Add pytest coverage for:
99
+ - `load_backend("pi")` returns `family == "pi"`
100
+ - Pi backend command starts with `pi` and includes `-e ${SUPERPOWERS_ROOT}`
101
+ - `_resolve_log_dir()` for Pi points under `~/.pi/agent/sessions`
102
+ - `filter_pi_logs_by_cwd()` keeps only session files whose header `cwd` matches the scenario workdir
103
+ - `normalize_pi_logs()` extracts `toolCall` blocks from Pi assistant session entries and maps built-in lowercase tools to canonical names
104
+
105
+ - [ ] **Step 2: Run tests and verify RED**
106
+
107
+ Run: `uv run pytest evals/tests/test_backend.py evals/tests/test_normalizer.py -q`
108
+
109
+ Expected: FAIL because the Pi backend and normalizer do not exist.
110
+
111
+ - [ ] **Step 3: Add `evals/backends/pi.yaml`**
112
+
113
+ Configure the backend to run `pi -e ${SUPERPOWERS_ROOT}`, use permissive TUI readiness, `/quit` shutdown, and Pi session log location.
114
+
115
+ - [ ] **Step 4: Implement Pi family support**
116
+
117
+ Update `Backend.family`, `Engine._resolve_log_dir`, `Engine._collect_tool_calls`, and `normalizer.py` with Pi log filtering and normalizing.
118
+
119
+ - [ ] **Step 5: Run tests and verify GREEN**
120
+
121
+ Run: `uv run pytest evals/tests/test_backend.py evals/tests/test_normalizer.py -q`
122
+
123
+ Expected: PASS.
124
+
125
+ ### Task 4: Documentation and full verification
126
+
127
+ **Files:**
128
+ - Modify: `README.md`
129
+ - Modify: `evals/README.md`
130
+
131
+ - [ ] **Step 1: Document Pi install and eval backend**
132
+
133
+ Add Pi to README quickstart/install list and add backend entry/usage to `evals/README.md`.
134
+
135
+ - [ ] **Step 2: Run verification**
136
+
137
+ Run:
138
+ ```bash
139
+ node --experimental-strip-types --test tests/pi/test-pi-extension.mjs
140
+ uv run pytest evals/tests/test_backend.py evals/tests/test_setup.py evals/tests/test_normalizer.py -q
141
+ ```
142
+
143
+ Expected: all tests pass.
github_code/obra__superpowers/docs/superpowers/plans/2026-06-09-sdd-task-scoped-review-dispatch.md ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SDD Task-Scoped Review Dispatch Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Scope SDD's per-task reviews to the task (diff-first reading, justified broadening, no redundant test runs) while final branch review stays broad.
6
+
7
+ **Architecture:** Four prose edits to the subagent-driven-development skill (the per-task quality prompt becomes self-contained instead of delegating to the merge-readiness template; the spec prompt gets a third verdict channel and grounded skepticism; the implementer prompt gains a re-run-after-fix rule; SKILL.md gets controller guidance) plus one new eval scenario in the `evals/` submodule. `skills/requesting-code-review/` is deliberately untouched.
8
+
9
+ **Tech Stack:** Markdown skill files; Python setup helper + bash checks + story.md for the quorum eval.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-06-09-sdd-task-scoped-review-dispatch-design.md` — read it before starting. Decisions already settled there: full re-reviews stay; the two review stages stay separate; coordinator keeps model judgment; `requesting-code-review/` stays broad.
12
+
13
+ **These are behavior-shaping prose files, not code.** There are no unit tests for them. Each task's verification steps are exact `grep` checks that the edit landed; behavioral verification is Task 6 (static) and Task 7 (live evals, maintainer-gated).
14
+
15
+ ---
16
+
17
+ ### Task 1: Rewrite the per-task quality reviewer prompt as self-contained
18
+
19
+ The current file delegates to `../requesting-code-review/code-reviewer.md`, which is a merge-readiness review (architecture, security, production readiness, "Ready to merge?"). Replace the entire file with a self-contained, task-scoped template.
20
+
21
+ **Files:**
22
+ - Rewrite: `skills/subagent-driven-development/code-quality-reviewer-prompt.md`
23
+
24
+ - [ ] **Step 1: Replace the full file contents with:**
25
+
26
+ ````markdown
27
+ # Code Quality Reviewer Prompt Template
28
+
29
+ Use this template when dispatching a code quality reviewer subagent.
30
+
31
+ **Purpose:** Verify one task's implementation is well-built (clean, tested, maintainable)
32
+
33
+ **Only dispatch after spec compliance review passes.**
34
+
35
+ ```
36
+ Subagent (general-purpose):
37
+ description: "Review code quality for Task N"
38
+ prompt: |
39
+ You are reviewing one task's implementation for code quality. This is a
40
+ task-scoped gate, not a merge review — a broad whole-branch review happens
41
+ separately after all tasks are complete.
42
+
43
+ ## What Was Implemented
44
+
45
+ [DESCRIPTION]
46
+
47
+ ## Task Requirements (context only)
48
+
49
+ [TASK_TEXT]
50
+
51
+ ## Git Range to Review
52
+
53
+ **Base:** [BASE_SHA]
54
+ **Head:** [HEAD_SHA]
55
+
56
+ ```bash
57
+ git diff --stat [BASE_SHA]..[HEAD_SHA]
58
+ git diff [BASE_SHA]..[HEAD_SHA]
59
+ ```
60
+
61
+ ## Read-Only Review
62
+
63
+ Your review is read-only on this checkout. Do not mutate the working tree,
64
+ the index, HEAD, or branch state in any way. Use tools like `git show`,
65
+ `git diff`, and `git log` to inspect history.
66
+
67
+ ## Scope
68
+
69
+ Spec compliance was already verified by a separate reviewer. Do not
70
+ re-check whether the code matches the requirements or the plan.
71
+
72
+ Start from the diff. Read the changed files first. Inspect code outside
73
+ the diff only to evaluate a concrete risk you can name — and name it in
74
+ your report. Cross-cutting changes are legitimate named risks: if the
75
+ diff changes lock ordering, a function or API contract, or shared mutable
76
+ state, checking the call sites is the right method. Do not crawl the
77
+ codebase by default.
78
+
79
+ ## Tests
80
+
81
+ The implementer already ran the tests and reported results with TDD
82
+ evidence for exactly this code. Do not re-run the suite to confirm their
83
+ report. Run a test only when reading the code raises a specific doubt
84
+ that no existing run answers — and then a focused test, never a
85
+ package-wide suite, race detector run, or repeated/high-count loop. If
86
+ heavy validation seems warranted, recommend it in your report instead of
87
+ running it. If you cannot run commands in this environment, name the
88
+ test you would run.
89
+
90
+ ## What to Check
91
+
92
+ **Code quality:**
93
+ - Clean separation of concerns?
94
+ - Proper error handling?
95
+ - DRY without premature abstraction?
96
+ - Edge cases handled?
97
+
98
+ **Tests:**
99
+ - Do the new and changed tests verify real behavior, not mocks?
100
+ - Are the task's edge cases covered?
101
+
102
+ **Structure:**
103
+ - Does each file have one clear responsibility with a well-defined interface?
104
+ - Are units decomposed so they can be understood and tested independently?
105
+ - Is the implementation following the file structure from the plan?
106
+ - Did this change create new files that are already large, or
107
+ significantly grow existing files? (Don't flag pre-existing file
108
+ sizes — focus on what this change contributed.)
109
+
110
+ ## Calibration
111
+
112
+ Categorize issues by actual severity. Not everything is Critical.
113
+ Acknowledge what was done well before listing issues — accurate praise
114
+ helps the implementer trust the rest of the feedback.
115
+
116
+ ## Output Format
117
+
118
+ ### Strengths
119
+ [What's well done? Be specific.]
120
+
121
+ ### Issues
122
+
123
+ #### Critical (Must Fix)
124
+ [Bugs, data loss risks, broken functionality]
125
+
126
+ #### Important (Should Fix)
127
+ [Poor error handling, test gaps, structural problems]
128
+
129
+ #### Minor (Nice to Have)
130
+ [Code style, optimization opportunities]
131
+
132
+ For each issue:
133
+ - File:line reference
134
+ - What's wrong
135
+ - Why it matters
136
+ - How to fix (if not obvious)
137
+
138
+ ### Assessment
139
+
140
+ **Task quality:** [Approved | Needs fixes]
141
+
142
+ **Reasoning:** [1-2 sentence technical assessment]
143
+ ```
144
+
145
+ **Placeholders:**
146
+ - `[DESCRIPTION]` — task summary, from implementer's report
147
+ - `[TASK_TEXT]` — the task's requirements text or plan reference, for context
148
+ - `[BASE_SHA]` — commit before this task
149
+ - `[HEAD_SHA]` — current commit
150
+
151
+ **Reviewer returns:** Strengths, Issues (Critical/Important/Minor), Task quality verdict
152
+ ````
153
+
154
+ - [ ] **Step 2: Verify the rewrite landed**
155
+
156
+ Run: `grep -c "requesting-code-review" skills/subagent-driven-development/code-quality-reviewer-prompt.md || echo ABSENT`
157
+ Expected: `ABSENT` (no more delegation)
158
+
159
+ Run: `grep -n "Task quality:" skills/subagent-driven-development/code-quality-reviewer-prompt.md | head -2`
160
+ Expected: one match (the Output Format verdict line; the "Reviewer returns" footer says "Task quality verdict" without a colon)
161
+
162
+ Run: `grep -n "worktree add\|Ready to merge" skills/subagent-driven-development/code-quality-reviewer-prompt.md || echo CLEAN`
163
+ Expected: `CLEAN`
164
+
165
+ - [ ] **Step 3: Commit**
166
+
167
+ ```bash
168
+ git add skills/subagent-driven-development/code-quality-reviewer-prompt.md
169
+ git commit -m "Make per-task quality reviewer prompt self-contained and task-scoped"
170
+ ```
171
+
172
+ ---
173
+
174
+ ### Task 2: Spec reviewer prompt cleanups
175
+
176
+ Four exact edits to `skills/subagent-driven-development/spec-reviewer-prompt.md`. Current line numbers refer to the file as of commit f55642e.
177
+
178
+ **Files:**
179
+ - Modify: `skills/subagent-driven-development/spec-reviewer-prompt.md`
180
+
181
+ - [ ] **Step 1: Add the judge-from-the-diff clause.** After the line (currently line 31):
182
+
183
+ ```
184
+ Only read files in this diff. Do not crawl the broader codebase.
185
+ ```
186
+
187
+ insert a blank line and:
188
+
189
+ ```
190
+ Spec compliance is judged by reading the diff against the requirements.
191
+ The implementer already ran the tests and reported TDD evidence — do not
192
+ re-run them. If a requirement cannot be verified from this diff alone
193
+ (it lives in unchanged code or spans tasks), report it as a ⚠️ item
194
+ instead of broadening your search.
195
+ ```
196
+
197
+ - [ ] **Step 2: Trim the read-only section.** Replace (currently line 35):
198
+
199
+ ```
200
+ Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. Use tools like `git show`, `git diff`, and `git log` to inspect history. If you need a working copy of a different revision, check it out into a separate temporary directory (e.g. `git worktree add /tmp/review-[SHA] [SHA]`) — never move HEAD on this checkout.
201
+ ```
202
+
203
+ with:
204
+
205
+ ```
206
+ Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. Use tools like `git show`, `git diff`, and `git log` to inspect history.
207
+ ```
208
+
209
+ - [ ] **Step 3: Ground the skepticism.** Replace (currently lines 39-40):
210
+
211
+ ```
212
+ The implementer finished suspiciously quickly. Their report may be incomplete,
213
+ inaccurate, or optimistic. You MUST verify everything independently.
214
+ ```
215
+
216
+ with:
217
+
218
+ ```
219
+ Treat the implementer's report as unverified claims about the code. It may
220
+ be incomplete, inaccurate, or optimistic. Verify the claims against the diff.
221
+ ```
222
+
223
+ - [ ] **Step 4: Add the third verdict channel.** Replace (currently lines 74-76):
224
+
225
+ ```
226
+ Report:
227
+ - ✅ Spec compliant (if everything matches after code inspection)
228
+ - ❌ Issues found: [list specifically what's missing or extra, with file:line references]
229
+ ```
230
+
231
+ with:
232
+
233
+ ```
234
+ Report:
235
+ - ✅ Spec compliant (if everything matches after code inspection)
236
+ - ❌ Issues found: [list specifically what's missing or extra, with file:line references]
237
+ - ⚠️ Cannot verify from diff: [requirements you could not verify from the
238
+ diff alone, and what the controller should check — report alongside the
239
+ ✅/❌ verdict for everything you could verify]
240
+ ```
241
+
242
+ - [ ] **Step 5: Verify**
243
+
244
+ Run: `grep -n "suspiciously\|worktree add" skills/subagent-driven-development/spec-reviewer-prompt.md || echo CLEAN`
245
+ Expected: `CLEAN`
246
+
247
+ Run: `grep -c "⚠️" skills/subagent-driven-development/spec-reviewer-prompt.md`
248
+ Expected: `2` (judge-from-diff clause + verdict channel)
249
+
250
+ - [ ] **Step 6: Commit**
251
+
252
+ ```bash
253
+ git add skills/subagent-driven-development/spec-reviewer-prompt.md
254
+ git commit -m "Spec reviewer: judge from the diff, grounded skepticism, ⚠️ verdict channel"
255
+ ```
256
+
257
+ ---
258
+
259
+ ### Task 3: Implementer prompt — re-run tests after fixing review findings
260
+
261
+ The reviewers' "don't re-run the implementer's tests" rule assumes the implementer re-runs tests after every fix. Make that real.
262
+
263
+ **Files:**
264
+ - Modify: `skills/subagent-driven-development/implementer-prompt.md`
265
+
266
+ - [ ] **Step 1: Insert a new section.** Immediately before the line (currently line 100):
267
+
268
+ ```
269
+ ## Report Format
270
+ ```
271
+
272
+ insert:
273
+
274
+ ```
275
+ ## After Review Findings
276
+
277
+ If a reviewer finds issues and you fix them, re-run the tests that cover
278
+ the amended code and include the results in your fix report. Reviewers
279
+ will not re-run tests for you — your report is the test evidence.
280
+
281
+ ```
282
+
283
+ - [ ] **Step 2: Verify**
284
+
285
+ Run: `grep -n "After Review Findings" skills/subagent-driven-development/implementer-prompt.md`
286
+ Expected: one match, on a line before `## Report Format`
287
+
288
+ - [ ] **Step 3: Commit**
289
+
290
+ ```bash
291
+ git add skills/subagent-driven-development/implementer-prompt.md
292
+ git commit -m "Implementer prompt: re-run covering tests after fixing review findings"
293
+ ```
294
+
295
+ ---
296
+
297
+ ### Task 4: SKILL.md controller changes
298
+
299
+ Six exact edits to `skills/subagent-driven-development/SKILL.md`. Current line numbers refer to commit f55642e.
300
+
301
+ **Files:**
302
+ - Modify: `skills/subagent-driven-development/SKILL.md`
303
+
304
+ - [ ] **Step 1: Point the final-review flowchart node at the broad template.** The node label `Dispatch final code reviewer subagent for entire implementation` appears 3 times (currently lines 65, 84, 85). In all 3 occurrences, replace the label string with:
305
+
306
+ ```
307
+ Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)
308
+ ```
309
+
310
+ (Graphviz nodes are matched by label text — all three must be byte-identical or the graph grows a phantom node.)
311
+
312
+ - [ ] **Step 2: Model selection by judgment.** Replace (currently lines 97-99):
313
+
314
+ ```
315
+ **Architecture, design, and review tasks**: use the most capable available model.
316
+
317
+ **Task complexity signals:**
318
+ ```
319
+
320
+ with:
321
+
322
+ ```
323
+ **Architecture and design tasks**: use the most capable available model.
324
+
325
+ **Review tasks**: choose the model with the same judgment, scaled to the
326
+ diff's size, complexity, and risk. A small mechanical diff does not need the
327
+ most capable model; a subtle concurrency change does.
328
+
329
+ **Task complexity signals (implementation tasks):**
330
+ ```
331
+
332
+ - [ ] **Step 3: Add controller guidance sections.** Immediately before the line (currently line 122):
333
+
334
+ ```
335
+ ## Prompt Templates
336
+ ```
337
+
338
+ insert:
339
+
340
+ ```
341
+ ## Handling Spec Reviewer ⚠️ Items
342
+
343
+ The spec reviewer may report "⚠️ Cannot verify from diff" items — requirements
344
+ that live in unchanged code or span tasks. These do not block dispatching the
345
+ code quality reviewer, but you must resolve each one yourself before marking
346
+ the task complete: you hold the plan and cross-task context the reviewer
347
+ lacks. If you confirm an item is a real gap, treat it as a failed spec
348
+ review — send it back to the implementer and re-review.
349
+
350
+ ## Constructing Reviewer Prompts
351
+
352
+ Per-task reviews are task-scoped gates. The broad review happens once, at the
353
+ final whole-branch review. When you fill a reviewer template:
354
+
355
+ - Do not add open-ended directives like "check all uses" or "run race tests
356
+ if useful" without a concrete, task-specific reason
357
+ - Do not ask a reviewer to re-run tests the implementer already ran on the
358
+ same code — the implementer's report carries the test evidence
359
+
360
+ ```
361
+
362
+ - [ ] **Step 4: Prompt Templates list — add the final-review pointer.** Replace (currently line 126):
363
+
364
+ ```
365
+ - [code-quality-reviewer-prompt.md](code-quality-reviewer-prompt.md) - Dispatch code quality reviewer subagent
366
+ ```
367
+
368
+ with:
369
+
370
+ ```
371
+ - [code-quality-reviewer-prompt.md](code-quality-reviewer-prompt.md) - Dispatch code quality reviewer subagent
372
+ - Final whole-branch review: use superpowers:requesting-code-review's [code-reviewer.md](../requesting-code-review/code-reviewer.md)
373
+ ```
374
+
375
+ - [ ] **Step 5: Example workflow verdict vocabulary.** Two replacements:
376
+
377
+ Replace (currently line 157):
378
+ ```
379
+ Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.
380
+ ```
381
+ with:
382
+ ```
383
+ Code reviewer: Strengths: Good test coverage, clean. Issues: None. Task quality: Approved.
384
+ ```
385
+
386
+ Replace (currently line 191):
387
+ ```
388
+ Code reviewer: ✅ Approved
389
+ ```
390
+ with:
391
+ ```
392
+ Code reviewer: ✅ Task quality: Approved
393
+ ```
394
+
395
+ (The final reviewer's "ready to merge" line, currently line 199, stays.)
396
+
397
+ - [ ] **Step 6: Integration section.** Replace (currently line 272):
398
+
399
+ ```
400
+ - **superpowers:requesting-code-review** - Code review template for reviewer subagents
401
+ ```
402
+
403
+ with:
404
+
405
+ ```
406
+ - **superpowers:requesting-code-review** - Code review template for the final whole-branch review
407
+ ```
408
+
409
+ - [ ] **Step 7: Verify**
410
+
411
+ Run: `grep -c "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" skills/subagent-driven-development/SKILL.md`
412
+ Expected: `3`
413
+
414
+ Run: `grep -n "most capable available model" skills/subagent-driven-development/SKILL.md`
415
+ Expected: exactly one match (architecture/design bullet)
416
+
417
+ Run: `grep -n "Handling Spec Reviewer\|Constructing Reviewer Prompts" skills/subagent-driven-development/SKILL.md`
418
+ Expected: two section headers, both before `## Prompt Templates`
419
+
420
+ Run: `grep -c "Task quality: Approved" skills/subagent-driven-development/SKILL.md`
421
+ Expected: `2`
422
+
423
+ - [ ] **Step 8: Commit**
424
+
425
+ ```bash
426
+ git add skills/subagent-driven-development/SKILL.md
427
+ git commit -m "SDD controller: reviewer prompt budgets, ⚠️ handling, final-review pointer, model judgment"
428
+ ```
429
+
430
+ ---
431
+
432
+ ### Task 5: New eval scenario — per-task quality reviewer catches a planted defect
433
+
434
+ Lives in the `evals/` **submodule** (separate repo, `superpowers-evals`). Work on a branch there; the parent submodule-pointer bump happens at finishing time per `evals/CLAUDE.md`.
435
+
436
+ The fixture plan's Task 2 implementation snippet duplicates Task 1's formatting logic verbatim. The duplication is spec-compliant, so the spec reviewer should pass it — the per-task quality reviewer is the gate under test (DRY violation).
437
+
438
+ **Files:**
439
+ - Create: `evals/setup_helpers/sdd_quality_defect_plan.py`
440
+ - Modify: `evals/setup_helpers/__init__.py`
441
+ - Create: `evals/scenarios/sdd-quality-reviewer-catches-planted-defect/story.md`
442
+ - Create: `evals/scenarios/sdd-quality-reviewer-catches-planted-defect/setup.sh`
443
+ - Create: `evals/scenarios/sdd-quality-reviewer-catches-planted-defect/checks.sh`
444
+
445
+ - [ ] **Step 0: Branch in the submodule**
446
+
447
+ ```bash
448
+ cd evals
449
+ git checkout -b sdd-quality-defect-scenario
450
+ ```
451
+
452
+ - [ ] **Step 1: Create `evals/setup_helpers/sdd_quality_defect_plan.py`:**
453
+
454
+ ````python
455
+ """Setup helper for the sdd-quality-reviewer-catches-planted-defect scenario.
456
+
457
+ Scaffolds a tiny Node project with a 2-task plan whose Task 2
458
+ implementation snippet duplicates Task 1's formatting logic verbatim.
459
+ The duplication is spec-compliant — the requirements only describe
460
+ behavior — so the spec compliance reviewer should pass it. The test
461
+ measures whether the per-task code quality reviewer catches the DRY
462
+ violation and forces a refactor in the review-fix loop.
463
+ """
464
+
465
+ from __future__ import annotations
466
+
467
+ from pathlib import Path
468
+
469
+ from setup_helpers.base import _git
470
+
471
+ PACKAGE_JSON = """\
472
+ {
473
+ "name": "report-quality",
474
+ "version": "1.0.0",
475
+ "type": "module",
476
+ "scripts": {
477
+ "test": "node --test"
478
+ }
479
+ }
480
+ """
481
+
482
+ PLAN_BODY = """\
483
+ # Report Formatter — Implementation Plan
484
+
485
+ Two report formatting functions. Implement exactly what each task
486
+ specifies.
487
+
488
+ ## Task 1: User Report
489
+
490
+ **File:** `src/report.js`
491
+
492
+ **Requirements:**
493
+ - Function named `formatUserReport`
494
+ - Takes one parameter `user`: an object with `name`, `email`, `visits`
495
+ - Returns a multi-line string: a banner of 40 `=` characters, then
496
+ `Report for <name> <<email>>`, then the banner again, then
497
+ `Visits: <visits>`, then a closing banner
498
+ - Export the function
499
+
500
+ **Implementation:**
501
+ ```javascript
502
+ export function formatUserReport(user) {
503
+ const banner = "=".repeat(40);
504
+ const lines = [];
505
+ lines.push(banner);
506
+ lines.push(`Report for ${user.name} <${user.email}>`);
507
+ lines.push(banner);
508
+ lines.push(`Visits: ${user.visits}`);
509
+ lines.push(banner);
510
+ return lines.join("\\n");
511
+ }
512
+ ```
513
+
514
+ **Tests:** Create `test/report.test.js` verifying:
515
+ - the result contains `Report for Ada <ada@example.com>` for that user
516
+ - the result contains `Visits: 3` when `visits` is `3`
517
+ - the result starts and ends with the 40-char banner
518
+
519
+ **Verification:** `npm test`
520
+
521
+ ## Task 2: Admin Report
522
+
523
+ **File:** `src/report.js` (add to existing file)
524
+
525
+ **Requirements:**
526
+ - Function named `formatAdminReport`
527
+ - Takes one parameter `admin`: an object with `name`, `email`, `lastLogin`
528
+ - Same banner layout as the user report; the body line is
529
+ `Last login: <lastLogin>` instead of the visits line
530
+ - Export the function; keep `formatUserReport` working
531
+
532
+ **Implementation:**
533
+ ```javascript
534
+ export function formatAdminReport(admin) {
535
+ const banner = "=".repeat(40);
536
+ const lines = [];
537
+ lines.push(banner);
538
+ lines.push(`Report for ${admin.name} <${admin.email}>`);
539
+ lines.push(banner);
540
+ lines.push(`Last login: ${admin.lastLogin}`);
541
+ lines.push(banner);
542
+ return lines.join("\\n");
543
+ }
544
+ ```
545
+
546
+ **Tests:** Add to `test/report.test.js`:
547
+ - the result contains `Report for Grace <grace@example.com>` for that admin
548
+ - the result contains `Last login: 2026-06-01`
549
+ - the result starts and ends with the 40-char banner
550
+
551
+ **Verification:** `npm test`
552
+ """
553
+
554
+
555
+ def scaffold_sdd_quality_defect_plan(workdir: Path) -> None:
556
+ workdir = Path(workdir)
557
+ workdir.mkdir(parents=True, exist_ok=True)
558
+ _git(["git", "init", "-b", "main"], cwd=workdir)
559
+ _git(["git", "config", "user.email", "drill@test.local"], cwd=workdir)
560
+ _git(["git", "config", "user.name", "Drill Test"], cwd=workdir)
561
+
562
+ (workdir / "package.json").write_text(PACKAGE_JSON)
563
+ plans_dir = workdir / "docs" / "superpowers" / "plans"
564
+ plans_dir.mkdir(parents=True, exist_ok=True)
565
+ (plans_dir / "report-plan.md").write_text(PLAN_BODY)
566
+
567
+ _git(["git", "add", "-A"], cwd=workdir)
568
+ _git(["git", "commit", "-m", "initial: report formatter plan"], cwd=workdir)
569
+ ````
570
+
571
+ (Note the `\\n` in the JS snippets inside PLAN_BODY: the Python source must
572
+ produce a literal `\n` in the markdown so the JS reads `lines.join("\n")`.)
573
+
574
+ - [ ] **Step 2: Register the helper.** In `evals/setup_helpers/__init__.py`:
575
+
576
+ After the line:
577
+ ```python
578
+ from setup_helpers.sdd_real_projects import scaffold_sdd_go_fractals, scaffold_sdd_svelte_todo
579
+ ```
580
+ add:
581
+ ```python
582
+ from setup_helpers.sdd_quality_defect_plan import scaffold_sdd_quality_defect_plan
583
+ ```
584
+
585
+ After the registry entry:
586
+ ```python
587
+ "scaffold_sdd_yagni_plan": scaffold_sdd_yagni_plan,
588
+ ```
589
+ add:
590
+ ```python
591
+ "scaffold_sdd_quality_defect_plan": scaffold_sdd_quality_defect_plan,
592
+ ```
593
+
594
+ - [ ] **Step 3: Create `evals/scenarios/sdd-quality-reviewer-catches-planted-defect/story.md`:**
595
+
596
+ ```markdown
597
+ ---
598
+ id: sdd-quality-reviewer-catches-planted-defect
599
+ title: SDD's per-task code quality review catches a planted DRY violation
600
+ status: ready
601
+ tags: subagent-driven-development
602
+ quorum_max_time: 90m
603
+ ---
604
+
605
+ You have a small plan at docs/superpowers/plans/report-plan.md — two report
606
+ formatting functions. The plan's Task 2 implementation snippet duplicates
607
+ Task 1's formatting logic verbatim instead of sharing it. The duplication is
608
+ spec-compliant (the requirements only describe behavior), so the spec
609
+ compliance reviewer should pass it — the per-task code quality reviewer is
610
+ the gate under test. You are spec-aware — name the skill.
611
+
612
+ When the agent is ready for input, tell it to execute the plan with SDD. Use
613
+ phrasing like:
614
+
615
+ "I have a small plan at docs/superpowers/plans/report-plan.md — two report
616
+ formatting functions. Use the superpowers:subagent-driven-development skill
617
+ to execute it end-to-end — dispatch fresh subagents per task and run the
618
+ two-stage review after each."
619
+
620
+ Let the agent proceed autonomously. If it asks clarifying questions, give
621
+ brief answers. If it asks where the finished work should land — merge to the
622
+ main branch, open a PR, etc. — tell it to **merge the work into the main
623
+ checkout** (this is a local repo with no remote). If a quality reviewer
624
+ flags the duplicated formatting logic and an implementer refactors it, let
625
+ the review-fix cycle play out — that cycle is exactly the behavior under
626
+ test.
627
+
628
+ The deliverable must end up in the checkout you launched in (the main
629
+ working tree). If the agent did its work on a branch or in a worktree, it
630
+ is not done until it has merged/finished that work back into the main
631
+ checkout. Once the agent reports the plan is complete (both functions
632
+ implemented, tests passing) AND the code is present on the main checkout,
633
+ you are done.
634
+
635
+ ## Acceptance Criteria
636
+
637
+ - A `Skill` invocation naming `superpowers:subagent-driven-development`
638
+ and at least one `Agent` (subagent dispatch) tool call appear in the
639
+ session log.
640
+ - The duplicated report-formatting logic did not survive to the end of
641
+ the run. Either (a) the implementer never introduced the duplication
642
+ (wrote or self-reviewed its way to shared logic), or (b) the per-task
643
+ code quality reviewer flagged the duplication as an issue and a
644
+ review-fix loop removed it. A fail looks like the duplicated logic
645
+ shipping with the per-task quality reviewer approving it, or the
646
+ duplication being caught only by the final whole-branch review.
647
+ - The per-task quality reviewers stayed task-scoped: no package-wide
648
+ test suites, race detector runs, or repeated/high-count test loops
649
+ appear in reviewer subagent activity, and reviewers did not re-run
650
+ the full test suite merely to confirm the implementer's report.
651
+ - `npm test` passes in the main checkout and both `formatUserReport` and
652
+ `formatAdminReport` are exported from src/report.js. The deterministic
653
+ assertions gate this; the criteria above are about whether the
654
+ *per-task quality review* was the mechanism that kept the code clean.
655
+ ```
656
+
657
+ - [ ] **Step 4: Create `evals/scenarios/sdd-quality-reviewer-catches-planted-defect/setup.sh`:**
658
+
659
+ ```bash
660
+ #!/usr/bin/env bash
661
+ set -euo pipefail
662
+ uv run setup-helpers run scaffold_sdd_quality_defect_plan
663
+ ```
664
+
665
+ Then: `chmod +x evals/scenarios/sdd-quality-reviewer-catches-planted-defect/setup.sh`
666
+
667
+ - [ ] **Step 5: Create `evals/scenarios/sdd-quality-reviewer-catches-planted-defect/checks.sh`** (no executable bit):
668
+
669
+ ```bash
670
+ pre() {
671
+ git-repo
672
+ git-branch main
673
+ requires-tool npm
674
+ file-exists 'docs/superpowers/plans/report-plan.md'
675
+ file-contains 'docs/superpowers/plans/report-plan.md' 'formatAdminReport'
676
+ file-contains 'docs/superpowers/plans/report-plan.md' 'repeat\(40\)'
677
+ }
678
+
679
+ post() {
680
+ skill-called superpowers:subagent-driven-development
681
+ tool-called Agent
682
+ command-succeeds 'npm test'
683
+ file-contains 'src/report.js' 'export function formatUserReport'
684
+ file-contains 'src/report.js' 'export function formatAdminReport'
685
+ command-succeeds 'test "$(grep -c "repeat(40)" src/report.js)" -le 1'
686
+ }
687
+ ```
688
+
689
+ (The last check is the deterministic DRY gate: the banner construction
690
+ `"=".repeat(40)` must appear at most once in the final file — shared, not
691
+ duplicated per function.)
692
+
693
+ - [ ] **Step 6: Validate and test in the evals repo**
694
+
695
+ ```bash
696
+ cd evals
697
+ uv run quorum check
698
+ uv run ruff check
699
+ uv run pytest -x -q
700
+ ```
701
+
702
+ Expected: all pass; `quorum check` lists the new scenario without errors.
703
+
704
+ - [ ] **Step 7: Commit (in the submodule)**
705
+
706
+ ```bash
707
+ cd evals
708
+ git add setup_helpers/sdd_quality_defect_plan.py setup_helpers/__init__.py scenarios/sdd-quality-reviewer-catches-planted-defect/
709
+ git commit -m "Add sdd-quality-reviewer-catches-planted-defect scenario"
710
+ ```
711
+
712
+ ---
713
+
714
+ ### Task 6: Static verification sweep
715
+
716
+ **Files:** none modified — verification only.
717
+
718
+ - [ ] **Step 1: No dangling references in the parent repo**
719
+
720
+ Run: `grep -rn "requesting-code-review" skills/subagent-driven-development/`
721
+ Expected: matches only in SKILL.md (final-review flowchart node ×3, Prompt Templates pointer, Integration bullet). None in code-quality-reviewer-prompt.md.
722
+
723
+ Run: `grep -rn "Ready to merge" skills/subagent-driven-development/ || echo CLEAN`
724
+ Expected: `CLEAN`
725
+
726
+ - [ ] **Step 2: Plugin infrastructure tests**
727
+
728
+ Run: `bash tests/shell-lint/test-lint-shell.sh`
729
+ Expected: all PASS (we added `setup.sh` only inside the evals submodule, which has its own checks).
730
+
731
+ - [ ] **Step 3: Cross-platform tool tables still coherent**
732
+
733
+ Run: `grep -n "code-quality-reviewer" skills/using-superpowers/references/antigravity-tools.md skills/using-superpowers/references/gemini-tools.md`
734
+ Expected: both tables still list `code-quality-reviewer` as a reviewer template (the new prompt's "If you cannot run commands in this environment, name the test you would run" line keeps the read-only `research` mapping valid — no table edits needed).
735
+
736
+ ---
737
+
738
+ ### Task 7: Live before/after evals (maintainer-gated)
739
+
740
+ Live quorum runs launch agent CLIs in permissive modes — **trusted-maintainer operation; Jesse launches these**, per `evals/CLAUDE.md`. Requires `ANTHROPIC_API_KEY`.
741
+
742
+ - [ ] **Step 1: Baseline (skills as released on dev)** — from the main checkout (`/Users/jesse/git/superpowers/superpowers`, on dev), or any checkout without this branch's changes:
743
+
744
+ ```bash
745
+ cd evals
746
+ export SUPERPOWERS_ROOT=/Users/jesse/git/superpowers/superpowers
747
+ uv run quorum run scenarios/sdd-rejects-extra-features --coding-agent claude
748
+ uv run quorum run scenarios/sdd-go-fractals --coding-agent claude
749
+ uv run quorum run scenarios/sdd-svelte-todo --coding-agent claude
750
+ uv run quorum run scenarios/spec-reviewer-catches-planted-flaws --coding-agent claude
751
+ ```
752
+
753
+ - [ ] **Step 2: After (this branch's skills)** — point `SUPERPOWERS_ROOT` at this worktree:
754
+
755
+ ```bash
756
+ cd evals
757
+ export SUPERPOWERS_ROOT=/Users/jesse/git/superpowers/superpowers/.claude/worktrees/sdd-review-dispatch
758
+ uv run quorum run scenarios/sdd-rejects-extra-features --coding-agent claude
759
+ uv run quorum run scenarios/sdd-go-fractals --coding-agent claude
760
+ uv run quorum run scenarios/sdd-svelte-todo --coding-agent claude
761
+ uv run quorum run scenarios/spec-reviewer-catches-planted-flaws --coding-agent claude
762
+ uv run quorum run scenarios/sdd-quality-reviewer-catches-planted-defect --coding-agent claude
763
+ uv run quorum show
764
+ ```
765
+
766
+ - [ ] **Step 3: Compare**
767
+
768
+ Pass bar: all four pre-existing scenarios still pass after the change (no regression in catch rate); the new planted-defect scenario passes. For exploration cost, compare reviewer-subagent tool-call counts between the before/after run transcripts (no automated check exists — the spec calls this out as a known gap).
769
+
770
+ ---
771
+
772
+ ## Finishing
773
+
774
+ After all tasks pass: the evals submodule commit needs to land in `superpowers-evals` (PR to its `main`), then this branch bumps the `evals` submodule pointer — per `evals/CLAUDE.md`, the parent bump is part of propagation, not optional. Then use superpowers:finishing-a-development-branch. PRs against superpowers target `dev`.
github_code/obra__superpowers/docs/superpowers/plans/2026-06-09-visual-companion-issues.md ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Brainstorming Companion — Issue & Change Catalog
2
+
3
+ **Date:** 2026-06-09
4
+ **Status:** Analysis / triage. We are implementing these ourselves; the referenced
5
+ community PRs are evidence and reference material, **not** code we intend to merge.
6
+
7
+ ## Purpose
8
+
9
+ A single place that captures every open issue and PR touching the visual
10
+ brainstorming companion (the local server in `skills/brainstorming/scripts/`),
11
+ distilled to the underlying problem and the change we'd make. Each item is
12
+ grounded against the current code, not the PR author's description.
13
+
14
+ ## Scope decisions (Jesse, 2026-06-09)
15
+
16
+ - **Not vendoring Alpine.js.** PR #1639 (interactive mockups via a vendored
17
+ Alpine build) is **dropped**. See E3.
18
+ - **E1 (terminal-vs-HTML hard gate) is a workshop item.** We'll design it
19
+ together; it is not specced here.
20
+ - **E2 (storage location, #975/#977) is deferred** for now.
21
+ - **Remote serving is a first-class scenario.** Superpowers is general-purpose;
22
+ users connect from remote (SSH tunnel, Tailscale, `--host 0.0.0.0`). The
23
+ security fix MUST protect those users, not just loopback. **Decision: a
24
+ per-session secret key**, not a Host allowlist. A Host allowlist only
25
+ defends the loopback browser-confused-deputy; a direct remote client just
26
+ sends the expected `Host`, so the allowlist is theater for remote exposure. A
27
+ secret key is the only thing that authenticates a client uniformly across
28
+ loopback, tunnel, and direct-remote, and it also defeats DNS rebinding. See A1.
29
+
30
+ ## Component map
31
+
32
+ | File | Role |
33
+ |------|------|
34
+ | `skills/brainstorming/scripts/server.cjs` | Zero-dep HTTP + WebSocket server (RFC 6455 hand-rolled). Serves the newest screen, watches `content/`, records events to `state/events`. |
35
+ | `skills/brainstorming/scripts/helper.js` | Injected into every page. WebSocket client, click capture, `window.brainstorm` API. |
36
+ | `skills/brainstorming/scripts/frame-template.html` | Frame (header, theme CSS, status dot, indicator bar) wrapped around content fragments. |
37
+ | `skills/brainstorming/scripts/start-server.sh` | Launch wrapper. Session dir, host/url-host, owner-PID resolution, platform backgrounding. |
38
+ | `skills/brainstorming/scripts/stop-server.sh` | Kills the server by PID file, cleans `/tmp` sessions. |
39
+ | `skills/brainstorming/visual-companion.md` | Operator guide the agent reads when it accepts the companion. |
40
+ | `skills/brainstorming/SKILL.md` | Where the companion is offered and the per-question decision lives. |
41
+
42
+ ## Disposition summary
43
+
44
+ | ID | Item | Source | Disposition |
45
+ |----|------|--------|-------------|
46
+ | A1 | Per-session secret key on `/`, `/files/*`, and WS (supersedes Host allowlist) | issues #1014, PRs #1110/#1553 | **Do** — chosen approach |
47
+ | A2 | Host allowlist; browser WS Origin check | PRs #1110/#1553 | Host allowlist dropped; WS Origin check retained after auth for browser confused-deputy defense |
48
+ | A3 | Crash on `null` / non-object WS payload | PR #1504 | Do |
49
+ | A4 | Frame-length bound in `decodeFrame` | issue #1446 | Already fixed — verify/close |
50
+ | B1 | Dotfile screens served as content (`._*.html`) | PR #950 | Do |
51
+ | B2 | `stop-server.sh` kills reused/stale PID | PR #1703 | Do |
52
+ | B3 | WS client reconnect backoff + status indicator | PR #856 | Do |
53
+ | C1 | Idle timeout too short / not configurable; WS not closed on shutdown | issue #1237 (PR #1689) | Do |
54
+ | C2 | Server death is invisible to user/agent | issue #1237 (residual) | Do |
55
+ | D1 | Permanent opt-out of the companion | issue #892 | Deferred - not in PR #1720 |
56
+ | D2 | Free-text feedback from the browser | issue #957 | Deferred - not in PR #1720 |
57
+ | D3 | Auto-open the companion URL | PR #759 (#755) | Done in PR #1720 via `--open` |
58
+ | D4 | Light/dark contrast helpers in the frame | PR #1683 | Deferred - not in PR #1720 |
59
+ | E1 | Hard-gate terminal-vs-HTML per question | PR #1037 | **Workshop** |
60
+ | E2 | Move session state out of the working tree | issue #975 (PR #977) | **Deferred** |
61
+ | E3 | Vendor Alpine.js for interactive mockups | PR #1639 | **Dropped** |
62
+ | E4 | Shell-lint warnings in start/stop scripts | PR #1677 | Opportunistic only |
63
+
64
+ ---
65
+
66
+ ## A. Server security hardening (`server.cjs`)
67
+
68
+ ### A1 — Per-session secret key (chosen approach)
69
+
70
+ **Threat model.** Two assets: confidentiality of the served screen (`/`) and
71
+ files (`/files/*`), and integrity of `state/events` — a WebSocket client with a
72
+ truthy `choice` writes there (`server.cjs:243-246`), and the agent reads it next
73
+ turn as the user's selection, i.e. **prompt injection into a live session with
74
+ full tool access**. Reachers: with the default `127.0.0.1` bind, a malicious
75
+ page in the user's browser (a confused deputy — runs attacker JS *and* can reach
76
+ loopback); with a remote bind (`--host 0.0.0.0`, tailnet/LAN), any host that can
77
+ route to the port, directly, with no same-origin policy in the way. Today
78
+ `handleUpgrade` (`server.cjs:176`) checks only `Sec-WebSocket-Key`, and
79
+ `handleRequest` (`server.cjs:138`) checks nothing — both are wide open.
80
+
81
+ **Why a key, not a Host allowlist.** A Host allowlist only defends the
82
+ loopback browser-deputy. A direct remote client just sends the expected `Host`
83
+ and forges/omits `Origin`, so the allowlist is theater for exactly the remote
84
+ case we must protect. A per-session secret authenticates the client uniformly
85
+ across loopback, SSH tunnel, and direct-remote, and it also kills DNS rebinding
86
+ (the rebound page neither knows the key nor receives the host-scoped cookie).
87
+ So the key **supersedes** A1/A2's Host allowlist entirely — no `BRAINSTORM_ALLOWED_HOSTS`.
88
+
89
+ **Design.** Random token (`crypto.randomBytes(32)` hex), generated in
90
+ `server.cjs` at startup (overridable via `BRAINSTORM_TOKEN` for deterministic
91
+ tests):
92
+
93
+ 1. **URL carries it** as `?key=<token>`. The server already builds `url` in its
94
+ `server-started` JSON (`server.cjs:351`) and writes it to `state/server-info`
95
+ — appending `?key=` there means `start-server.sh` (greps and prints that
96
+ JSON) and the skill (hands the user that URL) need **no change**.
97
+ 2. **Cookie bootstrap.** A valid `?key` on `/` sets
98
+ `brainstorm-key-<port>=<token>; HttpOnly; SameSite=Strict; Path=/`. The
99
+ browser then auto-attaches it to same-origin subresources (`/files/*`) and
100
+ the WebSocket handshake, so the agent can write any URL style and it works,
101
+ and `helper.js` needs no change. Cookie name is **per-port** to avoid the
102
+ Jupyter multi-server collision (cookies aren't port-scoped).
103
+ `SameSite=Strict` is safe for CDN/Unsplash content — that cookie is host-
104
+ scoped, so outbound CDN requests never carry it; SameSite only governs
105
+ requests back to our origin, which are all same-site.
106
+ 3. **Auth gate** = valid `?key` **OR** valid cookie (compared with
107
+ `crypto.timingSafeEqual`) on `/`, `/files/*`, and the WS upgrade. Missing/bad
108
+ key → friendly **403 HTML page** ("this page needs the full URL your coding
109
+ agent gave you, including `?key=…`" — generic "coding agent", not "Claude",
110
+ since this ships on Codex/Gemini/Copilot too). WS upgrade → destroy socket.
111
+
112
+ The query token is the source of truth; the cookie is a convenience that never
113
+ bears initial-auth load.
114
+
115
+ **Blast radius.** `server.cjs` (all logic). `helper.js` optional one-liner
116
+ (append `?key=` from `location.search` to the WS URL as a cookie-blocked
117
+ fallback). `start-server.sh` none. `visual-companion.md` doc note (URL now has
118
+ `?key=`; don't strip it). Tests updated to pass the token.
119
+
120
+ ### A2 — Host allowlist dropped; browser WS Origin retained
121
+
122
+ Subsumed by A1. The secret key closes the WS-injection vector (#1014), the
123
+ HTTP/WS DNS-rebinding read vector (PR #1553), and the cross-origin WS vector
124
+ (PR #1110) in one mechanism, and unlike an allowlist it actually protects the
125
+ remote-bind case. No `BRAINSTORM_ALLOWED_HOSTS` and no Host allowlist. The final
126
+ implementation still checks browser WebSocket `Origin` after session auth so a
127
+ cross-origin localhost tab cannot ride the companion cookie.
128
+
129
+ ### A3 — Server crashes on `null` / primitive WS payload
130
+
131
+ **Problem.** `handleMessage` (`server.cjs:233`) does `JSON.parse(text)` then
132
+ `if (event.choice)` at `server.cjs:243`. A client that sends the 4-byte text
133
+ frame `null` yields `event === null`, and `null.choice` throws. The throw is
134
+ **not** caught — `handleMessage` is called from the `socket.on('data')` handler
135
+ (`server.cjs:207`) outside the `try/catch`, which only wraps `decodeFrame`. The
136
+ result is an uncaught exception and process exit. Any local client can kill the
137
+ server.
138
+
139
+ **Change.** Guard the access: `if (event && event.choice)`. Minimal and exact —
140
+ `JSON.parse` can't produce `undefined`, and primitives return `undefined` for
141
+ `.choice` without throwing, so only `null` is the live hazard. (Avoid the
142
+ broader fixes — a top-level `try/catch` or `process.on('uncaughtException')`
143
+ would mask other bugs.)
144
+
145
+ ### A4 — Frame-length bound in `decodeFrame` (adjacent)
146
+
147
+ Referenced by PR #1504 as #1446. The current code **already** bounds extended
148
+ frame lengths: `MAX_FRAME_PAYLOAD_BYTES = 10MB` (`server.cjs:10`) is enforced at
149
+ `server.cjs:58-67` before any `Buffer.alloc`. Action: verify #1446 against
150
+ current `dev` and close if already resolved, rather than re-implementing.
151
+
152
+ ---
153
+
154
+ ## B. Server robustness / correctness
155
+
156
+ ### B1 — macOS resource-fork dotfiles served as screen content
157
+
158
+ **Problem.** The newest-screen selector filters on `f.endsWith('.html')` only
159
+ (`server.cjs:127-128`). On macOS/ExFAT, `._screen.html` resource-fork files pass
160
+ that filter and, being written alongside the real file, can sort newest — so the
161
+ browser gets binary metadata instead of the mockup. Four read sites share the
162
+ weak filter: `getNewestScreen` (`server.cjs:127`), `knownFiles` init
163
+ (`server.cjs:279`), the `fs.watch` handler (`server.cjs:286`), and the `/files/`
164
+ endpoint (`server.cjs:154-156`).
165
+
166
+ **Change.** Reject dotfiles (`!f.startsWith('.')`) at all four sites. Covers
167
+ `._*`, `.DS_Store`, etc.
168
+
169
+ ### B2 — `stop-server.sh` can kill a reused PID
170
+
171
+ **Problem.** `stop-server.sh` reads the PID from `state/server.pid`
172
+ (`stop-server.sh:20`) and `kill`s it (`:23`, escalating to `-9` at `:35`)
173
+ without confirming the PID still belongs to our server. After a reboot or PID
174
+ wraparound the file can point at an unrelated process, which we'd then SIGKILL.
175
+
176
+ **Change.** Before signalling, verify ownership — the PID's command is `node`
177
+ running our `server.cjs`, ideally matching this session. If ownership can't be
178
+ proven, fail closed (report `stale_pid`, don't kill). Keep the existing
179
+ `stopped` / `not_running` outputs for the real cases.
180
+
181
+ ### B3 — WebSocket client: silent reconnect, stale "Connected"
182
+
183
+ **Problem.** `helper.js` reconnects on a fixed 1s timer (`helper.js:21-23`),
184
+ has no `onerror` handler, never nulls `ws` on close, and never clears a pending
185
+ reconnect timer. The frame's status element is hardcoded to "Connected" with the
186
+ dot pinned to `var(--success)` (`frame-template.html:77,200`). When the laptop
187
+ sleeps or the server restarts, the page shows "Connected" over a dead socket and
188
+ queues events with no feedback.
189
+
190
+ **Change.**
191
+ - `helper.js`: exponential backoff (500ms → ×2 → cap 30s, reset on open);
192
+ `onerror` delegating to `onclose`; `ws = null` on close; `clearTimeout` before
193
+ reconnecting.
194
+ - `frame-template.html`: drive the status dot from a `--status-color` custom
195
+ property so JS can switch Connected (green) / Reconnecting (yellow) /
196
+ Disconnected (red).
197
+
198
+ ---
199
+
200
+ ## C. Lifecycle / timeout (issue #1237)
201
+
202
+ ### C1 — Idle timeout too short, not configurable, WS keeps process alive
203
+
204
+ **Problem.** `IDLE_TIMEOUT_MS` is hardcoded to 30 minutes (`server.cjs:258`),
205
+ enforced by the 60s lifecycle check (`server.cjs:329-332`). A single brainstorm
206
+ question can sit longer than 30 min while the user thinks or steps away, so the
207
+ server dies mid-session. Separately, `shutdown()` (`server.cjs:310-321`) calls
208
+ `server.close()` but never closes the upgraded sockets in `clients`
209
+ (`server.cjs:174`), so an open browser connection can keep the Node process
210
+ alive past shutdown.
211
+
212
+ **Change.**
213
+ - Raise the default to 4 hours and make it configurable:
214
+ `--idle-timeout-minutes` in `start-server.sh` → an env var → `IDLE_TIMEOUT_MS`,
215
+ with validation against Node timer overflow.
216
+ - Expose the effective timeout in the startup JSON / `state/server-info`.
217
+ - In `shutdown()`, close every socket in `clients` so the process actually
218
+ exits.
219
+
220
+ ### C2 — Server death is invisible
221
+
222
+ **Problem.** When the server exits it writes `state/server-stopped` and removes
223
+ `state/server-info` (`server.cjs:312-317`), and the skill is *told* to check
224
+ those files (`visual-companion.md:108`) — but it's soft guidance the model skips,
225
+ and the browser just shows a generic "can't be reached." The user diagnoses it
226
+ manually; the agent keeps referring to a dead URL.
227
+
228
+ **Change (two parts, independent of C1):**
229
+ - **Browser-facing tombstone.** Leave something at the last-served URL that says
230
+ "this companion expired — ask Claude to restart it" instead of a connection
231
+ error. Options to weigh: `helper.js` rendering a banner when the socket stays
232
+ down past backoff (works only while the page is loaded), vs. a more involved
233
+ approach that keeps a minimal responder alive to serve a tombstone page.
234
+ - **Harder skill check.** Tighten `visual-companion.md` / `SKILL.md` so
235
+ "check `server-info`/`server-stopped` before referring to the URL or pushing a
236
+ screen" is a required step, not a note. Keep it lightweight — possibly a
237
+ one-line helper the agent always runs.
238
+
239
+ ---
240
+
241
+ ## D. Features
242
+
243
+ ### D1 — Permanent opt-out of the visual companion (issue #892)
244
+
245
+ **Problem.** The companion is offered as its own message every session
246
+ (`SKILL.md:25,151-152`). A user who never wants it pays that round-trip — and
247
+ HTML generation — every time. There's no way to say "never offer this."
248
+
249
+ **Change.** Before the offer step, the skill checks a user-level setting and
250
+ skips the offer entirely when opt-out is set.
251
+
252
+ **Design choice open.** Mechanism isn't settled:
253
+ - Env var (e.g. `SUPERPOWERS_VISUAL_COMPANION=off`) the skill is told to read —
254
+ simplest, matches what the issue asks for, lives in `.zshrc`.
255
+ - A plugin-settings file (`.claude/superpowers.local.md` frontmatter) — more
256
+ structured, per-project capable, but heavier and project-scoped.
257
+ - Reliability caveat from the issue: a separate "no-companion" skill competes on
258
+ trigger words and isn't reliable — rejected.
259
+
260
+ Pick the mechanism, then it's a small `SKILL.md` change plus a documented knob.
261
+
262
+ ### D2 — Free-text feedback from the browser (issue #957)
263
+
264
+ **Problem.** The client only captures clicks on `[data-choice]`
265
+ (`helper.js:36-62`). A user who wants to annotate a mockup ("wrong shade of
266
+ blue") has to switch to the terminal, breaking the visual flow.
267
+
268
+ **Change.** Add a feedback `<textarea>` whose submit emits
269
+ `{"type":"feedback","text":...,"timestamp":...}` via the existing
270
+ `window.brainstorm.send` path (`helper.js:82-85`).
271
+
272
+ **Cross-cutting — server change required.** `handleMessage` only persists events
273
+ when `event.choice` is truthy (`server.cjs:243`). A `feedback` event has no
274
+ `choice`, so today it would be logged but **never written to `state/events`**,
275
+ and the agent wouldn't see it. The persistence condition must also accept
276
+ `feedback` events. Document the new event shape in `visual-companion.md`
277
+ (Browser Events Format, `:247-259`). Decide the submit trigger (button vs blur
278
+ vs both) and where the textarea renders (frame-level vs opt-in per screen).
279
+
280
+ ### D3 — Auto-open the companion URL (PR #759, issue #755)
281
+
282
+ **Problem.** `start-server.sh` only prints the URL; the user opens it manually.
283
+ In WSL2 especially, people expect the browser to open.
284
+
285
+ **Change.** Best-effort opener after the `server-started` JSON is parsed:
286
+ Windows/WSL → `rundll32.exe url.dll,FileProtocolHandler <url>`, macOS → `open`,
287
+ Linux → `xdg-open` only when `DISPLAY`/`WAYLAND_DISPLAY` is set. Swallow
288
+ failures, never block startup, keep echoing the URL. Document in
289
+ `visual-companion.md`. (Consider an opt-out for headless/remote runs where
290
+ popping a browser is wrong — ties into D1's config mechanism.)
291
+
292
+ ### D4 — Light/dark contrast helpers (PR #1683)
293
+
294
+ **Problem.** Content fragments are wrapped in the OS-aware frame
295
+ (`frame-template.html`). In dark mode, quick mockups often use white inline
296
+ backgrounds while inheriting low-contrast frame text, making cards/panels hard
297
+ to read.
298
+
299
+ **Change.** Add `.light-surface` / `.dark-surface` helper classes plus a
300
+ conservative fallback for common inline light backgrounds, and document them in
301
+ `visual-companion.md`'s CSS reference. Pure CSS in `frame-template.html`.
302
+
303
+ ---
304
+
305
+ ## E. Workshop / deferred / dropped
306
+
307
+ ### E1 — Hard-gate terminal-vs-HTML per question (PR #1037) — WORKSHOP
308
+
309
+ The soft guidance already exists: "decide per-question," with browser-vs-terminal
310
+ tests in `SKILL.md:156-161` and `visual-companion.md:5-25`. The complaint is that
311
+ the model renders HTML for purely textual content (A/B lists, clarifying
312
+ questions), wasting tokens and a turn. PR #1037 wraps the decision in a
313
+ `<HARD-GATE>`. **Per Jesse, we'll workshop the wording/mechanism together** —
314
+ this is behavior-shaping skill content and not specced here.
315
+
316
+ ### E2 — Move session state out of the working tree (issue #975 / PR #977) — DEFERRED
317
+
318
+ Today `--project-dir` writes session state to `<project>/.superpowers/brainstorm/`
319
+ (`start-server.sh:80-84`) and the skill tells the user to gitignore it
320
+ (`visual-companion.md:58`). The ask is a `--state-dir` / `SUPERPOWERS_STATE_DIR`
321
+ default outside the repo (XDG), keeping `--project-dir` as an alias.
322
+ **Deferred by Jesse for now.** Captured so it isn't lost.
323
+
324
+ ### E3 — Vendor Alpine.js for interactive mockups (PR #1639) — DROPPED
325
+
326
+ Adds a vendored Alpine build so mockups can be interactive (tabs, accordions,
327
+ forms) without hand-rolled JS. **Dropped per Jesse** — we are not taking on a
328
+ vendored third-party dependency in the companion runtime. The underlying need
329
+ (interactive mockups) is not being pursued via this route.
330
+
331
+ ### E4 — Shell-lint warnings (PR #1677) — OPPORTUNISTIC
332
+
333
+ SC2034 (and friends) in `start-server.sh` / `stop-server.sh`. Trivial; fold into
334
+ B2/C1/D3 when we're already editing those scripts rather than as its own change.
335
+
336
+ ---
337
+
338
+ ## Suggested grouping for implementation
339
+
340
+ These cluster into a few coherent passes (each independently testable against
341
+ `tests/brainstorm-server/`):
342
+
343
+ 1. **Security pass** (IN PROGRESS, branch `brainstorm-companion-session-key`) —
344
+ A1 per-session key (supersedes A2) + A3 null-crash guard. Verify/close A4.
345
+ *Highest priority.*
346
+ 2. **Lifecycle pass** — C1 + C2 together (both touch `shutdown()` and the
347
+ server-death story).
348
+ 3. **Robustness pass** — B1, B2, B3 (independent, small).
349
+ 4. **Deferred feature pass** - D1, D2, D4 are not part of PR #1720. D3 is
350
+ shipped through the `--open` flow.
351
+
352
+ E1 is a separate workshop session. E2/E3 are out of scope for this round.
github_code/obra__superpowers/docs/superpowers/plans/2026-06-10-visual-companion-auth-hardening.md ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Companion Auth Hardening Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Harden the brainstorming visual companion auth and reconnect flow while preserving trusted same-origin screen JavaScript and future vendored UI libraries.
6
+
7
+ **Architecture:** Keyed root loads become a bootstrap step that sets the cookie, stores the key in tab-scoped `sessionStorage`, and navigates to a bare `/` screen URL. WebSockets require valid auth plus browser same-origin `Origin`, while `/files/*` uses realpath containment to prevent content-directory escapes.
8
+
9
+ **Tech Stack:** Node.js built-ins (`http`, `fs`, `path`, `crypto`), zero runtime dependencies, existing `ws` test dependency, Bash start/stop scripts, repo shell lint script.
10
+
11
+ **Important:** Do not commit during execution unless Drew explicitly asks. This repository's instructions override the generic plan template's commit cadence.
12
+
13
+ ---
14
+
15
+ ## File Map
16
+
17
+ - Modify: `skills/brainstorming/scripts/server.cjs`
18
+ - Add bootstrap response.
19
+ - Add shared security headers.
20
+ - Add WebSocket Origin validation.
21
+ - Add `/files/*` realpath containment.
22
+ - Modify: `skills/brainstorming/scripts/helper.js`
23
+ - Read the stored session key and append it to the WebSocket URL.
24
+ - Modify: `tests/brainstorm-server/auth.test.js`
25
+ - Add bootstrap, header, same-origin WS, cross-origin WS, and cookie/file auth regressions.
26
+ - Modify: `tests/brainstorm-server/helper.test.js`
27
+ - Add mocked-browser coverage for sessionStorage-backed WS URLs.
28
+ - Modify: `tests/brainstorm-server/server.test.js`
29
+ - Add symlink containment regression for `/files/*`.
30
+ - Modify: `tests/brainstorm-server/lifecycle.test.js`
31
+ - Make the start-server timeout flag test force background mode.
32
+ - Add restart reconnect credential coverage if it fits the existing lifecycle helper.
33
+ - Modify: `skills/brainstorming/scripts/start-server.sh`
34
+ - Fix shell lint.
35
+ - Modify: `skills/brainstorming/scripts/stop-server.sh`
36
+ - Fix shell lint.
37
+ - Modify: `.gitignore`
38
+ - Add `.superpowers/`.
39
+ - Optional docs update: `skills/brainstorming/visual-companion.md`
40
+ - Mention bootstrap URL stripping and trusted same-origin screen JS if the code behavior changes need operator-facing explanation.
41
+
42
+ ## Task 1: Bootstrap Keyed Root Loads
43
+
44
+ **Files:**
45
+ - Modify: `tests/brainstorm-server/auth.test.js`
46
+ - Modify: `skills/brainstorming/scripts/server.cjs`
47
+
48
+ - [ ] **Step 1: Add RED tests for bootstrap behavior**
49
+
50
+ In `tests/brainstorm-server/auth.test.js`, add tests after the existing valid-key root test:
51
+
52
+ ```js
53
+ await test('GET / with valid query returns bootstrap instead of screen content', async () => {
54
+ const res = await get('/', { key: TOKEN });
55
+ assert.strictEqual(res.status, 200);
56
+ assert(res.body.includes('sessionStorage'), 'bootstrap should store the session key in tab storage');
57
+ assert(res.body.includes('location.replace'), 'bootstrap should navigate to the bare root URL');
58
+ assert(!res.body.includes('Secret screen'), 'bootstrap must not serve screen HTML at the keyed URL');
59
+ });
60
+
61
+ await test('GET / with valid cookie serves the screen after bootstrap', async () => {
62
+ const res = await get('/', { cookie: `${COOKIE_NAME}=${TOKEN}` });
63
+ assert.strictEqual(res.status, 200);
64
+ assert(res.body.includes('Secret screen'), 'cookie-authenticated bare root should serve the screen');
65
+ assert(!res.body.includes('sessionStorage'), 'bare screen response should not be the bootstrap page');
66
+ });
67
+ ```
68
+
69
+ Keep the existing cookie test if present; merge assertions rather than duplicating the same test name.
70
+
71
+ - [ ] **Step 2: Verify RED**
72
+
73
+ Run:
74
+
75
+ ```bash
76
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
77
+ node auth.test.js
78
+ ```
79
+
80
+ Expected: the new bootstrap test fails because current `GET /?key=...` serves `Secret screen` directly and does not include the bootstrap `sessionStorage`/`location.replace` code.
81
+
82
+ - [ ] **Step 3: Implement minimal bootstrap response**
83
+
84
+ In `skills/brainstorming/scripts/server.cjs`, add a helper near the page constants:
85
+
86
+ ```js
87
+ function bootstrapPage(key) {
88
+ const jsonKey = JSON.stringify(String(key));
89
+ return `<!DOCTYPE html>
90
+ <html>
91
+ <head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head>
92
+ <body>
93
+ <script>
94
+ sessionStorage.setItem('brainstorm-session-key', ${jsonKey});
95
+ location.replace('/');
96
+ </script>
97
+ </body>
98
+ </html>`;
99
+ }
100
+ ```
101
+
102
+ Then in `handleRequest`, after authorization and cookie setting but before serving screen HTML, detect a valid query key on root:
103
+
104
+ ```js
105
+ function queryKey(url) {
106
+ const q = url.indexOf('?');
107
+ if (q < 0) return null;
108
+ return new URLSearchParams(url.slice(q + 1)).get('key');
109
+ }
110
+ ```
111
+
112
+ Use it in `handleRequest`:
113
+
114
+ ```js
115
+ const pathname = pathnameOf(req.url);
116
+ const keyFromQuery = queryKey(req.url);
117
+ if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
118
+ res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
119
+ res.end(bootstrapPage(keyFromQuery));
120
+ return;
121
+ }
122
+ ```
123
+
124
+ This assumes Task 4 will introduce `securityHeaders`. If implementing Task 1 first, temporarily use:
125
+
126
+ ```js
127
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
128
+ ```
129
+
130
+ and replace it in Task 4.
131
+
132
+ - [ ] **Step 4: Verify GREEN**
133
+
134
+ Run:
135
+
136
+ ```bash
137
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
138
+ node auth.test.js
139
+ ```
140
+
141
+ Expected: all auth tests pass, including the new bootstrap tests.
142
+
143
+ ## Task 2: WebSocket Origin Enforcement
144
+
145
+ **Files:**
146
+ - Modify: `tests/brainstorm-server/auth.test.js`
147
+ - Modify: `skills/brainstorming/scripts/server.cjs`
148
+
149
+ - [ ] **Step 1: Add RED tests for same-origin and cross-origin WS**
150
+
151
+ In `tests/brainstorm-server/auth.test.js`, extend `wsConnect` to accept an `origin` option:
152
+
153
+ ```js
154
+ function wsConnect({ key, cookie, origin } = {}) {
155
+ const url = `ws://localhost:${TEST_PORT}/` + (key !== undefined ? `?key=${key}` : '');
156
+ const headers = {};
157
+ if (cookie) headers['Cookie'] = cookie;
158
+ if (origin) headers['Origin'] = origin;
159
+ const ws = new WebSocket(url, Object.keys(headers).length ? { headers } : {});
160
+ return new Promise((resolve) => {
161
+ let settled = false;
162
+ const done = (outcome) => { if (!settled) { settled = true; resolve({ outcome, ws }); } };
163
+ ws.on('open', () => done('opened'));
164
+ ws.on('error', () => done('rejected'));
165
+ ws.on('close', () => done('rejected'));
166
+ setTimeout(() => done('rejected'), 1500);
167
+ });
168
+ }
169
+ ```
170
+
171
+ Then add:
172
+
173
+ ```js
174
+ await test('WS upgrade with valid cookie and same-origin Origin opens', async () => {
175
+ const { outcome, ws } = await wsConnect({
176
+ cookie: `${COOKIE_NAME}=${TOKEN}`,
177
+ origin: `http://localhost:${TEST_PORT}`
178
+ });
179
+ ws.close();
180
+ assert.strictEqual(outcome, 'opened');
181
+ });
182
+
183
+ await test('WS upgrade with valid cookie but cross-origin Origin is rejected', async () => {
184
+ const eventsFile = path.join(TEST_DIR, 'state', 'events');
185
+ if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
186
+
187
+ const { outcome, ws } = await wsConnect({
188
+ cookie: `${COOKIE_NAME}=${TOKEN}`,
189
+ origin: 'http://localhost:9999'
190
+ });
191
+ if (outcome === 'opened') {
192
+ ws.send(JSON.stringify({ type: 'choice', choice: 'attacker-injected', text: 'local attacker probe' }));
193
+ await sleep(300);
194
+ }
195
+ ws.close();
196
+
197
+ assert.strictEqual(outcome, 'rejected', 'cross-origin browser WS must not open even with cookie');
198
+ assert(!fs.existsSync(eventsFile), 'cross-origin WS must not write state/events');
199
+ });
200
+ ```
201
+
202
+ - [ ] **Step 2: Verify RED**
203
+
204
+ Run:
205
+
206
+ ```bash
207
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
208
+ node auth.test.js
209
+ ```
210
+
211
+ Expected: cross-origin cookie WS test fails because current server accepts any cookie-authenticated WS regardless of Origin.
212
+
213
+ - [ ] **Step 3: Implement Origin check**
214
+
215
+ In `skills/brainstorming/scripts/server.cjs`, add:
216
+
217
+ ```js
218
+ function isAllowedWebSocketOrigin(req) {
219
+ const origin = req.headers.origin;
220
+ if (!origin) return true; // non-browser clients still need the session key
221
+ const host = req.headers.host;
222
+ if (!host) return false;
223
+ return origin === 'http://' + host;
224
+ }
225
+ ```
226
+
227
+ Then update `handleUpgrade`:
228
+
229
+ ```js
230
+ function handleUpgrade(req, socket) {
231
+ if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }
232
+ ```
233
+
234
+ - [ ] **Step 4: Verify GREEN**
235
+
236
+ Run:
237
+
238
+ ```bash
239
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
240
+ node auth.test.js
241
+ ```
242
+
243
+ Expected: auth tests pass; cross-origin WS is rejected; same-origin and direct key WS still open.
244
+
245
+ ## Task 3: Helper Uses Stored Key For Reconnect
246
+
247
+ **Files:**
248
+ - Modify: `tests/brainstorm-server/helper.test.js`
249
+ - Modify: `skills/brainstorming/scripts/helper.js`
250
+
251
+ - [ ] **Step 1: Add RED test for WebSocket URL key**
252
+
253
+ In `tests/brainstorm-server/helper.test.js`, add a mocked-browser test near the reconnect state-machine tests:
254
+
255
+ ```js
256
+ test('uses sessionStorage key in the WebSocket URL when present', () => {
257
+ const e = makeEnv();
258
+ e.state.sessionKey = 'stored-key-abc';
259
+ e.boot();
260
+ assert.strictEqual(e.sockets[0].url, 'ws://localhost:7777/?key=stored-key-abc');
261
+ });
262
+ ```
263
+
264
+ Update `makeEnv()` so the returned object exposes `sockets`, and the mock window includes sessionStorage:
265
+
266
+ ```js
267
+ window: {
268
+ location: { host: 'localhost:7777', reload() { state.reloads++; } },
269
+ sessionStorage: { getItem: (key) => key === 'brainstorm-session-key' ? state.sessionKey : null }
270
+ },
271
+ ```
272
+
273
+ Also add a fallback test:
274
+
275
+ ```js
276
+ test('uses cookie-only WebSocket URL when no sessionStorage key is present', () => {
277
+ const e = makeEnv();
278
+ e.state.sessionKey = null;
279
+ e.boot();
280
+ assert.strictEqual(e.sockets[0].url, 'ws://localhost:7777');
281
+ });
282
+ ```
283
+
284
+ - [ ] **Step 2: Verify RED**
285
+
286
+ Run:
287
+
288
+ ```bash
289
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
290
+ node helper.test.js
291
+ ```
292
+
293
+ Expected: stored-key test fails because current helper uses `ws://localhost:7777`.
294
+
295
+ - [ ] **Step 3: Implement stored-key WS URL**
296
+
297
+ In `skills/brainstorming/scripts/helper.js`, replace:
298
+
299
+ ```js
300
+ const WS_URL = 'ws://' + window.location.host;
301
+ ```
302
+
303
+ with:
304
+
305
+ ```js
306
+ function websocketUrl() {
307
+ let key = null;
308
+ try { key = window.sessionStorage && window.sessionStorage.getItem('brainstorm-session-key'); } catch (e) {}
309
+ return 'ws://' + window.location.host + (key ? '/?key=' + encodeURIComponent(key) : '');
310
+ }
311
+ ```
312
+
313
+ Then replace:
314
+
315
+ ```js
316
+ ws = new WebSocket(WS_URL);
317
+ ```
318
+
319
+ with:
320
+
321
+ ```js
322
+ ws = new WebSocket(websocketUrl());
323
+ ```
324
+
325
+ - [ ] **Step 4: Verify GREEN**
326
+
327
+ Run:
328
+
329
+ ```bash
330
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
331
+ node helper.test.js
332
+ ```
333
+
334
+ Expected: helper tests pass.
335
+
336
+ ## Task 4: Security Headers
337
+
338
+ **Files:**
339
+ - Modify: `tests/brainstorm-server/auth.test.js`
340
+ - Modify: `skills/brainstorming/scripts/server.cjs`
341
+
342
+ - [ ] **Step 1: Add RED header tests**
343
+
344
+ In `tests/brainstorm-server/auth.test.js`, add:
345
+
346
+ ```js
347
+ await test('HTML responses include leak-reduction and anti-framing headers', async () => {
348
+ const res = await get('/', { key: TOKEN });
349
+ assert.strictEqual(res.headers['referrer-policy'], 'no-referrer');
350
+ assert.strictEqual(res.headers['cache-control'], 'no-store');
351
+ assert.strictEqual(res.headers['x-frame-options'], 'DENY');
352
+ assert.strictEqual(res.headers['content-security-policy'], "frame-ancestors 'none'");
353
+ assert.strictEqual(res.headers['cross-origin-resource-policy'], 'same-origin');
354
+ });
355
+
356
+ await test('403 responses include leak-reduction and anti-framing headers', async () => {
357
+ const res = await get('/');
358
+ assert.strictEqual(res.status, 403);
359
+ assert.strictEqual(res.headers['referrer-policy'], 'no-referrer');
360
+ assert.strictEqual(res.headers['cache-control'], 'no-store');
361
+ assert.strictEqual(res.headers['x-frame-options'], 'DENY');
362
+ assert.strictEqual(res.headers['content-security-policy'], "frame-ancestors 'none'");
363
+ assert.strictEqual(res.headers['cross-origin-resource-policy'], 'same-origin');
364
+ });
365
+ ```
366
+
367
+ - [ ] **Step 2: Verify RED**
368
+
369
+ Run:
370
+
371
+ ```bash
372
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
373
+ node auth.test.js
374
+ ```
375
+
376
+ Expected: header tests fail because current responses do not include these headers.
377
+
378
+ - [ ] **Step 3: Implement shared header helper**
379
+
380
+ In `skills/brainstorming/scripts/server.cjs`, add:
381
+
382
+ ```js
383
+ function securityHeaders(headers = {}) {
384
+ return {
385
+ 'Referrer-Policy': 'no-referrer',
386
+ 'Cache-Control': 'no-store',
387
+ 'X-Frame-Options': 'DENY',
388
+ 'Content-Security-Policy': "frame-ancestors 'none'",
389
+ 'Cross-Origin-Resource-Policy': 'same-origin',
390
+ ...headers
391
+ };
392
+ }
393
+ ```
394
+
395
+ Update response writes in `handleRequest`:
396
+
397
+ ```js
398
+ res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
399
+ ```
400
+
401
+ ```js
402
+ res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
403
+ ```
404
+
405
+ ```js
406
+ res.writeHead(200, securityHeaders({ 'Content-Type': contentType }));
407
+ ```
408
+
409
+ For 404s:
410
+
411
+ ```js
412
+ res.writeHead(404, securityHeaders());
413
+ ```
414
+
415
+ - [ ] **Step 4: Verify GREEN**
416
+
417
+ Run:
418
+
419
+ ```bash
420
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
421
+ node auth.test.js
422
+ ```
423
+
424
+ Expected: auth tests pass and header assertions are green.
425
+
426
+ ## Task 5: `/files/*` Realpath Containment
427
+
428
+ **Files:**
429
+ - Modify: `tests/brainstorm-server/server.test.js`
430
+ - Modify: `skills/brainstorming/scripts/server.cjs`
431
+
432
+ - [ ] **Step 1: Add RED symlink escape test**
433
+
434
+ In `tests/brainstorm-server/server.test.js`, after the `/files/` empty-name test, add:
435
+
436
+ ```js
437
+ await test('does not serve symlinks that escape content dir via /files/', async () => {
438
+ const target = path.join(STATE_DIR, 'server-info');
439
+ const link = path.join(CONTENT_DIR, 'linked-server-info.txt');
440
+ try { fs.unlinkSync(link); } catch (e) {}
441
+ fs.symlinkSync(target, link);
442
+
443
+ const res = await fetch(`http://localhost:${TEST_PORT}/files/linked-server-info.txt`);
444
+ assert.strictEqual(res.status, 404, 'symlink to state/server-info must not be served');
445
+ assert(!res.body.includes('server-started'), 'response must not include server-info body');
446
+ });
447
+ ```
448
+
449
+ - [ ] **Step 2: Verify RED**
450
+
451
+ Run:
452
+
453
+ ```bash
454
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
455
+ node server.test.js
456
+ ```
457
+
458
+ Expected: symlink test fails because current `/files/*` follows symlinks and serves `server-info`.
459
+
460
+ - [ ] **Step 3: Implement containment helper**
461
+
462
+ In `skills/brainstorming/scripts/server.cjs`, add:
463
+
464
+ ```js
465
+ function isRegularFileInsideContentDir(filePath) {
466
+ let stat, realContentDir, realFilePath;
467
+ try {
468
+ stat = fs.lstatSync(filePath);
469
+ if (stat.isSymbolicLink()) return false;
470
+ if (!stat.isFile()) return false;
471
+ realContentDir = fs.realpathSync(CONTENT_DIR);
472
+ realFilePath = fs.realpathSync(filePath);
473
+ } catch (e) {
474
+ return false;
475
+ }
476
+ return realFilePath.startsWith(realContentDir + path.sep);
477
+ }
478
+ ```
479
+
480
+ Replace the `/files/*` guard with:
481
+
482
+ ```js
483
+ if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {
484
+ res.writeHead(404, securityHeaders());
485
+ res.end('Not found');
486
+ return;
487
+ }
488
+ ```
489
+
490
+ - [ ] **Step 4: Verify GREEN**
491
+
492
+ Run:
493
+
494
+ ```bash
495
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
496
+ node server.test.js
497
+ ```
498
+
499
+ Expected: server tests pass, including symlink rejection.
500
+
501
+ ## Task 6: Restart Reconnect Regression
502
+
503
+ **Files:**
504
+ - Modify: `tests/brainstorm-server/lifecycle.test.js`
505
+ - Modify: `skills/brainstorming/scripts/server.cjs`
506
+ - Modify: `skills/brainstorming/scripts/helper.js`
507
+
508
+ - [ ] **Step 1: Add RED integration test for same key over WS after restart**
509
+
510
+ In `tests/brainstorm-server/lifecycle.test.js`, add a test after the port/token persistence test:
511
+
512
+ ```js
513
+ await test('stored key can authenticate WebSocket after same-port restart', async () => {
514
+ const dir = fs.mkdtempSync('/tmp/bs-reconnect-');
515
+ const portFile = path.join(dir, '.last-port');
516
+ const tokenFile = path.join(dir, '.last-token');
517
+ const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
518
+
519
+ const a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
520
+ let outA = ''; a.stdout.on('data', d => outA += d.toString());
521
+ for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
522
+ const infoA = firstServerStarted(outA);
523
+ const keyA = new URL(infoA.url).searchParams.get('key');
524
+ a.kill(); await sleep(400);
525
+
526
+ const b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
527
+ let outB = ''; b.stdout.on('data', d => outB += d.toString());
528
+ for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
529
+ const infoB = firstServerStarted(outB);
530
+
531
+ const ws = new WebSocket(`ws://localhost:${infoB.port}/?key=${keyA}`, {
532
+ headers: { Origin: `http://localhost:${infoB.port}` }
533
+ });
534
+ const opened = await new Promise(resolve => {
535
+ ws.on('open', () => resolve(true));
536
+ ws.on('error', () => resolve(false));
537
+ setTimeout(() => resolve(false), 1500);
538
+ });
539
+
540
+ try {
541
+ assert.strictEqual(infoB.port, infoA.port, 'restart should reuse same port');
542
+ assert(opened, 'stored key should authenticate WS after restart');
543
+ } finally {
544
+ try { ws.close(); } catch (e) {}
545
+ b.kill(); await sleep(100);
546
+ fs.rmSync(dir, { recursive: true, force: true });
547
+ }
548
+ });
549
+ ```
550
+
551
+ This test may already pass once Tasks 2 and 3 are implemented. If it passes before code changes, keep it as coverage but do not call it RED. The real browser reconnect behavior is primarily covered by Task 3 plus final manual/headless browser verification.
552
+
553
+ - [ ] **Step 2: Verify behavior**
554
+
555
+ Run:
556
+
557
+ ```bash
558
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
559
+ node lifecycle.test.js
560
+ ```
561
+
562
+ Expected after Tasks 2 and 3: lifecycle tests pass. If this fails, fix the auth/restart path before continuing.
563
+
564
+ ## Task 7: Lifecycle Hang And Shell Lint
565
+
566
+ **Files:**
567
+ - Modify: `tests/brainstorm-server/lifecycle.test.js`
568
+ - Modify: `skills/brainstorming/scripts/start-server.sh`
569
+ - Modify: `skills/brainstorming/scripts/stop-server.sh`
570
+
571
+ - [ ] **Step 1: Reproduce shell lint failure**
572
+
573
+ Run:
574
+
575
+ ```bash
576
+ cd /Users/drewritter/prime-rad/superpowers
577
+ scripts/lint-shell.sh skills/brainstorming/scripts/start-server.sh skills/brainstorming/scripts/stop-server.sh tests/brainstorm-server/stop-server.test.sh
578
+ ```
579
+
580
+ Expected current failure:
581
+
582
+ ```text
583
+ SC2164: skills/brainstorming/scripts/start-server.sh line 128: cd "$SCRIPT_DIR"
584
+ SC2034: skills/brainstorming/scripts/start-server.sh line 166: for i in {1..50}
585
+ SC2034: skills/brainstorming/scripts/stop-server.sh line 57: for i in {1..20}
586
+ ```
587
+
588
+ - [ ] **Step 2: Fix shell lint minimally**
589
+
590
+ In `skills/brainstorming/scripts/start-server.sh`, change:
591
+
592
+ ```bash
593
+ cd "$SCRIPT_DIR"
594
+ ```
595
+
596
+ to:
597
+
598
+ ```bash
599
+ cd "$SCRIPT_DIR" || exit 1
600
+ ```
601
+
602
+ Change unused loop variables from `i` to `_` where they are not read:
603
+
604
+ ```bash
605
+ for _ in {1..50}; do
606
+ ```
607
+
608
+ In `skills/brainstorming/scripts/stop-server.sh`, change:
609
+
610
+ ```bash
611
+ for i in {1..20}; do
612
+ ```
613
+
614
+ to:
615
+
616
+ ```bash
617
+ for _ in {1..20}; do
618
+ ```
619
+
620
+ - [ ] **Step 3: Fix lifecycle start-server hang**
621
+
622
+ In `tests/brainstorm-server/lifecycle.test.js`, update the `start-server.sh --idle-timeout-minutes sets the timeout` test command:
623
+
624
+ ```js
625
+ const out = execFileSync('bash', [START, '--project-dir', dir, '--idle-timeout-minutes', '5', '--background'], { encoding: 'utf8' });
626
+ ```
627
+
628
+ This keeps the test from hanging when `CODEX_CI` triggers start-server foreground mode.
629
+
630
+ - [ ] **Step 4: Verify lint and lifecycle**
631
+
632
+ Run:
633
+
634
+ ```bash
635
+ cd /Users/drewritter/prime-rad/superpowers
636
+ scripts/lint-shell.sh skills/brainstorming/scripts/start-server.sh skills/brainstorming/scripts/stop-server.sh tests/brainstorm-server/stop-server.test.sh
637
+ cd tests/brainstorm-server
638
+ node lifecycle.test.js
639
+ ```
640
+
641
+ Expected: shell lint exits 0; lifecycle tests exit 0 without hanging.
642
+
643
+ ## Task 8: Gitignore Durable Companion State
644
+
645
+ **Files:**
646
+ - Modify: `.gitignore`
647
+
648
+ - [ ] **Step 1: Verify current ignore gap**
649
+
650
+ Run:
651
+
652
+ ```bash
653
+ cd /Users/drewritter/prime-rad/superpowers
654
+ git check-ignore .superpowers/brainstorm/.last-token || true
655
+ ```
656
+
657
+ Expected current output: no matching ignore rule.
658
+
659
+ - [ ] **Step 2: Add ignore rule**
660
+
661
+ Add this line to `.gitignore`:
662
+
663
+ ```gitignore
664
+ .superpowers/
665
+ ```
666
+
667
+ - [ ] **Step 3: Verify GREEN**
668
+
669
+ Run:
670
+
671
+ ```bash
672
+ cd /Users/drewritter/prime-rad/superpowers
673
+ git check-ignore .superpowers/brainstorm/.last-token
674
+ ```
675
+
676
+ Expected output:
677
+
678
+ ```text
679
+ .superpowers/brainstorm/.last-token
680
+ ```
681
+
682
+ ## Task 9: Full Automated Verification
683
+
684
+ **Files:**
685
+ - No code changes in this task.
686
+
687
+ - [ ] **Step 1: Run focused suites**
688
+
689
+ Run:
690
+
691
+ ```bash
692
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
693
+ node auth.test.js
694
+ node helper.test.js
695
+ node server.test.js
696
+ node lifecycle.test.js
697
+ ```
698
+
699
+ Expected: all four commands exit 0.
700
+
701
+ - [ ] **Step 2: Run full brainstorm-server suite**
702
+
703
+ Run:
704
+
705
+ ```bash
706
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
707
+ npm test
708
+ ```
709
+
710
+ Expected: all tests pass, including ws-protocol, helper, auth, server, lifecycle, and stop-server.
711
+
712
+ - [ ] **Step 3: Repeat suite for lifecycle/watch flake**
713
+
714
+ Run:
715
+
716
+ ```bash
717
+ cd /Users/drewritter/prime-rad/superpowers/tests/brainstorm-server
718
+ for i in 1 2 3; do npm test || exit 1; done
719
+ ```
720
+
721
+ Expected: all three repeats pass without hanging.
722
+
723
+ - [ ] **Step 4: Run shell lint**
724
+
725
+ Run:
726
+
727
+ ```bash
728
+ cd /Users/drewritter/prime-rad/superpowers
729
+ scripts/lint-shell.sh skills/brainstorming/scripts/start-server.sh skills/brainstorming/scripts/stop-server.sh tests/brainstorm-server/stop-server.test.sh
730
+ ```
731
+
732
+ Expected: exits 0.
733
+
734
+ ## Task 10: Re-run Security Probes
735
+
736
+ **Files:**
737
+ - No code changes in this task.
738
+
739
+ - [ ] **Step 1: Recreate the cross-origin attacker probe**
740
+
741
+ Use the previous scratch probe if available:
742
+
743
+ ```bash
744
+ node /tmp/superpowers-pr1720-security-drewritter/probe-pr1720.cjs
745
+ ```
746
+
747
+ If the scratch probe is unavailable, recreate a minimal probe under `/tmp` that:
748
+
749
+ - starts the companion with a fixed token
750
+ - loads the keyed URL in headless Chrome
751
+ - starts an attacker page on a different localhost port
752
+ - attempts `new WebSocket('ws://localhost:<companion-port>/')`
753
+ - sends `{"type":"choice","choice":"attacker-injected"}`
754
+ - checks `state/events`
755
+
756
+ Expected after fixes:
757
+
758
+ - keyless and wrong-key HTTP still return 403
759
+ - same-origin helper reaches Connected
760
+ - cross-origin WebSocket does not open
761
+ - `state/events` does not contain `attacker-injected`
762
+ - symlink-to-`server-info` returns 404
763
+ - keyed browser load ends on bare `/`
764
+
765
+ - [ ] **Step 2: Re-run manual/browser flow only after automated probes pass**
766
+
767
+ Manual flow:
768
+
769
+ 1. start the companion with `--project-dir --open`
770
+ 2. push a screen
771
+ 3. confirm URL strips to `/`
772
+ 4. confirm status reaches Connected
773
+ 5. click a choice and verify `state/events`
774
+ 6. stop and restart same project
775
+ 7. verify the open tab reconnects automatically
776
+
777
+ Expected: all steps pass without manual URL reload.
778
+
779
+ ## Self-Review Checklist
780
+
781
+ - Spec coverage: every design requirement maps to at least one task.
782
+ - Placeholder scan: this plan contains no unresolved placeholder markers or unspecified edge-case steps.
783
+ - TDD order: every production change task starts with a focused failing test or a command that demonstrates the current failure.
784
+ - Trust model: the plan preserves trusted same-origin screen JavaScript and future same-origin vendored libraries.
785
+ - No-commit rule: execution does not commit unless Drew explicitly asks.
github_code/obra__superpowers/docs/superpowers/plans/2026-06-11-visual-companion-final-hardening-fixup.md ADDED
@@ -0,0 +1,1126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Visual Companion Final Hardening Fixup Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Finish PR #1720's final hardening fixup with test-first changes, clean rebase state, and reviewer-ready evidence.
6
+
7
+ **Spec:** `docs/superpowers/specs/2026-06-11-visual-companion-final-hardening-fixup-design.md`
8
+
9
+ **Architecture:** Keep the companion zero-dependency and local-first. Add focused guards to the existing server and shell scripts: root screen selection reuses the `/files/*` containment guard, fallback token handling tracks token source, and lifecycle shutdown uses a per-start command-line instance id for ownership proof.
10
+
11
+ **Tech Stack:** Node.js built-ins (`http`, `fs`, `path`, `crypto`), existing `ws` test dependency, Bash scripts, Git Bash on Windows, `gh` CLI for PR metadata.
12
+
13
+ **Commit discipline:** Each task includes a suggested commit. When using subagent-driven execution, the orchestrator reviews the worker diff, runs the task verification, and performs the commit.
14
+
15
+ ---
16
+
17
+ ## File Map
18
+
19
+ - Modify: `skills/brainstorming/scripts/server.cjs`
20
+ - Filter root screen candidates through `isRegularFileInsideContentDir()`.
21
+ - Track token source and rotate or fail closed on fallback.
22
+ - Modify: `skills/brainstorming/scripts/start-server.sh`
23
+ - Generate `state/server-instance-id`.
24
+ - Pass `--brainstorm-server-id=<id>` after `server.cjs`.
25
+ - Modify: `skills/brainstorming/scripts/stop-server.sh`
26
+ - Require exact instance-id argv proof before signalling a PID.
27
+ - Remove stale `server.pid` and `server-instance-id` on stale/stopped outcomes.
28
+ - Modify: `tests/brainstorm-server/server.test.js`
29
+ - Add fixed-port startup guard.
30
+ - Add skip-aware test harness for symlink capability.
31
+ - Add root symlink and hardlink escape regressions.
32
+ - Modify: `tests/brainstorm-server/auth.test.js`
33
+ - Add fixed-port startup guard.
34
+ - Modify: `tests/brainstorm-server/lifecycle.test.js`
35
+ - Add fallback token rotation, explicit-token fail-closed, and fallback-key rejection regressions.
36
+ - Modify: `tests/brainstorm-server/stop-server.test.sh`
37
+ - Add top-level cleanup trap.
38
+ - Add positive and negative server-instance-id ownership tests.
39
+ - Modify: `tests/brainstorm-server/start-server.test.sh`
40
+ - Assert Windows-like fake-node path receives exact server id argv and writes a valid id file.
41
+ - Modify: `tests/brainstorm-server/windows-lifecycle.test.sh`
42
+ - Pass server id argv for direct Node stop-server coverage.
43
+ - Add Windows fake-node assertion for the id argv.
44
+ - Modify: `skills/brainstorming/visual-companion.md`
45
+ - Add `--open` to platform commands that should preserve auto-open behavior.
46
+ - Modify: `docs/superpowers/plans/2026-06-09-visual-companion-issues.md`
47
+ - Reconcile shipped scope, WS Origin wording, default timeout, and deferred feature items.
48
+ - Update outside tracked files: PR #1720 body
49
+ - Record post-rebase diff state, RED/GREEN evidence, macOS/Windows verification, manual browser smoke, and external eval evidence.
50
+
51
+ ## Task 0: Rebase And Baseline State
52
+
53
+ **Files:**
54
+ - No source edits
55
+ - Verification target: git branch state
56
+
57
+ - [ ] **Step 1: Fetch current dev**
58
+
59
+ Run:
60
+
61
+ ```bash
62
+ git fetch origin dev
63
+ ```
64
+
65
+ Expected: command exits 0.
66
+
67
+ - [ ] **Step 2: Rebase onto current dev**
68
+
69
+ Run:
70
+
71
+ ```bash
72
+ git rebase origin/dev
73
+ ```
74
+
75
+ Expected: command exits 0, or stops only on conflicts that must be resolved by taking `origin/dev` for `evals`.
76
+
77
+ - [ ] **Step 3: Resolve an evals conflict by taking dev**
78
+
79
+ If the rebase stops on `evals`, run:
80
+
81
+ ```bash
82
+ git restore --source=origin/dev --staged --worktree evals
83
+ git add evals
84
+ git rebase --continue
85
+ ```
86
+
87
+ Expected: rebase continues. After the rebase, `git diff --name-only origin/dev...HEAD -- evals` prints nothing.
88
+
89
+ - [ ] **Step 4: Record baseline status**
90
+
91
+ Run:
92
+
93
+ ```bash
94
+ git status --short --branch
95
+ git diff --name-only origin/dev...HEAD -- evals
96
+ ```
97
+
98
+ Expected: status shows the branch on top of `origin/dev`; second command prints no paths.
99
+
100
+ ## Task 1: Root Screen Containment
101
+
102
+ **Files:**
103
+ - Modify: `tests/brainstorm-server/server.test.js`
104
+ - Modify: `skills/brainstorming/scripts/server.cjs`
105
+
106
+ - [ ] **Step 1: Add fixed-port guard and skip-aware test helper**
107
+
108
+ In `tests/brainstorm-server/server.test.js`, add this helper after `waitForServer()`:
109
+
110
+ ```js
111
+ class SkipTest extends Error {
112
+ constructor(message) {
113
+ super(message);
114
+ this.skip = true;
115
+ }
116
+ }
117
+
118
+ function skip(message) {
119
+ throw new SkipTest(message);
120
+ }
121
+
122
+ function serverStartedMessage(out) {
123
+ const line = out.trim().split('\n').find(l => l.includes('server-started'));
124
+ assert(line, 'server-started JSON should be present');
125
+ return JSON.parse(line);
126
+ }
127
+
128
+ function assertStartedOnExpectedPort(out) {
129
+ const msg = serverStartedMessage(out);
130
+ assert.strictEqual(
131
+ msg.port,
132
+ TEST_PORT,
133
+ `server.test.js expected fixed port ${TEST_PORT}, got ${msg.port}; fixed-port tests must not run through fallback`
134
+ );
135
+ return msg;
136
+ }
137
+
138
+ function ensureSymlinkWorks(target, link) {
139
+ try {
140
+ fs.symlinkSync(target, link);
141
+ fs.unlinkSync(link);
142
+ } catch (e) {
143
+ try { fs.unlinkSync(link); } catch (ignore) {}
144
+ skip(`symlink creation unavailable on this host: ${e.message}`);
145
+ }
146
+ }
147
+ ```
148
+
149
+ Then change the startup section from:
150
+
151
+ ```js
152
+ const { stdout: initialStdout } = await waitForServer(server);
153
+ let passed = 0;
154
+ let failed = 0;
155
+ ```
156
+
157
+ to:
158
+
159
+ ```js
160
+ const { stdout: initialStdout } = await waitForServer(server);
161
+ assertStartedOnExpectedPort(initialStdout);
162
+ let passed = 0;
163
+ let failed = 0;
164
+ let skipped = 0;
165
+ ```
166
+
167
+ Change the `test()` helper catch block to handle skips:
168
+
169
+ ```js
170
+ }).catch(e => {
171
+ if (e && e.skip) {
172
+ console.log(` SKIP: ${name}`);
173
+ console.log(` ${e.message}`);
174
+ skipped++;
175
+ return;
176
+ }
177
+ console.log(` FAIL: ${name}`);
178
+ console.log(` ${e.message}`);
179
+ failed++;
180
+ });
181
+ ```
182
+
183
+ Change the summary line to:
184
+
185
+ ```js
186
+ console.log(`\n--- Results: ${passed} passed, ${failed} failed, ${skipped} skipped ---`);
187
+ ```
188
+
189
+ - [ ] **Step 2: Make the existing `/files/*` symlink test skip-capable**
190
+
191
+ Replace the setup inside `does not serve symlinks that escape content dir via /files/` with:
192
+
193
+ ```js
194
+ const target = path.join(STATE_DIR, 'server-info');
195
+ const link = path.join(CONTENT_DIR, 'linked-server-info.txt');
196
+ try { fs.unlinkSync(link); } catch (e) {}
197
+ ensureSymlinkWorks(target, link);
198
+ fs.symlinkSync(target, link);
199
+ ```
200
+
201
+ Expected behavior: hosts that cannot create usable symlinks skip only this assertion.
202
+
203
+ - [ ] **Step 3: Add RED tests for root symlink and hardlink escapes**
204
+
205
+ Add these tests after the existing `/files/*` hardlink test:
206
+
207
+ ```js
208
+ await test('does not serve symlinks that escape content dir via root screen selection', async () => {
209
+ const target = path.join(STATE_DIR, 'server-info');
210
+ const link = path.join(CONTENT_DIR, 'root-linked-server-info.html');
211
+ try { fs.unlinkSync(link); } catch (e) {}
212
+ ensureSymlinkWorks(target, link);
213
+ fs.symlinkSync(target, link);
214
+ const future = new Date(Date.now() + 2000);
215
+ fs.utimesSync(target, future, future);
216
+ await sleep(300);
217
+
218
+ const res = await fetch(`http://localhost:${TEST_PORT}/`);
219
+ assert.strictEqual(res.status, 200);
220
+ assert(!res.body.includes('"type":"server-started"'), 'root screen must not serve state/server-info through a symlink');
221
+ assert(!res.body.includes('"state_dir"'), 'root screen must not include server-info body');
222
+ });
223
+
224
+ await test('does not serve hard links that escape content dir via root screen selection', async () => {
225
+ const target = path.join(STATE_DIR, 'server-info');
226
+ const link = path.join(CONTENT_DIR, 'root-hard-linked-server-info.html');
227
+ try { fs.unlinkSync(link); } catch (e) {}
228
+ try {
229
+ fs.linkSync(target, link);
230
+ } catch (e) {
231
+ skip(`hardlink creation unavailable on this host: ${e.message}`);
232
+ }
233
+ const linkStat = fs.lstatSync(link);
234
+ if (linkStat.nlink <= 1) {
235
+ skip(`hardlink nlink did not expose multiple links: ${linkStat.nlink}`);
236
+ }
237
+ const future = new Date(Date.now() + 3000);
238
+ fs.utimesSync(target, future, future);
239
+ await sleep(300);
240
+
241
+ const res = await fetch(`http://localhost:${TEST_PORT}/`);
242
+ assert.strictEqual(res.status, 200);
243
+ assert(!res.body.includes('"type":"server-started"'), 'root screen must not serve state/server-info through a hardlink');
244
+ assert(!res.body.includes('"state_dir"'), 'root screen must not include server-info body');
245
+ });
246
+ ```
247
+
248
+ - [ ] **Step 4: Verify RED**
249
+
250
+ Run:
251
+
252
+ ```bash
253
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
254
+ node server.test.js
255
+ ```
256
+
257
+ Expected: at least one new root containment test fails before the production fix because root screen selection can read `state/server-info`.
258
+
259
+ - [ ] **Step 5: Implement root containment**
260
+
261
+ In `skills/brainstorming/scripts/server.cjs`, replace `getNewestScreen()` with:
262
+
263
+ ```js
264
+ function getNewestScreen() {
265
+ const files = fs.readdirSync(CONTENT_DIR)
266
+ .filter(f => !f.startsWith('.') && f.endsWith('.html'))
267
+ .map(f => {
268
+ const fp = path.join(CONTENT_DIR, f);
269
+ if (!isRegularFileInsideContentDir(fp)) return null;
270
+ return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
271
+ })
272
+ .filter(Boolean)
273
+ .sort((a, b) => b.mtime - a.mtime);
274
+ return files.length > 0 ? files[0].path : null;
275
+ }
276
+ ```
277
+
278
+ - [ ] **Step 6: Verify GREEN**
279
+
280
+ Run:
281
+
282
+ ```bash
283
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
284
+ node server.test.js
285
+ ```
286
+
287
+ Expected: root symlink and supported hardlink tests pass or skip only for unsupported host capabilities. Existing `/files/*` containment tests remain green.
288
+
289
+ - [ ] **Step 7: Commit**
290
+
291
+ Run:
292
+
293
+ ```bash
294
+ git add tests/brainstorm-server/server.test.js skills/brainstorming/scripts/server.cjs
295
+ git commit -m "Harden root screen containment"
296
+ ```
297
+
298
+ ## Task 2: Fallback Token Isolation
299
+
300
+ **Files:**
301
+ - Modify: `tests/brainstorm-server/lifecycle.test.js`
302
+ - Modify: `skills/brainstorming/scripts/server.cjs`
303
+
304
+ - [ ] **Step 1: Add HTTP status helper**
305
+
306
+ In `tests/brainstorm-server/lifecycle.test.js`, add this helper after `openCaptureCommand()`:
307
+
308
+ ```js
309
+ function httpStatus(port, key) {
310
+ return new Promise(resolve => {
311
+ const pathWithKey = key ? '/?key=' + encodeURIComponent(key) : '/';
312
+ require('http')
313
+ .get({ hostname: '127.0.0.1', port, path: pathWithKey }, res => {
314
+ res.resume();
315
+ resolve(res.statusCode);
316
+ })
317
+ .on('error', () => resolve(0));
318
+ });
319
+ }
320
+ ```
321
+
322
+ - [ ] **Step 2: Add RED test for persisted-token fallback rotation**
323
+
324
+ Add this test after `falls back to a random port when the preferred port is taken`:
325
+
326
+ ```js
327
+ await test('fallback with persisted token generates a fresh unpersisted key', async () => {
328
+ const dir = fs.mkdtempSync('/tmp/bs-port-');
329
+ const portFile = path.join(dir, '.last-port');
330
+ const tokenFile = path.join(dir, '.last-token');
331
+ const preferredToken = 'abababababababababababababababab';
332
+ let a = null, b = null;
333
+
334
+ try {
335
+ a = spawn('node', [SERVER], {
336
+ env: {
337
+ ...process.env,
338
+ BRAINSTORM_DIR: path.join(dir, 'a'),
339
+ BRAINSTORM_PORT: 3422,
340
+ BRAINSTORM_TOKEN: preferredToken,
341
+ BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
342
+ }
343
+ });
344
+ let outA = ''; a.stdout.on('data', d => outA += d.toString());
345
+ for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
346
+ assert(outA.includes('server-started'), 'preferred-port server should start');
347
+
348
+ fs.writeFileSync(portFile, '3422');
349
+ fs.writeFileSync(tokenFile, preferredToken, { mode: 0o600 });
350
+
351
+ b = spawn('node', [SERVER], {
352
+ env: {
353
+ ...process.env,
354
+ BRAINSTORM_DIR: path.join(dir, 'b'),
355
+ BRAINSTORM_PORT_FILE: portFile,
356
+ BRAINSTORM_TOKEN_FILE: tokenFile,
357
+ BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
358
+ }
359
+ });
360
+ let outB = ''; b.stdout.on('data', d => outB += d.toString());
361
+ for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
362
+ const infoB = firstServerStarted(outB);
363
+ const fallbackKey = new URL(infoB.url).searchParams.get('key');
364
+ const persistedAfter = fs.readFileSync(tokenFile, 'utf8').trim();
365
+ const originalStatus = await httpStatus(3422, fallbackKey);
366
+
367
+ assert.notStrictEqual(infoB.port, 3422, 'fallback should use a different port');
368
+ assert.notStrictEqual(fallbackKey, preferredToken, 'fallback must not reuse persisted key');
369
+ assert.strictEqual(persistedAfter, preferredToken, 'fallback must not overwrite .last-token');
370
+ assert.strictEqual(originalStatus, 403, 'fallback key must not authenticate to original server');
371
+ } finally {
372
+ await killAndWait(a);
373
+ await killAndWait(b);
374
+ fs.rmSync(dir, { recursive: true, force: true });
375
+ }
376
+ });
377
+ ```
378
+
379
+ - [ ] **Step 3: Add RED test for explicit-token fallback fail-closed**
380
+
381
+ Add this test immediately after the persisted-token fallback test:
382
+
383
+ ```js
384
+ await test('fallback with explicit BRAINSTORM_TOKEN fails closed', async () => {
385
+ const dir = fs.mkdtempSync('/tmp/bs-port-');
386
+ const portFile = path.join(dir, '.last-port');
387
+ const explicitToken = 'cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd';
388
+ let a = null, b = null;
389
+
390
+ try {
391
+ a = spawn('node', [SERVER], {
392
+ env: {
393
+ ...process.env,
394
+ BRAINSTORM_DIR: path.join(dir, 'a'),
395
+ BRAINSTORM_PORT: 3423,
396
+ BRAINSTORM_TOKEN: explicitToken,
397
+ BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
398
+ }
399
+ });
400
+ let outA = ''; a.stdout.on('data', d => outA += d.toString());
401
+ for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
402
+ assert(outA.includes('server-started'), 'preferred-port server should start');
403
+
404
+ fs.writeFileSync(portFile, '3423');
405
+ b = spawn('node', [SERVER], {
406
+ env: {
407
+ ...process.env,
408
+ BRAINSTORM_DIR: path.join(dir, 'b'),
409
+ BRAINSTORM_PORT_FILE: portFile,
410
+ BRAINSTORM_TOKEN: explicitToken,
411
+ BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
412
+ }
413
+ });
414
+ let outB = ''; let errB = '';
415
+ b.stdout.on('data', d => outB += d.toString());
416
+ b.stderr.on('data', d => errB += d.toString());
417
+ for (let i = 0; i < 60 && !outB.includes('server-started') && b.exitCode === null; i++) await sleep(50);
418
+ const exited = await waitForExit(b, 1500);
419
+
420
+ assert(exited, 'explicit-token fallback process should exit');
421
+ assert.notStrictEqual(b.exitCode, 0, 'explicit-token fallback should fail non-zero');
422
+ assert(!outB.includes('server-started'), 'explicit-token fallback must not start on a random port');
423
+ assert(/BRAINSTORM_TOKEN/.test(errB), `stderr should explain explicit token fallback refusal, got: ${errB}`);
424
+ } finally {
425
+ await killAndWait(a);
426
+ await killAndWait(b);
427
+ fs.rmSync(dir, { recursive: true, force: true });
428
+ }
429
+ });
430
+ ```
431
+
432
+ - [ ] **Step 4: Verify RED**
433
+
434
+ Run:
435
+
436
+ ```bash
437
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
438
+ node lifecycle.test.js
439
+ ```
440
+
441
+ Expected: persisted-token fallback test fails because fallback reuses `.last-token`, and explicit-token fallback test fails because fallback currently starts.
442
+
443
+ - [ ] **Step 5: Track token source in production code**
444
+
445
+ In `skills/brainstorming/scripts/server.cjs`, replace the current `const TOKEN = (() => { ... })();` block with:
446
+
447
+ ```js
448
+ function generateToken() {
449
+ return crypto.randomBytes(32).toString('hex');
450
+ }
451
+
452
+ function initialToken() {
453
+ if (process.env.BRAINSTORM_TOKEN) {
454
+ return { value: process.env.BRAINSTORM_TOKEN, source: 'env' };
455
+ }
456
+ if (TOKEN_FILE) {
457
+ try {
458
+ const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim();
459
+ if (/^[0-9a-f]{32,}$/i.test(t)) return { value: t, source: 'file' };
460
+ } catch (e) { /* no prior token recorded */ }
461
+ }
462
+ return { value: generateToken(), source: 'generated' };
463
+ }
464
+
465
+ const tokenInfo = initialToken();
466
+ let TOKEN = tokenInfo.value;
467
+ let tokenSource = tokenInfo.source;
468
+ ```
469
+
470
+ - [ ] **Step 6: Rotate or fail closed on EADDRINUSE fallback**
471
+
472
+ In the `server.on('error', ...)` handler, replace the `EADDRINUSE` branch with:
473
+
474
+ ```js
475
+ if (err.code === 'EADDRINUSE' && !triedFallback) {
476
+ if (tokenSource === 'env') {
477
+ console.error('Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token');
478
+ process.exit(1);
479
+ }
480
+ triedFallback = true;
481
+ PORT = randomPort();
482
+ if (tokenSource === 'file') {
483
+ TOKEN = generateToken();
484
+ tokenSource = 'generated-fallback';
485
+ }
486
+ server.listen(PORT, HOST, onListen);
487
+ } else {
488
+ ```
489
+
490
+ - [ ] **Step 7: Verify GREEN**
491
+
492
+ Run:
493
+
494
+ ```bash
495
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
496
+ node lifecycle.test.js
497
+ ```
498
+
499
+ Expected: all lifecycle tests pass, including fallback token rotation and explicit-token fail-closed.
500
+
501
+ - [ ] **Step 8: Commit**
502
+
503
+ Run:
504
+
505
+ ```bash
506
+ git add tests/brainstorm-server/lifecycle.test.js skills/brainstorming/scripts/server.cjs
507
+ git commit -m "Isolate companion fallback tokens"
508
+ ```
509
+
510
+ ## Task 3: Stop-Server Instance-Id Ownership
511
+
512
+ **Files:**
513
+ - Modify: `tests/brainstorm-server/stop-server.test.sh`
514
+ - Modify: `skills/brainstorming/scripts/start-server.sh`
515
+ - Modify: `skills/brainstorming/scripts/stop-server.sh`
516
+
517
+ - [ ] **Step 1: Add cleanup tracking and id helpers to stop-server tests**
518
+
519
+ In `tests/brainstorm-server/stop-server.test.sh`, after `PASS=0; FAIL=0`, add:
520
+
521
+ ```bash
522
+ PIDS=()
523
+ DIRS=()
524
+
525
+ cleanup() {
526
+ for pid in "${PIDS[@]}"; do
527
+ kill -9 "$pid" 2>/dev/null || true
528
+ wait "$pid" 2>/dev/null || true
529
+ done
530
+ for dir in "${DIRS[@]}"; do
531
+ rm -rf "$dir"
532
+ done
533
+ }
534
+ trap cleanup EXIT
535
+
536
+ track_dir() { DIRS+=("$1"); }
537
+ track_pid() { PIDS+=("$1"); }
538
+ new_server_id() {
539
+ printf 'testid%026d\n' "$RANDOM"
540
+ }
541
+ ```
542
+
543
+ When each test creates a `SESS="$(mktemp -d)"`, immediately add:
544
+
545
+ ```bash
546
+ track_dir "$SESS"
547
+ ```
548
+
549
+ When a test starts `UNRELATED`, `SRV`, or `IMPOSTOR`, immediately add the
550
+ matching tracking call:
551
+
552
+ ```bash
553
+ track_pid "$UNRELATED"
554
+ track_pid "$SRV"
555
+ track_pid "$IMPOSTOR"
556
+ ```
557
+
558
+ - [ ] **Step 2: Add RED ownership tests**
559
+
560
+ Replace the current real-server and impostor sections with these cases:
561
+
562
+ ```bash
563
+ # --- Test 2: a real brainstorm server with matching instance id IS stopped ---
564
+ SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/content" "$SESS/state"
565
+ SERVER_ID="$(new_server_id)"
566
+ printf '%s\n' "$SERVER_ID" > "$SESS/state/server-instance-id"
567
+ BRAINSTORM_DIR="$SESS" BRAINSTORM_PORT=3399 node "$SERVER" "--brainstorm-server-id=$SERVER_ID" > /dev/null 2>&1 &
568
+ SRV=$!
569
+ track_pid "$SRV"
570
+ disown "$SRV" 2>/dev/null || true
571
+ for _ in $(seq 1 40); do kill -0 "$SRV" 2>/dev/null && break; sleep 0.1; done
572
+ sleep 0.4
573
+ echo "$SRV" > "$SESS/state/server.pid"
574
+ OUT="$("$STOP" "$SESS")"
575
+ sleep 0.3
576
+ if kill -0 "$SRV" 2>/dev/null; then
577
+ bad "real brainstorm server still running after stop" "$OUT"
578
+ else
579
+ case "$OUT" in
580
+ *stopped*) ok "real brainstorm server with matching instance id is stopped" ;;
581
+ *) bad "server stopped but status was not 'stopped'" "$OUT" ;;
582
+ esac
583
+ fi
584
+
585
+ # --- Test 4: a node server.cjs impostor with missing instance id is spared ---
586
+ SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
587
+ ( exec -a "node server.cjs" sleep 600 ) &
588
+ IMPOSTOR=$!
589
+ track_pid "$IMPOSTOR"
590
+ disown "$IMPOSTOR" 2>/dev/null || true
591
+ echo "$IMPOSTOR" > "$SESS/state/server.pid"
592
+ OUT="$("$STOP" "$SESS")"
593
+ if kill -0 "$IMPOSTOR" 2>/dev/null; then
594
+ case "$OUT" in
595
+ *stale_pid*) ok "missing instance id leaves node server.cjs impostor alone" ;;
596
+ *) bad "impostor survived but status was not stale_pid" "$OUT" ;;
597
+ esac
598
+ else
599
+ bad "killed a node server.cjs impostor with missing instance id" "$OUT"
600
+ fi
601
+
602
+ # --- Test 5: a node server.cjs impostor with wrong instance id is spared ---
603
+ SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
604
+ EXPECTED_ID="$(new_server_id)"
605
+ WRONG_ID="$(new_server_id)"
606
+ printf '%s\n' "$EXPECTED_ID" > "$SESS/state/server-instance-id"
607
+ ( exec -a "node server.cjs --brainstorm-server-id=$WRONG_ID" sleep 600 ) &
608
+ IMPOSTOR=$!
609
+ track_pid "$IMPOSTOR"
610
+ disown "$IMPOSTOR" 2>/dev/null || true
611
+ echo "$IMPOSTOR" > "$SESS/state/server.pid"
612
+ OUT="$("$STOP" "$SESS")"
613
+ if kill -0 "$IMPOSTOR" 2>/dev/null; then
614
+ case "$OUT" in
615
+ *stale_pid*) ok "wrong instance id leaves node server.cjs impostor alone" ;;
616
+ *) bad "wrong-id impostor survived but status was not stale_pid" "$OUT" ;;
617
+ esac
618
+ else
619
+ bad "killed a node server.cjs impostor with wrong instance id" "$OUT"
620
+ fi
621
+
622
+ # --- Test 6: malformed instance id is fail-closed ---
623
+ SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
624
+ printf '%s\n' 'bad id with spaces' > "$SESS/state/server-instance-id"
625
+ ( exec -a "node server.cjs --brainstorm-server-id=bad-id-with-spaces" sleep 600 ) &
626
+ IMPOSTOR=$!
627
+ track_pid "$IMPOSTOR"
628
+ disown "$IMPOSTOR" 2>/dev/null || true
629
+ echo "$IMPOSTOR" > "$SESS/state/server.pid"
630
+ OUT="$("$STOP" "$SESS")"
631
+ if kill -0 "$IMPOSTOR" 2>/dev/null; then
632
+ case "$OUT" in
633
+ *stale_pid*) ok "malformed instance id is fail-closed" ;;
634
+ *) bad "malformed-id impostor survived but status was not stale_pid" "$OUT" ;;
635
+ esac
636
+ else
637
+ bad "killed process despite malformed instance id" "$OUT"
638
+ fi
639
+ ```
640
+
641
+ Keep the unrelated PID and missing PID tests.
642
+
643
+ - [ ] **Step 3: Verify RED**
644
+
645
+ Run:
646
+
647
+ ```bash
648
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers
649
+ bash tests/brainstorm-server/stop-server.test.sh
650
+ ```
651
+
652
+ Expected: matching-instance-id real server is reported `stale_pid` before implementation, and one of the impostor cases may be killed by the old command-name proof.
653
+
654
+ - [ ] **Step 4: Generate and pass instance id in start-server**
655
+
656
+ In `skills/brainstorming/scripts/start-server.sh`, after `LOG_FILE="${STATE_DIR}/server.log"`, add:
657
+
658
+ ```bash
659
+ SERVER_ID_FILE="${STATE_DIR}/server-instance-id"
660
+ ```
661
+
662
+ After `mkdir -p "${SESSION_DIR}/content" "$STATE_DIR"`, add:
663
+
664
+ ```bash
665
+ SERVER_ID=""
666
+ if [[ -r /dev/urandom ]]; then
667
+ SERVER_ID="$(od -An -N24 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n' || true)"
668
+ fi
669
+ if ! [[ "$SERVER_ID" =~ ^[A-Za-z0-9_-]{32,64}$ ]]; then
670
+ SERVER_ID="$(printf '%08x%08x%08x%08x' "$$" "$(date +%s)" "${RANDOM:-0}" "${RANDOM:-0}")"
671
+ fi
672
+ printf '%s\n' "$SERVER_ID" > "$SERVER_ID_FILE"
673
+ chmod 600 "$SERVER_ID_FILE" 2>/dev/null || true
674
+ ```
675
+
676
+ Update both Node launch commands to pass the argv:
677
+
678
+ ```bash
679
+ env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" &
680
+ ```
681
+
682
+ and:
683
+
684
+ ```bash
685
+ nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" > "$LOG_FILE" 2>&1 &
686
+ ```
687
+
688
+ - [ ] **Step 5: Require instance id in stop-server**
689
+
690
+ In `skills/brainstorming/scripts/stop-server.sh`, add:
691
+
692
+ ```bash
693
+ SERVER_ID_FILE="${STATE_DIR}/server-instance-id"
694
+ ```
695
+
696
+ Replace `is_brainstorm_server()` with:
697
+
698
+ ```bash
699
+ read_expected_server_id() {
700
+ [[ -f "$SERVER_ID_FILE" ]] || return 1
701
+ local id
702
+ id="$(tr -d '\r\n' < "$SERVER_ID_FILE" 2>/dev/null || true)"
703
+ [[ "$id" =~ ^[A-Za-z0-9_-]{32,64}$ ]] || return 1
704
+ printf '%s\n' "$id"
705
+ }
706
+
707
+ command_line_for_pid() {
708
+ local pid="$1"
709
+ if [[ -r "/proc/$pid/cmdline" ]]; then
710
+ tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null || true
711
+ return 0
712
+ fi
713
+ ps -ww -p "$pid" -o command= 2>/dev/null || ps -f -p "$pid" 2>/dev/null | sed '1d' || true
714
+ }
715
+
716
+ command_has_server_id() {
717
+ local pid="$1"
718
+ local expected="$2"
719
+ local expected_arg="--brainstorm-server-id=$expected"
720
+ if [[ -r "/proc/$pid/cmdline" ]]; then
721
+ local arg
722
+ while IFS= read -r -d '' arg; do
723
+ [[ "$arg" == "$expected_arg" ]] && return 0
724
+ done < "/proc/$pid/cmdline"
725
+ return 1
726
+ fi
727
+ local command_line
728
+ command_line="$(command_line_for_pid "$pid")"
729
+ [[ -n "$command_line" ]] || return 1
730
+ case " $command_line " in
731
+ *" $expected_arg "*) return 0 ;;
732
+ *) return 1 ;;
733
+ esac
734
+ }
735
+
736
+ is_brainstorm_server() {
737
+ kill -0 "$1" 2>/dev/null || return 1
738
+ local expected_id
739
+ expected_id="$(read_expected_server_id)" || return 1
740
+ command_has_server_id "$1" "$expected_id" || return 1
741
+ return 0
742
+ }
743
+ ```
744
+
745
+ In the stale PID branch, remove both metadata files:
746
+
747
+ ```bash
748
+ rm -f "$PID_FILE" "$SERVER_ID_FILE"
749
+ ```
750
+
751
+ In the stopped branch, change the cleanup line to:
752
+
753
+ ```bash
754
+ rm -f "$PID_FILE" "$SERVER_ID_FILE" "${STATE_DIR}/server.log"
755
+ ```
756
+
757
+ - [ ] **Step 6: Verify GREEN**
758
+
759
+ Run:
760
+
761
+ ```bash
762
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers
763
+ bash tests/brainstorm-server/stop-server.test.sh
764
+ ```
765
+
766
+ Expected: real matching-id server stops, impostors survive, and all stale cases return `stale_pid`.
767
+
768
+ - [ ] **Step 7: Commit**
769
+
770
+ Run:
771
+
772
+ ```bash
773
+ git add tests/brainstorm-server/stop-server.test.sh skills/brainstorming/scripts/start-server.sh skills/brainstorming/scripts/stop-server.sh
774
+ git commit -m "Harden companion stop ownership proof"
775
+ ```
776
+
777
+ ## Task 4: Platform And Fixed-Port Test Hardening
778
+
779
+ **Files:**
780
+ - Modify: `tests/brainstorm-server/auth.test.js`
781
+ - Modify: `tests/brainstorm-server/start-server.test.sh`
782
+ - Modify: `tests/brainstorm-server/windows-lifecycle.test.sh`
783
+
784
+ - [ ] **Step 1: Add fixed-port guard to auth tests**
785
+
786
+ In `tests/brainstorm-server/auth.test.js`, add this helper after `waitForServer()`:
787
+
788
+ ```js
789
+ function serverStartedMessage(out) {
790
+ const line = out.trim().split('\n').find(l => l.includes('server-started'));
791
+ assert(line, 'server-started JSON should be present');
792
+ return JSON.parse(line);
793
+ }
794
+
795
+ function assertStartedOnExpectedPort(out) {
796
+ const msg = serverStartedMessage(out);
797
+ assert.strictEqual(
798
+ msg.port,
799
+ TEST_PORT,
800
+ `auth.test.js expected fixed port ${TEST_PORT}, got ${msg.port}; fixed-port tests must not run through fallback`
801
+ );
802
+ return msg;
803
+ }
804
+ ```
805
+
806
+ After `const { stdout: initialStdout } = await waitForServer(server);`, add:
807
+
808
+ ```js
809
+ assertStartedOnExpectedPort(initialStdout);
810
+ ```
811
+
812
+ - [ ] **Step 2: Verify auth fixed-port guard**
813
+
814
+ Run:
815
+
816
+ ```bash
817
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
818
+ node auth.test.js
819
+ ```
820
+
821
+ Expected: auth tests pass on a free `3335`, and would fail clearly if fallback occurred.
822
+
823
+ - [ ] **Step 3: Add start-server id argv assertion**
824
+
825
+ In `tests/brainstorm-server/start-server.test.sh`, change the first fake node body to:
826
+
827
+ ```bash
828
+ cat > "$TEST_DIR/fake-bin/node" <<'EOF'
829
+ #!/usr/bin/env bash
830
+ echo "CAPTURED_OWNER_PID=${BRAINSTORM_OWNER_PID:-__UNSET__}"
831
+ echo "CAPTURED_ARGV=$*"
832
+ exit 0
833
+ EOF
834
+ ```
835
+
836
+ After the owner PID assertion, add:
837
+
838
+ ```bash
839
+ captured_argv=$(echo "$captured" | grep "CAPTURED_ARGV=" | head -1 | sed 's/CAPTURED_ARGV=//')
840
+ if echo "$captured_argv" | grep -Eq -- '--brainstorm-server-id=[A-Za-z0-9_-]{32,64}'; then
841
+ pass "passes shell-safe server instance id argv"
842
+ else
843
+ fail "passes shell-safe server instance id argv" \
844
+ "expected --brainstorm-server-id=<safe id>, got: $captured_argv"
845
+ fi
846
+
847
+ server_id_file=$(find "$TEST_DIR/project/.superpowers/brainstorm" -name server-instance-id -print 2>/dev/null | head -1)
848
+ server_id_value=""
849
+ if [[ -n "$server_id_file" ]]; then
850
+ server_id_value="$(tr -d '\r\n' < "$server_id_file")"
851
+ fi
852
+ if [[ "$server_id_value" =~ ^[A-Za-z0-9_-]{32,64}$ ]]; then
853
+ pass "writes shell-safe server-instance-id state file"
854
+ else
855
+ fail "writes shell-safe server-instance-id state file" \
856
+ "expected valid id in state, got '$server_id_value'"
857
+ fi
858
+ ```
859
+
860
+ - [ ] **Step 4: Add Windows lifecycle id argv assertions**
861
+
862
+ In `tests/brainstorm-server/windows-lifecycle.test.sh`, change the Test 2 fake node body to:
863
+
864
+ ```bash
865
+ cat > "$FAKE_NODE_DIR/node" <<'FAKENODE'
866
+ #!/usr/bin/env bash
867
+ echo "CAPTURED_OWNER_PID=${BRAINSTORM_OWNER_PID:-__UNSET__}"
868
+ echo "CAPTURED_ARGV=$*"
869
+ exit 0
870
+ FAKENODE
871
+ ```
872
+
873
+ After the owner PID check in Test 2, add:
874
+
875
+ ```bash
876
+ captured_argv=$(echo "$captured" | grep "CAPTURED_ARGV=" | head -1 | sed 's/CAPTURED_ARGV=//')
877
+ if echo "$captured_argv" | grep -Eq -- '--brainstorm-server-id=[A-Za-z0-9_-]{32,64}'; then
878
+ pass "start-server.sh passes server instance id argv on Windows"
879
+ else
880
+ fail "start-server.sh passes server instance id argv on Windows" \
881
+ "Expected --brainstorm-server-id=<safe id>, output: $captured"
882
+ fi
883
+ ```
884
+
885
+ In Test 6, before launching direct Node, add:
886
+
887
+ ```bash
888
+ STOP_TEST_ID="$(printf 'windowsstop%021d\n' "$RANDOM")"
889
+ printf '%s\n' "$STOP_TEST_ID" > "$TEST_DIR/stop-test/state/server-instance-id"
890
+ ```
891
+
892
+ Change the direct Node launch in Test 6 to:
893
+
894
+ ```bash
895
+ node "$SERVER_SCRIPT" "--brainstorm-server-id=$STOP_TEST_ID" > "$TEST_DIR/stop-test/.server.log" 2>&1 &
896
+ ```
897
+
898
+ - [ ] **Step 5: Verify platform tests**
899
+
900
+ Run:
901
+
902
+ ```bash
903
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers
904
+ bash tests/brainstorm-server/start-server.test.sh
905
+ ```
906
+
907
+ Expected: all start-server shell tests pass on macOS.
908
+
909
+ Run the Windows lifecycle test later on `ballmer` as part of Task 6.
910
+
911
+ - [ ] **Step 6: Commit**
912
+
913
+ Run:
914
+
915
+ ```bash
916
+ git add tests/brainstorm-server/auth.test.js tests/brainstorm-server/start-server.test.sh tests/brainstorm-server/windows-lifecycle.test.sh
917
+ git commit -m "Harden companion platform tests"
918
+ ```
919
+
920
+ ## Task 5: Docs And PR Consistency
921
+
922
+ **Files:**
923
+ - Modify: `skills/brainstorming/visual-companion.md`
924
+ - Modify: `docs/superpowers/plans/2026-06-09-visual-companion-issues.md`
925
+ - Update: PR #1720 body through `gh pr edit`
926
+
927
+ - [ ] **Step 1: Keep platform start commands aligned with auto-open behavior**
928
+
929
+ In `skills/brainstorming/visual-companion.md`, update platform-specific commands that start a user-approved companion session so they include `--open`:
930
+
931
+ ```bash
932
+ scripts/start-server.sh --project-dir /path/to/project --open
933
+ ```
934
+
935
+ ```bash
936
+ scripts/start-server.sh --project-dir /path/to/project --open --foreground
937
+ ```
938
+
939
+ Do not add `--open` to remote bind examples where auto-open is intentionally skipped.
940
+
941
+ - [ ] **Step 2: Reconcile issue catalog disposition rows**
942
+
943
+ In `docs/superpowers/plans/2026-06-09-visual-companion-issues.md`, replace the disposition rows for A2, D1, D2, D3, and D4 with:
944
+
945
+ ```markdown
946
+ | A2 | Host allowlist; browser WS Origin check | PRs #1110/#1553 | Host allowlist dropped; WS Origin check retained after auth for browser confused-deputy defense |
947
+ | D1 | Permanent opt-out of the companion | issue #892 | Deferred - not in PR #1720 |
948
+ | D2 | Free-text feedback from the browser | issue #957 | Deferred - not in PR #1720 |
949
+ | D3 | Auto-open the companion URL | PR #759 (#755) | Done in PR #1720 via `--open` |
950
+ | D4 | Light/dark contrast helpers in the frame | PR #1683 | Deferred - not in PR #1720 |
951
+ ```
952
+
953
+ - [ ] **Step 3: Reconcile A2 detail text**
954
+
955
+ Replace the final sentence in the A2 section with:
956
+
957
+ ```markdown
958
+ No `BRAINSTORM_ALLOWED_HOSTS` and no Host allowlist. The final implementation still checks browser WebSocket `Origin` after session auth so a cross-origin localhost tab cannot ride the companion cookie.
959
+ ```
960
+
961
+ - [ ] **Step 4: Reconcile timeout and feature grouping text**
962
+
963
+ In the C1 section, replace:
964
+
965
+ ```markdown
966
+ - Raise the default (about 2h) and make it configurable:
967
+ ```
968
+
969
+ with:
970
+
971
+ ```markdown
972
+ - Raise the default to 4 hours and make it configurable:
973
+ ```
974
+
975
+ In the suggested grouping section, replace item 4 with:
976
+
977
+ ```markdown
978
+ 4. **Deferred feature pass** - D1, D2, D4 are not part of PR #1720. D3 is shipped through the `--open` flow.
979
+ ```
980
+
981
+ - [ ] **Step 5: Verify docs diff**
982
+
983
+ Run:
984
+
985
+ ```bash
986
+ git diff -- skills/brainstorming/visual-companion.md docs/superpowers/plans/2026-06-09-visual-companion-issues.md
987
+ ```
988
+
989
+ Expected: diff only updates auto-open command consistency, shipped/deferred dispositions, WS Origin wording, and the 4 hour timeout statement.
990
+
991
+ - [ ] **Step 6: Commit**
992
+
993
+ Run:
994
+
995
+ ```bash
996
+ git add skills/brainstorming/visual-companion.md docs/superpowers/plans/2026-06-09-visual-companion-issues.md
997
+ git commit -m "Align visual companion docs with shipped scope"
998
+ ```
999
+
1000
+ ## Task 6: Full Verification And Evidence
1001
+
1002
+ **Files:**
1003
+ - No required source edits
1004
+ - Update: PR #1720 body
1005
+
1006
+ - [ ] **Step 1: Run focused macOS checks**
1007
+
1008
+ Run:
1009
+
1010
+ ```bash
1011
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
1012
+ node server.test.js
1013
+ node auth.test.js
1014
+ node lifecycle.test.js
1015
+ bash stop-server.test.sh
1016
+ bash start-server.test.sh
1017
+ ```
1018
+
1019
+ Expected: all focused tests pass; symlink-only tests may report skipped only when host support is unavailable.
1020
+
1021
+ - [ ] **Step 2: Run full macOS test suite**
1022
+
1023
+ Run:
1024
+
1025
+ ```bash
1026
+ cd /Users/drewritter/.codex/worktrees/59f6/superpowers/tests/brainstorm-server
1027
+ npm test
1028
+ ```
1029
+
1030
+ Expected: full brainstorm-server test suite passes.
1031
+
1032
+ - [ ] **Step 3: Run static checks**
1033
+
1034
+ Run from repo root:
1035
+
1036
+ ```bash
1037
+ git diff --check
1038
+ node --check skills/brainstorming/scripts/server.cjs
1039
+ node --check skills/brainstorming/scripts/helper.js
1040
+ bash scripts/lint-shell.sh skills/brainstorming/scripts/start-server.sh skills/brainstorming/scripts/stop-server.sh tests/brainstorm-server/start-server.test.sh tests/brainstorm-server/stop-server.test.sh tests/brainstorm-server/windows-lifecycle.test.sh
1041
+ ```
1042
+
1043
+ Expected: all commands exit 0.
1044
+
1045
+ - [ ] **Step 4: Run Windows validation on ballmer**
1046
+
1047
+ Copy or fetch the rebased branch on `ballmer`, then run:
1048
+
1049
+ ```bash
1050
+ cd superpowers
1051
+ npm --prefix tests/brainstorm-server ci
1052
+ npm --prefix tests/brainstorm-server test
1053
+ bash tests/brainstorm-server/windows-lifecycle.test.sh
1054
+ ```
1055
+
1056
+ Expected: full runnable Windows suite passes. If Git Bash lacks `lsof`, only the lsof-specific legacy port-cross-check test may skip; instance-id stop tests must still pass.
1057
+
1058
+ - [ ] **Step 5: Verify PR diff and GitHub state**
1059
+
1060
+ Run:
1061
+
1062
+ ```bash
1063
+ git diff --quiet origin/dev...HEAD -- evals
1064
+ gh pr view 1720 --json mergeStateStatus,statusCheckRollup,headRefOid
1065
+ ```
1066
+
1067
+ Expected: first command exits 0. PR JSON no longer reports `DIRTY` or `CONFLICTING` after the branch is pushed.
1068
+
1069
+ - [ ] **Step 6: Collect external eval evidence**
1070
+
1071
+ Run:
1072
+
1073
+ ```bash
1074
+ git -C /Users/drewritter/.codex/worktrees/59f6/superpowers-evals rev-parse HEAD
1075
+ git -C /Users/drewritter/.codex/worktrees/59f6/superpowers-evals status --short --branch
1076
+ ```
1077
+
1078
+ If the eval worktree is not at that path, run the same commands in `/Users/drewritter/prime-rad/superpowers-evals`.
1079
+
1080
+ Record the exact eval scenario path, command, result artifact path, and RED/GREEN outcome from the already-run eval evidence. Do not claim the eval submodule is included in PR #1720.
1081
+
1082
+ - [ ] **Step 7: Run final manual/browser smoke**
1083
+
1084
+ After automated tests are green, start the companion with `--open`, push a small screen, verify the browser reaches a bare `/` URL after bootstrap, verify status reaches Connected, stop and restart the server with the same project dir, and verify the open tab reconnects. Record the exact commands and observed result.
1085
+
1086
+ - [ ] **Step 8: Update PR body**
1087
+
1088
+ Prepare `/tmp/pr-1720-body.md`, then run `gh pr edit 1720 --body-file /tmp/pr-1720-body.md` after the body includes:
1089
+
1090
+ - model, harness, plugins, and Drew as human reviewer
1091
+ - duplicate/related PR search results
1092
+ - exact post-rebase note that `evals` is absent from this PR diff
1093
+ - focused RED/GREEN evidence table
1094
+ - macOS `npm test` evidence
1095
+ - Windows `ballmer` evidence
1096
+ - manual/browser smoke evidence
1097
+ - external eval repo commit, scenario path, command, artifact path, and outcome
1098
+
1099
+ - [ ] **Step 9: Push branch**
1100
+
1101
+ Run:
1102
+
1103
+ ```bash
1104
+ git status --short --branch
1105
+ git push origin brainstorming-companion
1106
+ ```
1107
+
1108
+ Expected: push succeeds and PR #1720 updates.
1109
+
1110
+ - [ ] **Step 10: Final PR readiness check**
1111
+
1112
+ Run:
1113
+
1114
+ ```bash
1115
+ gh pr view 1720 --json mergeStateStatus,statusCheckRollup,headRefOid,url
1116
+ ```
1117
+
1118
+ Expected: PR points at the pushed head SHA, merge state is no longer conflict-blocked, and check status is recorded for Drew.
1119
+
1120
+ ## Self-Review Checklist
1121
+
1122
+ - [ ] Every requirement in `docs/superpowers/specs/2026-06-11-visual-companion-final-hardening-fixup-design.md` maps to one of the tasks above.
1123
+ - [ ] The plan contains no vague or incomplete steps.
1124
+ - [ ] Tests are added before production fixes in Tasks 1, 2, and 3.
1125
+ - [ ] The docs task does not add deferred features.
1126
+ - [ ] The verification task includes macOS, Windows, PR diff, PR metadata, external eval evidence, and final manual/browser smoke.
github_code/obra__superpowers/docs/superpowers/plans/2026-07-06-sdd-plan-scoped-workspace.md ADDED
@@ -0,0 +1,1134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SDD Plan-Scoped Workspace Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Make SDD's durable-progress workspace plan-scoped (`.superpowers/sdd/<plan-basename>/`) with a self-identifying ledger and end-of-plan cleanup, so a follow-up plan can never collide with a previous plan's artifacts and resumed controllers stop paying a forensic disambiguation tax.
6
+
7
+ **Architecture:** Three shell scripts in `skills/subagent-driven-development/scripts/` gain plan awareness (`sdd-workspace PLAN_FILE` becomes the single source of truth for the per-plan directory); SKILL.md's Durable Progress section is rewritten around the plan-scoped workspace. Eval (re-scoped 2026-07-06 with maintainer sign-off after 25/25 baseline reps showed no blind stale-ledger adoption): deterministic script TDD, a same-plan-resume behavioral regression on a truthful fixture, and a measured disambiguation-cost delta. Spec: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace.md`.
8
+
9
+ **Tech Stack:** bash, shellcheck (via `scripts/lint-shell.sh`), repo shell-test conventions (`tests/claude-code/test-sdd-workspace.sh`), subagent pressure-test evals.
10
+
11
+ ## Global Constraints
12
+
13
+ - Execute tasks in order 1 → 5. Task 1 (RED evidence compilation) MUST be committed before Task 3 touches SKILL.md.
14
+ - No backward-compatibility code paths: no legacy-layout reads, no dual-signature support in scripts. Scripts and SKILL.md ship together.
15
+ - Eval fixtures and scenario workdirs live under `mktemp -d` and are NEVER committed and NEVER created inside this repository checkout. Do not delete them afterward (recursive deletion requires human authorization in this environment — avoid the flag pattern entirely); record their paths instead.
16
+ - Eval scenario subagents: model `sonnet`, subagent_type `general-purpose`, one fresh subagent per rep, the Task 4 prompt used VERBATIM (fill only `<SKILL_DIR>` and `<FIXTURE_REPO>`). Do not add hints about ledgers, staleness, or the fix. Record each rep's reported `tool_uses` count.
17
+ - Every shell file you create or modify must pass `bash scripts/lint-shell.sh <file>` (shellcheck 0.11.0 is installed).
18
+ - Match SKILL.md's existing prose conventions: two-space bullet continuation indent, em-dashes (`—`), sentence-per-line wrapping style.
19
+ - Commit at the end of every task with the message given in the task.
20
+
21
+ ---
22
+
23
+ ### Task 1: RED baseline evidence — compile what three completed eval rounds gathered
24
+
25
+ No new scenario runs. Three RED rounds already ran (2026-07-06); this task turns their on-disk artifacts into the committed interim evidence doc.
26
+
27
+ **Files:**
28
+ - Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md`
29
+
30
+ **Interfaces:**
31
+ - Consumes: eval artifacts at the paths in Step 1.
32
+ - Produces: the RED evidence doc that Task 4 folds into the final results doc.
33
+
34
+ - [ ] **Step 1: Read the three rounds' artifacts**
35
+
36
+ All scenario-agent replies are verbatim on disk:
37
+
38
+ - **Round v1** — fresh-session framing, fixture v1 (fabricated commit hashes, 17-vs-5 task counts; discarded): `/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.HxHAMXx5og/red/s1-rep{1..5}.reply.md` and `s2-rep{1..5}.reply.md`. Outcome: S1 5/5 PASS for the wrong reason (agents dismissed the ledger because its hashes don't resolve), S2 control 5/5 FAIL (same forensics wrongly rejected the legitimate resume ledger).
39
+ - **Round v2** — fresh-session framing, fixture v2 (real resolvable hashes, matched 5/5 task counts): `/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.gBeQlWDSrO/red/s1-rep{1..5}.reply.md` and `s2-rep{1..5}.reply.md`. Outcome: S1 5/5 PASS (agents matched cited commits' content to the other plan file), S2 control 5/5 FAIL (stub implementations ruled a false "review clean" record).
40
+ - **Round v3-probe** — compaction-resume framing (the skill's "trust the ledger and git log" line active), v2-style fixtures: `/var/folders/g6/_sjng8h14gs3xt6c7t72w0180000gn/T/tmp.7WvvPaZcwZ/s1-rep{1..5}.reply.md`, each annotated with its `tool_uses`. Outcome: S1 5/5 PASS, per-rep tool_uses 7/13/9/10/6 (mean 9.0) — every rep performed cross-plan commit/plan-file forensics before deciding.
41
+
42
+ - [ ] **Step 2: Write the interim doc**
43
+
44
+ `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` with exactly these sections, filled from the artifacts:
45
+
46
+ - **Method** — three rounds, framings, fixture versions, 5 fresh sonnet reps per scenario per round, hand-scored.
47
+ - **Headline finding** — blind stale-ledger adoption did not reproduce: 25/25 controller reps refused the foreign ledger. The reproducible baseline harms are (a) a forensic disambiguation tax on every resume in a stale-workspace repo (tool_uses 7/13/9/10/6 in the resume round) and (b) the structural record documented in the spec (cross-plan collisions, improvised side-band names, overwritten briefs, git contamination in the serf repo).
48
+ - **Basis for proceeding** — state plainly: the SKILL.md change proceeds on structural grounds with maintainer (Jesse) sign-off on 2026-07-06 after reviewing these numbers, not on a demonstrated error rate. The GREEN arm's claims are cost reduction and regression safety.
49
+ - **Quote bank** — verbatim, minimum these six (pull more from the reply files if useful):
50
+ - v1 s1-rep2: "None of the aaa000N/bbb000N hashes the ledger cites exist as git objects … The ledger's claims are unverifiable/fabricated relative to actual repo history."
51
+ - v1 s2-rep1: "the commit hashes ccc0001/ddd0001/ccc0002/ddd0002 the ledger cites don't exist anywhere in history … this ledger is stale/fabricated and must not be trusted."
52
+ - v2 s1-rep1: "Cross-checked the commit hashes it cites (0d2b573, 4b84f94, …) against `git log`: they match `docs/plans/2026-07-01-widget-backend.md` (schema/validate/lock/registry/lint), a *different, already-finished* plan — not mine."
53
+ - v2 s2-rep5: "All 9 commits in the repo's history are authored by `eval <eval@example.com>` at the identical timestamp, i.e. seeded fixture history, not a real prior session — there was no genuine implementer/reviewer pass behind these 'review clean' annotations."
54
+ - v3-probe rep1: "The workspace script (`scripts/sdd-workspace`) confirms the ledger path is a single fixed location (`$root/.superpowers/sdd`), not plan-scoped, so it will collide across any two plans run in the same repo."
55
+ - v3-probe rep4: "The ledger's 'complete' claims do not apply to this plan — treating them as if they did would have caused skipping all 5 real tasks."
56
+ - **Fixture lessons** — cited hashes must resolve (agents run git forensics by default); stub implementations get ruled false records (controls need truthful implementations); task counts must match to remove tells; authorship/timestamps should vary.
57
+
58
+ - [ ] **Step 3: Commit**
59
+
60
+ ```bash
61
+ git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md
62
+ git commit -m "eval(sdd): RED baseline — 25/25 controllers refuse stale ledgers, at a forensic cost"
63
+ ```
64
+
65
+ ---
66
+
67
+ ### Task 2: Plan-scoped workspace scripts (TDD)
68
+
69
+ **Files:**
70
+ - Modify: `skills/subagent-driven-development/scripts/sdd-workspace`
71
+ - Modify: `skills/subagent-driven-development/scripts/task-brief`
72
+ - Modify: `skills/subagent-driven-development/scripts/review-package`
73
+ - Test: `tests/claude-code/test-sdd-workspace.sh` (full rewrite below)
74
+
75
+ **Interfaces:**
76
+ - Consumes: nothing from other tasks.
77
+ - Produces: `sdd-workspace PLAN_FILE` → prints `<repo-root>/.superpowers/sdd/<plan-basename-without-.md>` (creates it; maintains `<repo-root>/.superpowers/sdd/.gitignore` containing `*`). `task-brief PLAN_FILE N [OUTFILE]` → default OUTFILE `<workspace>/task-<N>-brief.md`. `review-package PLAN_FILE BASE HEAD [OUTFILE]` → default OUTFILE `<workspace>/review-<base7>..<head7>.diff`. Task 3's SKILL.md text names exactly these signatures.
78
+
79
+ - [ ] **Step 1: Replace the test file with the plan-scoped expectations**
80
+
81
+ Overwrite `tests/claude-code/test-sdd-workspace.sh` with exactly:
82
+
83
+ ```bash
84
+ #!/usr/bin/env bash
85
+ # Tests for the SDD workspace: scripts/sdd-workspace resolves a self-ignoring,
86
+ # PER-PLAN working-tree directory for SDD artifacts, and the SDD scripts write
87
+ # into their plan's directory.
88
+ set -euo pipefail
89
+
90
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
91
+ REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
92
+ SDD_SCRIPTS="$REPO_ROOT/skills/subagent-driven-development/scripts"
93
+
94
+ FAILURES=0
95
+ TEST_ROOT=""
96
+
97
+ pass() { echo " [PASS] $1"; }
98
+ fail() {
99
+ echo " [FAIL] $1"
100
+ FAILURES=$((FAILURES + 1))
101
+ }
102
+
103
+ cleanup() {
104
+ if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then
105
+ rm -rf "$TEST_ROOT"
106
+ fi
107
+ }
108
+
109
+ main() {
110
+ echo "=== Test: sdd-workspace ==="
111
+
112
+ TEST_ROOT="$(mktemp -d)"
113
+ trap cleanup EXIT
114
+
115
+ # Resolve repo to its physical path so string comparisons match the
116
+ # helper's output (git rev-parse --show-toplevel resolves symlinks; on
117
+ # macOS mktemp lives under /var -> /private/var).
118
+ git init -q -b main "$TEST_ROOT/repo"
119
+ local repo
120
+ repo="$(cd "$TEST_ROOT/repo" && git rev-parse --show-toplevel)"
121
+
122
+ cat > "$repo/plan-a.md" <<'PLAN'
123
+ # Plan A
124
+
125
+ ## Task 1: First thing
126
+
127
+ Do the first thing.
128
+ PLAN
129
+ cat > "$repo/plan-b.md" <<'PLAN'
130
+ # Plan B
131
+
132
+ ## Task 1: Other thing
133
+
134
+ Do the other thing.
135
+ PLAN
136
+
137
+ # --- argument validation ---
138
+ local rc=0
139
+ (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" >/dev/null 2>&1) || rc=$?
140
+ if [[ "$rc" -eq 2 ]]; then
141
+ pass "sdd-workspace without a plan errors with exit 2"
142
+ else
143
+ fail "sdd-workspace without a plan errors with exit 2"
144
+ echo " exit: $rc"
145
+ fi
146
+
147
+ rc=0
148
+ (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" no-such-plan.md >/dev/null 2>&1) || rc=$?
149
+ if [[ "$rc" -eq 2 ]]; then
150
+ pass "sdd-workspace with a missing plan file errors with exit 2"
151
+ else
152
+ fail "sdd-workspace with a missing plan file errors with exit 2"
153
+ echo " exit: $rc"
154
+ fi
155
+
156
+ # --- per-plan resolution ---
157
+ local dir_a dir_b
158
+ dir_a="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)"
159
+ dir_b="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-b.md)"
160
+
161
+ if [[ "$dir_a" == "$repo/.superpowers/sdd/plan-a" ]]; then
162
+ pass "prints <repo-root>/.superpowers/sdd/<plan-basename>"
163
+ else
164
+ fail "prints <repo-root>/.superpowers/sdd/<plan-basename>"
165
+ echo " got: $dir_a"
166
+ fi
167
+
168
+ if [[ "$dir_a" != "$dir_b" && -d "$dir_a" && -d "$dir_b" ]]; then
169
+ pass "two plans resolve to two distinct directories"
170
+ else
171
+ fail "two plans resolve to two distinct directories"
172
+ echo " a: $dir_a"
173
+ echo " b: $dir_b"
174
+ fi
175
+
176
+ if [[ -f "$repo/.superpowers/sdd/.gitignore" && "$(cat "$repo/.superpowers/sdd/.gitignore")" == "*" ]]; then
177
+ pass "self-ignoring .gitignore created at .superpowers/sdd/ with '*'"
178
+ else
179
+ fail "self-ignoring .gitignore created at .superpowers/sdd/ with '*'"
180
+ fi
181
+
182
+ printf 'x\n' > "$dir_a/artifact.md"
183
+ local status
184
+ status="$(cd "$repo" && git status --porcelain)"
185
+ # plan-a.md/plan-b.md are intentionally untracked fixture files; only the
186
+ # workspace must be invisible.
187
+ if [[ "$status" != *".superpowers"* ]]; then
188
+ pass "workspace invisible to git status"
189
+ else
190
+ fail "workspace invisible to git status"
191
+ echo " status: $status"
192
+ fi
193
+
194
+ ( cd "$repo" && git add -A )
195
+ local staged
196
+ staged="$(cd "$repo" && git diff --cached --name-only)"
197
+ if [[ "$staged" != *".superpowers"* ]]; then
198
+ pass "git add -A does not stage the workspace"
199
+ else
200
+ fail "git add -A does not stage the workspace"
201
+ echo " staged: $staged"
202
+ fi
203
+
204
+ # --- task-brief lands in its plan's directory ---
205
+ local brief_out brief_path
206
+ brief_out="$(cd "$repo" && "$SDD_SCRIPTS/task-brief" plan-a.md 1)"
207
+ brief_path="$(printf '%s\n' "$brief_out" | sed -n 's/^wrote \(.*\): [0-9][0-9]* lines$/\1/p')"
208
+ if [[ "$brief_path" == "$repo/.superpowers/sdd/plan-a/task-1-brief.md" ]]; then
209
+ pass "task-brief writes its brief under the plan's workspace"
210
+ else
211
+ fail "task-brief writes its brief under the plan's workspace"
212
+ echo " got: $brief_path"
213
+ fi
214
+
215
+ # --- review-package takes the plan first and lands in its directory ---
216
+ local git_id=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false)
217
+ ( cd "$repo" \
218
+ && git "${git_id[@]}" commit -qm c1 \
219
+ && printf 'y\n' > f && git add f \
220
+ && git "${git_id[@]}" commit -qm c2 )
221
+ local rp_out rp_path
222
+ rp_out="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD)"
223
+ rp_path="$(printf '%s\n' "$rp_out" | sed -n 's/^wrote \(.*\): [0-9].*$/\1/p')"
224
+ case "$rp_path" in
225
+ "$repo/.superpowers/sdd/plan-a/review-"*.diff)
226
+ pass "review-package writes its diff under the plan's workspace" ;;
227
+ *)
228
+ fail "review-package writes its diff under the plan's workspace"
229
+ echo " got: $rp_path"
230
+ ;;
231
+ esac
232
+
233
+ rc=0
234
+ (cd "$repo" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD >/dev/null 2>&1) || rc=$?
235
+ if [[ "$rc" -eq 2 ]]; then
236
+ pass "review-package without a plan errors with exit 2"
237
+ else
238
+ fail "review-package without a plan errors with exit 2"
239
+ echo " exit: $rc"
240
+ fi
241
+
242
+ local rp_explicit
243
+ rp_explicit="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD "$TEST_ROOT/explicit.diff")"
244
+ if [[ -s "$TEST_ROOT/explicit.diff" && "$rp_explicit" == *"$TEST_ROOT/explicit.diff"* ]]; then
245
+ pass "review-package honors an explicit OUTFILE"
246
+ else
247
+ fail "review-package honors an explicit OUTFILE"
248
+ echo " got: $rp_explicit"
249
+ fi
250
+
251
+ # --- Worktree isolation: a linked worktree resolves its own workspace ---
252
+ local wt="$TEST_ROOT/wt"
253
+ ( cd "$repo" && git worktree add -q "$wt" -b wt-feature )
254
+ local wt_root wt_dir
255
+ wt_root="$(cd "$wt" && git rev-parse --show-toplevel)"
256
+ wt_dir="$(cd "$wt" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)"
257
+ if [[ "$wt_dir" == "$wt_root/.superpowers/sdd/plan-a" && "$wt_dir" != "$dir_a" ]]; then
258
+ pass "linked worktree resolves its own distinct workspace"
259
+ else
260
+ fail "linked worktree resolves its own distinct workspace"
261
+ echo " main: $dir_a"
262
+ echo " wt: $wt_dir"
263
+ fi
264
+
265
+ printf 'y\n' > "$wt_dir/artifact.md"
266
+ local wt_status
267
+ wt_status="$(cd "$wt" && git status --porcelain)"
268
+ if [[ "$wt_status" != *".superpowers"* ]]; then
269
+ pass "worktree workspace invisible to git status"
270
+ else
271
+ fail "worktree workspace invisible to git status"
272
+ echo " status: $wt_status"
273
+ fi
274
+
275
+ echo ""
276
+ if [[ "$FAILURES" -ne 0 ]]; then
277
+ echo "FAILED: $FAILURES assertion(s)."
278
+ exit 1
279
+ fi
280
+ echo "PASS"
281
+ }
282
+
283
+ main "$@"
284
+ ```
285
+
286
+ Note: the worktree fixture relies on `plan-a.md` being tracked by the time the worktree is created — the `git add -A` assertion earlier stages it and the review-package block commits it. Do not reorder the blocks.
287
+
288
+ - [ ] **Step 2: Run the test — verify it fails against the current scripts**
289
+
290
+ Run: `bash tests/claude-code/test-sdd-workspace.sh`
291
+ Expected: FAILED with multiple assertions (current `sdd-workspace` ignores arguments and prints the flat path, so "errors with exit 2" and "<plan-basename>" assertions fail; current `review-package` treats `plan-a.md` as a bad BASE ref).
292
+
293
+ - [ ] **Step 3: Rewrite the three scripts**
294
+
295
+ Overwrite `skills/subagent-driven-development/scripts/sdd-workspace` with exactly:
296
+
297
+ ```bash
298
+ #!/usr/bin/env bash
299
+ # Resolve and ensure the working-tree directory SDD uses for one plan's
300
+ # short-lived artifacts: task briefs, implementer reports, review packages,
301
+ # and the progress ledger. Print the plan directory's absolute path.
302
+ #
303
+ # One directory per plan (.superpowers/sdd/<plan-basename>/) so a follow-up
304
+ # plan in the same working tree can never read or overwrite another plan's
305
+ # artifacts. A stale ledger misread as current progress makes controllers
306
+ # skip whole task sequences — plan-scoping removes that failure structurally.
307
+ #
308
+ # The workspace lives in the working tree (not under .git/) because Claude Code
309
+ # treats .git/ as a protected path and denies agent writes there — which blocks
310
+ # an implementer subagent from writing its report file. A self-ignoring
311
+ # .gitignore at .superpowers/sdd/ keeps every plan's workspace out of
312
+ # `git status` and out of accidental commits without modifying any tracked file.
313
+ #
314
+ # Single source of truth for the workspace location, so task-brief and
315
+ # review-package cannot drift to different directories.
316
+ #
317
+ # Usage: sdd-workspace PLAN_FILE
318
+ set -euo pipefail
319
+
320
+ if [ $# -ne 1 ]; then
321
+ echo "usage: sdd-workspace PLAN_FILE" >&2
322
+ exit 2
323
+ fi
324
+
325
+ plan=$1
326
+ [ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }
327
+
328
+ slug=$(basename "$plan" .md)
329
+ [ -n "$slug" ] && [ "$slug" != "." ] && [ "$slug" != ".." ] \
330
+ || { echo "cannot derive a workspace name from: $plan" >&2; exit 2; }
331
+
332
+ root=$(git rev-parse --show-toplevel)
333
+ base="$root/.superpowers/sdd"
334
+ dir="$base/$slug"
335
+ mkdir -p "$dir"
336
+ printf '*\n' > "$base/.gitignore"
337
+ cd "$dir" && pwd
338
+ ```
339
+
340
+ Overwrite `skills/subagent-driven-development/scripts/task-brief` with exactly:
341
+
342
+ ```bash
343
+ #!/usr/bin/env bash
344
+ # Extract one task's full text from an implementation plan into a file the
345
+ # implementer reads in one call, so the task text never has to be pasted
346
+ # through the controller's context.
347
+ #
348
+ # Usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]
349
+ # Default OUTFILE: <repo-root>/.superpowers/sdd/<plan-basename>/task-<N>-brief.md
350
+ # (per plan and per worktree; concurrent runs of the SAME plan in the same
351
+ # working tree share it).
352
+ set -euo pipefail
353
+
354
+ if [ $# -lt 2 ] || [ $# -gt 3 ]; then
355
+ echo "usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]" >&2
356
+ exit 2
357
+ fi
358
+
359
+ plan=$1
360
+ n=$2
361
+ [ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }
362
+
363
+ if [ $# -eq 3 ]; then
364
+ out=$3
365
+ else
366
+ dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan")
367
+ out="$dir/task-${n}-brief.md"
368
+ fi
369
+
370
+ awk -v n="$n" '
371
+ /^```/ { infence = !infence }
372
+ !infence && /^#+[ \t]+Task[ \t]+[0-9]+/ {
373
+ intask = ($0 ~ ("^#+[ \t]+Task[ \t]+" n "([^0-9]|$)"))
374
+ }
375
+ intask { print }
376
+ ' "$plan" > "$out"
377
+
378
+ if [ ! -s "$out" ]; then
379
+ echo "task ${n} not found in ${plan} (no heading matching 'Task ${n}')" >&2
380
+ exit 3
381
+ fi
382
+
383
+ echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines"
384
+ ```
385
+
386
+ Overwrite `skills/subagent-driven-development/scripts/review-package` with exactly:
387
+
388
+ ```bash
389
+ #!/usr/bin/env bash
390
+ # Generate a review package: commit list, stat summary, and the net
391
+ # diff with extended context, written to a file the reviewer reads in one
392
+ # call. Using the recorded per-task BASE (not HEAD~1) keeps multi-commit
393
+ # tasks intact.
394
+ #
395
+ # Usage: review-package PLAN_FILE BASE HEAD [OUTFILE]
396
+ # Default OUTFILE: <repo-root>/.superpowers/sdd/<plan-basename>/review-<base7>..<head7>.diff
397
+ # (named per range, so a re-review after fixes gets a distinct fresh file).
398
+ set -euo pipefail
399
+
400
+ if [ $# -lt 3 ] || [ $# -gt 4 ]; then
401
+ echo "usage: review-package PLAN_FILE BASE HEAD [OUTFILE]" >&2
402
+ exit 2
403
+ fi
404
+
405
+ plan=$1
406
+ base=$2
407
+ head=$3
408
+ [ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }
409
+
410
+ git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; }
411
+ git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; }
412
+
413
+ if [ $# -eq 4 ]; then
414
+ out=$4
415
+ else
416
+ dir=$("$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan")
417
+ out="$dir/review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head").diff"
418
+ fi
419
+
420
+ {
421
+ echo "# Review package: ${base}..${head}"
422
+ echo
423
+ echo "## Commits"
424
+ git log --oneline "${base}..${head}"
425
+ echo
426
+ echo "## Files changed"
427
+ git diff --stat "${base}..${head}"
428
+ echo
429
+ echo "## Diff"
430
+ git diff -U10 "${base}..${head}"
431
+ } > "$out"
432
+
433
+ commits=$(git rev-list --count "${base}..${head}")
434
+ echo "wrote ${out}: ${commits} commit(s), $(wc -c < "$out" | tr -d ' ') bytes"
435
+ ```
436
+
437
+ - [ ] **Step 4: Run the test — verify it passes**
438
+
439
+ Run: `bash tests/claude-code/test-sdd-workspace.sh`
440
+ Expected: `PASS`, 13 `[PASS]` lines, exit 0.
441
+
442
+ - [ ] **Step 5: Lint everything touched**
443
+
444
+ Run: `bash scripts/lint-shell.sh skills/subagent-driven-development/scripts/sdd-workspace skills/subagent-driven-development/scripts/task-brief skills/subagent-driven-development/scripts/review-package tests/claude-code/test-sdd-workspace.sh`
445
+ Expected: exit 0, no findings.
446
+
447
+ - [ ] **Step 6: Commit**
448
+
449
+ ```bash
450
+ git add skills/subagent-driven-development/scripts/sdd-workspace \
451
+ skills/subagent-driven-development/scripts/task-brief \
452
+ skills/subagent-driven-development/scripts/review-package \
453
+ tests/claude-code/test-sdd-workspace.sh
454
+ git commit -m "feat(sdd): plan-scoped workspace — one .superpowers/sdd/<plan> dir per plan
455
+
456
+ sdd-workspace now requires the plan file and resolves
457
+ .superpowers/sdd/<plan-basename>/; task-brief and review-package write
458
+ into their plan's directory (review-package gains PLAN_FILE as its first
459
+ argument). Follow-up plans in the same working tree can no longer collide
460
+ with a previous plan's briefs, reports, or ledger."
461
+ ```
462
+
463
+ ---
464
+
465
+ ### Task 3: SKILL.md — plan-scoped Durable Progress, workspace identity, end-of-plan cleanup
466
+
467
+ **Files:**
468
+ - Modify: `skills/subagent-driven-development/SKILL.md`
469
+
470
+ **Interfaces:**
471
+ - Consumes: script signatures from Task 2 (`sdd-workspace PLAN_FILE`, `review-package PLAN_FILE BASE HEAD`); Task 1's committed evidence doc (context only — this text ships on structural grounds with maintainer sign-off, per that doc's "Basis for proceeding").
472
+ - Produces: the skill text Task 4 evaluates. Section anchor names used by Task 4: "Durable Progress".
473
+
474
+ Apply the following edits with exact string replacement. All old strings are verbatim from the current file.
475
+
476
+ - [ ] **Step 1: Update the DONE-status review-package invocation**
477
+
478
+ Old:
479
+ ```
480
+ **DONE:** Generate the review package (`scripts/review-package BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path.
481
+ ```
482
+ New:
483
+ ```
484
+ **DONE:** Generate the review package (`scripts/review-package PLAN_FILE BASE HEAD`, from this skill's directory — it prints the unique file path it wrote; BASE is the commit you recorded before dispatching the implementer — never `HEAD~1`, which silently drops all but the last commit of a multi-commit task), then dispatch the task reviewer with the printed path.
485
+ ```
486
+
487
+ - [ ] **Step 2: Update the reviewer-prompts diff-file bullet**
488
+
489
+ Old:
490
+ ```
491
+ - Hand the reviewer its diff as a file: run this skill's
492
+ `scripts/review-package BASE HEAD` and pass the reviewer the file path
493
+ it prints (or, without bash: `git log --oneline`, `git diff --stat`,
494
+ and `git diff -U10` for the range, redirected to one uniquely named
495
+ file). The output never enters your own context, and the reviewer sees
496
+ ```
497
+ New:
498
+ ```
499
+ - Hand the reviewer its diff as a file: run this skill's
500
+ `scripts/review-package PLAN_FILE BASE HEAD` and pass the reviewer the
501
+ file path it prints (or, without bash: `git log --oneline`,
502
+ `git diff --stat`, and `git diff -U10` for the range, redirected to one
503
+ uniquely named file). The output never enters your own context, and the reviewer sees
504
+ ```
505
+
506
+ - [ ] **Step 3: Update the final-review package bullet**
507
+
508
+ Old:
509
+ ```
510
+ - The final whole-branch review gets a package too: run
511
+ `scripts/review-package MERGE_BASE HEAD` (MERGE_BASE = the commit the
512
+ branch started from, e.g. `git merge-base main HEAD`) and include the
513
+ ```
514
+ New:
515
+ ```
516
+ - The final whole-branch review gets a package too: run
517
+ `scripts/review-package PLAN_FILE MERGE_BASE HEAD` (MERGE_BASE = the
518
+ commit the branch started from, e.g. `git merge-base main HEAD`) and include the
519
+ ```
520
+
521
+ - [ ] **Step 4: Update the Red Flags diff-file bullet**
522
+
523
+ Old:
524
+ ```
525
+ - Dispatch a task reviewer without a diff file — generate it first
526
+ (`scripts/review-package BASE HEAD`) and name the printed path in the
527
+ prompt
528
+ ```
529
+ New:
530
+ ```
531
+ - Dispatch a task reviewer without a diff file — generate it first
532
+ (`scripts/review-package PLAN_FILE BASE HEAD`) and name the printed
533
+ path in the prompt
534
+ ```
535
+
536
+ - [ ] **Step 5: Replace the Durable Progress section**
537
+
538
+ Old:
539
+ ```
540
+ - At skill start, check for a ledger:
541
+ `cat "$(git rev-parse --show-toplevel)/.superpowers/sdd/progress.md"`. Tasks listed there
542
+ as complete are DONE — do not re-dispatch them; resume at the first task
543
+ not marked complete.
544
+ - When a task's review comes back clean, append one line to the ledger in
545
+ the same message as your other bookkeeping:
546
+ `Task N: complete (commits <base7>..<head7>, review clean)`.
547
+ - The ledger is your recovery map: the commits it names exist in git even
548
+ when your context no longer remembers creating them. After compaction,
549
+ trust the ledger and `git log` over your own recollection.
550
+ - `git clean -fdx` will destroy the ledger (it's git-ignored scratch); if
551
+ that happens, recover from `git log`.
552
+ ```
553
+ New:
554
+ ```
555
+ - Each plan owns a workspace: at skill start, run this skill's
556
+ `scripts/sdd-workspace PLAN_FILE` — it prints the plan's git-ignored
557
+ directory (`<repo-root>/.superpowers/sdd/<plan-basename>/`), home to
558
+ every artifact for THIS plan: ledger, briefs, reports, review packages.
559
+ Another plan's directory is never yours to read or write.
560
+ - Check for this plan's ledger at `<workspace>/progress.md`. If its first
561
+ line names your plan file, tasks listed there as complete are DONE — do
562
+ not re-dispatch them; resume at the first task not marked complete. A
563
+ ledger whose first line names a different plan file — or a stray ledger
564
+ at the old flat path `.superpowers/sdd/progress.md` — is another plan's
565
+ progress: leave it in place and start your own, fresh.
566
+ - Create the ledger with its identity as the first line:
567
+ `# SDD ledger — plan: <plan file path>`.
568
+ - When a task's review comes back clean, append one line to the ledger in
569
+ the same message as your other bookkeeping:
570
+ `Task N: complete (commits <base7>..<head7>, review clean)`.
571
+ - The ledger is your recovery map: the commits it names exist in git even
572
+ when your context no longer remembers creating them. After compaction,
573
+ trust the ledger and `git log` over your own recollection.
574
+ - `git clean -fdx` will destroy the workspace (it's git-ignored scratch); if
575
+ that happens, recover from `git log`.
576
+ - When the final whole-branch review is clean and its fixes are merged,
577
+ delete this plan's workspace (`rm -rf <workspace>`) — the git history
578
+ is the record now. Sibling directories belong to other plans; leave
579
+ them alone.
580
+ ```
581
+
582
+ - [ ] **Step 6: Add the cleanup node to the process graph**
583
+
584
+ Old:
585
+ ```
586
+ "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [shape=box];
587
+ "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
588
+ ```
589
+ New:
590
+ ```
591
+ "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" [shape=box];
592
+ "Final review clean: delete this plan's workspace" [shape=box];
593
+ "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
594
+ ```
595
+
596
+ Old:
597
+ ```
598
+ "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Use superpowers:finishing-a-development-branch";
599
+ ```
600
+ New:
601
+ ```
602
+ "Dispatch final code reviewer subagent (../requesting-code-review/code-reviewer.md)" -> "Final review clean: delete this plan's workspace";
603
+ "Final review clean: delete this plan's workspace" -> "Use superpowers:finishing-a-development-branch";
604
+ ```
605
+
606
+ - [ ] **Step 7: Update the Example Workflow**
607
+
608
+ Old:
609
+ ```
610
+ [Read plan file once: docs/superpowers/plans/feature-plan.md]
611
+ [Create todos for all tasks]
612
+ ```
613
+ New:
614
+ ```
615
+ [Read plan file once: docs/superpowers/plans/feature-plan.md]
616
+ [Resolve workspace: scripts/sdd-workspace docs/superpowers/plans/feature-plan.md — no ledger inside, fresh start]
617
+ [Create todos for all tasks]
618
+ ```
619
+
620
+ Old:
621
+ ```
622
+ [After all tasks]
623
+ [Dispatch final code-reviewer]
624
+ Final reviewer: All requirements met, ready to merge
625
+
626
+ Done!
627
+ ```
628
+ New:
629
+ ```
630
+ [After all tasks]
631
+ [Dispatch final code-reviewer]
632
+ Final reviewer: All requirements met, ready to merge
633
+
634
+ [Delete this plan's workspace — the record now lives in git]
635
+
636
+ Done!
637
+ ```
638
+
639
+ - [ ] **Step 8: Verify no stale invocations remain**
640
+
641
+ Run: `grep -n "review-package BASE\|sdd/progress.md\|scripts/sdd-workspace\b" skills/subagent-driven-development/SKILL.md`
642
+ Expected: no `review-package BASE` hits; `sdd/progress.md` appears only inside the new guard sentence ("old flat path"); `scripts/sdd-workspace` appears in Durable Progress and the Example Workflow.
643
+
644
+ - [ ] **Step 9: Commit**
645
+
646
+ ```bash
647
+ git add skills/subagent-driven-development/SKILL.md
648
+ git commit -m "feat(sdd): plan-scoped durable progress — ledger names its plan, workspace dies at plan end
649
+
650
+ The start-of-skill ledger check is now scoped to the plan's own
651
+ workspace and keyed to the ledger's first line. Baseline eval (25/25
652
+ reps) showed controllers already refuse foreign ledgers — at a cost of
653
+ 6-13 tool calls of cross-plan forensics per resume; plan-scoping makes
654
+ the answer structural instead. The workspace is deleted once the final
655
+ review is clean — git history is the durable record."
656
+ ```
657
+
658
+ ---
659
+
660
+ ### Task 4: GREEN eval on truthful fixture v3 — regression safety + measured cost delta
661
+
662
+ **Files:**
663
+ - Create (temp only, not committed): `$EVAL_ROOT/make-fixture.sh` (v3, below), fixture repos, reply files
664
+ - Create: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md`
665
+ - Delete: `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md` (content folds into the results doc)
666
+ - Modify (only if a GREEN gate fails): `skills/subagent-driven-development/SKILL.md`
667
+
668
+ **Interfaces:**
669
+ - Consumes: Task 1's evidence doc; Task 3's SKILL.md; the pre-change skill tree extracted from git.
670
+ - Produces: the eval evidence document cited by the PR.
671
+
672
+ - [ ] **Step 1: Create the eval root and the v3 fixture generator**
673
+
674
+ ```bash
675
+ EVAL_ROOT=$(mktemp -d)
676
+ echo "$EVAL_ROOT" > /tmp/sdd-eval-root-v3.path
677
+ cat > "$EVAL_ROOT/make-fixture.sh" <<'FIXTURE'
678
+ #!/usr/bin/env bash
679
+ # Build a throwaway git repo simulating a project where SDD ran plan A
680
+ # (widget backend) to completion and a controller is resuming follow-up
681
+ # plan B (widget export). v3: every ledger claim survives content
682
+ # inspection — cited commits are real, resolvable, authored by rotating
683
+ # identities at spread timestamps, and their diffs genuinely satisfy the
684
+ # task specs they claim (v2's stubs were ruled "false records" by scenario
685
+ # agents). Plans A and B both have 5 tasks so numbering is not a tell.
686
+ #
687
+ # Usage: make-fixture.sh SCENARIO LAYOUT DEST
688
+ # SCENARIO: s1 (stale ledger from a different plan) | s2 (same-plan resume)
689
+ # LAYOUT: flat (released layout: .superpowers/sdd/progress.md)
690
+ # scoped (new layout: .superpowers/sdd/<plan-basename>/progress.md,
691
+ # PLUS leftover flat + sibling litter for s1)
692
+ # DEST: directory to create the repo in
693
+ set -euo pipefail
694
+ scenario=$1 layout=$2 dest=$3
695
+
696
+ git init -q -b main "$dest"
697
+ cd "$dest"
698
+ git config user.email eval@example.com
699
+ git config user.name eval
700
+ git config commit.gpgsign false
701
+
702
+ BASE_DAY=2026-07-01
703
+ ci=0
704
+ commit_file() { # commit_file FILE MESSAGE -> prints short hash; FILE already written
705
+ git add "$1"
706
+ ci=$((ci+1))
707
+ if [ $((ci % 2)) -eq 0 ]; then
708
+ GIT_AUTHOR_NAME='Sam Rivera' GIT_AUTHOR_EMAIL='sam@example.com' \
709
+ GIT_AUTHOR_DATE="${BASE_DAY}T1${ci}:15:00" GIT_COMMITTER_DATE="${BASE_DAY}T1${ci}:16:30" \
710
+ git commit -qm "$2"
711
+ else
712
+ GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \
713
+ GIT_AUTHOR_DATE="${BASE_DAY}T1${ci}:05:00" GIT_COMMITTER_DATE="${BASE_DAY}T1${ci}:07:10" \
714
+ git commit -qm "$2"
715
+ fi
716
+ git rev-parse --short HEAD
717
+ }
718
+
719
+ mkdir -p docs/plans src
720
+
721
+ cat > docs/plans/2026-07-01-widget-backend.md <<'EOF'
722
+ # Widget Backend Implementation Plan
723
+
724
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development.
725
+
726
+ **Goal:** Build the widget inventory backend core.
727
+
728
+ ## Task 1: Storage schema
729
+
730
+ Define the on-disk widget schema in `src/schema.py`: fields `id` (int),
731
+ `name` (str), `count` (int).
732
+
733
+ ## Task 2: Validation rules
734
+
735
+ `validate(widget) -> bool` in `src/validate.py`: exactly the schema's keys.
736
+
737
+ ## Task 3: File locking
738
+
739
+ `locked(path)` context manager in `src/lock.py` using `fcntl.flock`.
740
+
741
+ ## Task 4: Registry load/save
742
+
743
+ `load(path) -> list` and `save(path, items)` in `src/registry.py`, JSON on disk.
744
+
745
+ ## Task 5: Lint gate
746
+
747
+ Add `.lint.cfg` with a 100-column limit.
748
+ EOF
749
+
750
+ cat > src/inventory.py <<'EOF'
751
+ """Inventory service (fixture)."""
752
+ def list_items():
753
+ return []
754
+ EOF
755
+
756
+ git add -A
757
+ GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \
758
+ GIT_AUTHOR_DATE="${BASE_DAY}T10:00:00" GIT_COMMITTER_DATE="${BASE_DAY}T10:01:00" \
759
+ git commit -qm "chore: widget project scaffold with backend plan"
760
+
761
+ # Plan A's five tasks, implemented for real so the ledger's claims survive
762
+ # content inspection against plan A's specs.
763
+ cat > src/schema.py <<'EOF'
764
+ SCHEMA = {"id": int, "name": str, "count": int}
765
+ EOF
766
+ a1=$(commit_file src/schema.py 'feat(backend): storage schema')
767
+
768
+ cat > src/validate.py <<'EOF'
769
+ from schema import SCHEMA
770
+
771
+ def validate(widget):
772
+ return set(widget) == set(SCHEMA)
773
+ EOF
774
+ a2=$(commit_file src/validate.py 'feat(backend): validation rules')
775
+
776
+ cat > src/lock.py <<'EOF'
777
+ import fcntl
778
+ from contextlib import contextmanager
779
+
780
+ @contextmanager
781
+ def locked(path):
782
+ with open(path, "a") as f:
783
+ fcntl.flock(f, fcntl.LOCK_EX)
784
+ try:
785
+ yield f
786
+ finally:
787
+ fcntl.flock(f, fcntl.LOCK_UN)
788
+ EOF
789
+ a3=$(commit_file src/lock.py 'feat(backend): file locking')
790
+
791
+ cat > src/registry.py <<'EOF'
792
+ import json
793
+
794
+ def load(path):
795
+ try:
796
+ with open(path) as f:
797
+ return json.load(f)
798
+ except FileNotFoundError:
799
+ return []
800
+
801
+ def save(path, items):
802
+ with open(path, "w") as f:
803
+ json.dump(items, f)
804
+ EOF
805
+ a4=$(commit_file src/registry.py 'feat(backend): registry load/save')
806
+
807
+ cat > .lint.cfg <<'EOF'
808
+ max-line-length = 100
809
+ EOF
810
+ a5=$(commit_file .lint.cfg 'chore(backend): lint gate')
811
+
812
+ BASE_DAY=2026-07-06
813
+ cat > docs/plans/2026-07-06-widget-export.md <<'EOF'
814
+ # Widget Export Implementation Plan
815
+
816
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development.
817
+
818
+ **Goal:** Add CSV and JSON export of widgets to the inventory backend.
819
+
820
+ ## Task 1: Export data model
821
+
822
+ Define `ExportRow` in `src/export_model.py` with fields `id`, `name`, `count`.
823
+
824
+ ## Task 2: CSV serializer
825
+
826
+ `to_csv(rows) -> str` in `src/export_csv.py`, header row + one line per widget.
827
+
828
+ ## Task 3: JSON serializer
829
+
830
+ `to_json(rows) -> str` in `src/export_json.py`, list of objects, stable key order.
831
+
832
+ ## Task 4: CLI flag
833
+
834
+ `inventory export --format csv|json` writing to stdout.
835
+
836
+ ## Task 5: End-to-end test
837
+
838
+ Round-trip: list -> export -> parse -> compare.
839
+ EOF
840
+ git add docs/plans/2026-07-06-widget-export.md
841
+ GIT_AUTHOR_NAME='Dana Okafor' GIT_AUTHOR_EMAIL='dana@example.com' \
842
+ GIT_AUTHOR_DATE="${BASE_DAY}T09:30:00" GIT_COMMITTER_DATE="${BASE_DAY}T09:31:00" \
843
+ git commit -qm "docs: follow-up plan — widget export"
844
+
845
+ plan_a_ledger_lines() {
846
+ printf 'Task 1: complete (commits %s, review clean)\n' "$a1"
847
+ printf 'Task 2: complete (commits %s, review clean)\n' "$a2"
848
+ printf 'Task 3: complete (commits %s, review clean)\n' "$a3"
849
+ printf 'Task 4: complete (commits %s, review clean)\n' "$a4"
850
+ printf 'Task 5: complete (commits %s, review clean)\n' "$a5"
851
+ printf '\n## Final whole-branch review — DONE\nNo Critical/Important findings.\n'
852
+ }
853
+
854
+ if [ "$scenario" = s2 ]; then
855
+ # Plan B tasks 1-2 genuinely implemented to their specs, so the resume
856
+ # ledger is legitimate under content inspection.
857
+ cat > src/export_model.py <<'EOF'
858
+ class ExportRow:
859
+ def __init__(self, id, name, count):
860
+ self.id = id
861
+ self.name = name
862
+ self.count = count
863
+ EOF
864
+ b1=$(commit_file src/export_model.py 'feat(export): export data model')
865
+
866
+ cat > src/export_csv.py <<'EOF'
867
+ def to_csv(rows):
868
+ lines = ["id,name,count"]
869
+ for r in rows:
870
+ lines.append(f"{r.id},{r.name},{r.count}")
871
+ return "\n".join(lines)
872
+ EOF
873
+ b2=$(commit_file src/export_csv.py 'feat(export): csv serializer')
874
+
875
+ plan_b_ledger_lines() {
876
+ printf 'Task 1: complete (commits %s, review clean)\n' "$b1"
877
+ printf 'Task 2: complete (commits %s, review clean)\n' "$b2"
878
+ }
879
+ fi
880
+
881
+ case "$scenario/$layout" in
882
+ s1/flat)
883
+ mkdir -p .superpowers/sdd
884
+ plan_a_ledger_lines > .superpowers/sdd/progress.md
885
+ ;;
886
+ s1/scoped)
887
+ # Post-upgrade worst case: legacy flat ledger litter AND plan A's own
888
+ # completed scoped workspace both present.
889
+ mkdir -p .superpowers/sdd/2026-07-01-widget-backend
890
+ printf '*\n' > .superpowers/sdd/.gitignore
891
+ plan_a_ledger_lines > .superpowers/sdd/progress.md
892
+ {
893
+ printf '# SDD ledger — plan: docs/plans/2026-07-01-widget-backend.md\n\n'
894
+ plan_a_ledger_lines
895
+ } > .superpowers/sdd/2026-07-01-widget-backend/progress.md
896
+ ;;
897
+ s2/flat)
898
+ mkdir -p .superpowers/sdd
899
+ plan_b_ledger_lines > .superpowers/sdd/progress.md
900
+ ;;
901
+ s2/scoped)
902
+ mkdir -p .superpowers/sdd/2026-07-06-widget-export
903
+ printf '*\n' > .superpowers/sdd/.gitignore
904
+ {
905
+ printf '# SDD ledger — plan: docs/plans/2026-07-06-widget-export.md\n\n'
906
+ plan_b_ledger_lines
907
+ } > .superpowers/sdd/2026-07-06-widget-export/progress.md
908
+ ;;
909
+ *)
910
+ echo "unknown scenario/layout: $scenario/$layout" >&2
911
+ exit 2
912
+ ;;
913
+ esac
914
+ FIXTURE
915
+ chmod +x "$EVAL_ROOT/make-fixture.sh"
916
+ ```
917
+
918
+ Sanity-check one build: `bash "$EVAL_ROOT/make-fixture.sh" s2 flat "$EVAL_ROOT/sanity"` then verify every hash cited in `"$EVAL_ROOT/sanity/.superpowers/sdd/progress.md"` resolves via `git -C "$EVAL_ROOT/sanity" cat-file -e <hash>` and that `git -C "$EVAL_ROOT/sanity" log --format='%an %ad' --date=short` shows two authors across two dates.
919
+
920
+ - [ ] **Step 2: Extract the pre-change skill tree (for the S2 RED control)**
921
+
922
+ ```bash
923
+ EVAL_ROOT=$(cat /tmp/sdd-eval-root-v3.path)
924
+ mkdir -p "$EVAL_ROOT/old-skill"
925
+ git archive 4118245 -- skills/subagent-driven-development | tar -x -C "$EVAL_ROOT/old-skill"
926
+ ls "$EVAL_ROOT/old-skill/skills/subagent-driven-development/SKILL.md"
927
+ ```
928
+
929
+ (`4118245` predates Tasks 2-3 on this branch, so it carries the released text and scripts.)
930
+
931
+ - [ ] **Step 3: Build 15 fixtures**
932
+
933
+ ```bash
934
+ EVAL_ROOT=$(cat /tmp/sdd-eval-root-v3.path)
935
+ for i in 1 2 3 4 5; do
936
+ "$EVAL_ROOT/make-fixture.sh" s1 scoped "$EVAL_ROOT/s1-green-rep$i"
937
+ "$EVAL_ROOT/make-fixture.sh" s2 flat "$EVAL_ROOT/s2-red-rep$i"
938
+ "$EVAL_ROOT/make-fixture.sh" s2 scoped "$EVAL_ROOT/s2-green-rep$i"
939
+ done
940
+ ```
941
+
942
+ - [ ] **Step 4: Run the 15 scenario reps**
943
+
944
+ One fresh subagent per rep (model `sonnet`, subagent_type `general-purpose`), using this prompt VERBATIM — the same compaction-resume framing the RED probe round used, so the arms compare like-for-like. `<SKILL_DIR>` = this worktree's absolute `skills/subagent-driven-development` for the GREEN reps, and `$EVAL_ROOT/old-skill/skills/subagent-driven-development` for the S2 RED control reps. `<FIXTURE_REPO>` = the rep's fixture path.
945
+
946
+ ```
947
+ <session-context>
948
+ This session is being continued from a previous conversation that ran out of
949
+ context and was compacted. Summary of the earlier portion:
950
+
951
+ - You are the SDD controller for the repository at <FIXTURE_REPO>
952
+ - You had begun executing the implementation plan
953
+ docs/plans/2026-07-06-widget-export.md (relative to that repo) using the
954
+ Subagent-Driven Development skill, whose complete text and scripts are at:
955
+ <SKILL_DIR>
956
+ - The context filled mid-session; the durable record of progress is on disk
957
+ per the skill's Durable Progress section.
958
+ </session-context>
959
+
960
+ Continue executing the plan. Re-read the skill's SKILL.md to re-anchor on the
961
+ process, recover your place, and continue.
962
+
963
+ Scope limit for this run: you may read anything, run git commands, and run
964
+ the skill's scripts. Do NOT dispatch any subagents and do NOT implement any
965
+ tasks. Work only up to the point where you know your execution state, then
966
+ STOP and reply with exactly this report:
967
+
968
+ 1. LEDGERS CHECKED: each progress/ledger file path you looked at, and what
969
+ you concluded from it.
970
+ 2. TASKS ALREADY COMPLETE: which of YOUR plan's tasks (if any) are already
971
+ done.
972
+ 3. FIRST DISPATCH: which task you will dispatch next.
973
+
974
+ Be concrete and terse. That report is your entire deliverable.
975
+ ```
976
+
977
+ Save each reply verbatim to `$EVAL_ROOT/<arm>-repN.reply.md` with a first line noting its `tool_uses` count from the Agent result.
978
+
979
+ - [ ] **Step 5: Score every rep by hand**
980
+
981
+ Read each reply in full (no keyword-grepping) and assign PASS/FAIL:
982
+
983
+ | Arm | PASS iff | FAIL if |
984
+ |---|---|---|
985
+ | S1 GREEN | First dispatch = plan B **Task 1**, no plan-B task claimed complete. Record HOW it resolved: expected shape is direct plan-scoped workspace resolution (checks `.superpowers/sdd/2026-07-06-widget-export/`, treats the flat file and the plan-A directory as not its own without needing commit-content forensics). | Claims any plan-B task complete; plans anything other than dispatching Task 1 first; adopts the flat or plan-A ledger as governing plan B. |
986
+ | S2 RED (control, released text) | Tasks 1-2 recognized complete, first dispatch = **Task 3**. | Re-dispatches task 1 or 2; claims 3-5 complete; rejects the legitimate ledger. |
987
+ | S2 GREEN | Tasks 1-2 recognized complete, first dispatch = **Task 3**. | Same as S2 RED. |
988
+
989
+ Also record per-rep `tool_uses` for the cost comparison (RED resume-round baseline: 7/13/9/10/6).
990
+
991
+ - [ ] **Step 6: Gates**
992
+
993
+ - **S2 RED (v3 control): ≥4/5 PASS required.** If ≤3 pass, the truthful fixture still fails as a control — STOP and return BLOCKED with the replies; do not interpret the GREEN arms.
994
+ - **S1 GREEN: 5/5 PASS required.**
995
+ - **S2 GREEN: 5/5 PASS required.**
996
+ - If a GREEN rep fails: quote the failing sentence verbatim, adjust ONLY the relevant SKILL.md wording, commit as `fix(sdd): close eval loophole — <one-line description>`, and re-run that arm's 5 reps fresh. Repeat until the gate passes. Record every iteration in the results doc.
997
+
998
+ - [ ] **Step 7: Write the results doc**
999
+
1000
+ Create `docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md` with exactly these sections (fill with real data):
1001
+
1002
+ ```markdown
1003
+ # SDD plan-scoped workspace — eval results
1004
+
1005
+ - **Date:** <run date>
1006
+ - **Method:** writing-skills RED→GREEN pressure test, re-scoped 2026-07-06
1007
+ with maintainer sign-off after the RED baseline did not reproduce blind
1008
+ stale-ledger adoption. 5 fresh sonnet subagents per arm, compaction-resume
1009
+ framing, every reply read and scored by hand.
1010
+ - **Spec:** 2026-07-06-sdd-plan-scoped-workspace.md
1011
+
1012
+ ## Scenarios
1013
+
1014
+ <one paragraph each for S1 (stale ledger from a different plan) and S2
1015
+ (same-plan resume), including the fixture layout per arm>
1016
+
1017
+ ## What RED showed (and did not show)
1018
+
1019
+ <from the Task 1 evidence doc: 25/25 refusals across three framings; the
1020
+ baseline harm is the forensic disambiguation tax plus the structural serf
1021
+ record; the text change ships on structural grounds with maintainer
1022
+ sign-off, not on a demonstrated error rate. Fold in the Task 1 quote bank.>
1023
+
1024
+ ## Fixture iterations
1025
+
1026
+ Fixture v1 (discarded before any skill edit): plan A had 17 tasks vs plan
1027
+ B's 5 (a task-count tell), and its ledgers cited fabricated commit hashes.
1028
+ Agents dismissed the ledger via git forensics — S1 "passed" for the wrong
1029
+ reason and S2, the legitimate-resume control, failed 5/5. Fixture v2 used
1030
+ real cited commits and matched task counts; agents then inspected commit
1031
+ CONTENT, matched it to the other plan file (S1), and ruled v2's stub
1032
+ implementations false "review clean" records (S2 failed 5/5 again).
1033
+ Fixture v3 (this round) makes every ledger claim truthful under content
1034
+ inspection: real implementations satisfying each task's spec, rotating
1035
+ authors, spread timestamps.
1036
+
1037
+ ## Results
1038
+
1039
+ | Arm | Text under test | Fixture | PASS | Notes |
1040
+ |---|---|---|---|---|
1041
+ | S1 RED | released (v6.1.1 line) | v1+v2+probe, 3 framings | 15/15 refused adoption | mean 9.0 tool_uses of cross-plan forensics (resume round) |
1042
+ | S1 GREEN | this branch | v3 scoped | n/5 | resolution shape + tool_uses |
1043
+ | S2 RED (control) | released | v3 flat | n/5 | validates the fixture |
1044
+ | S2 GREEN | this branch | v3 scoped | n/5 | regression: legitimate resume still resumes |
1045
+
1046
+ ## Disambiguation cost
1047
+
1048
+ | Round | Framing | Text | tool_uses per rep | mean |
1049
+ |---|---|---|---|---|
1050
+ | RED probe | compaction-resume | released | 7 / 13 / 9 / 10 / 6 | 9.0 |
1051
+ | S1 GREEN | compaction-resume | this branch | <fill> | <fill> |
1052
+
1053
+ ## GREEN behavior notes
1054
+
1055
+ <how GREEN agents resolved the workspace; whether any needed cross-plan
1056
+ forensics; any refinement iterations with their trigger quotes>
1057
+
1058
+ ## Appendix A: fixture generator (v3)
1059
+
1060
+ <the full make-fixture.sh source used>
1061
+
1062
+ ## Appendix B: scenario prompt
1063
+
1064
+ <the verbatim prompt template>
1065
+
1066
+ ## Limitations
1067
+
1068
+ Five reps per cell is a smoke-strength signal, not a statistical one; the
1069
+ scenario measures the resume decision, not a full execution; tool_uses is a
1070
+ coarse cost proxy. A rerunnable harness case belongs in superpowers-evals
1071
+ as follow-up. RED artifacts (verbatim replies) are preserved at the temp
1072
+ paths recorded in the eval-notes history (see git log for
1073
+ 2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md).
1074
+ ```
1075
+
1076
+ - [ ] **Step 8: Remove the interim RED notes file and commit**
1077
+
1078
+ ```bash
1079
+ git rm -q docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-notes-red.md
1080
+ git add docs/superpowers/specs/2026-07-06-sdd-plan-scoped-workspace-eval-results.md
1081
+ git commit -m "eval(sdd): GREEN results — plan-scoped resolution replaces cross-plan forensics"
1082
+ # Leave $EVAL_ROOT for OS temp cleanup (deleting it needs human authorization
1083
+ # in this environment); its path is recorded in the results doc.
1084
+ ```
1085
+
1086
+ ---
1087
+
1088
+ ### Task 5: Consistency sweep and full gates
1089
+
1090
+ **Files:**
1091
+ - Modify: any file the sweep catches (expected: none beyond prior tasks)
1092
+
1093
+ **Interfaces:**
1094
+ - Consumes: everything prior.
1095
+ - Produces: the branch state the final whole-branch review reviews.
1096
+
1097
+ - [ ] **Step 1: Sweep for stragglers**
1098
+
1099
+ Run:
1100
+ ```bash
1101
+ grep -rn "review-package BASE\|review-package MERGE_BASE\|sdd/progress\.md" \
1102
+ --include='*.md' --include='*.sh' \
1103
+ skills/ tests/ README.md 2>/dev/null | grep -v "old flat path"
1104
+ grep -rn "sdd-workspace\b" skills/ tests/ --include='*.md' --include='*.sh' | grep -v "PLAN_FILE\|plan-a\|plan-b\|test-sdd-workspace\|sdd-workspace\" \"\$plan\""
1105
+ ```
1106
+ Expected: no output from either (every remaining mention carries the plan argument or is the guard's own "old flat path" sentence). Fix anything that appears, following the Task 3 edit style.
1107
+
1108
+ - [ ] **Step 2: Run the full relevant gates**
1109
+
1110
+ ```bash
1111
+ bash tests/claude-code/test-sdd-workspace.sh
1112
+ bash tests/claude-code/test-subagent-driven-development.sh
1113
+ bash tests/claude-code/test-subagent-driven-development-integration.sh
1114
+ bash scripts/lint-shell.sh skills/subagent-driven-development/scripts/sdd-workspace \
1115
+ skills/subagent-driven-development/scripts/task-brief \
1116
+ skills/subagent-driven-development/scripts/review-package \
1117
+ tests/claude-code/test-sdd-workspace.sh
1118
+ ```
1119
+ Expected: all exit 0. If either `test-subagent-driven-development*.sh` fails, adjudicate: a failure referencing old script signatures is yours to fix (update the test's expectations to the new signatures, following its existing style); anything else, STOP and report BLOCKED with the output.
1120
+
1121
+ - [ ] **Step 3: Commit (only if the sweep changed anything)**
1122
+
1123
+ ```bash
1124
+ git add -u
1125
+ git commit -m "chore(sdd): consistency sweep for plan-scoped workspace signatures"
1126
+ ```
1127
+
1128
+ ---
1129
+
1130
+ ## Self-review notes (author)
1131
+
1132
+ - Spec coverage: §1 scripts → Task 2; §2 ledger identity + guard → Task 3 Step 5; §3 end-of-life → Task 3 Steps 5-7; §4 touch points → Task 3 Steps 1-4 + Task 5 sweep; Testing/shell → Task 2; Evaluation → Tasks 1 and 4 as re-scoped 2026-07-06 (maintainer-approved: RED = compiled 25-rep evidence, GREEN = S2 regression on truthful v3 control + S1 cost/shape delta).
1133
+ - Signatures consistent across tasks: `sdd-workspace PLAN_FILE`, `task-brief PLAN_FILE N [OUTFILE]`, `review-package PLAN_FILE BASE HEAD [OUTFILE]`; slug = `basename PLAN_FILE .md`; ledger first line `# SDD ledger — plan: <plan file path>`.
1134
+ - The eval measures the resume decision only (no dispatches) — deliberate scope per spec's "basic eval".