mirror of
https://github.com/obra/superpowers.git
synced 2026-04-19 21:42:41 +00:00
Compare commits
17 Commits
feature/op
...
v3.6.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
154d664373 | ||
|
|
8462c20cce | ||
|
|
a0c1e73a1d | ||
|
|
94e9e2596c | ||
|
|
1b878e4fa1 | ||
|
|
515c86fd07 | ||
|
|
e416a0e105 | ||
|
|
a08f7de64b | ||
|
|
207a23e4d5 | ||
|
|
c35c5f637e | ||
|
|
9a01a0dcc1 | ||
|
|
8c7826c34d | ||
|
|
4ae8fc8713 | ||
|
|
94089bdce5 | ||
|
|
9297fd24d5 | ||
|
|
d0806ba5af | ||
|
|
6ecd72c5bf |
@@ -9,7 +9,7 @@
|
||||
{
|
||||
"name": "superpowers",
|
||||
"description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques",
|
||||
"version": "3.4.0",
|
||||
"version": "3.6.2",
|
||||
"source": "./",
|
||||
"author": {
|
||||
"name": "Jesse Vincent",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "superpowers",
|
||||
"description": "Core skills library for Claude Code: TDD, debugging, collaboration patterns, and proven techniques",
|
||||
"version": "3.4.1",
|
||||
"version": "3.6.2",
|
||||
"author": {
|
||||
"name": "Jesse Vincent",
|
||||
"email": "jesse@fsck.com"
|
||||
|
||||
@@ -207,34 +207,12 @@ function runUseSkill(skillName) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract frontmatter and content
|
||||
// Extract frontmatter and content using shared core functions
|
||||
let content, frontmatter;
|
||||
try {
|
||||
const fullContent = fs.readFileSync(skillFile, 'utf8');
|
||||
const { name, description } = skillsCore.extractFrontmatter(skillFile);
|
||||
|
||||
// Extract just the content after frontmatter
|
||||
const lines = fullContent.split('\n');
|
||||
let inFrontmatter = false;
|
||||
let frontmatterEnded = false;
|
||||
const contentLines = [];
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.trim() === '---') {
|
||||
if (inFrontmatter) {
|
||||
frontmatterEnded = true;
|
||||
continue;
|
||||
}
|
||||
inFrontmatter = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (frontmatterEnded || !inFrontmatter) {
|
||||
contentLines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
content = contentLines.join('\n').trim();
|
||||
content = skillsCore.stripFrontmatter(fullContent);
|
||||
frontmatter = { name, description };
|
||||
} catch (error) {
|
||||
console.log(`Error reading skill file: ${error.message}`);
|
||||
@@ -251,7 +229,7 @@ function runUseSkill(skillName) {
|
||||
if (frontmatter.description) {
|
||||
console.log(`# ${frontmatter.description}`);
|
||||
}
|
||||
console.log(`# Supporting tools and docs are in ${skillDirectory}`);
|
||||
console.log(`# Skill-specific tools and reference files live in ${skillDirectory}`);
|
||||
console.log('# ============================================');
|
||||
console.log('');
|
||||
|
||||
@@ -286,4 +264,4 @@ switch (command) {
|
||||
console.log(' superpowers-codex use-skill superpowers:brainstorming');
|
||||
console.log(' superpowers-codex use-skill my-custom-skill');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,13 +14,67 @@ import * as skillsCore from '../../lib/skills-core.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const SuperpowersPlugin = async ({ project, client, $, directory, worktree }) => {
|
||||
export const SuperpowersPlugin = async ({ client, directory }) => {
|
||||
const homeDir = os.homedir();
|
||||
const projectSkillsDir = path.join(directory, '.opencode/skills');
|
||||
const superpowersSkillsDir = path.join(homeDir, '.config/opencode/superpowers/skills');
|
||||
// Derive superpowers skills dir from plugin location (works for both symlinked and local installs)
|
||||
const superpowersSkillsDir = path.resolve(__dirname, '../../skills');
|
||||
const personalSkillsDir = path.join(homeDir, '.config/opencode/skills');
|
||||
const promptsDir = path.join(homeDir, '.config/opencode/prompts');
|
||||
const promptFile = path.join(promptsDir, 'superpowers.txt');
|
||||
|
||||
// Helper to generate bootstrap content
|
||||
const getBootstrapContent = (compact = false) => {
|
||||
const usingSuperpowersPath = skillsCore.resolveSkillPath('using-superpowers', superpowersSkillsDir, personalSkillsDir);
|
||||
if (!usingSuperpowersPath) return null;
|
||||
|
||||
const fullContent = fs.readFileSync(usingSuperpowersPath.skillFile, 'utf8');
|
||||
const content = skillsCore.stripFrontmatter(fullContent);
|
||||
|
||||
const toolMapping = compact
|
||||
? `**Tool Mapping:** TodoWrite->update_plan, Task->@mention, Skill->use_skill
|
||||
|
||||
**Skills naming (priority order):** project: > personal > superpowers:`
|
||||
: `**Tool Mapping for OpenCode:**
|
||||
When skills reference tools you don't have, substitute OpenCode equivalents:
|
||||
- \`TodoWrite\` → \`update_plan\`
|
||||
- \`Task\` tool with subagents → Use OpenCode's subagent system (@mention)
|
||||
- \`Skill\` tool → \`use_skill\` custom tool
|
||||
- \`Read\`, \`Write\`, \`Edit\`, \`Bash\` → Your native tools
|
||||
|
||||
**Skills naming (priority order):**
|
||||
- Project skills: \`project:skill-name\` (in .opencode/skills/)
|
||||
- Personal skills: \`skill-name\` (in ~/.config/opencode/skills/)
|
||||
- Superpowers skills: \`superpowers:skill-name\`
|
||||
- Project skills override personal, which override superpowers when names match`;
|
||||
|
||||
return `<EXTREMELY_IMPORTANT>
|
||||
You have superpowers.
|
||||
|
||||
**IMPORTANT: The using-superpowers skill content is included below. It is ALREADY LOADED - you are currently following it. Do NOT use the use_skill tool to load "using-superpowers" - that would be redundant. Use use_skill only for OTHER skills.**
|
||||
|
||||
${content}
|
||||
|
||||
${toolMapping}
|
||||
</EXTREMELY_IMPORTANT>`;
|
||||
};
|
||||
|
||||
// Helper to inject bootstrap via session.prompt
|
||||
const injectBootstrap = async (sessionID, compact = false) => {
|
||||
const bootstrapContent = getBootstrapContent(compact);
|
||||
if (!bootstrapContent) return false;
|
||||
|
||||
try {
|
||||
await client.session.prompt({
|
||||
path: { id: sessionID },
|
||||
body: {
|
||||
noReply: true,
|
||||
parts: [{ type: "text", text: bootstrapContent, synthetic: true }]
|
||||
}
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
tool: {
|
||||
@@ -78,8 +132,8 @@ export const SuperpowersPlugin = async ({ project, client, $, directory, worktre
|
||||
body: {
|
||||
noReply: true,
|
||||
parts: [
|
||||
{ type: "text", text: `Loading skill: ${name || skill_name}` },
|
||||
{ type: "text", text: `${skillHeader}\n\n${content}` }
|
||||
{ type: "text", text: `Loading skill: ${name || skill_name}`, synthetic: true },
|
||||
{ type: "text", text: `${skillHeader}\n\n${content}`, synthetic: true }
|
||||
]
|
||||
}
|
||||
});
|
||||
@@ -133,72 +187,27 @@ export const SuperpowersPlugin = async ({ project, client, $, directory, worktre
|
||||
}
|
||||
})
|
||||
},
|
||||
"chat.message": async (input, output) => {
|
||||
// Only inject on first message of session (or every message if needed)
|
||||
if (!output.message.system || output.message.system.length === 0) {
|
||||
const usingSuperpowersPath = skillsCore.resolveSkillPath('using-superpowers', superpowersSkillsDir, personalSkillsDir);
|
||||
event: async ({ event }) => {
|
||||
// Extract sessionID from various event structures
|
||||
const getSessionID = () => {
|
||||
return event.properties?.info?.id ||
|
||||
event.properties?.sessionID ||
|
||||
event.session?.id;
|
||||
};
|
||||
|
||||
if (usingSuperpowersPath) {
|
||||
const fullContent = fs.readFileSync(usingSuperpowersPath.skillFile, 'utf8');
|
||||
const usingSuperpowersContent = skillsCore.stripFrontmatter(fullContent);
|
||||
|
||||
const toolMapping = `**Tool Mapping for OpenCode:**
|
||||
When skills reference tools you don't have, substitute OpenCode equivalents:
|
||||
- \`TodoWrite\` → \`update_plan\`
|
||||
- \`Task\` tool with subagents → Use OpenCode's subagent system (@mention)
|
||||
- \`Skill\` tool → \`use_skill\` custom tool
|
||||
- \`Read\`, \`Write\`, \`Edit\`, \`Bash\` → Your native tools
|
||||
|
||||
**Skills naming (priority order):**
|
||||
- Project skills: \`project:skill-name\` (in .opencode/skills/)
|
||||
- Personal skills: \`skill-name\` (in ~/.config/opencode/skills/)
|
||||
- Superpowers skills: \`superpowers:skill-name\`
|
||||
- Project skills override personal, which override superpowers when names match`;
|
||||
|
||||
output.message.system = `<EXTREMELY_IMPORTANT>
|
||||
You have superpowers.
|
||||
|
||||
${usingSuperpowersContent}
|
||||
|
||||
${toolMapping}
|
||||
</EXTREMELY_IMPORTANT>`;
|
||||
// Inject bootstrap at session creation (before first user message)
|
||||
if (event.type === 'session.created') {
|
||||
const sessionID = getSessionID();
|
||||
if (sessionID) {
|
||||
await injectBootstrap(sessionID, false);
|
||||
}
|
||||
}
|
||||
},
|
||||
event: async ({ event }) => {
|
||||
// Re-inject bootstrap after context compaction to maintain superpowers
|
||||
|
||||
// Re-inject bootstrap after context compaction (compact version to save tokens)
|
||||
if (event.type === 'session.compacted') {
|
||||
const usingSuperpowersPath = skillsCore.resolveSkillPath('using-superpowers', superpowersSkillsDir, personalSkillsDir);
|
||||
|
||||
if (usingSuperpowersPath) {
|
||||
const fullContent = fs.readFileSync(usingSuperpowersPath.skillFile, 'utf8');
|
||||
const content = skillsCore.stripFrontmatter(fullContent);
|
||||
|
||||
const toolMapping = `**Tool Mapping:** TodoWrite->update_plan, Task->@mention, Skill->use_skill
|
||||
|
||||
**Skills naming (priority order):** project: > personal > superpowers:`;
|
||||
|
||||
try {
|
||||
await client.session.prompt({
|
||||
path: { id: event.properties.sessionID },
|
||||
body: {
|
||||
noReply: true,
|
||||
parts: [{
|
||||
type: "text",
|
||||
text: `<EXTREMELY_IMPORTANT>
|
||||
You have superpowers.
|
||||
|
||||
${content}
|
||||
|
||||
${toolMapping}
|
||||
</EXTREMELY_IMPORTANT>`
|
||||
}]
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
// Silent failure - bootstrap will be missing but session continues
|
||||
console.error('Failed to re-inject superpowers after compaction:', err.message);
|
||||
}
|
||||
const sessionID = getSessionID();
|
||||
if (sessionID) {
|
||||
await injectBootstrap(sessionID, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
57
README.md
57
README.md
@@ -1,34 +1,28 @@
|
||||
# Superpowers
|
||||
|
||||
AI agents skip steps under time pressure. They bypass best practices when confident. They lack consistency across tasks. The result: bugs you didn't catch, designs you didn't validate, tests you didn't write.
|
||||
Superpowers is a complete software development workflow for your coding agents, built on top of a set of composable "skills" and some initial instructions that make sure your agent uses them.
|
||||
|
||||
**Superpowers fixes this.** Skills are mandatory instruction documents agents must follow. When a relevant skill exists, the agent checks for it, uses it, or fails the task.
|
||||
## How it works
|
||||
|
||||
## How It Works
|
||||
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.
|
||||
|
||||
At session start, the agent learns which skills exist. Before any task, the agent checks: "Does a skill match this work?" If yes, the agent loads and follows that skill.
|
||||
Once it's teased a spec out of the conversation, it shows it to you in chunks short enough to actually read and digest.
|
||||
|
||||
Skills are markdown files with proven workflows. The `test-driven-development` skill forces RED-GREEN-REFACTOR. No test-first? Delete the code and start over. The skill prevents rationalization.
|
||||
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.
|
||||
|
||||
## The Workflow
|
||||
Next up, once you say "go", it launches a *subagent-driven-development* process, having agents work through each engineering task, inspecting and reviewing their work, and continuing forward. It's not uncommon for Claude to be able to work autonomously for a couple hours at a time without deviating from the plan you put together.
|
||||
|
||||
**When you ask to build a feature:**
|
||||
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.
|
||||
|
||||
1. **brainstorming** - Activates before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. Saves design document.
|
||||
|
||||
2. **using-git-worktrees** - Activates after design approval. Creates isolated workspace on new branch, runs project setup, verifies clean test baseline.
|
||||
## Sponsorship
|
||||
|
||||
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.
|
||||
If Superpowers has helped you do stuff that makes money and you are so inclined, I'd greatly appreciate it if you'd consider [sponsoring my opensource work](https://github.com/sponsors/obra).
|
||||
|
||||
4. **subagent-driven-development** or **executing-plans** - Activates with plan. Dispatches fresh subagent per task (same session, fast iteration) or executes in batches (parallel session, human checkpoints).
|
||||
Thanks!
|
||||
|
||||
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.
|
||||
- Jesse
|
||||
|
||||
6. **requesting-code-review** - Activates between tasks. Reviews against plan, reports issues by severity. Critical issues block progress.
|
||||
|
||||
7. **finishing-a-development-branch** - Activates when tasks complete. Verifies tests, presents options (merge/PR/keep/discard), cleans up worktree.
|
||||
|
||||
**The agent checks for relevant skills before any task.** Mandatory workflows, not suggestions.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -83,22 +77,40 @@ Fetch and follow instructions from https://raw.githubusercontent.com/obra/superp
|
||||
|
||||
**Detailed docs:** [docs/README.opencode.md](docs/README.opencode.md)
|
||||
|
||||
## The Basic Workflow
|
||||
|
||||
1. **brainstorming** - Activates before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. Saves design document.
|
||||
|
||||
2. **using-git-worktrees** - Activates after design approval. Creates isolated workspace on new branch, runs project setup, verifies clean test baseline.
|
||||
|
||||
3. **writing-plans** - Activates with approved design. Breaks work into bite-sized tasks (2-5 minutes each). Every task has exact file paths, complete code, verification steps.
|
||||
|
||||
4. **subagent-driven-development** or **executing-plans** - Activates with plan. Dispatches fresh subagent per task (same session, fast iteration) or executes in batches (parallel session, human checkpoints).
|
||||
|
||||
5. **test-driven-development** - Activates during implementation. Enforces RED-GREEN-REFACTOR: write failing test, watch it fail, write minimal code, watch it pass, commit. Deletes code written before tests.
|
||||
|
||||
6. **requesting-code-review** - Activates between tasks. Reviews against plan, reports issues by severity. Critical issues block progress.
|
||||
|
||||
7. **finishing-a-development-branch** - Activates when tasks complete. Verifies tests, presents options (merge/PR/keep/discard), cleans up worktree.
|
||||
|
||||
**The agent checks for relevant skills before any task.** Mandatory workflows, not suggestions.
|
||||
|
||||
## What's Inside
|
||||
|
||||
### Skills Library
|
||||
|
||||
**Testing** (`skills/testing/`)
|
||||
**Testing**
|
||||
- **test-driven-development** - RED-GREEN-REFACTOR cycle
|
||||
- **condition-based-waiting** - Async test patterns
|
||||
- **testing-anti-patterns** - Common pitfalls to avoid
|
||||
|
||||
**Debugging** (`skills/debugging/`)
|
||||
**Debugging**
|
||||
- **systematic-debugging** - 4-phase root cause process
|
||||
- **root-cause-tracing** - Find the real problem
|
||||
- **verification-before-completion** - Ensure it's actually fixed
|
||||
- **defense-in-depth** - Multiple validation layers
|
||||
|
||||
**Collaboration** (`skills/collaboration/`)
|
||||
**Collaboration**
|
||||
- **brainstorming** - Socratic design refinement
|
||||
- **writing-plans** - Detailed implementation plans
|
||||
- **executing-plans** - Batch execution with checkpoints
|
||||
@@ -109,9 +121,8 @@ Fetch and follow instructions from https://raw.githubusercontent.com/obra/superp
|
||||
- **finishing-a-development-branch** - Merge/PR decision workflow
|
||||
- **subagent-driven-development** - Fast iteration with quality gates
|
||||
|
||||
**Meta** (`skills/meta/`)
|
||||
**Meta**
|
||||
- **writing-skills** - Create new skills following best practices
|
||||
- **sharing-skills** - Contribute skills back via branch and PR
|
||||
- **testing-skills-with-subagents** - Validate skill quality
|
||||
- **using-superpowers** - Introduction to the skills system
|
||||
|
||||
@@ -134,7 +145,7 @@ Skills live directly in this repository. To contribute:
|
||||
4. Use the `testing-skills-with-subagents` skill to validate quality
|
||||
5. Submit a PR
|
||||
|
||||
See `skills/meta/writing-skills/SKILL.md` for the complete guide.
|
||||
See `skills/writing-skills/SKILL.md` for the complete guide.
|
||||
|
||||
## Updating
|
||||
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
# Superpowers Release Notes
|
||||
|
||||
## [Unreleased]
|
||||
## v3.6.2 (2025-12-03)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Linux Compatibility**: Fixed polyglot hook wrapper (`run-hook.cmd`) to use POSIX-compliant syntax
|
||||
- Replaced bash-specific `${BASH_SOURCE[0]:-$0}` with standard `$0` on line 16
|
||||
- Resolves "Bad substitution" error on Ubuntu/Debian systems where `/bin/sh` is dash
|
||||
- Fixes #141
|
||||
|
||||
---
|
||||
|
||||
## v3.5.1 (2025-11-24)
|
||||
|
||||
### Changed
|
||||
|
||||
- **OpenCode Bootstrap Refactor**: Switched from `chat.message` hook to `session.created` event for bootstrap injection
|
||||
- Bootstrap now injects at session creation via `session.prompt()` with `noReply: true`
|
||||
- Explicitly tells the model that using-superpowers is already loaded to prevent redundant skill loading
|
||||
- Consolidated bootstrap content generation into shared `getBootstrapContent()` helper
|
||||
- Cleaner single-implementation approach (removed fallback pattern)
|
||||
|
||||
---
|
||||
|
||||
## v3.5.0 (2025-11-23)
|
||||
|
||||
### Added
|
||||
|
||||
@@ -12,7 +35,8 @@
|
||||
- Three-tier skill priority: project > personal > superpowers
|
||||
- Project-local skills support (`.opencode/skills/`)
|
||||
- Shared core module (`lib/skills-core.js`) for code reuse with Codex
|
||||
- Installation guide in `.opencode/INSTALL.md`
|
||||
- Automated test suite with proper isolation (`tests/opencode/`)
|
||||
- Platform-specific documentation (`docs/README.opencode.md`, `docs/README.codex.md`)
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -21,6 +45,12 @@
|
||||
- Single source of truth for skill discovery and parsing
|
||||
- Codex successfully loads ES modules via Node.js interop
|
||||
|
||||
- **Improved Documentation**: Rewrote README to explain problem/solution clearly
|
||||
- Removed duplicate sections and conflicting information
|
||||
- Added complete workflow description (brainstorm → plan → execute → finish)
|
||||
- Simplified platform installation instructions
|
||||
- Emphasized skill-checking protocol over automatic activation claims
|
||||
|
||||
---
|
||||
|
||||
## v3.4.1 (2025-10-31)
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
name: code-reviewer
|
||||
description: |
|
||||
Use this agent when a major project step has been completed and needs to be reviewed against the original plan and coding standards. Examples: <example>Context: The user is creating a code-review agent that should be called after a logical chunk of code is written. user: "I've finished implementing the user authentication system as outlined in step 3 of our plan" assistant: "Great work! Now let me use the code-reviewer agent to review the implementation against our plan and coding standards" <commentary>Since a major project step has been completed, use the code-reviewer agent to validate the work against the plan and identify any issues.</commentary></example> <example>Context: User has completed a significant feature implementation. user: "The API endpoints for the task management system are now complete - that covers step 2 from our architecture document" assistant: "Excellent! Let me have the code-reviewer agent examine this implementation to ensure it aligns with our plan and follows best practices" <commentary>A numbered step from the planning document has been completed, so the code-reviewer agent should review the work.</commentary></example>
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a Senior Code Reviewer with expertise in software architecture, design patterns, and best practices. Your role is to review completed project steps against original plans and ensure code quality standards are met.
|
||||
|
||||
212
docs/windows/polyglot-hooks.md
Normal file
212
docs/windows/polyglot-hooks.md
Normal file
@@ -0,0 +1,212 @@
|
||||
# Cross-Platform Polyglot Hooks for Claude Code
|
||||
|
||||
Claude Code plugins need hooks that work on Windows, macOS, and Linux. This document explains the polyglot wrapper technique that makes this possible.
|
||||
|
||||
## The Problem
|
||||
|
||||
Claude Code runs hook commands through the system's default shell:
|
||||
- **Windows**: CMD.exe
|
||||
- **macOS/Linux**: bash or sh
|
||||
|
||||
This creates several challenges:
|
||||
|
||||
1. **Script execution**: Windows CMD can't execute `.sh` files directly - it tries to open them in a text editor
|
||||
2. **Path format**: Windows uses backslashes (`C:\path`), Unix uses forward slashes (`/path`)
|
||||
3. **Environment variables**: `$VAR` syntax doesn't work in CMD
|
||||
4. **No `bash` in PATH**: Even with Git Bash installed, `bash` isn't in the PATH when CMD runs
|
||||
|
||||
## The Solution: Polyglot `.cmd` Wrapper
|
||||
|
||||
A polyglot script is valid syntax in multiple languages simultaneously. Our wrapper is valid in both CMD and bash:
|
||||
|
||||
```cmd
|
||||
: << 'CMDBLOCK'
|
||||
@echo off
|
||||
"C:\Program Files\Git\bin\bash.exe" -l -c "\"$(cygpath -u \"$CLAUDE_PLUGIN_ROOT\")/hooks/session-start.sh\""
|
||||
exit /b
|
||||
CMDBLOCK
|
||||
|
||||
# Unix shell runs from here
|
||||
"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh"
|
||||
```
|
||||
|
||||
### How It Works
|
||||
|
||||
#### On Windows (CMD.exe)
|
||||
|
||||
1. `: << 'CMDBLOCK'` - CMD sees `:` as a label (like `:label`) and ignores `<< 'CMDBLOCK'`
|
||||
2. `@echo off` - Suppresses command echoing
|
||||
3. The bash.exe command runs with:
|
||||
- `-l` (login shell) to get proper PATH with Unix utilities
|
||||
- `cygpath -u` converts Windows path to Unix format (`C:\foo` → `/c/foo`)
|
||||
4. `exit /b` - Exits the batch script, stopping CMD here
|
||||
5. Everything after `CMDBLOCK` is never reached by CMD
|
||||
|
||||
#### On Unix (bash/sh)
|
||||
|
||||
1. `: << 'CMDBLOCK'` - `:` is a no-op, `<< 'CMDBLOCK'` starts a heredoc
|
||||
2. Everything until `CMDBLOCK` is consumed by the heredoc (ignored)
|
||||
3. `# Unix shell runs from here` - Comment
|
||||
4. The script runs directly with the Unix path
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
hooks/
|
||||
├── hooks.json # Points to the .cmd wrapper
|
||||
├── session-start.cmd # Polyglot wrapper (cross-platform entry point)
|
||||
└── session-start.sh # Actual hook logic (bash script)
|
||||
```
|
||||
|
||||
### hooks.json
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup|resume|clear|compact",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.cmd\""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: The path must be quoted because `${CLAUDE_PLUGIN_ROOT}` may contain spaces on Windows (e.g., `C:\Program Files\...`).
|
||||
|
||||
## Requirements
|
||||
|
||||
### Windows
|
||||
- **Git for Windows** must be installed (provides `bash.exe` and `cygpath`)
|
||||
- Default installation path: `C:\Program Files\Git\bin\bash.exe`
|
||||
- If Git is installed elsewhere, the wrapper needs modification
|
||||
|
||||
### Unix (macOS/Linux)
|
||||
- Standard bash or sh shell
|
||||
- The `.cmd` file must have execute permission (`chmod +x`)
|
||||
|
||||
## Writing Cross-Platform Hook Scripts
|
||||
|
||||
Your actual hook logic goes in the `.sh` file. To ensure it works on Windows (via Git Bash):
|
||||
|
||||
### Do:
|
||||
- Use pure bash builtins when possible
|
||||
- Use `$(command)` instead of backticks
|
||||
- Quote all variable expansions: `"$VAR"`
|
||||
- Use `printf` or here-docs for output
|
||||
|
||||
### Avoid:
|
||||
- External commands that may not be in PATH (sed, awk, grep)
|
||||
- If you must use them, they're available in Git Bash but ensure PATH is set up (use `bash -l`)
|
||||
|
||||
### Example: JSON Escaping Without sed/awk
|
||||
|
||||
Instead of:
|
||||
```bash
|
||||
escaped=$(echo "$content" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | awk '{printf "%s\\n", $0}')
|
||||
```
|
||||
|
||||
Use pure bash:
|
||||
```bash
|
||||
escape_for_json() {
|
||||
local input="$1"
|
||||
local output=""
|
||||
local i char
|
||||
for (( i=0; i<${#input}; i++ )); do
|
||||
char="${input:$i:1}"
|
||||
case "$char" in
|
||||
$'\\') output+='\\' ;;
|
||||
'"') output+='\"' ;;
|
||||
$'\n') output+='\n' ;;
|
||||
$'\r') output+='\r' ;;
|
||||
$'\t') output+='\t' ;;
|
||||
*) output+="$char" ;;
|
||||
esac
|
||||
done
|
||||
printf '%s' "$output"
|
||||
}
|
||||
```
|
||||
|
||||
## Reusable Wrapper Pattern
|
||||
|
||||
For plugins with multiple hooks, you can create a generic wrapper that takes the script name as an argument:
|
||||
|
||||
### run-hook.cmd
|
||||
```cmd
|
||||
: << 'CMDBLOCK'
|
||||
@echo off
|
||||
set "SCRIPT_DIR=%~dp0"
|
||||
set "SCRIPT_NAME=%~1"
|
||||
"C:\Program Files\Git\bin\bash.exe" -l -c "cd \"$(cygpath -u \"%SCRIPT_DIR%\")\" && \"./%SCRIPT_NAME%\""
|
||||
exit /b
|
||||
CMDBLOCK
|
||||
|
||||
# Unix shell runs from here
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
|
||||
SCRIPT_NAME="$1"
|
||||
shift
|
||||
"${SCRIPT_DIR}/${SCRIPT_NAME}" "$@"
|
||||
```
|
||||
|
||||
### hooks.json using the reusable wrapper
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" validate-bash.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "bash is not recognized"
|
||||
CMD can't find bash. The wrapper uses the full path `C:\Program Files\Git\bin\bash.exe`. If Git is installed elsewhere, update the path.
|
||||
|
||||
### "cygpath: command not found" or "dirname: command not found"
|
||||
Bash isn't running as a login shell. Ensure `-l` flag is used.
|
||||
|
||||
### Path has weird `\/` in it
|
||||
`${CLAUDE_PLUGIN_ROOT}` expanded to a Windows path ending with backslash, then `/hooks/...` was appended. Use `cygpath` to convert the entire path.
|
||||
|
||||
### Script opens in text editor instead of running
|
||||
The hooks.json is pointing directly to the `.sh` file. Point to the `.cmd` wrapper instead.
|
||||
|
||||
### Works in terminal but not as hook
|
||||
Claude Code may run hooks differently. Test by simulating the hook environment:
|
||||
```powershell
|
||||
$env:CLAUDE_PLUGIN_ROOT = "C:\path\to\plugin"
|
||||
cmd /c "C:\path\to\plugin\hooks\session-start.cmd"
|
||||
```
|
||||
|
||||
## Related Issues
|
||||
|
||||
- [anthropics/claude-code#9758](https://github.com/anthropics/claude-code/issues/9758) - .sh scripts open in editor on Windows
|
||||
- [anthropics/claude-code#3417](https://github.com/anthropics/claude-code/issues/3417) - Hooks don't work on Windows
|
||||
- [anthropics/claude-code#6023](https://github.com/anthropics/claude-code/issues/6023) - CLAUDE_PROJECT_DIR not found
|
||||
@@ -6,7 +6,7 @@
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh"
|
||||
"command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
19
hooks/run-hook.cmd
Executable file
19
hooks/run-hook.cmd
Executable file
@@ -0,0 +1,19 @@
|
||||
: << 'CMDBLOCK'
|
||||
@echo off
|
||||
REM Polyglot wrapper: runs .sh scripts cross-platform
|
||||
REM Usage: run-hook.cmd <script-name> [args...]
|
||||
REM The script should be in the same directory as this wrapper
|
||||
|
||||
if "%~1"=="" (
|
||||
echo run-hook.cmd: missing script name >&2
|
||||
exit /b 1
|
||||
)
|
||||
"C:\Program Files\Git\bin\bash.exe" -l "%~dp0%~1" %2 %3 %4 %5 %6 %7 %8 %9
|
||||
exit /b
|
||||
CMDBLOCK
|
||||
|
||||
# Unix shell runs from here
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
SCRIPT_NAME="$1"
|
||||
shift
|
||||
"${SCRIPT_DIR}/${SCRIPT_NAME}" "$@"
|
||||
@@ -17,9 +17,27 @@ fi
|
||||
# Read using-superpowers content
|
||||
using_superpowers_content=$(cat "${PLUGIN_ROOT}/skills/using-superpowers/SKILL.md" 2>&1 || echo "Error reading using-superpowers skill")
|
||||
|
||||
# Escape outputs for JSON
|
||||
using_superpowers_escaped=$(echo "$using_superpowers_content" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | awk '{printf "%s\\n", $0}')
|
||||
warning_escaped=$(echo "$warning_message" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | awk '{printf "%s\\n", $0}')
|
||||
# Escape outputs for JSON using pure bash
|
||||
escape_for_json() {
|
||||
local input="$1"
|
||||
local output=""
|
||||
local i char
|
||||
for (( i=0; i<${#input}; i++ )); do
|
||||
char="${input:$i:1}"
|
||||
case "$char" in
|
||||
$'\\') output+='\\' ;;
|
||||
'"') output+='\"' ;;
|
||||
$'\n') output+='\n' ;;
|
||||
$'\r') output+='\r' ;;
|
||||
$'\t') output+='\t' ;;
|
||||
*) output+="$char" ;;
|
||||
esac
|
||||
done
|
||||
printf '%s' "$output"
|
||||
}
|
||||
|
||||
using_superpowers_escaped=$(escape_for_json "$using_superpowers_content")
|
||||
warning_escaped=$(escape_for_json "$warning_message")
|
||||
|
||||
# Output context injection as JSON
|
||||
cat <<EOF
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
# Bisection script to find which test creates unwanted files/state
|
||||
# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
|
||||
# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'
|
||||
|
||||
@@ -94,7 +94,7 @@ for test in "${tests[@]}"; do
|
||||
|
||||
if [ ! -f "$test_path" ]; then
|
||||
echo " [SKIP] Test file not found: $test"
|
||||
((skipped++))
|
||||
skipped=$((skipped + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
@@ -111,13 +111,13 @@ for test in "${tests[@]}"; do
|
||||
duration=$((end_time - start_time))
|
||||
echo ""
|
||||
echo " [PASS] $test (${duration}s)"
|
||||
((passed++))
|
||||
passed=$((passed + 1))
|
||||
else
|
||||
end_time=$(date +%s)
|
||||
duration=$((end_time - start_time))
|
||||
echo ""
|
||||
echo " [FAIL] $test (${duration}s)"
|
||||
((failed++))
|
||||
failed=$((failed + 1))
|
||||
fi
|
||||
else
|
||||
# Capture output for non-verbose mode
|
||||
@@ -125,7 +125,7 @@ for test in "${tests[@]}"; do
|
||||
end_time=$(date +%s)
|
||||
duration=$((end_time - start_time))
|
||||
echo " [PASS] (${duration}s)"
|
||||
((passed++))
|
||||
passed=$((passed + 1))
|
||||
else
|
||||
end_time=$(date +%s)
|
||||
duration=$((end_time - start_time))
|
||||
@@ -133,7 +133,7 @@ for test in "${tests[@]}"; do
|
||||
echo ""
|
||||
echo " Output:"
|
||||
echo "$output" | sed 's/^/ /'
|
||||
((failed++))
|
||||
failed=$((failed + 1))
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
@@ -30,17 +30,8 @@ description: A test skill for unit testing
|
||||
This is the content.
|
||||
EOF
|
||||
|
||||
# Run Node.js test
|
||||
result=$(node --input-type=module <<'NODESCRIPT'
|
||||
import { extractFrontmatter } from '$HOME/.config/opencode/superpowers/lib/skills-core.js';
|
||||
const result = extractFrontmatter(process.env.TEST_HOME + '/test-skill/SKILL.md');
|
||||
console.log(JSON.stringify(result));
|
||||
NODESCRIPT
|
||||
) 2>&1 || true
|
||||
|
||||
# Try alternative approach if module import fails
|
||||
if ! echo "$result" | grep -q "test-skill"; then
|
||||
result=$(node -e "
|
||||
# Run Node.js test using inline function (avoids ESM path resolution issues in test env)
|
||||
result=$(node -e "
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
@@ -76,7 +67,6 @@ function extractFrontmatter(filePath) {
|
||||
const result = extractFrontmatter('$TEST_HOME/test-skill/SKILL.md');
|
||||
console.log(JSON.stringify(result));
|
||||
" 2>&1)
|
||||
fi
|
||||
|
||||
if echo "$result" | grep -q '"name":"test-skill"'; then
|
||||
echo " [PASS] extractFrontmatter parses name correctly"
|
||||
@@ -372,5 +362,79 @@ else
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Test 5: Test checkForUpdates function
|
||||
echo ""
|
||||
echo "Test 5: Testing checkForUpdates..."
|
||||
|
||||
# Create a test git repo
|
||||
mkdir -p "$TEST_HOME/test-repo"
|
||||
cd "$TEST_HOME/test-repo"
|
||||
git init --quiet
|
||||
git config user.email "test@test.com"
|
||||
git config user.name "Test"
|
||||
echo "test" > file.txt
|
||||
git add file.txt
|
||||
git commit -m "initial" --quiet
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
# Test checkForUpdates on repo without remote (should return false, not error)
|
||||
result=$(node -e "
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
function checkForUpdates(repoDir) {
|
||||
try {
|
||||
const output = execSync('git fetch origin && git status --porcelain=v1 --branch', {
|
||||
cwd: repoDir,
|
||||
timeout: 3000,
|
||||
encoding: 'utf8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
const statusLines = output.split('\n');
|
||||
for (const line of statusLines) {
|
||||
if (line.startsWith('## ') && line.includes('[behind ')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Test 1: Repo without remote should return false (graceful error handling)
|
||||
const result1 = checkForUpdates('$TEST_HOME/test-repo');
|
||||
console.log('NO_REMOTE:', result1);
|
||||
|
||||
// Test 2: Non-existent directory should return false
|
||||
const result2 = checkForUpdates('$TEST_HOME/nonexistent');
|
||||
console.log('NONEXISTENT:', result2);
|
||||
|
||||
// Test 3: Non-git directory should return false
|
||||
const result3 = checkForUpdates('$TEST_HOME');
|
||||
console.log('NOT_GIT:', result3);
|
||||
" 2>&1)
|
||||
|
||||
if echo "$result" | grep -q 'NO_REMOTE: false'; then
|
||||
echo " [PASS] checkForUpdates handles repo without remote gracefully"
|
||||
else
|
||||
echo " [FAIL] checkForUpdates should return false for repo without remote"
|
||||
echo " Result: $result"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if echo "$result" | grep -q 'NONEXISTENT: false'; then
|
||||
echo " [PASS] checkForUpdates handles non-existent directory"
|
||||
else
|
||||
echo " [FAIL] checkForUpdates should return false for non-existent directory"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if echo "$result" | grep -q 'NOT_GIT: false'; then
|
||||
echo " [PASS] checkForUpdates handles non-git directory"
|
||||
else
|
||||
echo " [FAIL] checkForUpdates should return false for non-git directory"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== All skills-core library tests passed ==="
|
||||
|
||||
Reference in New Issue
Block a user