diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8338865..4d83572 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "compound-engineering-feat-python", - "version": "2.5.2", - "description": "Python-specialized development tools with microservice support. 33 agents, 21 commands, 26 skills, 1 MCP server.", + "version": "3.0.0", + "description": "Python-specialized development tools with microservice support, built on superpowers. 32 agents, 18 commands, 21 skills, 1 MCP server.", "hooks": { "SessionStart": [ { diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d4a02d..76d0d30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,71 @@ All notable changes to the compound-engineering-feat-python plugin will be docum The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.0.0] - 2026-05-25 + +### Changed +- Plugin now requires the `superpowers` plugin as a foundation. All generic workflow + primitives (brainstorming, planning, execution, review, git worktrees, parallel + agents, skill writing) are delegated to superpowers; this plugin focuses on + Python/Django/FastAPI domain value and microservice orchestration. +- Workflow commands rewritten as thin wrappers that delegate to superpowers skills: + `/workflows:brainstorm` → `superpowers:brainstorming`, `/workflows:plan` → + `superpowers:writing-plans`, `/workflows:work` → `superpowers:executing-plans` + (+ Python quality gate), `/workflows:review` → `superpowers:requesting-code-review`. +- Microservice Focus Gate logic extracted from each workflow command into a new + `microservice-focus` skill. +- Brainstorm artifact paths changed from `docs/brainstorms/` to + `docs/superpowers/specs/` (and `{service}/docs/superpowers/specs/` in multi-service + mode), matching superpowers vocabulary ("spec" instead of "brainstorm doc"). +- `scripts/check-dependencies.sh` now warns if the superpowers plugin is not detected. +- `` block in `CLAUDE.md` normalized from `connections:` (single line) + to `dependencies:` (list format), matching the workflow commands and the + `microservice-focus` skill. + +### Removed +- `/workflows:compound` command (knowledge-capture pattern dropped). Deprecation shim + remains for one major cycle. +- `/lfg` and `/slfg` autonomous pipelines (users orchestrate stages directly). + Deprecation shims remain for one major cycle. +- 6 skills replaced by superpowers equivalents: `brainstorming`, `git-worktree`, + `skill-creator`, `create-agent-skills`, `orchestrating-swarms`, and `compound-docs` + (the last because its only consumer was `/workflows:compound`). +- `learnings-researcher` agent (read from the now-removed `docs/solutions/` pattern). +- Knowledge-compounding pattern (`docs/solutions/`) — historical files in user repos + remain untouched (and `/workflows:review` still protects them from accidental + deletion) but are no longer read or written by this plugin. +- `compound` key from `workflow_skills` in `compound-engineering.local.md` schema. + Existing keys are silently ignored. + +### Deprecated +- `/lfg`, `/slfg`, `/workflows:compound` exist as shims that print a migration message + when invoked. They will be removed entirely in v4.0.0. + +### Added +- `microservice-focus` skill consolidating service discovery, `--services` parsing, + multi-service prompting via `AskUserQuestion`, and `` block construction. + +### Migration +- Install superpowers: + ``` + /plugin marketplace add anthropics/claude-plugins-official + /plugin install superpowers@claude-plugins-official + ``` +- Replace any `/lfg`, `/slfg`, or `/workflows:compound` invocations with the + appropriate sequence of `/workflows:brainstorm` → `/workflows:plan` → + `/workflows:work` → `/workflows:review` (or `superpowers:dispatching-parallel-agents` + within stages for parallel work). +- Move any documents under `docs/brainstorms/` to `docs/superpowers/specs/` if you + want them auto-discovered by `/workflows:plan` (path-only rename; no schema change). +- Remove the `compound:` line from your project's `compound-engineering.local.md` + if present (harmless to leave, but cleaner to drop). + +### Summary + +32 agents, 18 active commands (+ 3 deprecation shims for one major cycle), 21 skills, 1 MCP server. Requires the `superpowers` plugin. + +--- + ## [2.5.2] - 2026-04-20 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index 04231d2..1bddd7b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -48,13 +48,12 @@ skills/ - `/workflows:plan` - Create implementation plans - `/workflows:review` - Run comprehensive code reviews - `/workflows:work` - Execute work items systematically -- `/workflows:compound` - Document solved problems **Why `workflows:`?** Claude Code has built-in `/plan` and `/review` commands. Using `name: workflows:plan` in frontmatter creates a unique `/workflows:plan` command with no collision. ## Skill Compliance Checklist -When adding or modifying skills, verify compliance with skill-creator spec: +When adding or modifying skills, verify compliance with the official skill spec (see `superpowers:writing-skills`): ### YAML Frontmatter (Required) @@ -102,11 +101,12 @@ When spawning sub-agents via Task tool, include a standardized `` ``` services: service-a (./service-a), service-b (./service-b) - connections: service-a depends on lib-common (pyproject.toml) + dependencies: + - service-a depends on lib-common (shared DTOs) ``` -All commands and skills MUST include this block when spawning sub-agents to prevent focus loss in nested delegation chains. +All commands and skills MUST include this block when spawning sub-agents to prevent focus loss in nested delegation chains. The full Focus Gate protocol and `` template now live in the `microservice-focus` skill. Workflow commands invoke that skill once instead of inlining the logic. ### Pipeline Mode @@ -119,9 +119,8 @@ All workflow commands accept `--services` argument for automated invocation: | Doc Type | Single Service | Cross-Service | |----------|---------------|---------------| -| Brainstorms | Single doc mentioning affected services | `{service}/docs/brainstorms/...` per service | -| Plans | `{service}/docs/plans/...` | Root overview + per-service plan files | -| Solutions | `{service}/docs/solutions/...` | Root `docs/solutions/...` with service refs | +| Specs | `docs/superpowers/specs/...` | `{service}/docs/superpowers/specs/...` per service | +| Plans | `docs/superpowers/plans/...` (or `{service}/docs/superpowers/plans/...`) | Root overview at `docs/superpowers/plans/...` + per-service plan files | ## Workflow Skills Configuration @@ -134,7 +133,6 @@ workflow_skills: plan: [django-patterns] work: [django-patterns, pytest-patterns] review: [django-patterns, pytest-patterns] - compound: [django-patterns] --- ``` @@ -149,6 +147,3 @@ Project-local skills in `.claude/skills/` can also be listed here by name. - If the user asks for something that will cause problems (bad architecture, wrong pattern, fragile code), push back before implementing. - Be direct and honest, even if it means disagreeing. A wrong decision caught early saves hours of rework. -## Documentation - -See `docs/solutions/plugin-versioning-requirements.md` for detailed versioning workflow. diff --git a/README.md b/README.md index 8b28345..b40a4eb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Compound Engineering feat. Python -A Claude Code plugin that supercharges Python development with 33 specialized agents, 21 commands, 26 skills, and an MCP server — all wired into a cohesive engineering workflow. Built for Django, FastAPI, pytest, Pydantic, PostgreSQL, and PostGIS projects, with first-class support for multi-service monorepos. +A Claude Code plugin that supercharges Python development with 32 specialized agents, 18 commands, 21 skills, and an MCP server — built on Anthropic's `superpowers` plugin for workflow primitives. Specialized for Django, FastAPI, pytest, Pydantic, PostgreSQL, and PostGIS projects, with first-class support for multi-service monorepos. > Fork of [Compound Engineering Plugin](https://github.com/EveryInc/compound-engineering-plugin) by [Kieran Klaassen](https://github.com/kieranklaassen), fully rewritten for the Python ecosystem. @@ -9,15 +9,22 @@ A Claude Code plugin that supercharges Python development with 33 specialized ag Instead of generic AI assistance, this plugin gives Claude deep knowledge of Python frameworks and enforces a structured engineering workflow: ``` -/workflows:brainstorm → /workflows:plan → /workflows:work → /workflows:review → /workflows:compound +/workflows:brainstorm → /workflows:plan → /workflows:work → /workflows:review ``` Each step loads relevant skills (Django patterns, pytest conventions, PostgreSQL optimization...), spawns specialized review agents, and enforces quality gates — tests must pass, linting must be clean, pre-commit hooks must succeed — before anything ships. -For the impatient: `/lfg` runs the entire pipeline autonomously, from plan to PR. - ## Installation +### Prerequisite: Install superpowers + +This plugin requires the `superpowers` plugin (provides generic workflow primitives). + +``` +/plugin marketplace add anthropics/claude-plugins-official +/plugin install superpowers@claude-plugins-official +``` + This plugin is distributed as its own Claude Code marketplace. Add the repo, then install: ``` @@ -51,29 +58,24 @@ Checked automatically on session start — you'll see warnings for anything miss /workflows:plan add rate limiting with Redis sliding window # Execute the plan -/workflows:work docs/plans/2026-04-01-rate-limiting.md +/workflows:work docs/superpowers/plans/2026-04-01-rate-limiting.md # Review the changes /workflows:review - -# Document what you learned -/workflows:compound - -# Or just do it all at once -/lfg add rate limiting to the payment API ``` +Brainstorm specs land at `docs/superpowers/specs/`; plans at `docs/superpowers/plans/`. + ## Core Workflow Commands Commands use `workflows:` prefix to avoid collisions with Claude Code built-ins (`/plan`, `/review`). | Command | Purpose | |---------|---------| -| `/workflows:brainstorm` | Explore requirements and approaches before committing to a plan | -| `/workflows:plan` | Generate implementation plans with size-appropriate detail | -| `/workflows:work` | Execute a plan with incremental commits, quality gates, and test-fix loops | -| `/workflows:review` | Multi-agent code review with configurable reviewer roster | -| `/workflows:compound` | Capture solved problems as searchable documentation in `docs/solutions/` | +| `/workflows:brainstorm` | Explore requirements before planning (delegates to `superpowers:brainstorming`) | +| `/workflows:plan` | Generate implementation plans (delegates to `superpowers:writing-plans`) | +| `/workflows:work` | Execute a plan with Python quality gates (delegates to `superpowers:executing-plans`) | +| `/workflows:review` | Multi-agent Python code review (delegates to `superpowers:requesting-code-review`) | Each workflow command: - Loads project-specific skills from `compound-engineering.local.md` configuration @@ -84,8 +86,6 @@ Each workflow command: | Command | Description | |---------|-------------| -| `/lfg` | Full autonomous pipeline: plan → deepen → work → review → test → video → PR | -| `/slfg` | Same as `/lfg` but uses swarm mode for parallel execution | | `/deepen-plan` | Enrich a plan with parallel research agents for each section | | `/changelog` | Generate changelogs from recent merges | | `/create-agent-skill` | Guided skill creation | @@ -101,7 +101,16 @@ Each workflow command: | `/report-bug` | Report a plugin bug | | `/heal-skill` | Fix skill documentation issues | -## Agents (33) +### Deprecated commands (v3.0.0) + +These commands were removed in v3.0.0; they remain as shims that print a migration message and will be deleted in v4.0.0: + +- `/workflows:compound` — knowledge-capture pattern dropped; no replacement. +- `/lfg`, `/slfg` — autonomous pipelines dropped; orchestrate stages directly. + +See CHANGELOG.md v3.0.0 for migration details. + +## Agents (32) Agents run as sub-processes during workflows. They are grouped by specialization. @@ -169,7 +178,6 @@ Agents use a 3-tier model strategy to optimize cost without sacrificing quality: | `best-practices-researcher` | sonnet | External best practices (checks skills first) | | `framework-docs-researcher` | sonnet | Framework documentation and patterns | | `git-history-analyzer` | sonnet | Git history and code evolution | -| `learnings-researcher` | haiku | Past solutions from `docs/solutions/` | | `repo-research-analyst` | sonnet | Repository structure and conventions | ### Design @@ -189,10 +197,12 @@ Agents use a 3-tier model strategy to optimize cost without sacrificing quality: | `pr-comment-resolver` | sonnet | PR comment resolution | | `spec-flow-analyzer` | opus | User flow gap analysis | -## Skills (26) +## Skills (21) Skills provide domain knowledge that agents and workflows load on demand. They contain reference documentation, conventions, and patterns. +Workflow primitives (brainstorming, git worktrees, skill writing, parallel agents) now come from the `superpowers` plugin. + ### Python Core - **`python-style`** — PEP 8, naming, imports, logging with emoji prefixes - **`python-typing`** — Type hints, Pydantic v2, Protocol, generics @@ -217,23 +227,18 @@ Skills provide domain knowledge that agents and workflows load on demand. They c - **`agent-native-architecture`** — Agent-native app patterns (action parity, context injection, shared workspace, dynamic capability discovery) - **`frontend-design`** — Production-grade frontend interfaces +### Microservice Support +- **`microservice-focus`** — Service discovery, `--services` parsing, multi-service prompting, and `` block construction + ### Development Tools -- **`compound-docs`** — Structured solution documentation -- **`create-agent-skills`** — Skill authoring guide -- **`skill-creator`** — Skill creation framework - **`setup`** — Interactive project configuration for review agents and workflow skills ### Content & Workflow -- **`brainstorming`** — Collaborative exploration techniques - **`commit`** — Conventional commits with gitmoji, logical grouping, pre-commit handling - **`document-review`** — Structured document improvement - **`file-todos`** — File-based todo tracking -- **`git-worktree`** — Parallel development with Git worktrees - **`resolve-pr-parallel`** — Parallel PR comment resolution -### Multi-Agent Orchestration -- **`orchestrating-swarms`** — Multi-agent coordination with TeammateTool and Task system - ### Integrations - **`rclone`** — Cloud storage uploads (S3, R2, B2) - **`agent-browser`** — CLI browser automation via Vercel's agent-browser @@ -275,7 +280,6 @@ workflow_skills: plan: [django-patterns] work: [django-patterns, pytest-patterns] review: [django-patterns, pytest-patterns] - compound: [django-patterns] --- ``` @@ -289,7 +293,7 @@ The `/setup` skill auto-detects your stack (Django, FastAPI, DRF, Celery, SQLAlc ## Microservice Support -For multi-service monorepos, the plugin provides: +For multi-service monorepos, the plugin provides. Focus Gate logic now lives in the `microservice-focus` skill, invoked once by each workflow command. - **Auto-detection** — Discovers services via `*/pyproject.toml` at root level - **Focus Gate** — Each workflow command prompts for relevant services (or accepts `--services` argument) @@ -309,9 +313,8 @@ All workflow commands accept `--services` for automated invocation: | Doc Type | Single Service | Multi-Service | |----------|---------------|---------------| -| Brainstorms | Single document | `{service}/docs/brainstorms/` per service | -| Plans | `docs/plans/` | Root overview + per-service plan files | -| Solutions | `docs/solutions/` | `{service}/docs/solutions/` with cross-refs | +| Specs | `docs/superpowers/specs/` | `{service}/docs/superpowers/specs/` per service | +| Plans | `docs/superpowers/plans/` | Root overview + per-service plan files under `{service}/docs/superpowers/plans/` | ## How It Works @@ -326,25 +329,11 @@ The work command is the engine that turns plans into shipped code: Every commit goes through a test-and-fix gate: run tests → fix failures → stage → commit → if pre-commit fails → fix → re-test → retry. Never ships with failing tests, never skips hooks. -### Swarm Mode - -For complex features, `/slfg` or explicit swarm mode spawns parallel worker agents: - -``` -Team lead → spawns implementers + testers → monitors via Task system → ships when done -``` - -Uses Claude Code's TeammateTool system with dependency-aware task scheduling. - -### Knowledge Compounding - -`/workflows:compound` captures solutions in `docs/solutions/` with YAML frontmatter. The `learnings-researcher` agent searches these during future reviews, so past solutions inform new work. Knowledge compounds. - ## Version History See [CHANGELOG.md](CHANGELOG.md) for detailed version history. -**Current version: 2.4.0** +**Current version: 3.0.0** ## Contributing diff --git a/agents/research/best-practices-researcher.md b/agents/research/best-practices-researcher.md index 940ee10..e44e1db 100644 --- a/agents/research/best-practices-researcher.md +++ b/agents/research/best-practices-researcher.md @@ -40,9 +40,9 @@ Before going online, check if curated knowledge already exists in skills: - FastAPI → `fastapi-patterns`, `fastapi-sqlalchemy` - Frontend/Design → `frontend-design`, `swiss-design` - TypeScript/React → `react-best-practices` - - AI/Agents → `agent-native-architecture`, `create-agent-skills` - - Documentation → `compound-docs`, `every-style-editor` - - File operations → `rclone`, `git-worktree` + - AI/Agents → `agent-native-architecture` + - Documentation → `every-style-editor` + - File operations → `rclone` - Image generation → `gemini-imagegen` 3. **Extract Patterns from Skills**: diff --git a/agents/research/git-history-analyzer.md b/agents/research/git-history-analyzer.md index 0fe058b..933b93c 100644 --- a/agents/research/git-history-analyzer.md +++ b/agents/research/git-history-analyzer.md @@ -56,4 +56,4 @@ When analyzing, consider: Your insights should help developers understand not just what the code does, but why it evolved to its current state, informing better decisions for future changes. -Note that files in `docs/plans/` and `docs/solutions/` are compound-engineering pipeline artifacts created by `/workflows:plan`. They are intentional, permanent living documents — do not recommend their removal or characterize them as unnecessary. +Note that files in `docs/plans/` are compound-engineering pipeline artifacts created by `/workflows:plan`. They are intentional, permanent living documents — do not recommend their removal or characterize them as unnecessary. diff --git a/agents/research/learnings-researcher.md b/agents/research/learnings-researcher.md deleted file mode 100644 index 3af9696..0000000 --- a/agents/research/learnings-researcher.md +++ /dev/null @@ -1,264 +0,0 @@ ---- -name: learnings-researcher -description: "Searches docs/solutions/ for relevant past solutions by frontmatter metadata. Use before implementing features or fixing problems to surface institutional knowledge and prevent repeated mistakes." -model: haiku ---- - - - -Context: User is about to implement a feature involving email processing. -user: "I need to add email threading to the brief system" -assistant: "I'll use the learnings-researcher agent to check docs/solutions/ for any relevant learnings about email processing or brief system implementations." -Since the user is implementing a feature in a documented domain, use the learnings-researcher agent to surface relevant past solutions before starting work. - - -Context: User is debugging a performance issue. -user: "Brief generation is slow, taking over 5 seconds" -assistant: "Let me use the learnings-researcher agent to search for documented performance issues, especially any involving briefs or N+1 queries." -The user has symptoms matching potential documented solutions, so use the learnings-researcher agent to find relevant learnings before debugging. - - -Context: Planning a new feature that touches multiple modules. -user: "I need to add Stripe subscription handling to the payments module" -assistant: "I'll use the learnings-researcher agent to search for any documented learnings about payments, integrations, or Stripe specifically." -Before implementing, check institutional knowledge for gotchas, patterns, and lessons learned in similar domains. - - - -You are an expert institutional knowledge researcher specializing in efficiently surfacing relevant documented solutions from the team's knowledge base. Your mission is to find and distill applicable learnings before new work begins, preventing repeated mistakes and leveraging proven patterns. - -## Search Strategy (Grep-First Filtering) - -Solution docs live in `docs/solutions/` (root) and optionally in `{service}/docs/solutions/` (per-service) when microservice mode is active. Search both locations. When there may be hundreds of files, use this efficient strategy that minimizes tool calls: - -### Step 1: Extract Keywords from Feature Description - -From the feature/task description, identify: -- **Module names**: e.g., "BriefSystem", "EmailProcessing", "payments" -- **Technical terms**: e.g., "N+1", "caching", "authentication" -- **Problem indicators**: e.g., "slow", "error", "timeout", "memory" -- **Component types**: e.g., "model", "controller", "job", "api" - -### Step 2: Category-Based Narrowing (Optional but Recommended) - -If the feature type is clear, narrow the search using category-specific glob patterns (matches both root and per-service paths): - -| Feature Type | Search Glob | -|--------------|-------------| -| Performance work | `**/docs/solutions/performance-issues/**/*.md` | -| Database changes | `**/docs/solutions/database-issues/**/*.md` | -| Bug fix | `**/docs/solutions/runtime-errors/**/*.md`, `**/docs/solutions/logic-errors/**/*.md` | -| Security | `**/docs/solutions/security-issues/**/*.md` | -| UI work | `**/docs/solutions/ui-bugs/**/*.md` | -| Integration | `**/docs/solutions/integration-issues/**/*.md` | -| General/unclear | `**/docs/solutions/**/*.md` (all) | - -### Step 3: Grep Pre-Filter (Critical for Efficiency) - -**Use Grep to find candidate files BEFORE reading any content.** Run multiple Grep calls in parallel. Use `glob="**/docs/solutions/**/*.md"` to search both root and per-service solution directories: - -```bash -# Search for keyword matches in frontmatter fields (run in PARALLEL, case-insensitive) -Grep: pattern="title:.*email" glob="**/docs/solutions/**/*.md" output_mode=files_with_matches -i=true -Grep: pattern="tags:.*(email|mail|smtp)" glob="**/docs/solutions/**/*.md" output_mode=files_with_matches -i=true -Grep: pattern="module:.*(Brief|Email)" glob="**/docs/solutions/**/*.md" output_mode=files_with_matches -i=true -Grep: pattern="component:.*background_job" glob="**/docs/solutions/**/*.md" output_mode=files_with_matches -i=true -``` - -**Pattern construction tips:** -- Use `|` for synonyms: `tags:.*(payment|billing|stripe|subscription)` -- Include `title:` - often the most descriptive field -- Use `-i=true` for case-insensitive matching -- Include related terms the user might not have mentioned - -**Why this works:** Grep scans file contents without reading into context. Only matching filenames are returned, dramatically reducing the set of files to examine. - -**Combine results** from all Grep calls to get candidate files (typically 5-20 files instead of 200). - -**If Grep returns >25 candidates:** Re-run with more specific patterns or combine with category narrowing. - -**If Grep returns <3 candidates:** Do a broader content search (not just frontmatter fields) as fallback: -```bash -Grep: pattern="email" glob="**/docs/solutions/**/*.md" output_mode=files_with_matches -i=true -``` - -### Step 3b: Always Check Critical Patterns - -**Regardless of Grep results**, always read the critical patterns file: - -```bash -Read: docs/solutions/patterns/critical-patterns.md -``` - -This file contains must-know patterns that apply across all work - high-severity issues promoted to required reading. Scan for patterns relevant to the current feature/task. - -### Step 4: Read Frontmatter of Candidates Only - -For each candidate file from Step 3, read the frontmatter: - -```bash -# Read frontmatter only (limit to first 30 lines) -Read: [file_path] with limit:30 -``` - -Extract these fields from the YAML frontmatter: -- **module**: Which module/system the solution applies to -- **problem_type**: Category of issue (see schema below) -- **component**: Technical component affected -- **symptoms**: Array of observable symptoms -- **root_cause**: What caused the issue -- **tags**: Searchable keywords -- **severity**: critical, high, medium, low - -### Step 5: Score and Rank Relevance - -Match frontmatter fields against the feature/task description: - -**Strong matches (prioritize):** -- `module` matches the feature's target module -- `tags` contain keywords from the feature description -- `symptoms` describe similar observable behaviors -- `component` matches the technical area being touched - -**Moderate matches (include):** -- `problem_type` is relevant (e.g., `performance_issue` for optimization work) -- `root_cause` suggests a pattern that might apply -- Related modules or components mentioned - -**Weak matches (skip):** -- No overlapping tags, symptoms, or modules -- Unrelated problem types - -### Step 6: Full Read of Relevant Files - -Only for files that pass the filter (strong or moderate matches), read the complete document to extract: -- The full problem description -- The solution implemented -- Prevention guidance -- Code examples - -### Step 7: Return Distilled Summaries - -For each relevant document, return a summary in this format: - -```markdown -### [Title from document] -- **File**: docs/solutions/[category]/[filename].md -- **Module**: [module from frontmatter] -- **Problem Type**: [problem_type] -- **Relevance**: [Brief explanation of why this is relevant to the current task] -- **Key Insight**: [The most important takeaway - the thing that prevents repeating the mistake] -- **Severity**: [severity level] -``` - -## Frontmatter Schema Reference - -Reference the [yaml-schema.md](../../skills/compound-docs/references/yaml-schema.md) for the complete schema. Key enum values: - -**problem_type values:** -- build_error, test_failure, runtime_error, performance_issue -- database_issue, security_issue, ui_bug, integration_issue -- logic_error, developer_experience, workflow_issue -- best_practice, documentation_gap - -**component values:** -- django_model, django_view, django_serializer, django_template -- fastapi_endpoint, sqlalchemy_model, pydantic_model, service_layer -- celery_task, database, middleware, api_client -- authentication, payments, development_workflow, testing_framework, documentation, tooling - -**root_cause values:** -- missing_relationship, missing_prefetch, missing_index, wrong_api -- queryset_issue, async_issue, task_timing, memory_leak -- config_error, logic_error, test_isolation, missing_validation -- missing_permission, missing_workflow_step, inadequate_documentation -- missing_tooling, incomplete_setup - -**Category directories (mapped from problem_type):** -- `docs/solutions/build-errors/` -- `docs/solutions/test-failures/` -- `docs/solutions/runtime-errors/` -- `docs/solutions/performance-issues/` -- `docs/solutions/database-issues/` -- `docs/solutions/security-issues/` -- `docs/solutions/ui-bugs/` -- `docs/solutions/integration-issues/` -- `docs/solutions/logic-errors/` -- `docs/solutions/developer-experience/` -- `docs/solutions/workflow-issues/` -- `docs/solutions/best-practices/` -- `docs/solutions/documentation-gaps/` - -## Output Format - -Structure your findings as: - -```markdown -## Institutional Learnings Search Results - -### Search Context -- **Feature/Task**: [Description of what's being implemented] -- **Keywords Used**: [tags, modules, symptoms searched] -- **Files Scanned**: [X total files] -- **Relevant Matches**: [Y files] - -### Critical Patterns (Always Check) -[Any matching patterns from critical-patterns.md] - -### Relevant Learnings - -#### 1. [Title] -- **File**: [path] -- **Module**: [module] -- **Relevance**: [why this matters for current task] -- **Key Insight**: [the gotcha or pattern to apply] - -#### 2. [Title] -... - -### Recommendations -- [Specific actions to take based on learnings] -- [Patterns to follow] -- [Gotchas to avoid] - -### No Matches -[If no relevant learnings found, explicitly state this] -``` - -## Efficiency Guidelines - -**DO:** -- Use Grep to pre-filter files BEFORE reading any content (critical for 100+ files) -- Run multiple Grep calls in PARALLEL for different keywords -- Include `title:` in Grep patterns - often the most descriptive field -- Use OR patterns for synonyms: `tags:.*(payment|billing|stripe)` -- Use `-i=true` for case-insensitive matching -- Use category directories to narrow scope when feature type is clear -- Do a broader content Grep as fallback if <3 candidates found -- Re-narrow with more specific patterns if >25 candidates found -- Always read the critical patterns file (Step 3b) -- Only read frontmatter of Grep-matched candidates (not all files) -- Filter aggressively - only fully read truly relevant files -- Prioritize high-severity and critical patterns -- Extract actionable insights, not just summaries -- Note when no relevant learnings exist (this is valuable information too) - -**DON'T:** -- Read frontmatter of ALL files (use Grep to pre-filter first) -- Run Grep calls sequentially when they can be parallel -- Use only exact keyword matches (include synonyms) -- Skip the `title:` field in Grep patterns -- Proceed with >25 candidates without narrowing first -- Read every file in full (wasteful) -- Return raw document contents (distill instead) -- Include tangentially related learnings (focus on relevance) -- Skip the critical patterns file (always check it) - -## Integration Points - -This agent is designed to be invoked by: -- `/workflows:plan` - To inform planning with institutional knowledge -- `/deepen-plan` - To add depth with relevant learnings -- Manual invocation before starting work on a feature - -The goal is to surface relevant learnings in under 30 seconds for a typical solutions directory, enabling fast knowledge retrieval during planning phases. diff --git a/agents/review/code-simplicity-reviewer.md b/agents/review/code-simplicity-reviewer.md index 7811148..8793161 100644 --- a/agents/review/code-simplicity-reviewer.md +++ b/agents/review/code-simplicity-reviewer.md @@ -48,7 +48,7 @@ When reviewing code, you will: - Eliminate extensibility points without clear use cases - Question generic solutions for specific problems - Remove "just in case" code - - Never flag `docs/plans/*.md` or `docs/solutions/*.md` for removal — these are compound-engineering pipeline artifacts created by `/workflows:plan` and used as living documents by `/workflows:work` + - Never flag `docs/plans/*.md` for removal — these are compound-engineering pipeline artifacts created by `/workflows:plan` and used as living documents by `/workflows:work` 6. **Optimize for Readability**: - Prefer self-documenting code over comments diff --git a/commands/create-agent-skill.md b/commands/create-agent-skill.md index 9ec53f9..35ae6cd 100644 --- a/commands/create-agent-skill.md +++ b/commands/create-agent-skill.md @@ -1,9 +1,9 @@ --- name: create-agent-skill description: Create or edit Claude Code skills with expert guidance on structure and best practices -allowed-tools: Skill(create-agent-skills) +allowed-tools: Skill(superpowers:writing-skills) argument-hint: [skill description or requirements] disable-model-invocation: true --- -Invoke the create-agent-skills skill for: $ARGUMENTS +Invoke the superpowers:writing-skills skill for: $ARGUMENTS diff --git a/commands/deepen-plan.md b/commands/deepen-plan.md index 77bc452..e8cf261 100644 --- a/commands/deepen-plan.md +++ b/commands/deepen-plan.md @@ -24,8 +24,8 @@ The result is a deeply grounded, production-ready plan with concrete implementat #$ARGUMENTS **If the plan path above is empty:** -1. Check for recent plans: `ls -la docs/plans/` -2. Ask the user: "Which plan would you like to deepen? Please provide the path (e.g., `docs/plans/2026-01-15-feat-my-feature-plan.md`)." +1. Check for recent plans: `ls -la docs/superpowers/plans/ docs/plans/ 2>/dev/null` (the second path is for plans created before v3.0.0). +2. Ask the user: "Which plan would you like to deepen? Please provide the path (e.g., `docs/superpowers/plans/2026-05-25-feat-my-feature.md`)." Do not proceed until you have a valid plan file path. @@ -142,130 +142,7 @@ Task general-purpose: "Use the security-patterns skill at ~/.claude/skills/secur **No limit on skill sub-agents. Spawn one for every skill that could possibly be relevant.** -### 3. Discover and Apply Learnings/Solutions - - -Check for documented learnings from /workflows:compound. These are solved problems stored as markdown files. Spawn a sub-agent for each learning to check if it's relevant. - - -**LEARNINGS LOCATION - Check these exact folders:** - -``` -docs/solutions/ <-- PRIMARY: Project-level learnings (created by /workflows:compound) -├── performance-issues/ -│ └── *.md -├── debugging-patterns/ -│ └── *.md -├── configuration-fixes/ -│ └── *.md -├── integration-issues/ -│ └── *.md -├── deployment-issues/ -│ └── *.md -└── [other-categories]/ - └── *.md -``` - -**Step 1: Find ALL learning markdown files** - -Run these commands to get every learning file: - -```bash -# PRIMARY LOCATION - Project learnings -find docs/solutions -name "*.md" -type f 2>/dev/null - -# If docs/solutions doesn't exist, check alternate locations: -find .claude/docs -name "*.md" -type f 2>/dev/null -find ~/.claude/docs -name "*.md" -type f 2>/dev/null -``` - -**Step 2: Read frontmatter of each learning to filter** - -Each learning file has YAML frontmatter with metadata. Read the first ~20 lines of each file to get: - -```yaml ---- -title: "N+1 Query Fix for Briefs" -category: performance-issues -tags: [django-orm, n-plus-one, select-related, prefetch-related] -module: Briefs -symptom: "Slow page load, multiple queries in logs" -root_cause: "Missing includes on association" ---- -``` - -**For each .md file, quickly scan its frontmatter:** - -```bash -# Read first 20 lines of each learning (frontmatter + summary) -head -20 docs/solutions/**/*.md -``` - -**Step 3: Filter - only spawn sub-agents for LIKELY relevant learnings** - -Compare each learning's frontmatter against the plan: -- `tags:` - Do any tags match technologies/patterns in the plan? -- `category:` - Is this category relevant? (e.g., skip deployment-issues if plan is UI-only) -- `module:` - Does the plan touch this module? -- `symptom:` / `root_cause:` - Could this problem occur with the plan? - -**SKIP learnings that are clearly not applicable:** -- Plan is frontend-only → skip `database-migrations/` learnings -- Plan is frontend-only → skip `python-specific/` learnings -- Plan has no auth → skip `authentication-issues/` learnings - -**SPAWN sub-agents for learnings that MIGHT apply:** -- Any tag overlap with plan technologies -- Same category as plan domain -- Similar patterns or concerns - -**Step 4: Spawn sub-agents for filtered learnings** - -For each learning that passes the filter: - -``` -Task general-purpose: " -LEARNING FILE: [full path to .md file] - -1. Read this learning file completely -2. This learning documents a previously solved problem - -Check if this learning applies to this plan: - ---- -[full plan content] ---- - -If relevant: -- Explain specifically how it applies -- Quote the key insight or solution -- Suggest where/how to incorporate it - -If NOT relevant after deeper analysis: -- Say 'Not applicable: [reason]' -" -``` - -**Example filtering:** -``` -# Found 15 learning files, plan is about "Django/FastAPI API caching" - -# SPAWN (likely relevant): -docs/solutions/performance-issues/n-plus-one-queries.md # tags: [django-orm] ✓ -docs/solutions/performance-issues/redis-cache-stampede.md # tags: [caching, redis] ✓ -docs/solutions/configuration-fixes/redis-connection-pool.md # tags: [redis] ✓ - -# SKIP (clearly not applicable): -docs/solutions/deployment-issues/docker-memory-quota.md # not about caching -docs/solutions/frontend-issues/celery-race-condition.md # plan is API, not async tasks -docs/solutions/authentication-issues/jwt-expiry.md # plan has no auth -``` - -**Spawn sub-agents in PARALLEL for all filtered learnings.** - -**These learnings are institutional knowledge - applying them prevents repeating past mistakes.** - -### 4. Launch Per-Section Research Agents +### 3. Launch Per-Section Research Agents For each major section in the plan, spawn dedicated sub-agents to research improvements. Use the Explore agent type for open-ended research. @@ -295,7 +172,7 @@ mcp__plugin_compound-engineering_context7__query-docs: Query documentation for s Search for recent (2024-2026) articles, blog posts, and documentation on topics in the plan. -### 5. Discover and Run ALL Review Agents +### 4. Discover and Run ALL Review Agents Dynamically discover every available agent and run them ALL against the plan. Don't filter, don't skip, don't assume relevance. 40+ parallel agents is fine. Use everything available. @@ -361,7 +238,7 @@ Task [agent-name]: "Review this plan using your expertise. Apply all your checks Research agents (like `best-practices-researcher`, `framework-docs-researcher`, `git-history-analyzer`, `repo-research-analyst`) should also be run for relevant plan sections. -### 6. Wait for ALL Agents and Synthesize Everything +### 5. Wait for ALL Agents and Synthesize Everything Wait for ALL parallel agents to complete - skills, research agents, review agents, everything. Then synthesize all findings into a comprehensive enhancement. @@ -370,11 +247,10 @@ Wait for ALL parallel agents to complete - skills, research agents, review agent **Collect outputs from ALL sources:** 1. **Skill-based sub-agents** - Each skill's full output (code examples, patterns, recommendations) -2. **Learnings/Solutions sub-agents** - Relevant documented learnings from /workflows:compound -3. **Research agents** - Best practices, documentation, real-world examples -4. **Review agents** - All feedback from every reviewer (architecture, security, performance, simplicity, etc.) -5. **Context7 queries** - Framework documentation and patterns -6. **Web searches** - Current best practices and articles +2. **Research agents** - Best practices, documentation, real-world examples +3. **Review agents** - All feedback from every reviewer (architecture, security, performance, simplicity, etc.) +4. **Context7 queries** - Framework documentation and patterns +5. **Web searches** - Current best practices and articles **For each agent's findings, extract:** - [ ] Concrete recommendations (actionable items) @@ -385,7 +261,6 @@ Wait for ALL parallel agents to complete - skills, research agents, review agent - [ ] Edge cases discovered (handling strategies) - [ ] Documentation links (references) - [ ] Skill-specific patterns (from matched skills) -- [ ] Relevant learnings (past solutions that apply - prevent repeating mistakes) **Deduplicate and prioritize:** - Merge similar recommendations from multiple agents @@ -393,7 +268,7 @@ Wait for ALL parallel agents to complete - skills, research agents, review agent - Flag conflicting advice for human review - Group by plan section -### 7. Enhance Plan Sections +### 6. Enhance Plan Sections Merge research findings back into the plan, adding depth without changing the original structure. @@ -430,7 +305,7 @@ Merge research findings back into the plan, adding depth without changing the or - [Documentation URL 2] ``` -### 8. Add Enhancement Summary +### 7. Add Enhancement Summary At the top of the plan, add a summary section: @@ -451,7 +326,7 @@ At the top of the plan, add a summary section: - [Important finding 2] ``` -### 9. Update Plan File +### 8. Update Plan File **Write the enhanced plan:** - Preserve original filename diff --git a/commands/lfg.md b/commands/lfg.md index 86f40e5..9696b1d 100644 --- a/commands/lfg.md +++ b/commands/lfg.md @@ -1,20 +1,20 @@ --- name: lfg -description: Full autonomous engineering workflow +description: "(DEPRECATED v3.0.0 — removed in v4.0.0) Full autonomous pipeline" argument-hint: "[feature description]" -disable-model-invocation: true --- -Run these slash commands in order. Do not do anything else. Do not stop between steps — complete every step through to the end. +# `/lfg` — Removed in v3.0.0 -1. **Optional:** If the `ralph-wiggum` skill is available, run `/ralph-wiggum:ralph-loop "finish all slash commands" --completion-promise "DONE"`. If not available or it fails, skip and continue to step 2 immediately. -2. `/workflows:plan $ARGUMENTS` -3. `/compound-engineering:deepen-plan` -4. `/workflows:work` -5. `/workflows:review` -6. `/compound-engineering:resolve_todo_parallel` -7. `/compound-engineering:test-browser` -8. `/compound-engineering:feature-video` -9. Output `DONE` when video is in PR +The `/lfg` autonomous pipeline was removed in v3.0.0. Users now orchestrate the stages directly, which keeps each step interruptible and reviewable. -Start with step 2 now (or step 1 if ralph-wiggum is available). +Run the stages in sequence: + +1. `/workflows:brainstorm ""` — explore and write a spec. +2. `/workflows:plan ` — turn the spec into an implementation plan. +3. `/workflows:work ` — execute the plan with the Python quality gate. +4. `/workflows:review` — multi-agent review of the resulting PR. + +Each stage now delegates to a `superpowers:*` skill underneath. See `CHANGELOG.md` v3.0.0 for the full rationale. + +This shim will be removed entirely in v4.0.0. diff --git a/commands/resolve_todo_parallel.md b/commands/resolve_todo_parallel.md index afd653d..5b8315d 100644 --- a/commands/resolve_todo_parallel.md +++ b/commands/resolve_todo_parallel.md @@ -12,7 +12,7 @@ Resolve all TODO comments using parallel processing. Get all unresolved TODOs from the /todos/\*.md directory -If any todo recommends deleting, removing, or gitignoring files in `docs/plans/` or `docs/solutions/`, skip it and mark it as `wont_fix`. These are compound-engineering pipeline artifacts that are intentional and permanent. +If any todo recommends deleting, removing, or gitignoring files in `docs/plans/`, skip it and mark it as `wont_fix`. These are compound-engineering pipeline artifacts that are intentional and permanent. ### 2. Plan diff --git a/commands/slfg.md b/commands/slfg.md index 050d24e..b051ac9 100644 --- a/commands/slfg.md +++ b/commands/slfg.md @@ -1,32 +1,22 @@ --- name: slfg -description: Full autonomous engineering workflow using swarm mode for parallel execution +description: "(DEPRECATED v3.0.0 — removed in v4.0.0) Swarm-mode autonomous pipeline" argument-hint: "[feature description]" -disable-model-invocation: true --- -Swarm-enabled LFG. Run these steps in order, parallelizing where indicated. Do not stop between steps — complete every step through to the end. +# `/slfg` — Removed in v3.0.0 -## Sequential Phase +The `/slfg` swarm pipeline was removed in v3.0.0 along with the `orchestrating-swarms` skill it depended on. -1. **Optional:** If the `ralph-wiggum` skill is available, run `/ralph-wiggum:ralph-loop "finish all slash commands" --completion-promise "DONE"`. If not available or it fails, skip and continue to step 2 immediately. -2. `/workflows:plan $ARGUMENTS` -3. `/compound-engineering:deepen-plan` -4. `/workflows:work` — **Use swarm mode**: Make a Task list and launch an army of agent swarm subagents to build the plan +For parallel agent work, use the `superpowers:dispatching-parallel-agents` skill directly within any stage (most useful inside `/workflows:work` for independent tasks). -## Parallel Phase +For the rest of the pipeline, see `/lfg`'s migration message: -After work completes, launch steps 5 and 6 as **parallel swarm agents** (both only need code to be written): +1. `/workflows:brainstorm ""` +2. `/workflows:plan ` +3. `/workflows:work ` — invoke `superpowers:dispatching-parallel-agents` inside this for parallelism. +4. `/workflows:review` -5. `/workflows:review` — spawn as background Task agent -6. `/compound-engineering:test-browser` — spawn as background Task agent +See `CHANGELOG.md` v3.0.0 for the full rationale. -Wait for both to complete before continuing. - -## Finalize Phase - -7. `/compound-engineering:resolve_todo_parallel` — resolve any findings from the review -8. `/compound-engineering:feature-video` — record the final walkthrough and add to PR -9. Output `DONE` when video is in PR - -Start with step 1 now. +This shim will be removed entirely in v4.0.0. diff --git a/commands/workflows/brainstorm.md b/commands/workflows/brainstorm.md index 2d1199a..dca2c30 100644 --- a/commands/workflows/brainstorm.md +++ b/commands/workflows/brainstorm.md @@ -1,189 +1,79 @@ --- name: workflows:brainstorm -description: Explore requirements and approaches through collaborative dialogue before planning implementation -argument-hint: "[feature idea or problem to explore]" +description: Explore requirements and approaches before planning, with Python/microservice context loaded for downstream sub-agents +argument-hint: "[feature idea or problem to explore] [--services svc-a,svc-b]" --- -# Brainstorm a Feature or Improvement +# Brainstorm (Python) -**Note: The current year is 2026.** Use this when dating brainstorm documents. - -Brainstorming helps answer **WHAT** to build through collaborative dialogue. It precedes `/workflows:plan`, which answers **HOW** to build it. - -**Process knowledge:** Load the `brainstorming` skill for detailed question techniques, approach exploration patterns, and YAGNI principles. +This command is a thin wrapper that loads Python-specific context, runs the microservice focus gate, then delegates the brainstorming process to the `superpowers:brainstorming` skill. ## Feature Description #$ARGUMENTS -**If the feature description above is empty, ask the user:** "What would you like to explore? Please describe the feature, problem, or improvement you're thinking about." - -Do not proceed until you have a feature description from the user. - -## Microservice Mode: Focus Gate - -**Before proceeding, check if this is a multi-service monorepo:** - -1. If the user provided `--services service-a,service-b` in the arguments, use those as the focused services (skip interactive prompting) -2. If focused services are already in conversation context, use them -3. If neither: check if multiple `pyproject.toml` files exist at root level (`Glob("*/pyproject.toml")`). If yes, prompt the user: "This appears to be a multi-service repo. Which services are relevant to this brainstorm?" List discovered services and let user pick. -4. If single `pyproject.toml` or none found: proceed in single-service mode (original behavior) - -**When focused services are set:** Load full service context: - -1. **Load each service's description:** Read `{service}/.claude/prompt.md` (preferred) or `{service}/README.md` (first 50 lines) to understand what the service does -2. **Load tech stack:** Read `{service}/pyproject.toml` to extract package name, Python version, key dependencies (Django, FastAPI, Celery, etc.) -3. **Detect internal dependencies:** Cross-reference `pyproject.toml` dependencies between focused services to build the service-map -4. **List structure:** List `{service}/src/` (1 level deep) to understand app organization - -**Pass a rich `` block to all sub-agents:** -``` - - services: service-a (./service-a), service-b (./service-b) - - service-a: - description: [from prompt.md/README — what this service does] - stack: Django 5.0, Celery, PostgreSQL - structure: src/orders/, src/pricing/, src/shared/ +If the feature description above is empty, ask the user: "What would you like to explore? Please describe the feature, problem, or improvement you're thinking about." Do not proceed without one. - service-b: - description: [from prompt.md/README — what this service does] - stack: FastAPI, SQLAlchemy 2.0, Redis - structure: src/payments/, src/webhooks/ +## Prerequisites - dependencies: - - service-b depends on service-a (event schema) - - both depend on lib-common (shared DTOs) - -``` +If the `superpowers:brainstorming` skill is not available, halt and instruct the user: -**Use the service context to inform brainstorming:** When exploring approaches, consider each service's stack, purpose, and how they interact. Don't propose patterns that conflict with a service's existing architecture. +> "This command requires the `superpowers` plugin. Install it with: +> `/plugin marketplace add anthropics/claude-plugins-official` +> `/plugin install superpowers@claude-plugins-official`" -## Project Workflow Skills +## Step 1: Load Project Workflow Skills -Read `compound-engineering.local.md` in the project root. If found, parse the YAML frontmatter for `workflow_skills.brainstorm`. - -If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific knowledge (domain context, framework patterns, database conventions) that informs this workflow. They are additive — loaded alongside any skills this command already references (e.g., `brainstorming`, `document-review`). +Read `compound-engineering.local.md` in the project root. If found, parse the YAML frontmatter for `workflow_skills.brainstorm`. If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific Python/Django/domain context. If no config exists or no `workflow_skills` key is present, proceed without additional skills. -## Execution Flow - -### Phase 0: Assess Requirements Clarity - -Evaluate whether brainstorming is needed based on the feature description. - -**Clear requirements indicators:** -- Specific acceptance criteria provided -- Referenced existing patterns to follow -- Described exact expected behavior -- Constrained, well-defined scope - -**If requirements are already clear:** -Use **AskUserQuestion tool** to suggest: "Your requirements seem detailed enough to proceed directly to planning. Should I run `/workflows:plan` instead, or would you like to explore the idea further?" - -### Phase 1: Understand the Idea - -#### 1.1 Repository Research (Lightweight) - -Run a quick repo scan to understand existing patterns: - -- Task repo-research-analyst("Understand existing patterns related to: ") - -Focus on: similar features, established patterns, CLAUDE.md guidance. - -#### 1.2 Collaborative Dialogue - -Use the **AskUserQuestion tool** to ask questions **one at a time**. - -**Guidelines (see `brainstorming` skill for detailed techniques):** -- Prefer multiple choice when natural options exist -- Start broad (purpose, users) then narrow (constraints, edge cases) -- Validate assumptions explicitly -- Ask about success criteria - -**Exit condition:** Continue until the idea is clear OR user says "proceed" - -### Phase 2: Explore Approaches - -Propose **2-3 concrete approaches** based on research and conversation. - -For each approach, provide: -- Brief description (2-3 sentences) -- Pros and cons -- When it's best suited - -Lead with your recommendation and explain why. Apply YAGNI—prefer simpler solutions. - -Use **AskUserQuestion tool** to ask which approach the user prefers. - -### Phase 3: Capture the Design - -**Single-service mode:** Write a brainstorm document to `docs/brainstorms/YYYY-MM-DD--brainstorm.md`. - -**Microservice mode:** Write a brainstorm document **inside each focused service**: -- `{service}/docs/brainstorms/YYYY-MM-DD--brainstorm.md` for each affected service -- Each per-service document should focus on that service's role and decisions -- Add a `## Services` section listing all affected services and their roles, so `/workflows:plan` can auto-detect scope - -```markdown -## Services - -- **service-order**: Produces order events consumed by payment -- **service-payment**: Handles payment processing triggered by orders -- **lib-common**: Shared DTOs used by both services -``` - -**Document structure:** See the `brainstorming` skill for the template format. Key sections: What We're Building, Why This Approach, Key Decisions, Open Questions. - -Ensure the target `docs/brainstorms/` directory exists before writing. - -**IMPORTANT:** Before proceeding to Phase 4, check if there are any Open Questions listed in the brainstorm document. If there are open questions, YOU MUST ask the user about each one using AskUserQuestion before offering to proceed to planning. Move resolved questions to a "Resolved Questions" section. +## Step 2: Microservice Focus -### Phase 4: Handoff +Invoke the `microservice-focus` skill. It will: -Use **AskUserQuestion tool** to present next steps: +- Parse `--services` from `$ARGUMENTS` if present. +- Otherwise discover services via `Glob("*/pyproject.toml")` and prompt the user via `AskUserQuestion` if multiple services exist. +- Return the list of focused services + a `` block. -**Question:** "Brainstorm captured. What would you like to do next?" +In single-service mode, the skill returns an empty service list and empty focus context. Skip Step 4. -**Options:** -1. **Review and refine** - Improve the document through structured self-review -2. **Proceed to planning** - Run `/workflows:plan` (will auto-detect this brainstorm) -3. **Ask more questions** - I have more questions to clarify before moving on -4. **Done for now** - Return later +## Step 3: Delegate to superpowers -**If user selects "Ask more questions":** YOU (Claude) return to Phase 1.2 (Collaborative Dialogue) and continue asking the USER questions one at a time to further refine the design. The user wants YOU to probe deeper - ask about edge cases, constraints, preferences, or areas not yet explored. Continue until the user is satisfied, then return to Phase 4. +Invoke the `superpowers:brainstorming` skill. Pass: -**If user selects "Review and refine":** +- The user's feature description from `` as the topic. +- The `` block returned from Step 2 (so the superpowers skill includes it in any sub-agent prompts it spawns). +- A note that any Python `workflow_skills` listed above are already loaded in the conversation as additional context. -Load the `document-review` skill and apply it to the brainstorm document. +The superpowers skill drives the rest of the conversation (clarifying questions, approach exploration, design presentation, spec writing) and returns when the spec is written to the default path. Control then returns to this wrapper for Step 4. -When document-review returns "Review complete", present next steps: +## Step 4: Multi-service spec post-processing (multi-service only) -1. **Move to planning** - Continue to `/workflows:plan` with this document -2. **Done for now** - Brainstorming complete. To start planning later: `/workflows:plan [document-path]` +`superpowers:brainstorming` always writes ONE spec to the default path: `docs/superpowers/specs/YYYY-MM-DD--design.md`. It does not know about per-service paths. -## Output Summary +If Step 2 returned a non-empty service list, **after the superpowers skill returns**, this wrapper post-processes the spec: -When complete, display: +1. Read the spec at `docs/superpowers/specs/YYYY-MM-DD--design.md`. +2. For each focused service, write a copy to `{service}/docs/superpowers/specs/YYYY-MM-DD--design.md` (create the directory with `mkdir -p` first). +3. To each per-service copy, prepend a `## Services` section listing all focused services and their roles, so `/workflows:plan` can auto-detect scope on the next step. Example: -``` -Brainstorm complete! + ```markdown + ## Services -Document(s): [docs/brainstorms/YYYY-MM-DD--brainstorm.md | {service}/docs/brainstorms/...] + - **service-order**: Produces order events consumed by payment + - **service-payment**: Handles payment processing triggered by orders + - **lib-common**: Shared DTOs used by both services + ``` -Key decisions: -- [Decision 1] -- [Decision 2] +4. **Delete** the original root-level `docs/superpowers/specs/YYYY-MM-DD--design.md` to avoid duplication. (In single-service mode, this deletion does NOT happen — the root spec stays.) -Next: Run `/workflows:plan` when ready to implement. -``` +In single-service mode (Step 2 returned empty service list), this entire step is skipped — the root-level spec is the final artifact. -## Important Guidelines +## Output -- **Stay focused on WHAT, not HOW** - Implementation details belong in the plan -- **Ask one question at a time** - Don't overwhelm -- **Apply YAGNI** - Prefer simpler approaches -- **Keep outputs concise** - 200-300 words per section max +After the superpowers skill returns, summarize: -NEVER CODE! Just explore and document decisions. +- Spec path(s) written. +- The focused services (if multi-service mode). +- Suggested next step: `/workflows:plan `. diff --git a/commands/workflows/compound.md b/commands/workflows/compound.md index 484f42d..675745c 100644 --- a/commands/workflows/compound.md +++ b/commands/workflows/compound.md @@ -1,253 +1,18 @@ --- name: workflows:compound -description: Document a recently solved problem to compound your team's knowledge +description: "(DEPRECATED v3.0.0 — removed in v4.0.0) Document a recently solved problem" argument-hint: "[optional: brief context about the fix]" --- -# /compound +# `/workflows:compound` — Removed in v3.0.0 -Coordinate multiple subagents working in parallel to document a recently solved problem. +This command was removed in v3.0.0 along with the knowledge-compounding (`docs/solutions/`) pattern. There is no direct replacement: `superpowers` does not have an analog for post-solve documentation capture. -## Purpose +If you want to capture a learning from a recent fix: -Captures problem solutions while context is fresh, creating structured documentation in `docs/solutions/` with YAML frontmatter for searchability and future reference. Uses parallel subagents for maximum efficiency. +- Write a Markdown note in your project under whatever path your team uses for engineering notes. +- Or contribute the lesson back to a project-local skill via the `superpowers:writing-skills` skill. -**Why "compound"?** Each documented solution compounds your team's knowledge. The first time you solve a problem takes research. Document it, and the next occurrence takes minutes. Knowledge compounds. +See `CHANGELOG.md` v3.0.0 for the full rationale. -## Usage - -```bash -/workflows:compound # Document the most recent fix -/workflows:compound [brief context] # Provide additional context hint -``` - -## Project Workflow Skills - -Read `compound-engineering.local.md` in the project root. If found, parse the YAML frontmatter for `workflow_skills.compound`. - -If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific knowledge that helps produce more accurate and context-aware solution documentation. They are additive — loaded alongside any skills this command already references (e.g., `compound-docs`). - -If no config exists or no `workflow_skills` key is present, proceed without additional skills. - -## Execution Strategy: Two-Phase Orchestration - - -**Only ONE file gets written - the final documentation.** - -Phase 1 subagents return TEXT DATA to the orchestrator. They must NOT use Write, Edit, or create any files. Only the orchestrator (Phase 2) writes the final documentation file. - - -### Phase 1: Parallel Research - - - -Launch these subagents IN PARALLEL. Each returns text data to the orchestrator. - -#### 1. **Context Analyzer** - - Extracts conversation history - - Identifies problem type, component, symptoms - - Validates against schema - - Returns: YAML frontmatter skeleton - -#### 2. **Solution Extractor** - - Analyzes all investigation steps - - Identifies root cause - - Extracts working solution with code examples - - Returns: Solution content block - -#### 3. **Related Docs Finder** - - Searches `docs/solutions/` for related documentation - - Identifies cross-references and links - - Finds related GitHub issues - - Returns: Links and relationships - -#### 4. **Prevention Strategist** - - Develops prevention strategies - - Creates best practices guidance - - Generates test cases if applicable - - Returns: Prevention/testing content - -#### 5. **Category Classifier** - - Determines optimal `docs/solutions/` category - - Validates category against schema - - Suggests filename based on slug - - Returns: Final path and filename - - - -### Phase 2: Assembly & Write - - - -**WAIT for all Phase 1 subagents to complete before proceeding.** - -The orchestrating agent (main conversation) performs these steps: - -1. Collect all text results from Phase 1 subagents -2. Assemble complete markdown file from the collected pieces -3. Validate YAML frontmatter against schema -4. **Determine output location (microservice mode):** - - If focused services are in conversation context or services can be inferred (which service's code was changed): - - **Single service fix:** Write to `{service}/docs/solutions/[category]/[filename].md` - - **Cross-service fix:** Write to root `docs/solutions/[category]/[filename].md` with a `service:` field in YAML frontmatter listing affected services - - If no service context: Write to `docs/solutions/[category]/[filename].md` (default behavior) -5. Create directory if needed: `mkdir -p [output-path]/` -6. Write the SINGLE final file -7. Add `service: [service-name]` to YAML frontmatter if writing to a service-specific location - - - -### Phase 3: Optional Enhancement - -**WAIT for Phase 2 to complete before proceeding.** - - - -Based on problem type, optionally invoke specialized agents to review the documentation: - -- **performance_issue** → `performance-oracle` -- **security_issue** → `security-sentinel` -- **database_issue** → `data-integrity-guardian` -- **test_failure** → `pytest-reviewer` -- Any code-heavy issue → `python-style-reviewer` + `code-simplicity-reviewer` - - - -## What It Captures - -- **Problem symptom**: Exact error messages, observable behavior -- **Investigation steps tried**: What didn't work and why -- **Root cause analysis**: Technical explanation -- **Working solution**: Step-by-step fix with code examples -- **Prevention strategies**: How to avoid in future -- **Cross-references**: Links to related issues and docs - -## Preconditions - - - - Problem has been solved (not in-progress) - - - Solution has been verified working - - - Non-trivial problem (not simple typo or obvious error) - - - -## What It Creates - -**Organized documentation:** - -- File: `docs/solutions/[category]/[filename].md` - -**Categories auto-detected from problem:** - -- build-errors/ -- test-failures/ -- runtime-errors/ -- performance-issues/ -- database-issues/ -- security-issues/ -- ui-bugs/ -- integration-issues/ -- logic-errors/ - -## Common Mistakes to Avoid - -| ❌ Wrong | ✅ Correct | -|----------|-----------| -| Subagents write files like `context-analysis.md`, `solution-draft.md` | Subagents return text data; orchestrator writes one final file | -| Research and assembly run in parallel | Research completes → then assembly runs | -| Multiple files created during workflow | Single file: `docs/solutions/[category]/[filename].md` | - -## Success Output - -``` -✓ Documentation complete - -Subagent Results: - ✓ Context Analyzer: Identified performance_issue in brief_system - ✓ Solution Extractor: 3 code fixes - ✓ Related Docs Finder: 2 related issues - ✓ Prevention Strategist: Prevention strategies, test suggestions - ✓ Category Classifier: `performance-issues` - -Specialized Agent Reviews (Auto-Triggered): - ✓ performance-oracle: Validated query optimization approach - ✓ python-style-reviewer: Code examples meet Python conventions - ✓ code-simplicity-reviewer: Solution is appropriately minimal - -File created: -- docs/solutions/performance-issues/n-plus-one-brief-generation.md - -This documentation will be searchable for future reference when similar -issues occur in the Email Processing or Brief System modules. - -What's next? -1. Continue workflow (recommended) -2. Link related documentation -3. Update other references -4. View documentation -5. Other -``` - -## The Compounding Philosophy - -This creates a compounding knowledge system: - -1. First time you solve "N+1 query in brief generation" → Research (30 min) -2. Document the solution → docs/solutions/performance-issues/n-plus-one-briefs.md (5 min) -3. Next time similar issue occurs → Quick lookup (2 min) -4. Knowledge compounds → Team gets smarter - -The feedback loop: - -``` -Build → Test → Find Issue → Research → Improve → Document → Validate → Deploy - ↑ ↓ - └──────────────────────────────────────────────────────────────────────┘ -``` - -**Each unit of engineering work should make subsequent units of work easier—not harder.** - -## Auto-Invoke - - - "that worked" - "it's fixed" - "working now" - "problem solved" - - Use /workflows:compound [context] to document immediately without waiting for auto-detection. - -## Routes To - -`compound-docs` skill - -## Applicable Specialized Agents - -Based on problem type, these agents can enhance documentation: - -### Code Quality & Review -- **python-style-reviewer**: Reviews code examples for Python conventions -- **code-simplicity-reviewer**: Ensures solution code is minimal and clear -- **pattern-recognition-specialist**: Identifies anti-patterns or repeating issues - -### Specific Domain Experts -- **performance-oracle**: Analyzes performance_issue category solutions -- **security-sentinel**: Reviews security_issue solutions for vulnerabilities -- **pytest-reviewer**: Creates test cases for prevention strategies -- **data-integrity-guardian**: Reviews database_issue migrations and queries - -### Enhancement & Documentation -- **best-practices-researcher**: Enriches solution with industry best practices -- **every-style-editor**: Reviews documentation style and clarity -- **framework-docs-researcher**: Links to Python/PyPI documentation references - -### When to Invoke -- **Auto-triggered** (optional): Agents can run post-documentation for enhancement -- **Manual trigger**: User can invoke agents after /workflows:compound completes for deeper review -- **Customize agents**: Edit `compound-engineering.local.md` or invoke the `setup` skill to configure which review agents are used across all workflows - -## Related Commands - -- `/research [topic]` - Deep investigation (searches docs/solutions/ for patterns) -- `/workflows:plan` - Planning workflow (references documented solutions) +This shim will be removed entirely in v4.0.0. diff --git a/commands/workflows/plan.md b/commands/workflows/plan.md index 362b6ba..8161724 100644 --- a/commands/workflows/plan.md +++ b/commands/workflows/plan.md @@ -1,680 +1,80 @@ --- name: workflows:plan -description: Transform feature descriptions into well-structured project plans following conventions -argument-hint: "[feature description, bug report, or improvement idea]" +description: Transform a spec into a Python-flavored implementation plan, delegating plan-writing to superpowers +argument-hint: "[spec path, feature description, or bug report] [--services svc-a,svc-b]" --- -# Create a plan for a new feature or bug fix +# Plan (Python) -## Introduction +This command is a thin wrapper that loads Python-specific context, runs the microservice focus gate, then delegates plan writing to the `superpowers:writing-plans` skill. -**Note: The current year is 2026.** Use this when dating plans and searching for recent documentation. +## Input -Transform feature descriptions, bug reports, or improvement ideas into well-structured markdown files issues that follow project conventions and best practices. This command provides flexible detail levels to match your needs. + #$ARGUMENTS -## Feature Description +If the input is empty, ask the user: "What would you like to plan? Provide a spec path (typically under `docs/superpowers/specs/`) or a feature description." Do not proceed without one. - #$ARGUMENTS +## Prerequisites -**If the feature description above is empty, ask the user:** "What would you like to plan? Please describe the feature, bug fix, or improvement you have in mind." +If the `superpowers:writing-plans` skill is not available, halt and instruct the user: -Do not proceed until you have a clear feature description from the user. +> "This command requires the `superpowers` plugin. Install it with: +> `/plugin marketplace add anthropics/claude-plugins-official` +> `/plugin install superpowers@claude-plugins-official`" -## Microservice Mode: Focus Gate +## Step 1: Load Project Workflow Skills -**Check if this is a multi-service monorepo:** +Read `compound-engineering.local.md` in the project root. If `workflow_skills.plan` is set, load each listed skill now. They inform the plan with Python/Django/domain-specific patterns. -1. If the user provided `--services service-a,service-b` in the arguments, use those as focused services (skip interactive prompting) -2. If focused services are already in conversation context, use them -3. If neither: check if multiple `pyproject.toml` files exist (`Glob("*/pyproject.toml")`). If yes, prompt: "This appears to be a multi-service repo. Which services are involved?" List discovered services. -4. If single service or none: proceed in single-service mode (original behavior) +## Step 2: Microservice Focus -**When focused services are set:** Load full service context: +Invoke the `microservice-focus` skill. It will: -1. **Load each service's description:** Read `{service}/.claude/prompt.md` (preferred) or `{service}/README.md` (first 50 lines) to understand what the service does -2. **Load tech stack:** Read `{service}/pyproject.toml` to extract package name, Python version, key dependencies (Django, FastAPI, Celery, etc.) -3. **Detect internal dependencies:** Cross-reference `pyproject.toml` dependencies between focused services to build the service-map -4. **List structure:** List `{service}/src/` (1 level deep) to understand app organization +- Parse `--services` from `$ARGUMENTS` if present. +- Otherwise discover services via `Glob("*/pyproject.toml")` and prompt the user via `AskUserQuestion` if multiple services exist. +- Return the list of focused services + a `` block. -Also check for a `## Services` section in any detected brainstorm document to inherit scope. +In single-service mode, the skill returns an empty service list and empty focus context. Skip Step 4. -**Include a rich `` block in all sub-agent prompts:** -``` - - services: service-a (./service-a), service-b (./service-b) +If the input was a spec path, **also** check the spec for a `## Services` section. If present, merge those services into the focused list (the spec may have established scope during brainstorm). - service-a: - description: [from prompt.md/README — what this service does] - stack: Django 5.0, Celery, PostgreSQL - structure: src/orders/, src/pricing/, src/shared/ +## Step 3: Delegate to superpowers - service-b: - description: [from prompt.md/README — what this service does] - stack: FastAPI, SQLAlchemy 2.0, Redis - structure: src/payments/, src/webhooks/ +Invoke the `superpowers:writing-plans` skill. Pass: - dependencies: - - service-b depends on service-a (event schema) - - both depend on lib-common (shared DTOs) - -``` +- The input (spec path or feature description) as the planning topic. +- The `` block from Step 2. +- A note that loaded Python `workflow_skills` are available in conversation. -**Use the service context to inform planning:** When designing tasks and choosing implementation approaches, account for each service's stack and architecture. Don't propose Django patterns for a FastAPI service or vice versa. Use the dependency map to determine execution order and cross-service impacts. +The superpowers skill drives plan writing: file structure, task decomposition, bite-sized steps, self-review. It returns when the plan is written to its default path `docs/superpowers/plans/YYYY-MM-DD-.md`. Control then returns to this wrapper for Step 4. -## Project Workflow Skills +## Step 4: Multi-service plan post-processing (multi-service only) -Read `compound-engineering.local.md` in the project root. If found, parse the YAML frontmatter for `workflow_skills.plan`. +`superpowers:writing-plans` always writes ONE plan to the default root path. It does not know about per-service paths or the `services:` YAML frontmatter convention. -If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific knowledge (domain context, framework patterns, architecture guidance) that informs planning decisions. They are additive — loaded alongside any skills this command already references. +If Step 2 returned a non-empty service list, **after the superpowers skill returns**, this wrapper post-processes the plan: -If no config exists or no `workflow_skills` key is present, proceed without additional skills. +1. Read the plan at `docs/superpowers/plans/YYYY-MM-DD-.md`. +2. Add or update the YAML frontmatter to include a `services:` section so `/workflows:work` can execute in dependency order: -### 0. Idea Refinement - -**Check for brainstorm output first:** - -Before asking questions, look for recent brainstorm documents. In multi-service mode, scan both root and per-service locations: - -```bash -ls -la docs/brainstorms/*.md 2>/dev/null | head -10 -# In multi-service mode, also check per-service: -ls -la {service}/docs/brainstorms/*.md 2>/dev/null | head -10 -``` - -**Relevance criteria:** A brainstorm is relevant if: -- The topic (from filename or YAML frontmatter) semantically matches the feature description -- Created within the last 14 days -- If multiple candidates match, use the most recent one - -**If a relevant brainstorm exists:** -1. Read the brainstorm document -2. Announce: "Found brainstorm from [date]: [topic]. Using as context for planning." -3. Extract key decisions, chosen approach, and open questions -4. **Skip the idea refinement questions below** - the brainstorm already answered WHAT to build -5. Use brainstorm decisions as input to the research phase - -**If multiple brainstorms could match:** -Use **AskUserQuestion tool** to ask which brainstorm to use, or whether to proceed without one. - -**If no brainstorm found (or not relevant), run idea refinement:** - -Refine the idea through collaborative dialogue using the **AskUserQuestion tool**: - -- Ask questions one at a time to understand the idea fully -- Prefer multiple choice questions when natural options exist -- Focus on understanding: purpose, constraints and success criteria -- Continue until the idea is clear OR user says "proceed" - -**Gather signals for research decision.** During refinement, note: - -- **User's familiarity**: Do they know the codebase patterns? Are they pointing to examples? -- **User's intent**: Speed vs thoroughness? Exploration vs execution? -- **Topic risk**: Security, payments, external APIs warrant more caution -- **Uncertainty level**: Is the approach clear or open-ended? - -**Skip option:** If the feature description is already detailed, offer: -"Your description is clear. Should I proceed with research, or would you like to refine it further?" - -## Main Tasks - -### 1. Local Research (Always Runs - Parallel) - - -First, I need to understand the project's conventions, existing patterns, and any documented learnings. This is fast and local - it informs whether external research is needed. - - -Run these agents **in parallel** to gather local context: - -- Task repo-research-analyst(feature_description) -- Task learnings-researcher(feature_description) - -**What to look for:** -- **Repo research:** existing patterns, CLAUDE.md guidance, technology familiarity, pattern consistency -- **Learnings:** documented solutions in `docs/solutions/` that might apply (gotchas, patterns, lessons learned) - -These findings inform the next step. - -### 1.5. Research Decision - -Based on signals from Step 0 and findings from Step 1, decide on external research. - -**High-risk topics → always research.** Security, payments, external APIs, data privacy. The cost of missing something is too high. This takes precedence over speed signals. - -**Strong local context → skip external research.** Codebase has good patterns, CLAUDE.md has guidance, user knows what they want. External research adds little value. - -**Uncertainty or unfamiliar territory → research.** User is exploring, codebase has no examples, new technology. External perspective is valuable. - -**Announce the decision and proceed.** Brief explanation, then continue. User can redirect if needed. - -Examples: -- "Your codebase has solid patterns for this. Proceeding without external research." -- "This involves payment processing, so I'll research current best practices first." - -### 1.5b. External Research (Conditional) - -**Only run if Step 1.5 indicates external research is valuable.** - -Run these agents in parallel: - -- Task best-practices-researcher(feature_description) -- Task framework-docs-researcher(feature_description) - -### 1.6. Consolidate Research - -After all research steps complete, consolidate findings: - -- Document relevant file paths from repo research (e.g., `src/services/example_service.py:42`) -- **Include relevant institutional learnings** from `docs/solutions/` (key insights, gotchas to avoid) -- Note external documentation URLs and best practices (if external research was done) -- List related issues or PRs discovered -- Capture CLAUDE.md conventions - -**Optional validation:** Briefly summarize findings and ask if anything looks off or missing before proceeding to planning. - -### 2. Issue Planning & Structure - - -Think like a product manager - what would make this issue clear and actionable? Consider multiple perspectives - - -**Title & Categorization:** - -- [ ] Draft clear, searchable issue title using conventional format (e.g., `feat: Add user authentication`, `fix: Cart total calculation`) -- [ ] Determine issue type: enhancement, bug, refactor -- [ ] Convert title to filename: add today's date prefix, strip prefix colon, kebab-case, add `-plan` suffix - - Example: `feat: Add User Authentication` → `2026-01-21-feat-add-user-authentication-plan.md` - - Keep it descriptive (3-5 words after prefix) so plans are findable by context - -**Stakeholder Analysis:** - -- [ ] Identify who will be affected by this issue (end users, developers, operations) -- [ ] Consider implementation complexity and required expertise - -**Content Planning:** - -- [ ] Choose appropriate detail level based on issue complexity and audience -- [ ] List all necessary sections for the chosen template -- [ ] Gather supporting materials (error logs, screenshots, design mockups) -- [ ] Prepare code examples or reproduction steps if applicable, name the mock filenames in the lists - -### 3. SpecFlow Analysis - -After planning the issue structure, run SpecFlow Analyzer to validate and refine the feature specification: - -- Task compound-engineering:workflow:spec-flow-analyzer(feature_description, research_findings) - -**SpecFlow Analyzer Output:** - -- [ ] Review SpecFlow analysis results -- [ ] Incorporate any identified gaps or edge cases into the issue -- [ ] Update acceptance criteria based on SpecFlow findings - -### 4. Choose Implementation Detail Level - -Select how comprehensive you want the issue to be, simpler is mostly better. - -#### 📄 MINIMAL (Quick Issue) - -**Best for:** Simple bugs, small improvements, clear features - -**Includes:** - -- Problem statement or feature description -- Basic acceptance criteria -- Essential context only - -**Structure:** - -````markdown ---- -title: [Issue Title] -type: [feat|fix|refactor] -status: active -date: YYYY-MM-DD ---- - -# [Issue Title] - -[Brief problem/feature description] - -## Acceptance Criteria - -- [ ] Core requirement 1 -- [ ] Core requirement 2 - -## Context - -[Any critical information] - -## MVP - -### example.py - -```python -class Example: - def __init__(self, name: str) -> None: - self.name = name -``` - -## References - -- Related issue: #[issue_number] -- Documentation: [relevant_docs_url] -```` - -#### 📋 MORE (Standard Issue) - -**Best for:** Most features, complex bugs, team collaboration - -**Includes everything from MINIMAL plus:** - -- Detailed background and motivation -- Technical considerations -- Success metrics -- Dependencies and risks -- Basic implementation suggestions - -**Structure:** - -```markdown ---- -title: [Issue Title] -type: [feat|fix|refactor] -status: active -date: YYYY-MM-DD ---- - -# [Issue Title] - -## Overview - -[Comprehensive description] - -## Problem Statement / Motivation - -[Why this matters] - -## Proposed Solution - -[High-level approach] - -## Technical Considerations - -- Architecture impacts -- Performance implications -- Security considerations - -## System-Wide Impact - -- **Interaction graph**: [What callbacks/middleware/observers fire when this runs?] -- **Error propagation**: [How do errors flow across layers? Do retry strategies align?] -- **State lifecycle risks**: [Can partial failure leave orphaned/inconsistent state?] -- **API surface parity**: [What other interfaces expose similar functionality and need the same change?] -- **Integration test scenarios**: [Cross-layer scenarios that unit tests won't catch] - -## Acceptance Criteria - -- [ ] Detailed requirement 1 -- [ ] Detailed requirement 2 -- [ ] Testing requirements - -## Success Metrics - -[How we measure success] - -## Dependencies & Risks - -[What could block or complicate this] - -## References & Research - -- Similar implementations: [file_path:line_number] -- Best practices: [documentation_url] -- Related PRs: #[pr_number] -``` - -#### 📚 A LOT (Comprehensive Issue) - -**Best for:** Major features, architectural changes, complex integrations - -**Includes everything from MORE plus:** - -- Detailed implementation plan with phases -- Alternative approaches considered -- Extensive technical specifications -- Resource requirements and timeline -- Future considerations and extensibility -- Risk mitigation strategies -- Documentation requirements - -**Structure:** - -```markdown ---- -title: [Issue Title] -type: [feat|fix|refactor] -status: active -date: YYYY-MM-DD ---- - -# [Issue Title] - -## Overview - -[Executive summary] - -## Problem Statement - -[Detailed problem analysis] - -## Proposed Solution - -[Comprehensive solution design] - -## Technical Approach - -### Architecture - -[Detailed technical design] - -### Implementation Phases - -#### Phase 1: [Foundation] - -- Tasks and deliverables -- Success criteria -- Estimated effort - -#### Phase 2: [Core Implementation] - -- Tasks and deliverables -- Success criteria -- Estimated effort - -#### Phase 3: [Polish & Optimization] - -- Tasks and deliverables -- Success criteria -- Estimated effort - -## Alternative Approaches Considered - -[Other solutions evaluated and why rejected] - -## System-Wide Impact - -### Interaction Graph - -[Map the chain reaction: what callbacks, middleware, observers, and event handlers fire when this code runs? Trace at least two levels deep. Document: "Action X triggers Y, which calls Z, which persists W."] - -### Error & Failure Propagation - -[Trace errors from lowest layer up. List specific error classes and where they're handled. Identify retry conflicts, unhandled error types, and silent failure swallowing.] - -### State Lifecycle Risks - -[Walk through each step that persists state. Can partial failure orphan rows, duplicate records, or leave caches stale? Document cleanup mechanisms or their absence.] - -### API Surface Parity - -[List all interfaces (classes, DSLs, endpoints) that expose equivalent functionality. Note which need updating and which share the code path.] - -### Integration Test Scenarios - -[3-5 cross-layer test scenarios that unit tests with mocks would never catch. Include expected behavior for each.] - -## Acceptance Criteria - -### Functional Requirements - -- [ ] Detailed functional criteria - -### Non-Functional Requirements - -- [ ] Performance targets -- [ ] Security requirements -- [ ] Accessibility standards - -### Quality Gates - -- [ ] Test coverage requirements -- [ ] Documentation completeness -- [ ] Code review approval - -## Success Metrics - -[Detailed KPIs and measurement methods] - -## Dependencies & Prerequisites - -[Detailed dependency analysis] - -## Risk Analysis & Mitigation - -[Comprehensive risk assessment] - -## Resource Requirements - -[Team, time, infrastructure needs] - -## Future Considerations - -[Extensibility and long-term vision] - -## Documentation Plan - -[What docs need updating] - -## References & Research - -### Internal References - -- Architecture decisions: [file_path:line_number] -- Similar features: [file_path:line_number] -- Configuration: [file_path:line_number] - -### External References - -- Framework documentation: [url] -- Best practices guide: [url] -- Industry standards: [url] - -### Related Work - -- Previous PRs: #[pr_numbers] -- Related issues: #[issue_numbers] -- Design documents: [links] -``` - -### 5. Issue Creation & Formatting - - -Apply best practices for clarity and actionability, making the issue easy to scan and understand - - -**Content Formatting:** - -- [ ] Use clear, descriptive headings with proper hierarchy (##, ###) -- [ ] Include code examples in triple backticks with language syntax highlighting -- [ ] Add screenshots/mockups if UI-related (drag & drop or use image hosting) -- [ ] Use task lists (- [ ]) for trackable items that can be checked off -- [ ] Add collapsible sections for lengthy logs or optional details using `
` tags -- [ ] Apply appropriate emoji for visual scanning (🐛 bug, ✨ feature, 📚 docs, ♻️ refactor) - -**Cross-Referencing:** - -- [ ] Link to related issues/PRs using #number format -- [ ] Reference specific commits with SHA hashes when relevant -- [ ] Link to code using GitHub's permalink feature (press 'y' for permanent link) -- [ ] Mention relevant team members with @username if needed -- [ ] Add links to external resources with descriptive text - -**Code & Examples:** - -````markdown -# Good example with syntax highlighting and line references - - -```python -# src/services/user_service.py:42 -def process_user(user: User) -> None: - # Implementation here - ... -``` - -# Collapsible error logs - -
-Full error stacktrace - -`Error details here...` - -
-```` - -**AI-Era Considerations:** - -- [ ] Account for accelerated development with AI pair programming -- [ ] Include prompts or instructions that worked well during research -- [ ] Note which AI tools were used for initial exploration (Claude, Copilot, etc.) -- [ ] Emphasize comprehensive testing given rapid implementation -- [ ] Document any AI-generated code that needs human review - -### 6. Final Review & Submission - -**Pre-submission Checklist:** - -- [ ] Title is searchable and descriptive -- [ ] Labels accurately categorize the issue -- [ ] All template sections are complete -- [ ] Links and references are working -- [ ] Acceptance criteria are measurable -- [ ] Add names of files in pseudo code examples and todo lists -- [ ] Add an ERD mermaid diagram if applicable for new model changes - -## Write Plan File - -**REQUIRED: Write the plan file to disk before presenting any options.** - -### Single-Service Mode (default) - -```bash -mkdir -p docs/plans/ -``` - -Use the Write tool to save the complete plan to `docs/plans/YYYY-MM-DD---plan.md`. - -### Multi-Service Mode (when services are focused) - -**Add `services` YAML to the plan frontmatter** with dependency information from focus context: - -```yaml ---- -title: "feat: Feature Name" -type: feat -status: active -date: 2026-03-27 -services: - service-a: - depends_on: [] - service-b: - depends_on: - - service: service-a - reason: "Needs order.created event schema" - lib-common: - depends_on: [] ---- -``` - -Determine dependencies by cross-referencing `pyproject.toml` deps between focused services. Ask user to confirm or adjust the dependency graph. - -**For cross-service plans, write multiple files:** - -1. **Root overview:** `docs/plans/YYYY-MM-DD---plan.md` containing the dependency graph, execution order, links to per-service plans, and cross-cutting concerns -2. **Per-service plans:** `{service}/docs/plans/YYYY-MM-DD---plan.md` containing service-specific implementation tasks, acceptance criteria, and file changes - -Use the same base filename across all locations for traceability. Create directories with `mkdir -p` as needed. - -**For single-service in a multi-service repo:** Write only to `{service}/docs/plans/...` (no root overview needed). - -Confirm: "Plan written to docs/plans/[filename]" (and per-service locations if applicable) - -**Pipeline mode:** If invoked from an automated workflow (LFG, SLFG, or any `disable-model-invocation` context), skip all AskUserQuestion calls. Make decisions automatically and proceed to writing the plan without interactive prompts. - -## Output Format - -**Filename:** Use the date and kebab-case filename from Step 2 Title & Categorization. - -``` -docs/plans/YYYY-MM-DD---plan.md -``` - -Examples: -- ✅ `docs/plans/2026-01-15-feat-user-authentication-flow-plan.md` -- ✅ `docs/plans/2026-02-03-fix-checkout-race-condition-plan.md` -- ✅ `docs/plans/2026-03-10-refactor-api-client-extraction-plan.md` -- ❌ `docs/plans/2026-01-15-feat-thing-plan.md` (not descriptive - what "thing"?) -- ❌ `docs/plans/2026-01-15-feat-new-feature-plan.md` (too vague - what feature?) -- ❌ `docs/plans/2026-01-15-feat: user auth-plan.md` (invalid characters - colon and space) -- ❌ `docs/plans/feat-user-auth-plan.md` (missing date prefix) - -## Post-Generation Options - -After writing the plan file, use the **AskUserQuestion tool** to present these options: - -**Question:** "Plan ready at `docs/plans/YYYY-MM-DD---plan.md`. What would you like to do next?" - -**Options:** -1. **Open plan in editor** - Open the plan file for review -2. **Run `/deepen-plan`** - Enhance each section with parallel research agents (best practices, performance, UI) -3. **Run `/technical_review`** - Technical feedback from code-focused reviewers (DHH, Kieran, Simplicity) -4. **Review and refine** - Improve the document through structured self-review -5. **Start `/workflows:work`** - Begin implementing this plan locally -6. **Start `/workflows:work` on remote** - Begin implementing in Claude Code on the web (use `&` to run in background) -7. **Create Issue** - Create issue in project tracker (GitHub/Linear) - -Based on selection: -- **Open plan in editor** → Run `open docs/plans/.md` to open the file in the user's default editor -- **`/deepen-plan`** → Call the /deepen-plan command with the plan file path to enhance with research -- **`/technical_review`** → Call the /technical_review command with the plan file path -- **Review and refine** → Load `document-review` skill. -- **`/workflows:work`** → Call the /workflows:work command with the plan file path -- **`/workflows:work` on remote** → Run `/workflows:work docs/plans/.md &` to start work in background for Claude Code web -- **Create Issue** → See "Issue Creation" section below -- **Other** (automatically provided) → Accept free text for rework or specific changes - -**Note:** If running `/workflows:plan` with ultrathink enabled, automatically run `/deepen-plan` after plan creation for maximum depth and grounding. - -Loop back to options after Simplify or Other changes until user selects `/workflows:work` or `/technical_review`. - -## Issue Creation - -When user selects "Create Issue", detect their project tracker from CLAUDE.md: - -1. **Check for tracker preference** in user's CLAUDE.md (global or project): - - Look for `project_tracker: github` or `project_tracker: linear` - - Or look for mentions of "GitHub Issues" or "Linear" in their workflow section - -2. **If GitHub:** - - Use the title and type from Step 2 (already in context - no need to re-read the file): - - ```bash - gh issue create --title ": " --body-file <plan_path> + ```yaml + services: + service-a: + depends_on: [] + service-b: + depends_on: + - service: service-a + reason: "<inferred from focus context or asked>" ``` -3. **If Linear:** + Determine dependencies from the `<focus_context>` block's `dependencies:` section. Ask the user to confirm or adjust the graph before writing the final plan. - ```bash - linear issue create --title "<title>" --description "$(cat <plan_path>)" - ``` +3. **Per-service plan files** — for each focused service, write a copy of the plan to `{service}/docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md` (create the directory with `mkdir -p` first). Each per-service plan contains the tasks scoped to that service, the acceptance criteria, and the file changes for that service only. + +4. **Root overview** — keep the root-level plan at `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`. **Rewrite** its body to contain only: the dependency graph, execution order, links to the per-service plans (from sub-step 3), and any cross-cutting concerns. The detailed per-service tasks now live in the per-service files — they should NOT be duplicated in the root. -4. **If no tracker configured:** - Ask user: "Which project tracker do you use? (GitHub/Linear/Other)" - - Suggest adding `project_tracker: github` or `project_tracker: linear` to their CLAUDE.md +In single-service mode (Step 2 returned empty service list), this entire step is skipped — the root plan is the final artifact. -5. **After creation:** - - Display the issue URL - - Ask if they want to proceed to `/workflows:work` or `/technical_review` +## Output -NEVER CODE! Just research and write the plan. +Confirm: "Plan written to `<path>`" (and per-service locations if applicable). Suggest next step: `/workflows:work <plan-path>`. diff --git a/commands/workflows/review.md b/commands/workflows/review.md index 5ba0e45..3bf7b77 100644 --- a/commands/workflows/review.md +++ b/commands/workflows/review.md @@ -1,514 +1,127 @@ --- name: workflows:review -description: Perform exhaustive code reviews using multi-agent analysis, ultra-thinking, and worktrees -argument-hint: "[PR number, GitHub URL, branch name, or latest]" +description: Multi-agent Python code review, delegating review orchestration to superpowers and supplying Python-specific reviewer agents from project config +argument-hint: "[PR number, GitHub URL, branch name, or empty for current branch]" --- -# Review Command +# Review (Python) -<command_purpose> Perform exhaustive code reviews using multi-agent analysis, ultra-thinking, and Git worktrees for deep local inspection. </command_purpose> +This command is a thin wrapper around `superpowers:requesting-code-review`. It loads the Python reviewer agent roster from `compound-engineering.local.md`, supplies them to the superpowers orchestration, and adds Python-specific conditional agents for migrations. -## Introduction - -<role>Senior Code Review Architect with expertise in security, performance, architecture, and quality assurance</role> - -## Prerequisites - -<requirements> -- Git repository with GitHub CLI (`gh`) installed and authenticated -- Clean main/master branch -- Proper permissions to create worktrees and access the repository -- For document reviews: Path to a markdown file or document -</requirements> - -## Main Tasks - -### 1. Determine Review Target & Setup (ALWAYS FIRST) +## Review Target <review_target> #$ARGUMENTS </review_target> -<thinking> -First, I need to determine the review target type and set up the code for analysis. -</thinking> +If empty, default to the current branch's diff against the project default branch. -#### Immediate Actions: +## Prerequisites -<task_list> +If the `superpowers:requesting-code-review` skill is not available, halt and instruct the user: -- [ ] Determine review type: PR number (numeric), GitHub URL, file path (.md), or empty (current branch) -- [ ] Check current git branch -- [ ] If ALREADY on the target branch (PR branch, requested branch name, or the branch already checked out for review) → proceed with analysis on current branch -- [ ] If DIFFERENT branch than the review target → offer to use worktree: "Use git-worktree skill for isolated Call `skill: git-worktree` with branch name -- [ ] Fetch PR metadata using `gh pr view --json` for title, body, files, linked issues -- [ ] Set up language-specific analysis tools -- [ ] Prepare security scanning environment -- [ ] Make sure we are on the branch we are reviewing. Use gh pr checkout to switch to the branch or manually checkout the branch. +> "This command requires the `superpowers` plugin. Install it with: +> `/plugin marketplace add anthropics/claude-plugins-official` +> `/plugin install superpowers@claude-plugins-official`" -Ensure that the code is ready for analysis (either in worktree or on current branch). ONLY then proceed to the next step. +## Step 1: Determine target & checkout -</task_list> +1. Determine the review target type: + - Numeric → PR number; use `gh pr view --json` to fetch metadata. + - GitHub URL → extract PR number, then as above. + - File path ending in `.md` → document review; pass through to superpowers as a doc target. + - Empty → current branch. +2. If the target is a PR and the current branch differs, switch via `gh pr checkout <num>` or use the `superpowers:using-git-worktrees` skill for an isolated worktree. -#### Multi-Service Detection +## Step 2: Microservice Detection -**Auto-detect changed services from the PR diff:** +Auto-detect changed services from the diff: ```bash -git diff --name-only origin/main...HEAD | cut -d'/' -f1 | sort -u +git diff --name-only origin/<default-branch>...HEAD | cut -d'/' -f1 | sort -u ``` -Cross-reference the top-level directories against discovered services (`Glob("*/pyproject.toml")`). This identifies which services were changed in the PR. - -**If multiple services are detected:** Run review agents **per service independently** in the steps below. Each service gets its own set of review agents with findings scoped to that service. - -#### Protected Artifacts +Cross-reference the top-level directories against discovered services (`Glob("*/pyproject.toml")`). The intersection is the list of changed services. -<protected_artifacts> -The following paths are compound-engineering pipeline artifacts and must never be flagged for deletion, removal, or gitignore by any review agent: +If multiple services are changed, invoke the `microservice-focus` skill (passing `--services` from `$ARGUMENTS` if present) to build a `<focus_context>` block scoped to those services. Per-service agent roster loading happens in Step 3. -- `docs/plans/*.md` — Plan files created by `/workflows:plan`. These are living documents that track implementation progress (checkboxes are checked off by `/workflows:work`). -- `docs/solutions/*.md` — Solution documents created during the pipeline. -- `{service}/docs/plans/*.md` — Per-service plan files (microservice mode). -- `{service}/docs/solutions/*.md` — Per-service solution documents (microservice mode). - -If a review agent flags any file in these directories for cleanup or removal, discard that finding during synthesis. Do not create a todo for it. -</protected_artifacts> - -#### Load Review Agents +## Step 3: Load Reviewer Roster **Single-service or non-microservice mode:** -Read `compound-engineering.local.md` in the project root. If found, use `review_agents` from YAML frontmatter. - -**Multi-service mode (multiple services detected):** -For each changed service, check `{service}/compound-engineering.local.md` first. If present, use its `review_agents` (allows different agents per service — e.g., Django agents for one service, FastAPI agents for another). Fall back to root-level `compound-engineering.local.md`. - -If no settings file exists, invoke the `setup` skill to create one. Then read the newly created file and continue. - -#### Load Project Workflow Skills - -Read `compound-engineering.local.md` in the project root (already loaded above for review agents). Parse `workflow_skills.review` from the YAML frontmatter. - -If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific knowledge that helps contextualize review findings. They are additive — loaded alongside agents and skills already used by this command. - -#### Parallel Agents to review the PR: - -<parallel_tasks> - -**Single-service mode:** Run all configured review agents in parallel: - -``` -Task {agent-name}(PR content + review context from settings body) -``` - -**Multi-service mode:** For each changed service, run its configured agents in parallel. Include `<focus_context>` in each agent prompt so it scopes review to that service's files: - -``` -Task {agent-name}("Review changes in {service-name} only. -<focus_context> - service: {service-name} (./{service-name}) - changed_files: [list of changed files in this service] -</focus_context> -PR content + review context from settings body") -``` - -All per-service agents run in parallel across services. Findings are aggregated per service in the synthesis step. - -Additionally, always run these regardless of settings: -- Task agent-native-reviewer(PR content) - Verify new features are agent-accessible -- Task learnings-researcher(PR content) - Search docs/solutions/ for past issues related to this PR's modules and patterns - -</parallel_tasks> - -#### Conditional Agents (Run if applicable): - -<conditional_agents> - -These agents are run ONLY when the PR matches specific criteria. Check the PR files list to determine if they apply: - -**MIGRATIONS: If PR contains database migrations or schema changes:** - -- Task data-migration-expert(PR content) - Validates data migrations, checks for swapped values, verifies rollback safety -- Task deployment-verification-agent(PR content) - Creates Go/No-Go deployment checklist with SQL verification queries - -**When to run:** -- PR includes files matching `*/migrations/*.py` (Django migrations) -- PR includes files matching `alembic/versions/*.py` (Alembic migrations) -- PR modifies columns that store IDs, enums, or mappings -- PR includes data migration scripts or management commands -- PR title/body mentions: migration, backfill, data transformation, ID mapping - -**What these agents check:** -- `data-migration-expert`: Verifies hard-coded mappings match production reality (prevents swapped IDs), checks for orphaned associations, validates dual-write patterns -- `deployment-verification-agent`: Produces executable pre/post-deploy checklists with SQL queries, rollback procedures, and monitoring plans - -</conditional_agents> - -### 4. Ultra-Thinking Deep Dive Phases - -<ultrathink_instruction> For each phase below, spend maximum cognitive effort. Think step by step. Consider all angles. Question assumptions. And bring all reviews in a synthesis to the user.</ultrathink_instruction> - -<deliverable> -Complete system context map with component interactions -</deliverable> - -#### Phase 3: Stakeholder Perspective Analysis - -<thinking_prompt> ULTRA-THINK: Put yourself in each stakeholder's shoes. What matters to them? What are their pain points? </thinking_prompt> - -<stakeholder_perspectives> - -1. **Developer Perspective** <questions> - - - How easy is this to understand and modify? - - Are the APIs intuitive? - - Is debugging straightforward? - - Can I test this easily? </questions> - -2. **Operations Perspective** <questions> - - - How do I deploy this safely? - - What metrics and logs are available? - - How do I troubleshoot issues? - - What are the resource requirements? </questions> - -3. **End User Perspective** <questions> - - - Is the feature intuitive? - - Are error messages helpful? - - Is performance acceptable? - - Does it solve my problem? </questions> - -4. **Security Team Perspective** <questions> - - - What's the attack surface? - - Are there compliance requirements? - - How is data protected? - - What are the audit capabilities? </questions> - -5. **Business Perspective** <questions> - - What's the ROI? - - Are there legal/compliance risks? - - How does this affect time-to-market? - - What's the total cost of ownership? </questions> </stakeholder_perspectives> - -#### Phase 4: Scenario Exploration - -<thinking_prompt> ULTRA-THINK: Explore edge cases and failure scenarios. What could go wrong? How does the system behave under stress? </thinking_prompt> - -<scenario_checklist> - -- [ ] **Happy Path**: Normal operation with valid inputs -- [ ] **Invalid Inputs**: Null, empty, malformed data -- [ ] **Boundary Conditions**: Min/max values, empty collections -- [ ] **Concurrent Access**: Race conditions, deadlocks -- [ ] **Scale Testing**: 10x, 100x, 1000x normal load -- [ ] **Network Issues**: Timeouts, partial failures -- [ ] **Resource Exhaustion**: Memory, disk, connections -- [ ] **Security Attacks**: Injection, overflow, DoS -- [ ] **Data Corruption**: Partial writes, inconsistency -- [ ] **Cascading Failures**: Downstream service issues </scenario_checklist> - -### 6. Multi-Angle Review Perspectives - -#### Technical Excellence Angle - -- Code craftsmanship evaluation -- Engineering best practices -- Technical documentation quality -- Tooling and automation assessment - -#### Business Value Angle - -- Feature completeness validation -- Performance impact on users -- Cost-benefit analysis -- Time-to-market considerations - -#### Risk Management Angle - -- Security risk assessment -- Operational risk evaluation -- Compliance risk verification -- Technical debt accumulation - -#### Team Dynamics Angle - -- Code review etiquette -- Knowledge sharing effectiveness -- Collaboration patterns -- Mentoring opportunities - -### 4. Simplification and Minimalism Review - -Run the Task code-simplicity-reviewer() to see if we can simplify the code. +Read `compound-engineering.local.md` in the project root. Use `review_agents` from the YAML frontmatter. -### 5. Findings Synthesis and Todo Creation Using file-todos Skill +**Multi-service mode** (use the changed-service list computed in Step 2): +For each changed service from Step 2's list, check `{service}/compound-engineering.local.md` first (allows per-service agent rosters — e.g., Django agents for one, FastAPI for another). Fall back to root-level `compound-engineering.local.md`. -<critical_requirement> ALL findings MUST be stored in the todos/ directory using the file-todos skill. Create todo files immediately after synthesis - do NOT present findings for user approval first. Use the skill for structured todo management. </critical_requirement> +If no settings file exists: +- **Interactive mode** (no `--services` argument): invoke the `setup` skill to create one. Read the new file and continue. +- **Pipeline mode** (`--services` was passed): skip the setup skill and proceed without a Python reviewer roster (the always-on agents in Step 7 still run; superpowers' default review still happens). -#### Step 1: Synthesize All Findings +## Step 4: Load Project Workflow Skills -<thinking> -Consolidate all agent reports into a categorized list of findings. -Remove duplicates, prioritize by severity and impact. -</thinking> +From the same `compound-engineering.local.md`, parse `workflow_skills.review`. Load each listed skill now. They provide Python-specific context that helps interpret review findings. -<synthesis_tasks> +## Step 5: Identify Conditional Agents -- [ ] Collect findings from all parallel agents -- [ ] Surface learnings-researcher results: if past solutions are relevant, flag them as "Known Pattern" with links to docs/solutions/ files -- [ ] Discard any findings that recommend deleting or gitignoring files in `docs/plans/` or `docs/solutions/` (see Protected Artifacts above) -- [ ] Categorize by type: security, performance, architecture, quality, etc. -- [ ] Assign severity levels: 🔴 CRITICAL (P1), 🟡 IMPORTANT (P2), 🔵 NICE-TO-HAVE (P3) -- [ ] Remove duplicate or overlapping findings -- [ ] Estimate effort for each finding (Small/Medium/Large) +Some agents only run when the PR matches specific criteria: -</synthesis_tasks> +**Migration agents** — run if the PR contains any of: +- `*/migrations/*.py` (Django migrations) +- `alembic/versions/*.py` (Alembic migrations) +- Files modifying ID/enum/mapping columns +- Data migration scripts or management commands +- Title/body mentioning: migration, backfill, data transformation, ID mapping -#### Step 2: Create Todo Files Using file-todos Skill +If matched, add to the agent roster: +- `data-migration-expert` — validates data migrations, swapped IDs, rollback safety +- `deployment-verification-agent` — Go/No-Go checklist with SQL verification queries -<critical_instruction> Use the file-todos skill to create todo files for ALL findings immediately. Do NOT present findings one-by-one asking for user approval. Create all todo files in parallel using the skill, then summarize results to user. </critical_instruction> +## Step 6: Protected Artifacts -**Implementation Options:** +When synthesizing findings, **discard any recommendations to delete or gitignore** files matching: -**Option A: Direct File Creation (Fast)** +- `docs/plans/*.md`, `docs/superpowers/plans/*.md` +- `docs/superpowers/specs/*.md` +- `docs/solutions/*.md` (legacy; the knowledge-compounding pattern was dropped in v3.0.0 but historical files may remain in user repos) +- `{service}/docs/plans/*.md`, `{service}/docs/superpowers/plans/*.md` +- `{service}/docs/superpowers/specs/*.md` +- `{service}/docs/solutions/*.md` (legacy; same reason as above) -- Create todo files directly using Write tool -- All findings in parallel for speed -- Use standard template from `.claude/skills/file-todos/assets/todo-template.md` -- Follow naming convention: `{issue_id}-pending-{priority}-{description}.md` +These are living pipeline artifacts. Do not create todos for their removal. -**Option B: Sub-Agents in Parallel (Recommended for Scale)** For large PRs with 15+ findings, use sub-agents to create finding files in parallel: +## Step 7: Delegate to superpowers -```bash -# Launch multiple finding-creator agents in parallel -Task() - Create todos for first finding -Task() - Create todos for second finding -Task() - Create todos for third finding -etc. for each finding. -``` - -Sub-agents can: - -- Process multiple findings simultaneously -- Write detailed todo files with all sections filled -- Organize findings by severity -- Create comprehensive Proposed Solutions -- Add acceptance criteria and work logs -- Complete much faster than sequential processing - -**Execution Strategy:** - -1. Synthesize all findings into categories (P1/P2/P3) -2. Group findings by severity -3. Launch 3 parallel sub-agents (one per severity level) -4. Each sub-agent creates its batch of todos using the file-todos skill -5. Consolidate results and present summary - -**Process (Using file-todos Skill):** - -1. For each finding: - - - Determine severity (P1/P2/P3) - - Write detailed Problem Statement and Findings - - Create 2-3 Proposed Solutions with pros/cons/effort/risk - - Estimate effort (Small/Medium/Large) - - Add acceptance criteria and work log - -2. Use file-todos skill for structured todo management: - - ```bash - skill: file-todos - ``` - - The skill provides: - - - Template location: `.claude/skills/file-todos/assets/todo-template.md` - - Naming convention: `{issue_id}-{status}-{priority}-{description}.md` - - YAML frontmatter structure: status, priority, issue_id, tags, dependencies - - All required sections: Problem Statement, Findings, Solutions, etc. - -3. Create todo files in parallel: - - ```bash - {next_id}-pending-{priority}-{description}.md - ``` - -4. Examples: - - ``` - 001-pending-p1-path-traversal-vulnerability.md - 002-pending-p1-api-response-validation.md - 003-pending-p2-concurrency-limit.md - 004-pending-p3-unused-parameter.md - ``` - -5. Follow template structure from file-todos skill: `.claude/skills/file-todos/assets/todo-template.md` - -**Todo File Structure (from template):** - -Each todo must include: - -- **YAML frontmatter**: status, priority, issue_id, tags, dependencies -- **Problem Statement**: What's broken/missing, why it matters -- **Findings**: Discoveries from agents with evidence/location -- **Proposed Solutions**: 2-3 options, each with pros/cons/effort/risk -- **Recommended Action**: (Filled during triage, leave blank initially) -- **Technical Details**: Affected files, components, database changes -- **Acceptance Criteria**: Testable checklist items -- **Work Log**: Dated record with actions and learnings -- **Resources**: Links to PR, issues, documentation, similar patterns - -**File naming convention:** - -``` -{issue_id}-{status}-{priority}-{description}.md - -Examples: -- 001-pending-p1-security-vulnerability.md -- 002-pending-p2-performance-optimization.md -- 003-pending-p3-code-cleanup.md -``` - -**Status values:** - -- `pending` - New findings, needs triage/decision -- `ready` - Approved by manager, ready to work -- `complete` - Work finished - -**Priority values:** - -- `p1` - Critical (blocks merge, security/data issues) -- `p2` - Important (should fix, architectural/performance) -- `p3` - Nice-to-have (enhancements, cleanup) - -**Tagging:** Always add `code-review` tag, plus: `security`, `performance`, `architecture`, `python, django, fastapi`, `quality`, etc. - -#### Step 3: Summary Report - -After creating all todo files, present comprehensive summary: - -````markdown -## ✅ Code Review Complete +Invoke the `superpowers:requesting-code-review` skill. Pass: -**Review Target:** PR #XXXX - [PR Title] **Branch:** [branch-name] +- The review target (PR number, branch, or doc path). +- The full agent roster from Step 3 (so superpowers spawns each in parallel). +- The conditional migration agents from Step 5 (if applicable). +- The `<focus_context>` block from Step 2 (multi-service mode). +- The "protected artifacts" rule from Step 6 (so superpowers filters discardable findings). +- Always-on agents to include alongside the roster: + - `agent-native-reviewer` — verifies new features are agent-accessible + - `code-simplicity-reviewer` — final pass for simplicity and minimalism -### Findings Summary: +Note: this command does **NOT** spawn `learnings-researcher` (deleted in v3.0.0) and does NOT read `docs/solutions/` (knowledge-compounding pattern dropped). -- **Total Findings:** [X] -- **🔴 CRITICAL (P1):** [count] - BLOCKS MERGE -- **🟡 IMPORTANT (P2):** [count] - Should Fix -- **🔵 NICE-TO-HAVE (P3):** [count] - Enhancements +## Step 8: Synthesis & Todos -### Created Todo Files: +The superpowers skill handles parallel agent execution and findings collection. After it returns, **by default** use the `file-todos` skill to create one todo file per finding under `todos/`, using the standard naming `{issue_id}-pending-{priority}-{description}.md`. -**P1 - Critical (BLOCKS MERGE):** +**Exception** — if the user invoked the command with `--no-todos`, or if the user explicitly requested an inline summary during the conversation, surface findings as a categorized list (P1/P2/P3) without writing files. -- `001-pending-p1-{finding}.md` - {description} -- `002-pending-p1-{finding}.md` - {description} +## Step 9: Browser Test Offer (Optional) -**P2 - Important:** +After synthesis, offer browser testing via `AskUserQuestion`: -- `003-pending-p2-{finding}.md` - {description} -- `004-pending-p2-{finding}.md` - {description} +> "Want to run browser tests on the affected pages?" +> 1. Yes — run `/test-browser` +> 2. No — skip -**P3 - Nice-to-Have:** +If the user accepts, spawn a sub-agent to run `/test-browser` for the PR. The sub-agent uses the `agent-browser` skill to capture snapshots and check for console errors. -- `005-pending-p3-{finding}.md` - {description} +## Output -### Review Agents Used: - -- python-style-reviewer -- security-sentinel -- performance-oracle -- architecture-strategist -- agent-native-reviewer -- [other agents] - -### Next Steps: - -1. **Address P1 Findings**: CRITICAL - must be fixed before merge - - - Review each P1 todo in detail - - Implement fixes or request exemption - - Verify fixes before merging PR - -2. **Triage All Todos**: - ```bash - ls todos/*-pending-*.md # View all pending todos - /triage # Use slash command for interactive triage - ``` -```` - -3. **Work on Approved Todos**: - - ```bash - /resolve_todo_parallel # Fix all approved items efficiently - ``` - -4. **Track Progress**: - - Rename file when status changes: pending → ready → complete - - Update Work Log as you work - - Commit todos: `git add todos/ && git commit -m "refactor: add code review findings"` - -### Severity Breakdown: - -**🔴 P1 (Critical - Blocks Merge):** - -- Security vulnerabilities -- Data corruption risks -- Breaking changes -- Critical architectural issues - -**🟡 P2 (Important - Should Fix):** - -- Performance issues -- Significant architectural concerns -- Major code quality problems -- Reliability issues - -**🔵 P3 (Nice-to-Have):** - -- Minor improvements -- Code cleanup -- Optimization opportunities -- Documentation updates - -``` - -### 7. End-to-End Testing (Optional) - -<offer_testing> - -After presenting the Summary Report, offer browser testing: - -```markdown -**"Want to run browser tests on the affected pages?"** -1. Yes - run `/test-browser` -2. No - skip -``` - -</offer_testing> - -#### If User Accepts Web Testing: - -Spawn a subagent to run browser tests (preserves main context): - -``` -Task general-purpose("Run /test-browser for PR #[number]. Test all affected pages, check for console errors, handle failures by creating todos and fixing.") -``` - -The subagent will: -1. Identify pages affected by the PR -2. Navigate to each page and capture snapshots (using agent-browser CLI) -3. Check for console errors -4. Test critical interactions -5. Pause for human verification on OAuth/email/payment flows -6. Create P1 todos for any failures -7. Fix and retry until all tests pass - -**Standalone:** `/test-browser [PR number]` - -### Important: P1 Findings Block Merge - -Any **🔴 P1 (CRITICAL)** findings must be addressed before merging the PR. Present these prominently and ensure they're resolved before accepting the PR. -``` +Summarize: +- PR/branch reviewed. +- Number of P1/P2/P3 findings. +- Path to todos/ (if file-todos was used). +- Next-step recommendation (e.g., "Address P1 findings before merging"). diff --git a/commands/workflows/work.md b/commands/workflows/work.md index 0bb23d4..250fca4 100644 --- a/commands/workflows/work.md +++ b/commands/workflows/work.md @@ -1,584 +1,176 @@ --- name: workflows:work -description: Execute work plans efficiently while maintaining quality and finishing features -argument-hint: "[plan file, specification, or todo file path]" +description: Execute a plan via superpowers, gated by a Python-specific quality bar (pytest + ruff + mypy + pre-commit), with multi-service execution ordering preserved +argument-hint: "[plan file path]" --- -# Work Plan Execution Command +# Work (Python) -Execute a work plan efficiently while maintaining quality and finishing features. - -## Introduction - -This command takes a work document (plan, specification, or todo file) and executes it systematically. The focus is on **shipping complete features** by understanding requirements quickly, following existing patterns, and maintaining quality throughout. +This command is a wrapper around `superpowers:executing-plans`. It loads Python-specific context, runs the microservice focus gate, optionally honors per-service execution ordering, delegates plan execution, then enforces a Python quality gate before any PR is created. ## Input Document <input_document> #$ARGUMENTS </input_document> -## Project Workflow Skills - -Read `compound-engineering.local.md` in the project root. If found, parse the YAML frontmatter for `workflow_skills.work`. - -If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific knowledge (domain context, framework patterns, testing conventions) that informs implementation. They are additive — loaded alongside any skills this command already references (e.g., `git-worktree`, `commit`, `orchestrating-swarms`). +If empty, ask the user for a plan path (typically under `docs/superpowers/plans/` or `{service}/docs/superpowers/plans/`). Do not proceed without one. -If no config exists or no `workflow_skills` key is present, proceed without additional skills. +## Prerequisites -## Execution Workflow +If the `superpowers:executing-plans` skill is not available, halt and instruct the user: -### Phase 1: Quick Start +> "This command requires the `superpowers` plugin. Install it with: +> `/plugin marketplace add anthropics/claude-plugins-official` +> `/plugin install superpowers@claude-plugins-official`" -1. **Read Plan and Clarify** +## Step 1: Load Project Workflow Skills - - Read the work document completely - - Review any references or links provided in the plan - - If anything is unclear or ambiguous, ask clarifying questions now - - Get user approval to proceed - - **Do not skip this** - better to ask questions now than build the wrong thing +Read `compound-engineering.local.md`. If `workflow_skills.work` is set, load each listed skill now (e.g., `django-patterns`, `pytest-patterns`). -2. **Setup Environment** +## Step 2: Microservice Focus + Execution Order - First, check the current branch: +Invoke the `microservice-focus` skill. It will: - ```bash - current_branch=$(git branch --show-current) - default_branch=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@') +- Parse `--services` from `$ARGUMENTS` if present. +- Otherwise discover services via `Glob("*/pyproject.toml")` and prompt the user via `AskUserQuestion` if multiple services exist. +- Return the list of focused services + a `<focus_context>` block. - # Fallback if remote HEAD isn't set - if [ -z "$default_branch" ]; then - default_branch=$(git rev-parse --verify origin/main >/dev/null 2>&1 && echo "main" || echo "master") - fi - ``` - - **If already on a feature branch** (not the default branch): - - Ask: "Continue working on `[current_branch]`, or create a new branch?" - - If continuing, proceed to step 3 - - If creating new, follow Option A or B below +**If the plan's YAML frontmatter contains a `services:` section:** - **If on the default branch**, choose how to proceed: - - **Option A: Create a new branch** - ```bash - git pull origin [default_branch] - git checkout -b feature-branch-name - ``` - Use a meaningful name based on the work (e.g., `feat/user-authentication`, `fix/email-validation`). - - **Option B: Use a worktree (recommended for parallel development)** - ```bash - skill: git-worktree - # The skill will create a new branch from the default branch in an isolated worktree - ``` - - **Option C: Continue on the default branch** - - Requires explicit user confirmation - - Only proceed after user explicitly says "yes, commit to [default_branch]" - - Never commit directly to the default branch without explicit permission - - **Recommendation**: Use worktree if: - - You want to work on multiple features simultaneously - - You want to keep the default branch clean while experimenting - - You plan to switch between branches frequently - -3. **Create Todo List** - - Use TodoWrite to break plan into actionable tasks - - Include dependencies between tasks - - Prioritize based on what needs to be done first - - Include testing and quality check tasks - - Keep tasks specific and completable - -4. **Multi-Service Execution Planning** (only when `services:` YAML exists in plan frontmatter) - - If the plan frontmatter contains a `services:` section: - - a. **Load full service context** for each service in the YAML: - - Read `{service}/.claude/prompt.md` (preferred) or `{service}/README.md` (first 50 lines) to understand what the service does - - Read `{service}/pyproject.toml` to extract package name, Python version, key dependencies - - List `{service}/src/` (1 level deep) to understand app organization - - Cross-reference `pyproject.toml` dependencies between services to validate the declared dependency graph - - b. **Parse the dependency graph** from the YAML: - ```yaml - services: - service-a: - depends_on: [] - service-b: - depends_on: - - service: service-a - reason: "Needs order.created event schema" - ``` - - c. **Build topological execution order** (wavefront pattern): - - Group services into waves: Wave 1 = services with no dependencies, Wave 2 = services depending only on Wave 1, etc. - - Detect circular dependencies: if found, report to user and treat all services in the cycle as independent - - d. **Show execution plan with service context and get confirmation:** - ``` - Execution plan: - Wave 1 (no deps): - service-a — Order management (Django 5.0, Celery) - lib-common — Shared DTOs and schemas - Wave 2 (after wave 1): - service-b — Payment processing (FastAPI, SQLAlchemy) — depends on service-a - - Default: sequential execution in topological order. - Options: [Confirm] [Force parallel] [Force sequential] [Adjust order] - ``` - - **Pipeline mode:** Auto-confirm the execution order when invoked from an automated workflow. - - e. **Execute services in order, respecting each service's stack:** - - **Sequential (default):** Execute all tasks for service-a, then lib-common, then service-b. Each service's tasks are a group in the todo list. - - **Parallel (opt-in):** Use swarm mode — spawn one `general-purpose` worker agent per service with `run_in_background: true`. Use Task system with `addBlockedBy` to wire dependencies. Leader monitors progress via TaskList() and inbox. See the `orchestrating-swarms` skill for patterns. - - **Stack-aware execution:** Use the loaded service context to choose the right patterns per service. Don't apply Django patterns in a FastAPI service or vice versa. Run each service's own test command (`cd {service} && poetry run pytest` or as defined in its CLAUDE.md). - - f. **Failure handling:** - - **Sequential:** On failure, stop and ask user: retry, skip this service, or abort - - **Parallel:** Independent services continue. Dependent services stay blocked (auto via Task system). Notify user with: which service failed, error details, which downstream services are blocked. User decides: retry, skip (force-complete to unblock dependents), or abort. - - g. **Commits:** One feature branch for the whole feature. Use per-service commit messages: - ``` - feat(service-order): add order.created event publisher - feat(service-payment): add payment confirmation handler - ``` - -### Phase 2: Execute (Sonnet Sub-Agent) - -Phase 2 runs as a **Sonnet sub-agent** to optimize token costs. Implementation/coding is Sonnet's sweet spot — it follows plans precisely and costs ~5x less than Opus. The parent (Opus) orchestrates, plans, and reviews; Sonnet executes. - -**Spawn the implementation agent:** +1. Treat those as the focused services (override the prompt result). +2. Parse the dependency graph from the frontmatter. +3. Build a topological execution order (wavefront pattern): + - Wave 1: services with `depends_on: []` + - Wave 2: services depending only on Wave 1 + - etc. +4. Detect cycles: if found, report to user and treat services in the cycle as independent. +5. Show the execution plan and get user confirmation (skip in pipeline mode): ``` -Agent({ - description: "Implement plan tasks", - model: "sonnet", - mode: "auto", - prompt: <see below> -}) +Execution plan: + Wave 1 (no deps): + service-a — Order management (Django 5.0, Celery) + lib-common — Shared DTOs and schemas + Wave 2 (after wave 1): + service-b — Payment processing (FastAPI, SQLAlchemy) — depends on service-a + +Default: sequential execution in topological order. +Options: [Confirm] [Force parallel] [Force sequential] [Adjust order] ``` -**Build the prompt from Phase 1 context.** Include ALL of the following in the agent prompt: +**If the user picks `[Force parallel]`:** within each wave, invoke `superpowers:dispatching-parallel-agents` to run that wave's services concurrently (do NOT invoke the deleted `orchestrating-swarms` skill). Waves still run sequentially with respect to each other — only within a wave is parallelized. -1. The full plan content (read in Phase 1) -2. The todo list created in Phase 1 (copy the task breakdown) -3. The branch name and working directory -4. Any service context loaded during multi-service planning -5. Project coding standards from CLAUDE.md (summarize key rules) -6. The complete execution instructions below (copy them verbatim into the prompt) +**In single-service mode** (no `services:` frontmatter in the plan AND no `--services` argument), skip the wavefront/cycle/execution-order logic above — there's nothing to order. Step 3 passes no execution order parameter to superpowers; it runs as a single-service invocation. -**IMPORTANT**: The sub-agent starts with a blank context. It cannot see anything from Phase 1 unless you explicitly include it in the prompt. Be thorough — pass the plan, the task list, the branch, and the conventions. +## Step 3: Delegate plan execution to superpowers ---- +Invoke the `superpowers:executing-plans` skill (or `superpowers:subagent-driven-development` if the plan header recommends it). Pass: -<implementation_instructions> +- The plan path from `<input_document>`. +- The `<focus_context>` block. +- The execution order from Step 2 (so the skill processes tasks in the right wave order in multi-service mode). +- The test command to use per service: + - Single-service: `poetry run pytest` (or whatever the project's CLAUDE.md specifies) + - Multi-service: `cd {service} && poetry run pytest` for each service -These instructions are for the implementation sub-agent. Copy them into the agent prompt. +The superpowers skill handles the task loop, per-task commits, and incremental progress. **Instruct the skill to NOT invoke `superpowers:finishing-a-development-branch` at the end** — this wrapper owns the finishing flow (Steps 4 and 5) because it adds Python-specific value (quality gate before commit, Post-Deploy Monitoring section in PR). Control returns to this wrapper after the task loop completes (or escalates). -#### Task Execution Loop - -For each task in priority order: - -``` -while (tasks remain): - - Mark task as in_progress in TodoWrite - - Read any referenced files from the plan - - Look for similar patterns in codebase - - Implement following existing conventions - - Write tests for new functionality - - Run System-Wide Test Check (see below) - - Run tests after changes - - Mark task as completed in TodoWrite - - Mark off the corresponding checkbox in the plan file ([ ] → [x]) - - Evaluate for incremental commit (see below) -``` - -**System-Wide Test Check** — Before marking a task done, pause and ask: - -| Question | What to do | -|----------|------------| -| **What fires when this runs?** Callbacks, middleware, observers, event handlers — trace two levels out from your change. | Read the actual code (not docs) for callbacks on models you touch, middleware in the request chain, `after_*` hooks. | -| **Do my tests exercise the real chain?** If every dependency is mocked, the test proves your logic works *in isolation* — it says nothing about the interaction. | Write at least one integration test that uses real objects through the full callback/middleware chain. No mocks for the layers that interact. | -| **Can failure leave orphaned state?** If your code persists state (DB row, cache, file) before calling an external service, what happens when the service fails? Does retry create duplicates? | Trace the failure path with real objects. If state is created before the risky call, test that failure cleans up or that retry is idempotent. | -| **What other interfaces expose this?** Mixins, DSLs, alternative entry points (Agent vs Chat vs ChatMethods). | Grep for the method/behavior in related classes. If parity is needed, add it now — not as a follow-up. | -| **Do error strategies align across layers?** Retry middleware + application fallback + framework error handling — do they conflict or create double execution? | List the specific error classes at each layer. Verify your rescue list matches what the lower layer actually raises. | - -**When to skip:** Leaf-node changes with no callbacks, no state persistence, no parallel interfaces. If the change is purely additive (new helper method, new view partial), the check takes 10 seconds and the answer is "nothing fires, skip." - -**When this matters most:** Any change that touches models with callbacks, error handling with fallback/retry, or functionality exposed through multiple interfaces. - -**IMPORTANT**: Always update the original plan document by checking off completed items. Use the Edit tool to change `- [ ]` to `- [x]` for each task you finish. This keeps the plan as a living document showing progress and ensures no checkboxes are left unchecked. - -#### Incremental Commits - -After completing each task, evaluate whether to create an incremental commit: - -| Commit when... | Don't commit when... | -|----------------|---------------------| -| Logical unit complete (model, service, component) | Small part of a larger unit | -| Tests pass + meaningful progress | Tests failing | -| About to switch contexts (backend → frontend) | Purely scaffolding with no behavior | -| About to attempt risky/uncertain changes | Would need a "WIP" commit message | - -**Heuristic:** "Can I write a commit message that describes a complete, valuable change? If yes, commit. If the message would be 'WIP' or 'partial X', wait." - -**Commit workflow — test-and-fix gate (REQUIRED before every commit):** - -``` -LOOP until clean: - 1. Run tests (poetry run pytest / project test command) - → If tests fail: read failures, fix the code, re-run. Do NOT proceed to step 2. - 2. Stage files related to this logical unit (not `git add .`) - 3. Run `git commit` (this triggers pre-commit hooks) - → If pre-commit hooks fail: - a. Read the hook output to identify what failed - b. Fix the issues (formatting, imports, linting, type errors) - c. Auto-stage any auto-fixes the hooks applied - d. Go back to step 1 (re-run tests — hook fixes may break things) - → If pre-commit hooks pass: commit succeeds, move on -``` - -**Key rules:** -- NEVER commit with failing tests. Fix them first. -- NEVER skip pre-commit hooks with `--no-verify`. -- If a pre-commit hook auto-fixes files (black, isort, ruff), re-run tests after staging the fixes — auto-formatting can change behavior in rare cases. -- If stuck after 2 retry cycles, show the errors and ask the user. - -**Handling merge conflicts:** If conflicts arise during rebasing or merging, resolve them immediately. Incremental commits make conflict resolution easier since each commit is small and focused. - -**Note:** Incremental commits use clean conventional messages without attribution footers. The final Phase 4 commit/PR includes the full attribution. - -#### Follow Existing Patterns - -- The plan should reference similar code - read those files first -- Match naming conventions exactly -- Reuse existing components where possible -- Follow project coding standards (see CLAUDE.md) -- When in doubt, grep for similar implementations - -#### Test Continuously - -- Run relevant tests after each significant change -- Don't wait until the end to test -- Fix failures immediately -- Add new tests for new functionality -- **Unit tests with mocks prove logic in isolation. Integration tests with real objects prove the layers work together.** If your change touches callbacks, middleware, or error handling — you need both. - -#### Figma Design Sync (if applicable) - -For UI work with Figma designs: - -- Implement components following design specs -- Use figma-design-sync agent iteratively to compare -- Fix visual differences identified -- Repeat until implementation matches design - -#### Track Progress -- Keep TodoWrite updated as you complete tasks -- Note any blockers or unexpected discoveries -- Create new tasks if scope expands -- Keep user informed of major milestones - -</implementation_instructions> - ---- +## Step 4: Python Quality Gate (MANDATORY — blocks Step 5) -**After the sub-agent completes**, review its output before proceeding to Phase 3. If the agent reports blockers or unresolved issues, address them before moving on. If the agent failed or produced incomplete work, you may re-spawn it with additional context or handle the remaining tasks directly. +Step 5 cannot start until all checks in this step pass. This is not advisory. -### Phase 3: Quality Gate (MANDATORY — blocks Phase 4) - -Phase 4 CANNOT start until all checks in this phase pass. This is not advisory. - -1. **Run Full Test-and-Fix Cycle** +1. **Full Test-and-Fix Cycle** — loop until clean: ``` - LOOP until all pass: - 1. Run full test suite (poetry run pytest / project test command) - → If tests fail: fix the code, re-run. Do NOT proceed. - 2. Run linting (per CLAUDE.md / use python-lint agent) - → If linting fails: fix the issues, re-run tests (lint fixes can break things). - 3. Run pre-commit hooks on all staged files: `git stash && git stash pop` - or stage everything and do a dry run if the project supports it. - → If hooks fail: fix issues, re-run from step 1. + LOOP: + a. Run full test suite. Single-service: `poetry run pytest`. Multi-service: run each focused + service's test command in sequence (or in parallel if the user opted in). + → If tests fail: read failures, fix the code, re-run from (a). Do NOT proceed. + b. Run linting via the python-lint agent (ruff + mypy). + → If linting fails: fix issues, re-run from (a) — lint fixes can break tests. + c. Run pre-commit hooks on all staged files (`pre-commit run --all-files` or + `git stash && git stash pop` to trigger the install). + → If hooks fail: fix issues, re-run from (a). ``` - **Do not skip this cycle.** Every fix can introduce new failures — always re-run from the top after changes. - -2. **Consider Reviewer Agents** (Optional) - - Use for complex, risky, or large changes. Read agents from `compound-engineering.local.md` frontmatter (`review_agents`). If no settings file, invoke the `setup` skill to create one. + Do not skip this cycle. Every fix can introduce new failures — always re-run from the top. - Run configured agents in parallel with Task tool. Present findings and address critical issues. +2. **Optional Reviewer Agents** — for risky or large changes, read `review_agents` from `compound-engineering.local.md`. If present, spawn each in parallel via `Task`. Present findings; address critical ones before proceeding. -3. **Final Validation Checklist** (all must be true to proceed) - - [ ] All TodoWrite tasks marked completed - - [ ] Full test suite passes (not just the tests you wrote) +3. **Final Validation Checklist** — all must be true: + - [ ] All plan tasks marked completed (checkboxes in plan file) + - [ ] Full test suite passes (not just the tests added) - [ ] Linting passes with zero warnings - [ ] Pre-commit hooks pass on all changed files - [ ] Code follows existing patterns - - [ ] Figma designs match (if applicable) - [ ] No console errors or warnings - **If any check fails:** Fix the issue and re-run the full cycle. Do NOT proceed to Phase 4. - -4. **Prepare Operational Validation Plan** (REQUIRED) - - Add a `## Post-Deploy Monitoring & Validation` section to the PR description for every change. - - Include concrete: - - Log queries/search terms - - Metrics or dashboards to watch - - Expected healthy signals - - Failure signals and rollback/mitigation trigger - - Validation window and owner - - If there is truly no production/runtime impact, still include the section with: `No additional operational monitoring required` and a one-line reason. - -### Phase 4: Ship It - -**Prerequisite:** Phase 3 Quality Gate MUST have passed. If tests, linting, or pre-commit hooks are failing, go back to Phase 3 and fix them first. Do NOT ship broken code. - -1. **Create Commit** - - Use the `/commit` skill to analyze, group, and commit all changes with proper conventional + gitmoji format. This ensures changes are logically grouped and the commit message follows project conventions. - - ``` - /commit - ``` - - If the `/commit` skill's pre-commit hooks fail during commit: - - Fix the issues (don't skip with `--no-verify`) - - Re-run tests to ensure fixes didn't break anything - - Retry the commit - -2. **Capture and Upload Screenshots for UI Changes** (REQUIRED for any UI work) - - For **any** design changes, new views, or UI modifications, you MUST capture and upload screenshots: - - **Step 1: Start dev server** (if not running) - ```bash - # Django: python manage.py runserver - # FastAPI: uvicorn main:app --reload - ``` - - **Step 2: Capture screenshots with agent-browser CLI** - ```bash - agent-browser open http://localhost:3000/[route] - agent-browser snapshot -i - agent-browser screenshot output.png - ``` - See the `agent-browser` skill for detailed usage. - - **Step 3: Upload using imgup skill** - ```bash - skill: imgup - # Then upload each screenshot: - imgup -h pixhost screenshot.png # pixhost works without API key - # Alternative hosts: catbox, imagebin, beeimg - ``` - - **What to capture:** - - **New screens**: Screenshot of the new UI - - **Modified screens**: Before AND after screenshots - - **Design implementation**: Screenshot showing Figma design match - - **IMPORTANT**: Always include uploaded image URLs in PR description. This provides visual context for reviewers and documents the change. - -3. **Create Pull Request** - - ```bash - git push -u origin feature-branch-name - - gh pr create --title "Feature: [Description]" --body "$(cat <<'EOF' - ## Summary - - What was built - - Why it was needed - - Key decisions made - - ## Testing - - Tests added/modified - - Manual testing performed - - ## Post-Deploy Monitoring & Validation - - **What to monitor/search** - - Logs: - - Metrics/Dashboards: - - **Validation checks (queries/commands)** - - `command or query here` - - **Expected healthy behavior** - - Expected signal(s) - - **Failure signal(s) / rollback trigger** - - Trigger + immediate action - - **Validation window & owner** - - Window: - - Owner: - - **If no operational impact** - - `No additional operational monitoring required: <reason>` - - ## Before / After Screenshots - | Before | After | - |--------|-------| - | ![before](URL) | ![after](URL) | - - ## Figma Design - [Link if applicable] - - --- - - [![Compound Engineered](https://img.shields.io/badge/Compound-Engineered-6366f1)](https://github.com/BaronVonSario/compound-engineering-feat-python) 🤖 Generated with [Claude Code](https://claude.com/claude-code) - EOF - )" - ``` - -4. **Update Plan Status** - - If the input document has YAML frontmatter with a `status` field, update it to `completed`: - ``` - status: active → status: completed - ``` - -5. **Notify User** - - Summarize what was completed - - Link to PR - - Note any follow-up work needed - - Suggest next steps if applicable - ---- - -## Swarm Mode (Optional) + If any check fails: fix and re-run the full cycle. Do not proceed to Step 5. -For complex plans with multiple independent workstreams, enable swarm mode for parallel execution with coordinated agents. +4. **Operational Validation Plan** — REQUIRED before PR: -### When to Use Swarm Mode + Add a `## Post-Deploy Monitoring & Validation` section to the PR description for every change. Include: + - Log queries/search terms + - Metrics or dashboards to watch + - Expected healthy signals + - Failure signals + rollback/mitigation trigger + - Validation window + owner -| Use Swarm Mode when... | Use Standard Mode when... | -|------------------------|---------------------------| -| Plan has 5+ independent tasks | Plan is linear/sequential | -| Multiple specialists needed (review + test + implement) | Single-focus work | -| Want maximum parallelism | Simpler mental model preferred | -| Large feature with clear phases | Small feature or bug fix | + If truly no production/runtime impact: include the section with `No additional operational monitoring required: <reason>`. -### Enabling Swarm Mode +## Step 5: Ship It -To trigger swarm execution, say: +Prerequisite: Step 4 quality gate passed. If not, return to Step 4. -> "Make a Task list and launch an army of agent swarm subagents to build the plan" +1. **Create commit via the `commit` skill.** It analyzes, groups, and commits all changes with conventional + gitmoji format. Never skip pre-commit hooks with `--no-verify`. -Or explicitly request: "Use swarm mode for this work" +2. **Capture screenshots for UI changes** — for any design changes, new views, or UI modifications: + - Start dev server (Django: `python manage.py runserver`; FastAPI: `uvicorn main:app --reload`). + - Use the `agent-browser` skill to capture before/after screenshots. + - Upload via the `agent-browser` skill's upload mechanism and include URLs in the PR description. -### Swarm Workflow +3. **Create Pull Request:** -When swarm mode is enabled, the workflow changes: +```bash +git push -u origin <feature-branch-name> -1. **Create Team** - ``` - Teammate({ operation: "spawnTeam", team_name: "work-{timestamp}" }) - ``` - -2. **Create Task List with Dependencies** - - Parse plan into TaskCreate items - - Set up blockedBy relationships for sequential dependencies - - Independent tasks have no blockers (can run in parallel) - -3. **Spawn Specialized Teammates** - ``` - Task({ - team_name: "work-{timestamp}", - name: "implementer", - subagent_type: "general-purpose", - prompt: "Claim implementation tasks, execute, mark complete", - run_in_background: true - }) - - Task({ - team_name: "work-{timestamp}", - name: "tester", - subagent_type: "general-purpose", - prompt: "Claim testing tasks, run tests, mark complete", - run_in_background: true - }) - ``` +gh pr create --title "<type>: <Description>" --body "$(cat <<'EOF' +## Summary +- What was built +- Why it was needed +- Key decisions made -4. **Coordinate and Monitor** - - Team lead monitors task completion - - Spawn additional workers as phases unblock - - Handle plan approval if required +## Testing +- Tests added/modified +- Manual testing performed -5. **Cleanup** - ``` - Teammate({ operation: "requestShutdown", target_agent_id: "implementer" }) - Teammate({ operation: "requestShutdown", target_agent_id: "tester" }) - Teammate({ operation: "cleanup" }) - ``` +## Post-Deploy Monitoring & Validation +- **What to monitor/search** + - Logs: + - Metrics/Dashboards: +- **Validation checks (queries/commands)** + - `command or query here` +- **Expected healthy behavior** + - Expected signal(s) +- **Failure signal(s) / rollback trigger** + - Trigger + immediate action +- **Validation window & owner** + - Window: + - Owner: +- **If no operational impact** + - `No additional operational monitoring required: <reason>` -See the `orchestrating-swarms` skill for detailed swarm patterns and best practices. +## Before / After Screenshots (UI changes only) +| Before | After | +|--------|-------| +| ![before](URL) | ![after](URL) | --- -## Key Principles - -### Start Fast, Execute Faster - -- Get clarification once at the start, then execute -- Don't wait for perfect understanding - ask questions and move -- The goal is to **finish the feature**, not create perfect process - -### The Plan is Your Guide - -- Work documents should reference similar code and patterns -- Load those references and follow them -- Don't reinvent - match what exists - -### Test As You Go - -- Run tests after each change, not at the end -- Fix failures immediately -- Continuous testing prevents big surprises - -### Quality is Built In - -- Follow existing patterns -- Write tests for new code -- Run linting before pushing -- Use reviewer agents for complex/risky changes only - -### Ship Complete Features - -- Mark all tasks completed before moving on -- Don't leave features 80% done -- A finished feature that ships beats a perfect feature that doesn't - -## Quality Checklist - -Before creating PR, verify (Phase 3 Quality Gate must pass first): - -- [ ] All clarifying questions asked and answered -- [ ] All TodoWrite tasks marked completed -- [ ] **Full test suite passes** (not just your tests — run project's test command) -- [ ] **Linting passes with zero warnings** (use linting-agent) -- [ ] **Pre-commit hooks pass on all changed files** -- [ ] Code follows existing patterns -- [ ] Figma designs match implementation (if applicable) -- [ ] Before/after screenshots captured and uploaded (for UI changes) -- [ ] Commit messages follow conventional format -- [ ] PR description includes Post-Deploy Monitoring & Validation section (or explicit no-impact rationale) -- [ ] PR description includes summary, testing notes, and screenshots -- [ ] PR description includes Compound Engineered badge - -## When to Use Reviewer Agents - -**Don't use by default.** Use reviewer agents only when: - -- Large refactor affecting many files (10+) -- Security-sensitive changes (authentication, permissions, data access) -- Performance-critical code paths -- Complex algorithms or business logic -- User explicitly requests thorough review - -For most features: tests + linting + following patterns is sufficient. +[![Compound Engineered](https://img.shields.io/badge/Compound-Engineered-6366f1)](https://github.com/weorbitant/compound-engineering-feat-python-plugin) 🤖 Generated with [Claude Code](https://claude.com/claude-code) +EOF +)" +``` -## Common Pitfalls to Avoid +4. **Update plan status** — if the input plan has YAML frontmatter with a `status` field, update it from `active` → `completed`. -- **Analysis paralysis** - Don't overthink, read the plan and execute -- **Skipping clarifying questions** - Ask now, not after building wrong thing -- **Ignoring plan references** - The plan has links for a reason -- **Testing at the end** - Test continuously or suffer later -- **Forgetting TodoWrite** - Track progress or lose track of what's done -- **80% done syndrome** - Finish the feature, don't move on early -- **Over-reviewing simple changes** - Save reviewer agents for complex work +5. **Notify user** — summarize what shipped, link to PR, note any follow-ups. diff --git a/docs/superpowers/plans/2026-05-25-superpowers-refactor-plan.md b/docs/superpowers/plans/2026-05-25-superpowers-refactor-plan.md new file mode 100644 index 0000000..29b42eb --- /dev/null +++ b/docs/superpowers/plans/2026-05-25-superpowers-refactor-plan.md @@ -0,0 +1,1677 @@ +# Superpowers Refactor Implementation Plan + +> **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. + +**Goal:** Refactor `compound-engineering-feat-python` to v3.0.0 by requiring the `superpowers` plugin as foundation, delegating generic workflow primitives to it, and keeping only Python/Django/FastAPI/microservice-specific value in this plugin. + +**Architecture:** Each of the 4 surviving workflow commands becomes a thin wrapper that loads Python context, runs a consolidated `microservice-focus` skill, and delegates execution to a `superpowers:*` skill. Three dropped commands (`/workflows:compound`, `/lfg`, `/slfg`) become one-paragraph deprecation shims. Six duplicate skills and one obsolete agent are removed. Artifact paths shift from `docs/brainstorms/` to `docs/superpowers/specs/` to match superpowers vocabulary. + +**Tech Stack:** Markdown skill/command authoring per Claude Code plugin spec, Bash for SessionStart dependency check, YAML for config/frontmatter. + +**Reference:** See `docs/superpowers/specs/2026-05-25-superpowers-refactor-design.md` for the full design rationale. + +--- + +## File Structure + +### New files (4) +- `skills/microservice-focus/SKILL.md` — Skill entry, brief, links to references +- `skills/microservice-focus/references/focus-gate.md` — Service discovery + prompting protocol +- `skills/microservice-focus/references/focus-context-block.md` — `<focus_context>` template & propagation rules +- `skills/microservice-focus/references/service-discovery.md` — `Glob("*/pyproject.toml")` mechanics, dependency cross-reference algorithm + +### Files rewritten as thin wrappers (4) +- `commands/workflows/brainstorm.md` +- `commands/workflows/plan.md` +- `commands/workflows/work.md` (preserves Python quality gate, Phase 4 PR template) +- `commands/workflows/review.md` (preserves agent roster + multi-service detection; drops `learnings-researcher` and `docs/solutions/`) + +### Files rewritten as deprecation shims (3) +- `commands/workflows/compound.md` +- `commands/lfg.md` +- `commands/slfg.md` + +### Files deleted (7) +- `skills/brainstorming/` (directory) +- `skills/git-worktree/` (directory) +- `skills/skill-creator/` (directory) +- `skills/create-agent-skills/` (directory) +- `skills/orchestrating-swarms/` (directory) +- `skills/compound-docs/` (directory) +- `agents/research/learnings-researcher.md` (file) + +### Files updated (mechanical or medium scope) +- `.claude-plugin/plugin.json` — bump to 3.0.0, update description +- `scripts/check-dependencies.sh` — add superpowers detection +- `skills/setup/SKILL.md` — drop `compound` from generated `workflow_skills` keys +- `skills/setup/references/*.md` — same as above if referenced +- `skills/document-review/SKILL.md` — remove any reference to the deleted `brainstorming` skill if present +- `commands/heal-skill.md` — remove references to deleted skills +- `commands/resolve_todo_parallel.md` — remove references to deleted skills +- `commands/deepen-plan.md` — remove references to deleted skills/`docs/solutions/` +- `agents/research/best-practices-researcher.md` — remove reference to `learnings-researcher` / `docs/solutions/` +- `agents/research/git-history-analyzer.md` — same +- `agents/review/code-simplicity-reviewer.md` — same +- `CLAUDE.md` — remove stale `docs/solutions/plugin-versioning-requirements.md` reference, update output-paths table, drop `compound` from example YAML +- `CHANGELOG.md` — prepend v3.0.0 entry +- `README.md` — major rewrite per spec section 5 + +--- + +## Task 1: Create the `microservice-focus` skill + +**Files:** +- Create: `skills/microservice-focus/SKILL.md` +- Create: `skills/microservice-focus/references/focus-gate.md` +- Create: `skills/microservice-focus/references/focus-context-block.md` +- Create: `skills/microservice-focus/references/service-discovery.md` + +- [ ] **Step 1: Create the directory structure** + +```bash +mkdir -p skills/microservice-focus/references +``` + +- [ ] **Step 2: Write `skills/microservice-focus/SKILL.md`** + +````markdown +--- +name: microservice-focus +description: Use when a workflow command needs to detect multi-service monorepos, prompt for service scope, and propagate `<focus_context>` to sub-agents. Triggers when `--services` is passed, when focus context already exists in the conversation, or when multiple `pyproject.toml` files exist at the repo root. +--- + +# Microservice Focus + +Consolidates the service-discovery and focus-context-propagation logic used by every Python workflow command in this plugin. Invoked once per command; returns the focused service list plus a `<focus_context>` block ready to inject into sub-agent prompts. + +## When to invoke this skill + +A workflow command should invoke this skill exactly once, near the top of its execution, before delegating to a `superpowers:*` skill. + +## Inputs + +The skill expects to find one of the following, in priority order: + +1. A `--services service-a,service-b` argument parsed from the command's `$ARGUMENTS`. +2. An existing `<focus_context>` block in the conversation (set by a prior invocation). +3. Multiple `pyproject.toml` files at the repo root (multi-service repo). +4. None of the above → return single-service mode. + +## What the skill does + +1. **Parse `--services` if present.** Skip the interactive prompt and use those services as the focused set. +2. **Discover services on disk** when no explicit list was given. See [service-discovery.md](./references/service-discovery.md) for the exact glob and parsing rules. +3. **If multi-service and no explicit list:** use `AskUserQuestion` to prompt the user with the discovered services as multi-select options. See [focus-gate.md](./references/focus-gate.md) for the prompt format. +4. **Load each focused service's context:** `prompt.md` (preferred) or `README.md` (first 50 lines), `pyproject.toml`, and `src/` structure. Cross-reference internal dependencies to build the dependency map. +5. **Build the `<focus_context>` block.** See [focus-context-block.md](./references/focus-context-block.md) for the canonical template. +6. **Return** the service list + the `<focus_context>` block to the caller. The caller is responsible for injecting it into the prompts of any sub-agents or sub-skills it invokes. + +## Output contract + +The skill returns two pieces of information to the caller: + +- `services`: a list like `["service-a", "service-b"]`, or an empty list in single-service mode. +- `focus_context`: a `<focus_context>...</focus_context>` block ready to splice into sub-agent prompts. Empty string in single-service mode. + +## Single-service mode + +If only one (or zero) `pyproject.toml` is found and no `--services` argument was passed, the skill returns immediately with an empty service list and an empty focus context. The caller proceeds without per-service path overrides. + +## References + +- [focus-gate.md](./references/focus-gate.md) — Discovery + interactive prompting protocol +- [focus-context-block.md](./references/focus-context-block.md) — `<focus_context>` template & propagation rules +- [service-discovery.md](./references/service-discovery.md) — Glob mechanics, dependency cross-reference algorithm +```` + +- [ ] **Step 3: Write `skills/microservice-focus/references/focus-gate.md`** + +````markdown +# Focus Gate Protocol + +This file documents the interactive prompting protocol when multiple services exist but the user has not specified `--services`. + +## Step 1: Discovery + +Run `Glob("*/pyproject.toml")` from the repo root. Each match represents a candidate service. Strip the trailing `/pyproject.toml` to get the service name (e.g., `service-a/pyproject.toml` → `service-a`). + +If the glob returns 0 or 1 results, the repo is single-service. Return without prompting. + +## Step 2: Prompt + +If 2 or more services are discovered, use `AskUserQuestion` with `multiSelect: true`. Phrase the question to match the command context: + +- `/workflows:brainstorm` → "Which services are relevant to this brainstorm?" +- `/workflows:plan` → "Which services are involved in this plan?" +- `/workflows:work` → "Which services does this work touch?" +- `/workflows:review` → "Which services should be reviewed?" + +List discovered services as options. Each option's `label` is the service name; the `description` is a one-line summary read from `{service}/.claude/prompt.md` (first line) or `{service}/README.md` (first heading), or "Python service" as a fallback. + +## Step 3: Validate the user's selection + +If the user selects nothing or hits cancel, halt with: "No services selected. Re-invoke the command with `--services <list>` or pick services when prompted." + +If the user selects a subset, treat those as the focused services and proceed. + +## Step 4: Load per-service context + +For each focused service, in parallel where possible: + +1. Read `{service}/.claude/prompt.md` (preferred) — first 30 lines. +2. If not present, read `{service}/README.md` — first 50 lines. +3. Read `{service}/pyproject.toml` — extract `name`, Python version requirement, and the `dependencies`/`tool.poetry.dependencies` list. +4. Run `Glob("{service}/src/*/")` to enumerate top-level packages (apps, modules). + +Cache these loads — the same focused service may be referenced multiple times in the focus-context block. + +## Pipeline mode + +If the command was invoked from an automated workflow (e.g., orchestrating script passes a flag, or a `disable-model-invocation` context is detected), **skip the interactive prompt entirely**. Default behavior in pipeline mode without `--services`: treat the repo as single-service. +```` + +- [ ] **Step 4: Write `skills/microservice-focus/references/focus-context-block.md`** + +````markdown +# `<focus_context>` Block — Template and Propagation Rules + +## Canonical template + +``` +<focus_context> + services: <name-1> (./<name-1>), <name-2> (./<name-2>) + + <name-1>: + description: [from prompt.md/README — what this service does] + stack: [e.g., Django 5.0, Celery, PostgreSQL — derived from pyproject.toml] + structure: [e.g., src/orders/, src/pricing/, src/shared/] + + <name-2>: + description: [from prompt.md/README — what this service does] + stack: [e.g., FastAPI, SQLAlchemy 2.0, Redis] + structure: [e.g., src/payments/, src/webhooks/] + + dependencies: + - <name-2> depends on <name-1> (event schema) + - both depend on lib-common (shared DTOs) +</focus_context> +``` + +## Construction rules + +1. **`services:` line** lists all focused services with their paths in the format `<name> (./<name>)`. +2. **Per-service block** for each focused service includes `description`, `stack`, and `structure`. Pull these from the per-service context loaded in [focus-gate.md](./focus-gate.md). +3. **`dependencies:` section** lists internal dependencies cross-referenced from `pyproject.toml` files. Format each as a single line stating "X depends on Y (reason)". See [service-discovery.md](./service-discovery.md) for cross-reference logic. +4. **Omit any section** for which there is no data. An empty repo description, empty stack, or no detected dependencies = omit the line. + +## Propagation rules + +The caller (a workflow command) **must inject the full `<focus_context>` block into the prompt of every sub-agent or sub-skill it invokes**. This includes: + +- `superpowers:brainstorming` (via the wrapper's delegate step) +- `superpowers:writing-plans` +- `superpowers:executing-plans` +- `superpowers:requesting-code-review` +- Any Python review agent spawned by `/workflows:review` +- Any sub-task spawned by `Agent` or `Task` calls inside the command body + +The block is inserted near the top of the sub-agent prompt, before any task description, so the sub-agent reads the constraint up front. + +## Stack-aware behavior expectation + +Sub-agents that read this block should: + +- Apply Django patterns only in services whose stack lists Django. +- Apply FastAPI patterns only in services whose stack lists FastAPI. +- Respect each service's test/lint command (often visible in its `pyproject.toml` scripts or `CLAUDE.md`). +- Use the dependency map to choose execution order in multi-step operations. + +The wrapper command is not responsible for enforcing these — sub-agents act on the block. +```` + +- [ ] **Step 5: Write `skills/microservice-focus/references/service-discovery.md`** + +````markdown +# Service Discovery & Dependency Cross-Reference + +## Discovering services + +Single-line discovery: + +``` +Glob("*/pyproject.toml") +``` + +Each match represents one candidate service. Strip the suffix: + +``` +service-a/pyproject.toml → service-a +service-b/pyproject.toml → service-b +lib-common/pyproject.toml → lib-common +``` + +If the glob returns 0 results: not a Python repo — return single-service mode. +If 1 result: single-service repo — return single-service mode. +If 2+ results: multi-service repo — proceed with focus gate. + +## Reading service metadata + +For each discovered service: + +1. **Name and stack** — parse `{service}/pyproject.toml`. Extract: + - Package name (from `[tool.poetry].name` or `[project].name`) + - Python requirement (from `python` field) + - Dependency list (from `[tool.poetry.dependencies]` or `[project].dependencies`) + + The stack summary in `<focus_context>` is derived from notable dependencies: `django`, `fastapi`, `celery`, `sqlalchemy`, `psycopg2`/`psycopg`, `redis`, `pydantic`, etc. Pick the 2-4 most architecturally significant ones. + +2. **Description** — first usable text from `{service}/.claude/prompt.md` (first paragraph, max 200 chars) or `{service}/README.md` (first non-empty paragraph after the title, max 200 chars). + +3. **Structure** — enumerate `{service}/src/*/` top-level dirs and list as comma-separated. Limit to ~5 entries; if more exist, suffix with `, ...`. + +## Cross-referencing internal dependencies + +To detect that service-b depends on service-a: + +1. Build a list of all package names from the focused services (read from each `pyproject.toml`'s `name` field). +2. For each focused service, scan its `dependencies` list for entries that match another focused service's package name. +3. Record the dependency: "service-b depends on service-a". +4. Optionally infer the reason by reading the depending service's import statements or recent commits — leave blank if unknown. + +## Detecting `lib-*` shared libraries + +Any service whose name starts with `lib-` is treated as a library candidate. If multiple focused services depend on `lib-common` (or similar), surface that as a "both depend on lib-common" line in `dependencies:`. + +## Edge cases + +- **Service has no `src/`** — list the top-level Python packages instead, or omit `structure:`. +- **Service has no `pyproject.toml`** — skip; it should not have been discovered in the first place. +- **Circular dependency between focused services** — record both directions, do NOT halt; let the consumer skill decide how to handle it. +- **Service named identically to a top-level project module** — disambiguate by path, not by name. +```` + +- [ ] **Step 6: Verify the skill structure** + +```bash +ls -la skills/microservice-focus/ +ls -la skills/microservice-focus/references/ +``` + +Expected output: directory exists, `SKILL.md` present, `references/` contains 3 `.md` files. + +- [ ] **Step 7: Verify YAML frontmatter parses** + +```bash +head -5 skills/microservice-focus/SKILL.md +``` + +Expected output: 5 lines starting with `---`, with `name:` and `description:` keys, ending with the second `---`. + +- [ ] **Step 8: Commit** + +```bash +git add skills/microservice-focus/ +git commit -m "feat(skill): add microservice-focus skill + +Consolidates service discovery, --services parsing, multi-service +prompting, and <focus_context> block construction into a single +skill. Workflow commands invoke this once instead of duplicating +~50 lines of focus gate logic each." +``` + +--- + +## Task 2: Rewrite `/workflows:brainstorm` as a thin wrapper + +**Files:** +- Modify: `commands/workflows/brainstorm.md` (currently 189 lines → ~45 lines) + +- [ ] **Step 1: Replace the entire file content** + +Use the Write tool to overwrite `commands/workflows/brainstorm.md` with the following: + +````markdown +--- +name: workflows:brainstorm +description: Explore requirements and approaches before planning, with Python/microservice context loaded for downstream sub-agents +argument-hint: "[feature idea or problem to explore] [--services svc-a,svc-b]" +--- + +# Brainstorm (Python) + +This command is a thin wrapper that loads Python-specific context, runs the microservice focus gate, then delegates the brainstorming process to the `superpowers:brainstorming` skill. + +## Feature Description + +<feature_description> #$ARGUMENTS </feature_description> + +If the feature description above is empty, ask the user: "What would you like to explore? Please describe the feature, problem, or improvement you're thinking about." Do not proceed without one. + +## Prerequisites + +If the `superpowers:brainstorming` skill is not available, halt and instruct the user: + +> "This command requires the `superpowers` plugin. Install it with: +> `/plugin marketplace add anthropics/claude-plugins-official` +> `/plugin install superpowers@claude-plugins-official`" + +## Step 1: Load Project Workflow Skills + +Read `compound-engineering.local.md` in the project root. If found, parse the YAML frontmatter for `workflow_skills.brainstorm`. If the key contains a non-empty list of skill names, load each listed skill now. These provide project-specific Python/Django/domain context. + +If no config exists or no `workflow_skills` key is present, proceed without additional skills. + +## Step 2: Microservice Focus + +Invoke the `microservice-focus` skill. It will: + +- Parse `--services` from `$ARGUMENTS` if present. +- Otherwise discover services via `Glob("*/pyproject.toml")` and prompt the user via `AskUserQuestion` if multiple services exist. +- Return the list of focused services + a `<focus_context>` block. + +In single-service mode, the skill returns an empty service list and empty focus context. Skip Step 4. + +## Step 3: Delegate to superpowers + +Invoke the `superpowers:brainstorming` skill. Pass: + +- The user's feature description from `<feature_description>` as the topic. +- The `<focus_context>` block returned from Step 2 (so the superpowers skill includes it in any sub-agent prompts it spawns). +- A note that any Python `workflow_skills` listed above are already loaded in the conversation as additional context. + +The superpowers skill drives the rest of the conversation: clarifying questions, approach exploration, design presentation, spec writing. + +## Step 4: Multi-service spec path override + +`superpowers:brainstorming` writes its spec to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` by default. + +If Step 2 returned a non-empty service list, write **one spec per focused service** at: + +``` +{service}/docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md +``` + +Each per-service spec focuses on that service's role and decisions. Add a `## Services` section to each listing all focused services and their roles, so `/workflows:plan` can auto-detect scope on the next step. + +Create the `{service}/docs/superpowers/specs/` directories with `mkdir -p` as needed before writing. + +## Output + +After the superpowers skill returns, summarize: + +- Spec path(s) written. +- The focused services (if multi-service mode). +- Suggested next step: `/workflows:plan <spec-path>`. +```` + +- [ ] **Step 2: Verify the file was written** + +```bash +wc -l commands/workflows/brainstorm.md +head -5 commands/workflows/brainstorm.md +``` + +Expected: ~45 lines (was 189). Frontmatter intact with `name: workflows:brainstorm`. + +- [ ] **Step 3: Commit (deferred — bundle with other wrapper rewrites in Task 5's commit step)** + +Do not commit yet. The 4 wrapper rewrites commit together to keep the diff coherent. + +--- + +## Task 3: Rewrite `/workflows:plan` as a thin wrapper + +**Files:** +- Modify: `commands/workflows/plan.md` (currently 681 lines → ~55 lines) + +- [ ] **Step 1: Replace the entire file content** + +````markdown +--- +name: workflows:plan +description: Transform a spec into a Python-flavored implementation plan, delegating plan-writing to superpowers +argument-hint: "[spec path, feature description, or bug report] [--services svc-a,svc-b]" +--- + +# Plan (Python) + +This command is a thin wrapper that loads Python-specific context, runs the microservice focus gate, then delegates plan writing to the `superpowers:writing-plans` skill. + +## Input + +<input> #$ARGUMENTS </input> + +If the input is empty, ask the user: "What would you like to plan? Provide a spec path (typically under `docs/superpowers/specs/`) or a feature description." Do not proceed without one. + +## Prerequisites + +If the `superpowers:writing-plans` skill is not available, halt and instruct the user to install `superpowers` (same message format as `/workflows:brainstorm`). + +## Step 1: Load Project Workflow Skills + +Read `compound-engineering.local.md` in the project root. If `workflow_skills.plan` is set, load each listed skill now. They inform the plan with Python/Django/domain-specific patterns. + +## Step 2: Microservice Focus + +Invoke the `microservice-focus` skill. It returns focused services + `<focus_context>`. + +If the input was a spec path, **also** check the spec for a `## Services` section. If present, merge those services into the focused list (the spec may have established scope during brainstorm). + +## Step 3: Delegate to superpowers + +Invoke the `superpowers:writing-plans` skill. Pass: + +- The input (spec path or feature description) as the planning topic. +- The `<focus_context>` block from Step 2. +- A note that loaded Python `workflow_skills` are available in conversation. + +The superpowers skill drives plan writing: file structure, task decomposition, bite-sized steps, self-review. + +## Step 4: Multi-service plan output + +`superpowers:writing-plans` writes a single plan to `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md` by default. + +If Step 2 returned a non-empty service list, **also** add the following to the plan's YAML frontmatter so `/workflows:work` can execute in dependency order: + +```yaml +services: + service-a: + depends_on: [] + service-b: + depends_on: + - service: service-a + reason: "<inferred from focus context or asked>" +``` + +Determine dependencies from the `<focus_context>` block's `dependencies:` section. Ask the user to confirm or adjust the graph before writing the final plan. + +**For cross-service plans, write multiple files:** + +1. **Root overview:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md` — dependency graph, execution order, links to per-service plans, cross-cutting concerns. +2. **Per-service plans:** `{service}/docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md` — service-specific tasks, acceptance criteria, file changes. + +Use the same base filename across all locations for traceability. Create directories with `mkdir -p` as needed. + +**For single-service work in a multi-service repo:** write only to `{service}/docs/superpowers/plans/...` (no root overview needed). + +## Output + +Confirm: "Plan written to `<path>`" (and per-service locations if applicable). Suggest next step: `/workflows:work <plan-path>`. +```` + +- [ ] **Step 2: Verify** + +```bash +wc -l commands/workflows/plan.md +head -5 commands/workflows/plan.md +``` + +Expected: ~55 lines (was 681). Frontmatter intact. + +- [ ] **Step 3: Do not commit yet** — bundled commit at Task 5. + +--- + +## Task 4: Rewrite `/workflows:work` as a wrapper + Python quality gate + +**Files:** +- Modify: `commands/workflows/work.md` (currently 585 lines → ~140 lines; longest wrapper because the Python quality gate is the unique value) + +- [ ] **Step 1: Replace the entire file content** + +````markdown +--- +name: workflows:work +description: Execute a plan via superpowers, gated by a Python-specific quality bar (pytest + ruff + mypy + pre-commit), with multi-service execution ordering preserved +argument-hint: "[plan file path]" +--- + +# Work (Python) + +This command is a wrapper around `superpowers:executing-plans`. It loads Python-specific context, runs the microservice focus gate, optionally honors per-service execution ordering, delegates plan execution, then enforces a Python quality gate before any PR is created. + +## Input Document + +<input_document> #$ARGUMENTS </input_document> + +If empty, ask the user for a plan path (typically under `docs/superpowers/plans/` or `{service}/docs/superpowers/plans/`). Do not proceed without one. + +## Prerequisites + +If the `superpowers:executing-plans` skill is not available, halt and instruct the user to install `superpowers` (same message format as `/workflows:brainstorm`). + +## Step 1: Load Project Workflow Skills + +Read `compound-engineering.local.md`. If `workflow_skills.work` is set, load each listed skill now (e.g., `django-patterns`, `pytest-patterns`). + +## Step 2: Microservice Focus + Execution Order + +Invoke the `microservice-focus` skill. It returns the focused services + `<focus_context>`. + +**If the plan's YAML frontmatter contains a `services:` section:** + +1. Treat those as the focused services (override the prompt result). +2. Parse the dependency graph from the frontmatter. +3. Build a topological execution order (wavefront pattern): + - Wave 1: services with `depends_on: []` + - Wave 2: services depending only on Wave 1 + - etc. +4. Detect cycles: if found, report to user and treat services in the cycle as independent. +5. Show the execution plan and get user confirmation (skip in pipeline mode): + +``` +Execution plan: + Wave 1 (no deps): + service-a — Order management (Django 5.0, Celery) + lib-common — Shared DTOs and schemas + Wave 2 (after wave 1): + service-b — Payment processing (FastAPI, SQLAlchemy) — depends on service-a + +Default: sequential execution in topological order. +Options: [Confirm] [Force sequential] [Adjust order] +``` + +For parallel execution within a wave, use `superpowers:dispatching-parallel-agents` (do NOT invoke the deleted `orchestrating-swarms` skill). + +## Step 3: Delegate plan execution to superpowers + +Invoke the `superpowers:executing-plans` skill (or `superpowers:subagent-driven-development` if the plan header recommends it). Pass: + +- The plan path from `<input_document>`. +- The `<focus_context>` block. +- The execution order from Step 2 (so the skill processes tasks in the right wave order in multi-service mode). +- The test command to use per service: + - Single-service: `poetry run pytest` (or whatever the project's CLAUDE.md specifies) + - Multi-service: `cd {service} && poetry run pytest` for each service + +The superpowers skill handles the task loop, per-task commits, and incremental progress. + +## Step 4: Python Quality Gate (MANDATORY — blocks Step 5) + +Step 5 cannot start until all checks in this step pass. This is not advisory. + +1. **Full Test-and-Fix Cycle** — loop until clean: + + ``` + LOOP: + a. Run full test suite. Single-service: `poetry run pytest`. Multi-service: run each focused + service's test command in sequence (or in parallel if the user opted in). + → If tests fail: read failures, fix the code, re-run from (a). Do NOT proceed. + b. Run linting via the python-lint agent (ruff + mypy). + → If linting fails: fix issues, re-run from (a) — lint fixes can break tests. + c. Run pre-commit hooks on all staged files (`pre-commit run --all-files` or + `git stash && git stash pop` to trigger the install). + → If hooks fail: fix issues, re-run from (a). + ``` + + Do not skip this cycle. Every fix can introduce new failures — always re-run from the top. + +2. **Optional Reviewer Agents** — for risky or large changes, read `review_agents` from `compound-engineering.local.md`. If present, spawn each in parallel via `Task`. Present findings; address critical ones before proceeding. + +3. **Final Validation Checklist** — all must be true: + - [ ] All plan tasks marked completed (checkboxes in plan file) + - [ ] Full test suite passes (not just the tests added) + - [ ] Linting passes with zero warnings + - [ ] Pre-commit hooks pass on all changed files + - [ ] Code follows existing patterns + - [ ] No console errors or warnings + + If any check fails: fix and re-run the full cycle. Do not proceed to Step 5. + +4. **Operational Validation Plan** — REQUIRED before PR: + + Add a `## Post-Deploy Monitoring & Validation` section to the PR description for every change. Include: + - Log queries/search terms + - Metrics or dashboards to watch + - Expected healthy signals + - Failure signals + rollback/mitigation trigger + - Validation window + owner + + If truly no production/runtime impact: include the section with `No additional operational monitoring required: <reason>`. + +## Step 5: Ship It + +Prerequisite: Step 4 quality gate passed. If not, return to Step 4. + +1. **Create commit via the `commit` skill** (kept; not deleted in this refactor). It analyzes, groups, and commits all changes with conventional + gitmoji format. Never skip pre-commit hooks with `--no-verify`. + +2. **Capture screenshots for UI changes** — for any design changes, new views, or UI modifications: + - Start dev server (Django: `python manage.py runserver`; FastAPI: `uvicorn main:app --reload`). + - Use the `agent-browser` skill (kept) to capture before/after screenshots. + - Upload via the `agent-browser` skill's upload mechanism and include URLs in the PR description. + +3. **Create Pull Request:** + +```bash +git push -u origin <feature-branch-name> + +gh pr create --title "<type>: <Description>" --body "$(cat <<'EOF' +## Summary +- What was built +- Why it was needed +- Key decisions made + +## Testing +- Tests added/modified +- Manual testing performed + +## Post-Deploy Monitoring & Validation +- **What to monitor/search** + - Logs: + - Metrics/Dashboards: +- **Validation checks (queries/commands)** + - `command or query here` +- **Expected healthy behavior** + - Expected signal(s) +- **Failure signal(s) / rollback trigger** + - Trigger + immediate action +- **Validation window & owner** + - Window: + - Owner: +- **If no operational impact** + - `No additional operational monitoring required: <reason>` + +## Before / After Screenshots (UI changes only) +| Before | After | +|--------|-------| +| ![before](URL) | ![after](URL) | + +--- + +[![Compound Engineered](https://img.shields.io/badge/Compound-Engineered-6366f1)](https://github.com/weorbitant/compound-engineering-feat-python-plugin) 🤖 Generated with [Claude Code](https://claude.com/claude-code) +EOF +)" +``` + +4. **Update plan status** — if the input plan has YAML frontmatter with a `status` field, update it from `active` → `completed`. + +5. **Notify user** — summarize what shipped, link to PR, note any follow-ups. +```` + +- [ ] **Step 2: Verify** + +```bash +wc -l commands/workflows/work.md +head -5 commands/workflows/work.md +grep -c "poetry run pytest" commands/workflows/work.md +grep -c "Post-Deploy Monitoring" commands/workflows/work.md +``` + +Expected: ~140 lines, frontmatter intact, "poetry run pytest" appears (Python test cmd preserved), "Post-Deploy Monitoring" appears (PR template preserved). + +- [ ] **Step 3: Do not commit yet** — bundled commit at Task 5. + +--- + +## Task 5: Rewrite `/workflows:review` as a thin wrapper + +**Files:** +- Modify: `commands/workflows/review.md` (currently 514 lines → ~95 lines; preserves agent roster + multi-service detection; drops `learnings-researcher` + `docs/solutions/` references) + +- [ ] **Step 1: Replace the entire file content** + +````markdown +--- +name: workflows:review +description: Multi-agent Python code review, delegating review orchestration to superpowers and supplying Python-specific reviewer agents from project config +argument-hint: "[PR number, GitHub URL, branch name, or empty for current branch]" +--- + +# Review (Python) + +This command is a thin wrapper around `superpowers:requesting-code-review`. It loads the Python reviewer agent roster from `compound-engineering.local.md`, supplies them to the superpowers orchestration, and adds Python-specific conditional agents for migrations. + +## Review Target + +<review_target> #$ARGUMENTS </review_target> + +If empty, default to the current branch's diff against the project default branch. + +## Prerequisites + +If the `superpowers:requesting-code-review` skill is not available, halt and instruct the user to install `superpowers` (same message format as `/workflows:brainstorm`). + +## Step 1: Determine target & checkout + +1. Determine the review target type: + - Numeric → PR number; use `gh pr view --json` to fetch metadata. + - GitHub URL → extract PR number, then as above. + - File path ending in `.md` → document review; pass through to superpowers as a doc target. + - Empty → current branch. +2. If the target is a PR and the current branch differs, switch via `gh pr checkout <num>` or use the `superpowers:using-git-worktrees` skill for an isolated worktree. + +## Step 2: Microservice Detection + +Auto-detect changed services from the diff: + +```bash +git diff --name-only origin/<default-branch>...HEAD | cut -d'/' -f1 | sort -u +``` + +Cross-reference the top-level directories against discovered services (`Glob("*/pyproject.toml")`). The intersection is the list of changed services. + +If multiple services are changed, invoke the `microservice-focus` skill to build a `<focus_context>` block scoped to those services. Per-service agent roster loading happens in Step 3. + +## Step 3: Load Reviewer Roster + +**Single-service or non-microservice mode:** +Read `compound-engineering.local.md` in the project root. Use `review_agents` from the YAML frontmatter. + +**Multi-service mode:** +For each changed service, check `{service}/compound-engineering.local.md` first (allows per-service agent rosters — e.g., Django agents for one, FastAPI for another). Fall back to root-level `compound-engineering.local.md`. + +If no settings file exists, invoke the `setup` skill (kept) to create one. Read the new file and continue. + +## Step 4: Load Project Workflow Skills + +From the same `compound-engineering.local.md`, parse `workflow_skills.review`. Load each listed skill now. They provide Python-specific context that helps interpret review findings. + +## Step 5: Identify Conditional Agents + +Some agents only run when the PR matches specific criteria: + +**Migration agents** — run if the PR contains any of: +- `*/migrations/*.py` (Django migrations) +- `alembic/versions/*.py` (Alembic migrations) +- Files modifying ID/enum/mapping columns +- Data migration scripts or management commands +- Title/body mentioning: migration, backfill, data transformation, ID mapping + +If matched, add to the agent roster: +- `data-migration-expert` — validates data migrations, swapped IDs, rollback safety +- `deployment-verification-agent` — Go/No-Go checklist with SQL verification queries + +## Step 6: Protected Artifacts + +When synthesizing findings, **discard any recommendations to delete or gitignore** files matching: + +- `docs/plans/*.md`, `docs/superpowers/plans/*.md` +- `docs/superpowers/specs/*.md` +- `{service}/docs/plans/*.md`, `{service}/docs/superpowers/plans/*.md` +- `{service}/docs/superpowers/specs/*.md` + +These are living pipeline artifacts. Do not create todos for their removal. + +## Step 7: Delegate to superpowers + +Invoke the `superpowers:requesting-code-review` skill. Pass: + +- The review target (PR number, branch, or doc path). +- The full agent roster from Step 3 (so superpowers spawns each in parallel). +- The conditional migration agents from Step 5 (if applicable). +- The `<focus_context>` block from Step 2 (multi-service mode). +- The "protected artifacts" rule from Step 6 (so superpowers filters discardable findings). +- Always-on agents to include alongside the roster: + - `agent-native-reviewer` — verifies new features are agent-accessible + +Note: this command does **NOT** spawn `learnings-researcher` (deleted in v3.0.0) and does NOT read `docs/solutions/` (knowledge-compounding pattern dropped). + +## Step 8: Synthesis & Todos + +The superpowers skill handles parallel agent execution and findings collection. After it returns, use the `file-todos` skill (kept) to create one todo file per finding under `todos/`, using the standard naming `{issue_id}-pending-{priority}-{description}.md`. + +If the user prefers an inline summary instead of todo files, surface findings in a categorized list (P1/P2/P3) without writing files. + +## Step 9: Browser Test Offer (Optional) + +After synthesis, offer browser testing via `AskUserQuestion`: + +> "Want to run browser tests on the affected pages?" +> 1. Yes — run `/test-browser` +> 2. No — skip + +If the user accepts, spawn a sub-agent to run `/test-browser` for the PR. The sub-agent uses the `agent-browser` skill (kept) to capture snapshots and check for console errors. + +## Output + +Summarize: +- PR/branch reviewed. +- Number of P1/P2/P3 findings. +- Path to todos/ (if file-todos was used). +- Next-step recommendation (e.g., "Address P1 findings before merging"). +```` + +- [ ] **Step 2: Verify** + +```bash +wc -l commands/workflows/review.md +head -5 commands/workflows/review.md +! grep -q "learnings-researcher" commands/workflows/review.md +! grep -q "docs/solutions" commands/workflows/review.md +``` + +Expected: ~95 lines, frontmatter intact, no references to `learnings-researcher` or `docs/solutions` remain. + +- [ ] **Step 3: Commit all 4 wrapper rewrites together** + +```bash +git add commands/workflows/brainstorm.md commands/workflows/plan.md commands/workflows/work.md commands/workflows/review.md +git commit -m "refactor(workflows): rewrite 4 wrappers to delegate to superpowers + +- brainstorm → superpowers:brainstorming (loads Python skills + focus context) +- plan → superpowers:writing-plans (adds services: YAML for execution order) +- work → superpowers:executing-plans (keeps Python quality gate + PR template) +- review → superpowers:requesting-code-review (supplies Python agent roster, + drops learnings-researcher and docs/solutions/ references) + +Wrappers shrink from ~190-680 lines to ~45-140 lines each. All shared +microservice focus logic moves to the microservice-focus skill." +``` + +--- + +## Task 6: Convert `/workflows:compound`, `/lfg`, `/slfg` to deprecation shims + +**Files:** +- Modify: `commands/workflows/compound.md` +- Modify: `commands/lfg.md` +- Modify: `commands/slfg.md` + +- [ ] **Step 1: Replace `commands/workflows/compound.md`** + +````markdown +--- +name: workflows:compound +description: "(DEPRECATED v3.0.0 — removed in v4.0.0) Document a recently solved problem" +argument-hint: "[optional: brief context about the fix]" +--- + +# `/workflows:compound` — Removed in v3.0.0 + +This command was removed in v3.0.0 along with the knowledge-compounding (`docs/solutions/`) pattern. There is no direct replacement: `superpowers` does not have an analog for post-solve documentation capture. + +If you want to capture a learning from a recent fix: + +- Write a Markdown note in your project under whatever path your team uses for engineering notes. +- Or contribute the lesson back to a project-local skill via the `superpowers:writing-skills` skill. + +See `CHANGELOG.md` v3.0.0 for the full rationale. + +This shim will be removed entirely in v4.0.0. +```` + +- [ ] **Step 2: Replace `commands/lfg.md`** + +````markdown +--- +name: lfg +description: "(DEPRECATED v3.0.0 — removed in v4.0.0) Full autonomous pipeline" +argument-hint: "[feature description]" +--- + +# `/lfg` — Removed in v3.0.0 + +The `/lfg` autonomous pipeline was removed in v3.0.0. Users now orchestrate the stages directly, which keeps each step interruptible and reviewable. + +Run the stages in sequence: + +1. `/workflows:brainstorm "<your idea>"` — explore and write a spec. +2. `/workflows:plan <spec-path>` — turn the spec into an implementation plan. +3. `/workflows:work <plan-path>` — execute the plan with the Python quality gate. +4. `/workflows:review` — multi-agent review of the resulting PR. + +Each stage now delegates to a `superpowers:*` skill underneath. See `CHANGELOG.md` v3.0.0 for the full rationale. + +This shim will be removed entirely in v4.0.0. +```` + +- [ ] **Step 3: Replace `commands/slfg.md`** + +````markdown +--- +name: slfg +description: "(DEPRECATED v3.0.0 — removed in v4.0.0) Swarm-mode autonomous pipeline" +argument-hint: "[feature description]" +--- + +# `/slfg` — Removed in v3.0.0 + +The `/slfg` swarm pipeline was removed in v3.0.0 along with the `orchestrating-swarms` skill it depended on. + +For parallel agent work, use the `superpowers:dispatching-parallel-agents` skill directly within any stage (most useful inside `/workflows:work` for independent tasks). + +For the rest of the pipeline, see `/lfg`'s migration message: + +1. `/workflows:brainstorm "<idea>"` +2. `/workflows:plan <spec>` +3. `/workflows:work <plan>` — invoke `superpowers:dispatching-parallel-agents` inside this for parallelism. +4. `/workflows:review` + +See `CHANGELOG.md` v3.0.0 for the full rationale. + +This shim will be removed entirely in v4.0.0. +```` + +- [ ] **Step 4: Verify all three shims are short** + +```bash +wc -l commands/workflows/compound.md commands/lfg.md commands/slfg.md +``` + +Expected: each ~15-20 lines. + +- [ ] **Step 5: Commit** + +```bash +git add commands/workflows/compound.md commands/lfg.md commands/slfg.md +git commit -m "chore(deprecate): convert /workflows:compound, /lfg, /slfg to shims + +These 3 commands were removed in v3.0.0. Shims print a migration +message when invoked and will be removed entirely in v4.0.0." +``` + +--- + +## Task 7: Delete 6 obsolete skills + 1 obsolete agent + +**Files:** +- Delete: `skills/brainstorming/` +- Delete: `skills/git-worktree/` +- Delete: `skills/skill-creator/` +- Delete: `skills/create-agent-skills/` +- Delete: `skills/orchestrating-swarms/` +- Delete: `skills/compound-docs/` +- Delete: `agents/research/learnings-researcher.md` + +- [ ] **Step 1: Verify each skill exists before deletion** + +```bash +ls skills/brainstorming/ skills/git-worktree/ skills/skill-creator/ \ + skills/create-agent-skills/ skills/orchestrating-swarms/ skills/compound-docs/ +ls agents/research/learnings-researcher.md +``` + +All paths should exist. If any are already missing, note it and skip that deletion. + +- [ ] **Step 2: Delete the 6 skill directories** + +```bash +git rm -r skills/brainstorming/ skills/git-worktree/ skills/skill-creator/ \ + skills/create-agent-skills/ skills/orchestrating-swarms/ skills/compound-docs/ +``` + +- [ ] **Step 3: Delete the obsolete agent file** + +```bash +git rm agents/research/learnings-researcher.md +``` + +- [ ] **Step 4: Verify deletions are staged** + +```bash +git status --short | grep -E "^D" | wc -l +``` + +Expected: count corresponds to all the deleted files (multiple files per skill directory + 1 agent). + +- [ ] **Step 5: Commit** + +```bash +git commit -m "refactor: delete 6 duplicate skills + learnings-researcher agent + +Deleted skills (replaced by superpowers equivalents): +- brainstorming → superpowers:brainstorming +- git-worktree → superpowers:using-git-worktrees +- skill-creator → superpowers:writing-skills +- create-agent-skills → superpowers:writing-skills +- orchestrating-swarms → superpowers:dispatching-parallel-agents +- compound-docs → none (consumer /workflows:compound also dropped) + +Deleted agent: +- learnings-researcher → none (docs/solutions/ knowledge pattern dropped)" +``` + +--- + +## Task 8: Update `/setup` to drop `compound` from generated config + +**Files:** +- Modify: `skills/setup/SKILL.md` +- Modify: any file under `skills/setup/references/` that mentions `compound` key in YAML examples + +- [ ] **Step 1: Find references to `compound` in the setup skill** + +```bash +grep -rn "compound" skills/setup/ +``` + +- [ ] **Step 2: For each match, remove the line that adds `compound:` to the generated `workflow_skills` YAML** + +The generated YAML for a fresh user should be (note: only 4 keys, no `compound`): + +```yaml +workflow_skills: + brainstorm: [] + plan: [] + work: [] + review: [] +``` + +Update any inline example, instruction, or template that includes a `compound` line. + +Edit each match with the `Edit` tool to remove just the `compound: ...` line. Do not remove surrounding context. + +- [ ] **Step 3: Verify no `compound` references remain in the setup skill** + +```bash +grep -rn "compound" skills/setup/ +``` + +Expected: no matches, or only matches in unrelated contexts (e.g., the plugin name itself). Re-read each remaining match and decide individually. + +- [ ] **Step 4: Commit** + +```bash +git add skills/setup/ +git commit -m "refactor(setup): drop 'compound' key from generated workflow_skills + +/workflows:compound was removed in v3.0.0. /setup no longer offers +or writes a 'compound' key when generating compound-engineering.local.md. +Existing user configs with a 'compound' key are ignored silently." +``` + +--- + +## Task 9: Add `superpowers` detection to `scripts/check-dependencies.sh` + +**Files:** +- Modify: `scripts/check-dependencies.sh` + +- [ ] **Step 1: Read the current script to confirm structure** + +The current script declares a `missing=()` array, populates it by checking `command -v <tool>`, and prints warnings at the bottom. We add a new check for `superpowers` (filesystem-based, not `command -v`) and a new warning branch. + +- [ ] **Step 2: Add the superpowers detection block** + +Insert this block after the `rclone` check (after line 13 of the current script): + +```bash +# Check superpowers plugin (REQUIRED — provides workflow primitives) +if ! find ~/.claude/plugins -type d -name "superpowers" 2>/dev/null | grep -q .; then + missing+=("superpowers") +fi +``` + +Use the `Edit` tool with `old_string` = the rclone check block, `new_string` = the rclone check block + the new superpowers block. + +- [ ] **Step 3: Add the warning branch** + +Insert this block after the `rclone` warning branch (after line 34): + +```bash +if [[ " ${missing[*]} " =~ " superpowers " ]]; then + warning="$warning + - superpowers (REQUIRED — provides brainstorming, planning, execution, review primitives) + Install: /plugin marketplace add anthropics/claude-plugins-official + /plugin install superpowers@claude-plugins-official" +fi +``` + +Use the `Edit` tool with `old_string` = the rclone warning block, `new_string` = the rclone warning block + the new superpowers warning block. + +- [ ] **Step 4: Test the script with superpowers installed (should be silent)** + +```bash +bash scripts/check-dependencies.sh +``` + +Expected: no output (assuming superpowers is in `~/.claude/plugins/`). + +- [ ] **Step 5: Test the script as if superpowers were missing (manually simulate)** + +```bash +# Save the superpowers path aside (do NOT delete it) +SP=$(find ~/.claude/plugins -type d -name "superpowers" 2>/dev/null | head -1) +echo "Found at: $SP" +# Run with a fake HOME so find returns nothing +HOME=/tmp bash scripts/check-dependencies.sh +``` + +Expected: the warning message lists `superpowers (REQUIRED ...)`. + +- [ ] **Step 6: Commit** + +```bash +git add scripts/check-dependencies.sh +git commit -m "feat(deps): warn at session start when superpowers plugin is missing + +scripts/check-dependencies.sh now scans ~/.claude/plugins for a +superpowers directory and prints an install hint if absent. +Soft check (exit 0); the actual halt happens inside each wrapper +command when superpowers:<skill> is invoked." +``` + +--- + +## Task 10: Update `.claude-plugin/plugin.json` + +**Files:** +- Modify: `.claude-plugin/plugin.json` + +- [ ] **Step 1: Bump version and update description** + +Use the `Edit` tool to make these changes: + +Change `"version": "2.5.2"` → `"version": "3.0.0"`. + +Change the description from: +``` +"description": "Python-specialized development tools with microservice support. 33 agents, 21 commands, 26 skills, 1 MCP server." +``` + +to: +``` +"description": "Python-specialized development tools with microservice support, built on superpowers. 32 agents, 18 commands, 21 skills, 1 MCP server." +``` + +- [ ] **Step 2: Verify** + +```bash +grep -E '"version"|"description"' .claude-plugin/plugin.json +``` + +Expected: version is `3.0.0`; description mentions `built on superpowers` and the new counts. + +- [ ] **Step 3: Do not commit yet** — bundled with the documentation updates in Task 12. + +--- + +## Task 11: Update `CLAUDE.md` + +**Files:** +- Modify: `CLAUDE.md` + +- [ ] **Step 1: Delete the stale `docs/solutions/` reference line** + +Use the `Edit` tool. Find: +``` +See `docs/solutions/plugin-versioning-requirements.md` for detailed versioning workflow. +``` + +Replace with: (empty string — delete the entire line, including the surrounding "## Documentation" header if that whole section becomes empty) + +Actually, check whether the `## Documentation` section has other lines. If it has more lines, just delete the one stale line. If that's the only line, delete the entire section header too. + +- [ ] **Step 2: Remove the `compound` entry from the example YAML in the `Workflow Skills Configuration` section** + +Find this block: +```yaml +workflow_skills: + brainstorm: [django-patterns, holafly-domain] + plan: [django-patterns] + work: [django-patterns, pytest-patterns] + review: [django-patterns, pytest-patterns] + compound: [django-patterns] +``` + +Replace with: +```yaml +workflow_skills: + brainstorm: [django-patterns, holafly-domain] + plan: [django-patterns] + work: [django-patterns, pytest-patterns] + review: [django-patterns, pytest-patterns] +``` + +- [ ] **Step 3: Update the `Doc Output in Multi-Service Mode` table** + +Find this section header and table: +``` +### Doc Output in Multi-Service Mode + +| Doc Type | Single Service | Cross-Service | +|----------|---------------|---------------| +| Brainstorms | Single doc mentioning affected services | `{service}/docs/brainstorms/...` per service | +| Plans | `{service}/docs/plans/...` | Root overview + per-service plan files | +| Solutions | `{service}/docs/solutions/...` | Root `docs/solutions/...` with service refs | +``` + +Replace with: +``` +### Doc Output in Multi-Service Mode + +| Doc Type | Single Service | Cross-Service | +|----------|---------------|---------------| +| Specs | `docs/superpowers/specs/...` | `{service}/docs/superpowers/specs/...` per service | +| Plans | `docs/superpowers/plans/...` (or `{service}/docs/superpowers/plans/...`) | Root overview at `docs/superpowers/plans/...` + per-service plan files | +``` + +(Solutions row removed; vocabulary changed from "brainstorm" to "spec"; paths updated to `docs/superpowers/...`.) + +- [ ] **Step 4: Update the `Focus Context Propagation` subsection** + +Find the example that describes the `<focus_context>` block being included by all sub-agents. Add a sentence at the end: + +> "The full Focus Gate protocol and `<focus_context>` template now live in the `microservice-focus` skill. Workflow commands invoke that skill once instead of inlining the logic." + +Also keep the existing example block — it's still accurate. + +- [ ] **Step 5: Verify** + +```bash +! grep -q "docs/solutions/plugin-versioning-requirements" CLAUDE.md +! grep -q "compound: \[" CLAUDE.md +! grep -q "docs/brainstorms" CLAUDE.md +grep -q "microservice-focus" CLAUDE.md +``` + +All four checks should pass. + +- [ ] **Step 6: Do not commit yet** — bundled with Task 12. + +--- + +## Task 12: Update `CHANGELOG.md` and `README.md` + +**Files:** +- Modify: `CHANGELOG.md` +- Modify: `README.md` + +- [ ] **Step 1: Prepend the v3.0.0 entry to `CHANGELOG.md`** + +Read the current top of `CHANGELOG.md` first to see the format. Then prepend (before the most recent existing version's `## [...]` heading): + +````markdown +## [3.0.0] - 2026-05-25 + +### Changed +- Plugin now requires the `superpowers` plugin as a foundation. All generic workflow + primitives (brainstorming, planning, execution, review, git worktrees, parallel + agents, skill writing) are delegated to superpowers; this plugin focuses on + Python/Django/FastAPI domain value and microservice orchestration. +- Workflow commands rewritten as thin wrappers that delegate to superpowers skills: + `/workflows:brainstorm` → `superpowers:brainstorming`, `/workflows:plan` → + `superpowers:writing-plans`, `/workflows:work` → `superpowers:executing-plans` + (+ Python quality gate), `/workflows:review` → `superpowers:requesting-code-review`. +- Microservice Focus Gate logic extracted from each workflow command into a new + `microservice-focus` skill. +- Brainstorm artifact paths changed from `docs/brainstorms/` to + `docs/superpowers/specs/` (and `{service}/docs/superpowers/specs/` in multi-service + mode), matching superpowers vocabulary ("spec" instead of "brainstorm doc"). +- `scripts/check-dependencies.sh` now warns if the superpowers plugin is not detected. + +### Removed +- `/workflows:compound` command (knowledge-capture pattern dropped). Deprecation shim + remains for one major cycle. +- `/lfg` and `/slfg` autonomous pipelines (users orchestrate stages directly). + Deprecation shims remain for one major cycle. +- 6 skills replaced by superpowers equivalents: `brainstorming`, `git-worktree`, + `skill-creator`, `create-agent-skills`, `orchestrating-swarms`, and `compound-docs` + (the last because its only consumer was `/workflows:compound`). +- `learnings-researcher` agent (read from the now-removed `docs/solutions/` pattern). +- Knowledge-compounding pattern (`docs/solutions/`) — historical files in user repos + remain untouched but are no longer read or written by this plugin. +- `compound` key from `workflow_skills` in `compound-engineering.local.md` schema. + Existing keys are silently ignored. + +### Deprecated +- `/lfg`, `/slfg`, `/workflows:compound` exist as shims that print a migration message + when invoked. They will be removed entirely in v4.0.0. + +### Added +- `microservice-focus` skill consolidating service discovery, `--services` parsing, + multi-service prompting via `AskUserQuestion`, and `<focus_context>` block construction. + +### Migration +- Install superpowers: `/plugin install superpowers@claude-plugins-official`. +- Replace any `/lfg`, `/slfg`, or `/workflows:compound` invocations with the + appropriate sequence of `/workflows:brainstorm` → `/workflows:plan` → + `/workflows:work` → `/workflows:review` (or `superpowers:dispatching-parallel-agents` + within stages for parallel work). +- Move any documents under `docs/brainstorms/` to `docs/superpowers/specs/` if you + want them auto-discovered by `/workflows:plan` (path-only rename; no schema change). +- Remove the `compound:` line from your project's `compound-engineering.local.md` + if present (harmless to leave, but cleaner to drop). + +--- +```` + +- [ ] **Step 2: Rewrite `README.md` per the design spec** + +Read the current README first, then update each section: + +**Header tagline (line 3):** change to: "A Claude Code plugin that supercharges Python development with 32 specialized agents, 18 commands, 21 skills, and an MCP server — built on Anthropic's `superpowers` plugin for workflow primitives. Specialized for Django, FastAPI, pytest, Pydantic, PostgreSQL, and PostGIS projects, with first-class support for multi-service monorepos." + +**"What It Does" section:** replace the 5-step diagram with 4-step: +``` +/workflows:brainstorm → /workflows:plan → /workflows:work → /workflows:review +``` +Remove the "For the impatient: `/lfg` runs the entire pipeline autonomously" line. + +**Installation section:** add this prerequisite block ABOVE the existing install commands: +```markdown +### Prerequisite: Install superpowers + +This plugin requires the `superpowers` plugin (provides generic workflow primitives). + +``` +/plugin marketplace add anthropics/claude-plugins-official +/plugin install superpowers@claude-plugins-official +``` +``` + +**Quick Start section:** remove the `/workflows:compound` example line and the `/lfg add rate limiting to the payment API` line. Add a note after the example: "Brainstorm specs land at `docs/superpowers/specs/`; plans at `docs/superpowers/plans/`." + +**Core Workflow Commands table:** remove the `/workflows:compound` row. Update each remaining row's description to mention delegation, e.g.: +- `/workflows:brainstorm` | Explore requirements before planning (delegates to `superpowers:brainstorming`) +- `/workflows:plan` | Generate implementation plans (delegates to `superpowers:writing-plans`) +- `/workflows:work` | Execute a plan with Python quality gates (delegates to `superpowers:executing-plans`) +- `/workflows:review` | Multi-agent Python code review (delegates to `superpowers:requesting-code-review`) + +**Utility Commands table:** remove the `/lfg` and `/slfg` rows. + +**Add a new "Deprecated commands (v3.0.0)" subsection** after the Utility Commands table: +```markdown +### Deprecated commands (v3.0.0) + +These commands were removed in v3.0.0; they remain as shims that print a migration message and will be deleted in v4.0.0: + +- `/workflows:compound` — knowledge-capture pattern dropped; no replacement. +- `/lfg`, `/slfg` — autonomous pipelines dropped; orchestrate stages directly. + +See CHANGELOG.md v3.0.0 for migration details. +``` + +**Agents section header:** change "Agents (33)" → "Agents (32)". In the Research table, remove the `learnings-researcher` row. + +**Skills section header:** change "Skills (26)" → "Skills (21)". Remove these rows: `brainstorming`, `git-worktree`, `skill-creator`, `create-agent-skills`, `orchestrating-swarms`, `compound-docs`. Add a new `microservice-focus` row under a fitting category (Architecture & Design or a new "Microservice Support" subsection). Add a note: "Workflow primitives (brainstorming, git worktrees, skill writing, parallel agents) now come from the `superpowers` plugin." + +**"How It Works" → "Swarm Mode" subsection:** delete the entire subsection (used `/slfg`). + +**"How It Works" → "Knowledge Compounding" subsection:** delete the entire subsection (solutions pattern dropped). + +**"How It Works → The /workflows:work Pipeline" subsection:** keep — accurately describes the Python quality gate, which is still unique value. + +**Microservice Support section:** add a sentence in the intro: "Focus Gate logic now lives in the `microservice-focus` skill, invoked once by each workflow command." + +**Doc Output table:** update to: +``` +| Doc Type | Single Service | Multi-Service | +|----------|---------------|---------------| +| Specs | `docs/superpowers/specs/` | `{service}/docs/superpowers/specs/` per service | +| Plans | `docs/superpowers/plans/` | Root overview + per-service plan files under `{service}/docs/superpowers/plans/` | +``` +(Solutions row removed.) + +**Version History:** change "Current version: 2.4.0" → "Current version: 3.0.0". + +- [ ] **Step 3: Verify the README updates** + +```bash +grep -c "32 specialized agents\|32 agents" README.md +grep -c "18 commands" README.md +grep -c "21 skills" README.md +! grep -q "/workflows:compound" README.md | head -1 # except in "Deprecated" section +! grep -q "docs/solutions" README.md +grep -q "docs/superpowers/specs" README.md +grep -q "microservice-focus" README.md +grep -q "built on" README.md +grep -q "Current version: 3.0.0" README.md +``` + +Adjust expectations: `/workflows:compound`, `/lfg`, `/slfg` should still appear in the Deprecated commands subsection — exclude that section with `grep -v` if needed. + +- [ ] **Step 4: Commit plugin.json + CLAUDE.md + CHANGELOG.md + README.md together** + +```bash +git add .claude-plugin/plugin.json CLAUDE.md CHANGELOG.md README.md +git commit -m "docs: bump to v3.0.0, document superpowers refactor + +- plugin.json: 3.0.0 + new description (32 agents, 18 commands, 21 skills) +- CLAUDE.md: update Doc Output paths to docs/superpowers/, drop compound + from workflow_skills YAML example, delete stale docs/solutions/ link +- CHANGELOG.md: full v3.0.0 entry with Changed/Removed/Deprecated/Added + sections and a Migration block +- README.md: update header tagline + counts, add superpowers prerequisite + in install, remove compound/lfg/slfg from core tables (add Deprecated + subsection), drop Swarm Mode + Knowledge Compounding sections, update + Doc Output table to spec/plan vocabulary" +``` + +--- + +## Task 13: Audit and clean stale references in other commands/skills/agents + +**Files:** +- Audit: `commands/heal-skill.md` +- Audit: `commands/resolve_todo_parallel.md` +- Audit: `commands/deepen-plan.md` +- Audit: `skills/document-review/SKILL.md` +- Audit: `agents/research/best-practices-researcher.md` +- Audit: `agents/research/git-history-analyzer.md` +- Audit: `agents/review/code-simplicity-reviewer.md` + +- [ ] **Step 1: Run the grep sweep against all stale surfaces** + +```bash +# Should return ZERO hits in active code (CHANGELOG hits are OK) +grep -rn --include="*.md" "learnings-researcher" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "compound-docs" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "orchestrating-swarms" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "docs/solutions" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "docs/brainstorms" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +``` + +Each line returned represents a stale reference that needs fixing. + +- [ ] **Step 2: For each hit, edit the offending file** + +For each grep hit: + +1. Read the file at the matched line. +2. Determine the nature of the reference: + - Reference to the deleted **skill** by name (e.g., "Use the `orchestrating-swarms` skill") → remove the sentence or replace with the superpowers equivalent (e.g., "Use the `superpowers:dispatching-parallel-agents` skill"). + - Reference to the deleted **agent** (e.g., "Task learnings-researcher(...)") → remove the entire call. If the surrounding section becomes meaningless, remove the section. + - Reference to the deleted **directory** (e.g., "search `docs/solutions/`") → remove the sentence or replace with project-appropriate guidance. + +Use the `Edit` tool. Make surgical edits — do not rewrite whole files. + +Specifically expected to need edits: + +- **`commands/heal-skill.md`** — likely references the deleted `skill-creator` skill. Replace with `superpowers:writing-skills`. +- **`commands/resolve_todo_parallel.md`** — likely references `orchestrating-swarms`. Replace with `superpowers:dispatching-parallel-agents`. +- **`commands/deepen-plan.md`** — may reference `learnings-researcher` or `docs/solutions/`. Remove those. +- **`skills/document-review/SKILL.md`** — may reference the deleted `brainstorming` skill. Replace with `superpowers:brainstorming` if needed, or remove the reference. +- **`agents/research/best-practices-researcher.md`** — may reference `learnings-researcher` or `docs/solutions/`. Remove. +- **`agents/research/git-history-analyzer.md`** — same. +- **`agents/review/code-simplicity-reviewer.md`** — same. + +- [ ] **Step 3: Re-run the grep sweep** + +```bash +grep -rn --include="*.md" "learnings-researcher" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "compound-docs" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "orchestrating-swarms" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "docs/solutions" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "docs/brainstorms" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +``` + +Expected: each command returns no output. + +- [ ] **Step 4: Run extended grep sweep for the rest of the deleted skills** + +```bash +# These check for skill references by name. The local 'git-worktree' skill is deleted, +# so any reference like 'skill: git-worktree' or '`git-worktree` skill' is stale. +# References to 'superpowers:using-git-worktrees' are fine. +grep -rn --include="*.md" "skill: git-worktree\|\`git-worktree\` skill\|the git-worktree skill" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "skill: skill-creator\|\`skill-creator\` skill\|the skill-creator skill" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +grep -rn --include="*.md" "skill: create-agent-skills\|\`create-agent-skills\` skill" . | grep -v CHANGELOG | grep -v "docs/superpowers/" +# 'brainstorming' is trickier because superpowers:brainstorming is fine. Look for local refs: +grep -rn --include="*.md" "skill: brainstorming\b\|\`brainstorming\` skill\|the brainstorming skill" . | grep -v CHANGELOG | grep -v "docs/superpowers/" | grep -v "superpowers:" +``` + +For each hit, repeat Step 2's fix-and-edit process. + +- [ ] **Step 5: Verify `workflows:compound` references are scoped to the shim + CHANGELOG only** + +```bash +grep -rln "workflows:compound" . | grep -v CHANGELOG | grep -v "commands/workflows/compound.md" | grep -v "docs/superpowers/" +``` + +Expected: no output. If the brainstorm/plan wrappers or other commands still mention `workflows:compound` as a next step, replace with appropriate text. + +- [ ] **Step 6: Commit** + +```bash +git add -A +git commit -m "chore: scrub stale references to deleted skills/agents/dirs + +Updated commands and agents that still referenced learnings-researcher, +compound-docs, orchestrating-swarms, docs/solutions/, docs/brainstorms/, +or the deleted local skills (brainstorming, git-worktree, skill-creator, +create-agent-skills). Replacements use the superpowers:* equivalent +where one exists; otherwise the reference is removed." +``` + +--- + +## Task 14: Manual smoke test in a real Python project + +**Files:** none modified — verification only. + +This task cannot be performed inside the plugin repo itself; it requires a separate Python project (single-service and/or multi-service) where the plugin is installed. + +- [ ] **Step 1: Set up the test environment** + +In a separate Python project directory: + +```bash +# Ensure superpowers is installed +/plugin install superpowers@claude-plugins-official + +# Install this plugin (from local clone) +/plugin marketplace add /path/to/compound-engineering-feat-python-plugin +/plugin install compound-engineering-feat-python@compound-engineering-feat-python +``` + +- [ ] **Step 2: Smoke-test `/workflows:brainstorm` (single-service)** + +``` +/workflows:brainstorm "add request rate limiting to the API" +``` + +Expected: +- Command loads `superpowers:brainstorming` (no "skill not available" halt). +- Asks discovery questions in `superpowers:brainstorming`'s style. +- Writes a spec to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` (NOT `docs/brainstorms/`). + +- [ ] **Step 3: Smoke-test `/workflows:plan` (single-service)** + +``` +/workflows:plan docs/superpowers/specs/<file-from-step-2>.md +``` + +Expected: +- Loads `superpowers:writing-plans`. +- Produces a plan at `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`. + +- [ ] **Step 4: Smoke-test microservice mode** + +In a multi-service test repo (or simulate by creating 2 dummy `pyproject.toml` files in subdirs): + +``` +/workflows:brainstorm "add cross-service event bus" +``` + +Expected: +- `microservice-focus` skill triggers. +- User is prompted to select services via `AskUserQuestion`. +- Per-service specs land at `{service}/docs/superpowers/specs/`. + +- [ ] **Step 5: Smoke-test `/workflows:review` (no `learnings-researcher`)** + +``` +/workflows:review +``` + +Expected: +- Spawns configured Python review agents. +- Does NOT spawn `learnings-researcher` (verify in agent invocation list). +- Does NOT read `docs/solutions/`. + +- [ ] **Step 6: Smoke-test deprecation shims** + +``` +/workflows:compound +/lfg +/slfg +``` + +Expected: each prints its migration message and exits. No real work performed. + +- [ ] **Step 7: Smoke-test `check-dependencies.sh`** + +Temporarily move the local superpowers install: + +```bash +mv ~/.claude/plugins/<superpowers-path> /tmp/sp-backup +bash /path/to/plugin/scripts/check-dependencies.sh # via SessionStart on a new session +# Expected: warning printed listing superpowers as REQUIRED +mv /tmp/sp-backup ~/.claude/plugins/<superpowers-path> +``` + +- [ ] **Step 8: Record findings** + +If any smoke test fails, return to the relevant task above and fix. Re-test after the fix. Do not skip failures. + +If everything passes, the refactor is shippable. + +--- + +## Self-Review (run after writing the plan, before handoff) + +**1. Spec coverage:** + +Spec requirements → corresponding tasks: + +| Spec section | Task(s) | +|---|---| +| Require superpowers, remove duplicates | Tasks 7 (delete skills), 9 (check), 10 (plugin.json), 12 (README install) | +| Drop /workflows:compound | Task 6 (shim) | +| Drop /lfg, /slfg | Task 6 (shims) | +| 4 thin workflow wrappers | Tasks 2-5 | +| Microservice machinery → skill | Task 1 | +| 6 skills deleted | Task 7 | +| 1 agent deleted (learnings-researcher) | Task 7 | +| New microservice-focus skill | Task 1 | +| Adopt superpowers vocabulary (specs) | Tasks 2, 3 (path overrides), 11 (CLAUDE.md), 12 (README) | +| Drop solutions pattern | Tasks 5 (review wrapper), 7 (agent), 11/12 (docs) | +| compound key removed from config schema | Tasks 8 (setup), 11 (CLAUDE.md example), 12 (CHANGELOG migration note) | +| Plugin name unchanged | (no task — by omission) | +| v3.0.0 bump | Task 10 | +| Deprecation shims for /lfg, /slfg, /workflows:compound | Task 6 | +| check-dependencies.sh superpowers detection | Task 9 | +| README rewrite per scope table | Task 12 | +| CLAUDE.md updates | Task 11 | +| CHANGELOG v3.0.0 entry | Task 12 | +| Grep sweep verification | Task 13 | +| Smoke test plan | Task 14 | + +No gaps detected. + +**2. Placeholder scan:** + +The plan includes the full content of every new and rewritten file. There are no "TBD", "TODO", "implement later", or unspecified sections. Each step shows the exact change or full content. Verification commands include expected output. + +**3. Type/name consistency:** + +- `microservice-focus` skill name used consistently throughout (Task 1 SKILL.md frontmatter, Tasks 2-5 wrapper invocations, Task 11 CLAUDE.md, Task 12 README). +- `<focus_context>` block format identical between focus-context-block.md (Task 1) and the wrappers (Tasks 2-5). +- `docs/superpowers/specs/` and `docs/superpowers/plans/` paths used consistently across Tasks 2, 3, 11, 12, 13, 14. +- Wrapper delegate targets (`superpowers:brainstorming`, `superpowers:writing-plans`, `superpowers:executing-plans`, `superpowers:requesting-code-review`) match the spec's 4-wrapper mapping table. +- Version `3.0.0` consistent across plugin.json (Task 10), CHANGELOG (Task 12), README (Task 12). + +No inconsistencies detected. + +--- + +## Execution Handoff + +**Plan complete and saved to `docs/superpowers/plans/2026-05-25-superpowers-refactor-plan.md`. Two execution options:** + +**1. Subagent-Driven (recommended)** — I dispatch a fresh subagent per task, review between tasks, fast iteration. Best for this plan because tasks are largely independent (Task 1 is foundational; Tasks 2-5 share a commit at the end of Task 5; Tasks 6, 7, 8 are independent; Task 9, 10, 11, 12, 13 are largely independent; Task 14 is verification). + +**2. Inline Execution** — Execute tasks in this session using `superpowers:executing-plans`, batch execution with checkpoints for review. + +**Which approach?** diff --git a/docs/superpowers/specs/2026-05-25-superpowers-refactor-design.md b/docs/superpowers/specs/2026-05-25-superpowers-refactor-design.md new file mode 100644 index 0000000..4ccd3bf --- /dev/null +++ b/docs/superpowers/specs/2026-05-25-superpowers-refactor-design.md @@ -0,0 +1,365 @@ +--- +title: Refactor compound-engineering-feat-python on top of superpowers (v3.0.0) +date: 2026-05-25 +status: draft +--- + +# Refactor compound-engineering-feat-python on top of superpowers (v3.0.0) + +## Goal + +Refactor `compound-engineering-feat-python` (v2.5.2 → v3.0.0) so that the `superpowers` plugin is the foundation for all generic engineering workflow primitives (brainstorming, planning, execution, code review, git worktrees, parallel agents, skill writing). This plugin keeps and sharpens its unique value: Python/Django/FastAPI/pytest domain expertise + microservice orchestration. + +## Why + +The current plugin reimplements primitives that superpowers already provides (a `brainstorming` skill, a `git-worktree` skill, a `skill-creator` skill, an `orchestrating-swarms` skill, etc.). Maintaining two copies is wasted effort and drifts from upstream improvements. The `/workflows:compound` knowledge-capture pattern (`docs/solutions/`) has not paid off in practice and adds surface without returning value. + +This refactor commits to a clean division of labor: superpowers owns the generic workflow primitives, this plugin owns Python value. + +## Scope summary + +| Surface | v2.5.2 | v3.0.0 | +|---|---|---| +| Dependency on `superpowers` | None | Required | +| Workflow commands | 5 | 4 (drop `/workflows:compound`) | +| Autonomous pipelines | `/lfg`, `/slfg` | Removed (deprecation shims kept for one major cycle) | +| Total active commands | 21 | 18 + 3 deprecation shims | +| Total skills | 26 | 21 (6 deleted, 1 new) | +| Total agents | 33 | 32 (drop `learnings-researcher`) | +| MCP servers | 1 | 1 (unchanged) | +| Microservice machinery | Inline in each command | Consolidated into `microservice-focus` skill | +| Artifact vocabulary | "brainstorm doc", `docs/brainstorms/` | "spec", `docs/superpowers/specs/` | +| `compound-engineering.local.md` `workflow_skills` keys | `brainstorm`, `plan`, `work`, `review`, `compound` | `brainstorm`, `plan`, `work`, `review` | +| Knowledge-capture pattern (`docs/solutions/`) | Active | Dropped entirely | +| Plugin name | `compound-engineering-feat-python` | unchanged | + +## Architecture: thin-wrapper delegation + +Each surviving workflow command becomes a thin orchestration script with one job: load Python context, run the microservice focus gate, then hand off to a superpowers skill. The wrappers do NOT re-implement brainstorming/planning/execution/review logic — that lives entirely in superpowers. + +Standard wrapper anatomy (~30-40 lines instead of ~200-400): + +```markdown +--- +name: workflows:<step> +description: <Python-flavored description> +argument-hint: "[user input]" +--- + +# <Step name> (Python) + +<input> #$ARGUMENTS </input> + +## Prerequisites +If `superpowers:<skill>` is not available, halt and instruct the user to run +`/plugin install superpowers@claude-plugins-official`. + +## Step 1: Project Workflow Skills +Read `compound-engineering.local.md`. If found, parse `workflow_skills.<step>` and +load each listed skill. These provide project-specific Python/Django/domain context. + +## Step 2: Microservice Focus +Invoke the `microservice-focus` skill. It will: +- Discover services and prompt if needed (unless --services provided) +- Return the list of focused services + the <focus_context> block + +## Step 3: Delegate to superpowers +Invoke the `superpowers:<skill>` skill. Pass: +- The user's <input> as the topic +- The <focus_context> block (so the superpowers skill propagates it to its own sub-agents) +- The loaded Python workflow_skills (already in conversation) + +## Step 4: Python-specific output path overrides (multi-service only) +When the superpowers skill writes its artifact, override the path: +- Specs: {service}/docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md +- Plans: {service}/docs/superpowers/plans/... + root overview file +``` + +In single-service mode, no path overrides — defer to superpowers defaults (`docs/superpowers/specs/`, `docs/superpowers/plans/`). + +### The 4 wrapper mappings + +| Wrapper command | Delegates to | Python-specific value added | +|---|---|---| +| `/workflows:brainstorm` | `superpowers:brainstorming` | Loads Python `workflow_skills` + microservice focus context; overrides spec output path in multi-service mode | +| `/workflows:plan` | `superpowers:writing-plans` | Same — plus documents the dependency-aware execution order via plan frontmatter `services:` key (a convention writing-plans doesn't know about) | +| `/workflows:work` | `superpowers:executing-plans` | **Keeps the Phase 3 Python quality gate** (full test suite + ruff + mypy + pre-commit) since superpowers:executing-plans is language-agnostic. Invokes Python review/lint agents during the test-fix loop. The least-thin wrapper (~80 lines vs ~30-40 for the others). | +| `/workflows:review` | `superpowers:requesting-code-review` | Loads Python review agents from `compound-engineering.local.md` (django-reviewer, fastapi-reviewer, pytest-reviewer, etc.) and passes them as input to the superpowers review orchestration | + +`/workflows:review` does **NOT** spawn `learnings-researcher` (deleted) and does NOT read `docs/solutions/` (pattern dropped). + +## New skill: `microservice-focus` + +Consolidates the ~50 lines of "Focus Gate" logic currently duplicated across all 5 workflow commands. + +Structure: +``` +skills/microservice-focus/ +├── SKILL.md # Main skill (loaded by wrapper commands) +└── references/ + ├── focus-gate.md # Discovery + prompting protocol + ├── focus-context-block.md # <focus_context> template & propagation rules + └── service-discovery.md # Glob("*/pyproject.toml") + dependency cross-ref +``` + +SKILL.md frontmatter: +```yaml +--- +name: microservice-focus +description: Use when a workflow command needs to detect multi-service monorepos, prompt for service scope, and propagate <focus_context> to sub-agents. Triggers on --services arg, focus_context in conversation, or multiple pyproject.toml at root. +--- +``` + +Responsibilities (consolidated from current inline command logic): +1. Parse `--services` argument if present (skip prompt) +2. Discover services via `Glob("*/pyproject.toml")` +3. If multi-service and no `--services`: prompt user via `AskUserQuestion` for relevant services +4. Load each focused service's `prompt.md`/`README.md`, `pyproject.toml`, `src/` listing +5. Cross-reference internal dependencies +6. Build the standardized `<focus_context>` block for sub-agent propagation +7. Return service list + focus context for the caller to use + +## Deletion list + +### Commands deleted outright (none — see shims below) + +The 3 dropped commands are NOT deleted; they become deprecation shims (see next section). + +### Commands rewritten as deprecation shims (3 files) + +The following keep their .md files but become non-functional one-paragraph migration messages. Removed entirely in v4.0.0. + +``` +commands/workflows/compound.md # shim: "removed; no replacement, /workflows:compound's knowledge-capture pattern is dropped" +commands/lfg.md # shim: "removed; run /workflows:brainstorm → /workflows:plan → /workflows:work → /workflows:review manually" +commands/slfg.md # shim: "removed; use /superpowers:dispatching-parallel-agents within stages" +``` + +Each shim body is ~10 lines: title, one paragraph explaining the removal, the migration steps, and a CHANGELOG link. + +### Skills deleted (6 directories) + +``` +skills/brainstorming/ # → superpowers:brainstorming +skills/git-worktree/ # → superpowers:using-git-worktrees +skills/skill-creator/ # → superpowers:writing-skills +skills/create-agent-skills/ # → superpowers:writing-skills +skills/orchestrating-swarms/ # → superpowers:dispatching-parallel-agents +skills/compound-docs/ # → none (its only consumer was /workflows:compound) +``` + +### Agents deleted (1 file) + +``` +agents/research/learnings-researcher.md # read docs/solutions/, no longer needed +``` + +### Skills created (1 new directory) + +``` +skills/microservice-focus/ +├── SKILL.md +└── references/ + ├── focus-gate.md + ├── focus-context-block.md + └── service-discovery.md +``` + +### Files rewritten (significant content changes) + +``` +commands/workflows/brainstorm.md # thin wrapper, delegates to superpowers:brainstorming +commands/workflows/plan.md # thin wrapper, delegates to superpowers:writing-plans +commands/workflows/work.md # wrapper + Python quality gate, delegates to superpowers:executing-plans +commands/workflows/review.md # wrapper, delegates to superpowers:requesting-code-review +.claude-plugin/plugin.json # v3.0.0, updated counts, updated description +scripts/check-dependencies.sh # add superpowers detection (see below) +README.md # see scope table below +CHANGELOG.md # v3.0.0 entry with breaking changes + migration guide +CLAUDE.md # see scope table below; also delete stale docs/solutions/ pointer +``` + +### Grep-sweep checks (must return zero hits before merge) + +- `workflows:compound` (except in CHANGELOG and shim file) +- `/lfg\b`, `/slfg\b` (except in CHANGELOG and shim files) +- `learnings-researcher` +- `compound-docs` +- `docs/solutions` (except in CHANGELOG) +- `docs/brainstorms` (renamed to specs everywhere) +- `orchestrating-swarms`, `skill-creator` (as skill names), `create-agent-skills` +- Local skill references to `git-worktree` and `brainstorming` (distinguish from `superpowers:` versions, which are fine) + +Audit `commands/heal-skill.md` for any reference to deleted surfaces. + +## Config schema change: `compound-engineering.local.md` + +```yaml +# v2.5.2 +workflow_skills: + brainstorm: [django-patterns, holafly-domain] + plan: [django-patterns] + work: [django-patterns, pytest-patterns] + review: [django-patterns, pytest-patterns] + compound: [django-patterns] # ← removed + +# v3.0.0 +workflow_skills: + brainstorm: [django-patterns, holafly-domain] + plan: [django-patterns] + work: [django-patterns, pytest-patterns] + review: [django-patterns, pytest-patterns] +``` + +Behavior: if an existing user's config still has the `compound` key, the wrappers ignore it silently. No migration script needed. + +`/setup` command and `setup` skill: update to stop offering the `compound` key when generating or updating `compound-engineering.local.md`. + +## Dependency check: `scripts/check-dependencies.sh` + +Add a soft check that warns when the superpowers plugin is not detected on disk. The script runs in the SessionStart hook and exits 0 either way (warning, not gate). + +Detection: scan `~/.claude/plugins/` for a directory named `superpowers`. + +```bash +# Check superpowers plugin (REQUIRED — provides workflow primitives) +if ! find ~/.claude/plugins -type d -name "superpowers" 2>/dev/null | grep -q .; then + missing+=("superpowers") +fi +``` + +Warning entry: +``` +- superpowers (REQUIRED — provides brainstorming, planning, execution, review primitives) + Install: /plugin marketplace add anthropics/claude-plugins-official + /plugin install superpowers@claude-plugins-official +``` + +Belt-and-suspenders: each wrapper command also opens with "If `superpowers:<skill>` is not available, halt and instruct the user to install superpowers." This gives the LLM a defined behavior when the skill genuinely isn't loaded at command time. + +## README.md rewrite scope + +| Section | Change | +|---|---| +| Header tagline | "33 agents, 21 commands, 26 skills" → "32 agents, 18 commands, 21 skills" + "built on top of `superpowers`" | +| What It Does | 5-step `brainstorm→plan→work→review→compound` diagram → 4-step (no compound). Add: "Built on Anthropic's `superpowers` plugin for workflow primitives." | +| Installation | Add a `superpowers` prerequisite step BEFORE the plugin install — explicit `/plugin install superpowers` instruction | +| Quick Start | Remove `/workflows:compound` and `/lfg` examples. Add note that brainstorm specs land at `docs/superpowers/specs/` | +| Core Workflow Commands table | Remove compound row. Mention "delegates to `superpowers:X`" where relevant | +| Utility Commands table | Remove `/lfg` and `/slfg` rows | +| Agents (33) → Agents (32) | Drop `learnings-researcher` row from Research table | +| Skills (26) → Skills (21) | Remove the 6 deleted skill rows. Add `microservice-focus` row. Note that workflow primitives now come from `superpowers` | +| How It Works → /workflows:work Pipeline | Keep — describes the Python-specific quality gate (unique value) | +| How It Works → Swarm Mode | Remove subsection (used /slfg) | +| How It Works → Knowledge Compounding | Remove subsection (solutions pattern dropped) | +| Microservice Support | Note that Focus Gate logic now lives in the `microservice-focus` skill | +| Doc Output table | Update paths to `{service}/docs/superpowers/specs/` etc. Remove solutions row | +| Version History | "Current version: 3.0.0" | +| Deprecated commands subsection | New subsection (small) listing the 3 shims and pointing to CHANGELOG migration | + +## CLAUDE.md updates + +| Section | Change | +|---|---| +| Versioning Requirements | Unchanged | +| Directory Structure | Update — no `compound-docs` skill, etc. | +| Command Naming Convention | Unchanged (still 4 workflow commands using `workflows:` prefix) | +| Skill Compliance Checklist | Unchanged | +| Microservice Mode | "Focus Context Propagation" subsection notes the protocol now lives in `microservice-focus` skill — commands invoke it rather than inlining it. Update output paths table to `docs/superpowers/specs/` etc. and remove solutions row | +| Workflow Skills Configuration | Remove `compound` from example YAML | +| Interaction Style | Unchanged | +| Documentation | **Delete** the stale `See docs/solutions/plugin-versioning-requirements.md ...` line (file does not exist; broken reference) | + +## plugin.json changes + +```json +{ + "name": "compound-engineering-feat-python", + "version": "3.0.0", + "description": "Python-specialized development tools with microservice support, built on superpowers. 32 agents, 18 commands, 21 skills, 1 MCP server." +} +``` + +Note: Claude Code plugins do not (at time of writing) have a formal dependency-declaration mechanism in plugin.json. The superpowers requirement is enforced socially via README + the `check-dependencies.sh` warning + per-command halt-if-missing guard. + +## CHANGELOG entry (v3.0.0) + +```markdown +## [3.0.0] - 2026-05-25 + +### Changed +- Plugin now requires the `superpowers` plugin as a foundation. All generic workflow + primitives (brainstorming, planning, execution, review, git worktrees, parallel + agents, skill writing) are delegated to superpowers; this plugin focuses on + Python/Django/FastAPI domain value and microservice orchestration. +- Workflow commands rewritten as thin wrappers that delegate to superpowers skills: + `/workflows:brainstorm` → `superpowers:brainstorming`, `/workflows:plan` → + `superpowers:writing-plans`, `/workflows:work` → `superpowers:executing-plans` + (+ Python quality gate), `/workflows:review` → `superpowers:requesting-code-review`. +- Microservice Focus Gate logic extracted from each workflow command into a new + `microservice-focus` skill. +- Brainstorm artifact paths changed from `docs/brainstorms/` to + `docs/superpowers/specs/` (and `{service}/docs/superpowers/specs/` in multi-service + mode), matching superpowers vocabulary ("spec" instead of "brainstorm doc"). +- `scripts/check-dependencies.sh` now warns if the superpowers plugin is not detected. + +### Removed +- `/workflows:compound` command (knowledge-capture pattern dropped). Deprecation shim + remains for one major cycle. +- `/lfg` and `/slfg` autonomous pipelines (users orchestrate stages directly). + Deprecation shims remain for one major cycle. +- 6 skills replaced by superpowers equivalents: `brainstorming`, `git-worktree`, + `skill-creator`, `create-agent-skills`, `orchestrating-swarms`, and `compound-docs` + (the last because its only consumer was `/workflows:compound`). +- `learnings-researcher` agent (read from the now-removed `docs/solutions/` pattern). +- Knowledge-compounding pattern (`docs/solutions/`) — historical files in user repos + remain untouched but are no longer read or written by this plugin. +- `compound` key from `workflow_skills` in `compound-engineering.local.md` schema. + Existing keys are silently ignored. + +### Deprecated +- `/lfg`, `/slfg`, `/workflows:compound` exist as shims that print a migration message + when invoked. They will be removed entirely in v4.0.0. + +### Added +- `microservice-focus` skill consolidating service discovery, `--services` parsing, + multi-service prompting via `AskUserQuestion`, and `<focus_context>` block construction. + +### Migration +- Install superpowers: `/plugin install superpowers@claude-plugins-official`. +- Replace any `/lfg`, `/slfg`, or `/workflows:compound` invocations with the + appropriate sequence of `/workflows:brainstorm` → `/workflows:plan` → + `/workflows:work` → `/workflows:review` (or `/superpowers:dispatching-parallel-agents` + within stages for parallel work). +- Move any documents under `docs/brainstorms/` to `docs/superpowers/specs/` if you + want them auto-discovered by `/workflows:plan` (path-only rename; no schema change). +- Remove the `compound:` line from your project's `compound-engineering.local.md` + if present (harmless to leave, but cleaner to drop). +``` + +## Verification + +A grep sweep + manual smoke test is enough at this size. No automated tests exist for the plugin today and adding a test framework is out of scope. + +**Grep sweep (must return zero hits, modulo CHANGELOG and the 3 shim files):** +See the "Grep-sweep checks" subsection above. + +**Manual smoke test:** +1. In a Python project: `/workflows:brainstorm "add request rate limiting"` → verify it loads `superpowers:brainstorming` + Python skills, asks discovery questions, ultimately writes a spec to `docs/superpowers/specs/`. +2. In the same project: `/workflows:plan docs/superpowers/specs/<file>.md` → verify it loads `superpowers:writing-plans` and produces a plan. +3. In a multi-service repo: invoke `/workflows:brainstorm` and verify the `microservice-focus` skill prompts for services and the resulting spec lands at `{service}/docs/superpowers/specs/`. +4. Invoke `/workflows:review` and verify it spawns the configured Python review agents without spawning `learnings-researcher`. +5. Invoke each shim (`/lfg`, `/slfg`, `/workflows:compound`) and verify each prints its migration message without doing anything else. +6. Run `bash scripts/check-dependencies.sh` with superpowers uninstalled and verify the warning fires. + +**Pre-commit check:** the existing CLAUDE.md pre-commit checklist (version bump, CHANGELOG, README counts/tables) applies — do not merge without all three. + +## Out of scope + +- Plugin rename (chosen to keep `compound-engineering-feat-python`). +- Replacing the dropped knowledge-compounding pattern with anything new — fully dropped. +- Adding an automated test framework for the plugin itself. +- Migrating existing user `docs/solutions/` content anywhere — left in place but ignored. +- Migrating existing user `docs/brainstorms/` content to `docs/superpowers/specs/` — documented in migration notes, not automated. +- Changes to the 32 surviving agents (Python-domain reviewers/researchers) — they keep their current bodies. +- Changes to non-workflow utility commands (`/changelog`, `/triage`, `/deepen-plan`, `/feature-video`, etc.) other than removing references to deleted surfaces. diff --git a/scripts/check-dependencies.sh b/scripts/check-dependencies.sh index 52cddc5..5be94b1 100755 --- a/scripts/check-dependencies.sh +++ b/scripts/check-dependencies.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Check optional external dependencies and warn if missing +# Check external dependencies (some required, some optional) and warn if missing missing=() @@ -13,28 +13,40 @@ if ! command -v rclone &> /dev/null; then missing+=("rclone") fi +# Check superpowers plugin (REQUIRED — provides workflow primitives) +if ! find ~/.claude/plugins -type d -name "superpowers" 2>/dev/null | grep -q .; then + missing+=("superpowers") +fi + # If nothing is missing, exit silently if [ ${#missing[@]} -eq 0 ]; then exit 0 fi # Build warning message -warning="[compound-engineering] Optional dependencies not found:" +warning="[compound-engineering] Dependencies not found:" if [[ " ${missing[*]} " =~ " agent-browser " ]]; then warning="$warning - - agent-browser (browser automation, /test-browser, /feature-video, design agents) + - [OPTIONAL] agent-browser — browser automation, /test-browser, /feature-video, design agents Install: npm install -g agent-browser && agent-browser install" fi if [[ " ${missing[*]} " =~ " rclone " ]]; then warning="$warning - - rclone (cloud file uploads for /feature-video) + - [OPTIONAL] rclone — cloud file uploads for /feature-video Install: https://rclone.org/install/" fi +if [[ " ${missing[*]} " =~ " superpowers " ]]; then + warning="$warning + - [REQUIRED] superpowers — provides brainstorming, planning, execution, review primitives + Install: /plugin marketplace add anthropics/claude-plugins-official + /plugin install superpowers@claude-plugins-official" +fi + warning="$warning -Run the install commands above to enable these features." +Run the install commands above. [REQUIRED] dependencies must be installed for v3.0.0 workflow commands to work." echo "$warning" >&2 exit 0 diff --git a/skills/brainstorming/SKILL.md b/skills/brainstorming/SKILL.md deleted file mode 100644 index 00e23ed..0000000 --- a/skills/brainstorming/SKILL.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -name: brainstorming -description: This skill should be used before implementing features, building components, or making changes. It guides exploring user intent, approaches, and design decisions before planning. Triggers on "let's brainstorm", "help me think through", "what should we build", "explore approaches", ambiguous feature requests, or when the user's request has multiple valid interpretations that need clarification. -model: opus ---- - -# Brainstorming - -This skill provides detailed process knowledge for effective brainstorming sessions that clarify **WHAT** to build before diving into **HOW** to build it. - -## When to Use This Skill - -Brainstorming is valuable when: -- Requirements are unclear or ambiguous -- Multiple approaches could solve the problem -- Trade-offs need to be explored with the user -- The user hasn't fully articulated what they want -- The feature scope needs refinement - -Brainstorming can be skipped when: -- Requirements are explicit and detailed -- The user knows exactly what they want -- The task is a straightforward bug fix or well-defined change - -## Core Process - -### Phase 0: Assess Requirement Clarity - -Before diving into questions, assess whether brainstorming is needed. - -**Signals that requirements are clear:** -- User provided specific acceptance criteria -- User referenced existing patterns to follow -- User described exact behavior expected -- Scope is constrained and well-defined - -**Signals that brainstorming is needed:** -- User used vague terms ("make it better", "add something like") -- Multiple reasonable interpretations exist -- Trade-offs haven't been discussed -- User seems unsure about the approach - -If requirements are clear, suggest: "Your requirements seem clear. Consider proceeding directly to planning or implementation." - -### Phase 1: Understand the Idea - -Ask questions **one at a time** to understand the user's intent. Avoid overwhelming with multiple questions. - -**Question Techniques:** - -1. **Prefer multiple choice when natural options exist** - - Good: "Should the notification be: (a) email only, (b) in-app only, or (c) both?" - - Avoid: "How should users be notified?" - -2. **Start broad, then narrow** - - First: What is the core purpose? - - Then: Who are the users? - - Finally: What constraints exist? - -3. **Validate assumptions explicitly** - - "I'm assuming users will be logged in. Is that correct?" - -4. **Ask about success criteria early** - - "How will you know this feature is working well?" - -**Key Topics to Explore:** - -| Topic | Example Questions | -|-------|-------------------| -| Purpose | What problem does this solve? What's the motivation? | -| Users | Who uses this? What's their context? | -| Constraints | Any technical limitations? Timeline? Dependencies? | -| Success | How will you measure success? What's the happy path? | -| Edge Cases | What shouldn't happen? Any error states to consider? | -| Existing Patterns | Are there similar features in the codebase to follow? | - -**Exit Condition:** Continue until the idea is clear OR user says "proceed" or "let's move on" - -### Phase 2: Explore Approaches - -After understanding the idea, propose 2-3 concrete approaches. - -**Structure for Each Approach:** - -```markdown -### Approach A: [Name] - -[2-3 sentence description] - -**Pros:** -- [Benefit 1] -- [Benefit 2] - -**Cons:** -- [Drawback 1] -- [Drawback 2] - -**Best when:** [Circumstances where this approach shines] -``` - -**Guidelines:** -- Lead with a recommendation and explain why -- Be honest about trade-offs -- Consider YAGNI—simpler is usually better -- Reference codebase patterns when relevant - -### Phase 3: Capture the Design - -Summarize key decisions in a structured format. - -**Design Doc Structure:** - -```markdown ---- -date: YYYY-MM-DD -topic: <kebab-case-topic> ---- - -# <Topic Title> - -## What We're Building -[Concise description—1-2 paragraphs max] - -## Why This Approach -[Brief explanation of approaches considered and why this one was chosen] - -## Key Decisions -- [Decision 1]: [Rationale] -- [Decision 2]: [Rationale] - -## Open Questions -- [Any unresolved questions for the planning phase] - -## Next Steps -→ `/workflows:plan` for implementation details -``` - -**Output Location:** `docs/brainstorms/YYYY-MM-DD-<topic>-brainstorm.md` - -### Phase 4: Handoff - -Present clear options for what to do next: - -1. **Proceed to planning** → Run `/workflows:plan` -2. **Refine further** → Continue exploring the design -3. **Done for now** → User will return later - -## YAGNI Principles - -During brainstorming, actively resist complexity: - -- **Don't design for hypothetical future requirements** -- **Choose the simplest approach that solves the stated problem** -- **Prefer boring, proven patterns over clever solutions** -- **Ask "Do we really need this?" when complexity emerges** -- **Defer decisions that don't need to be made now** - -## Incremental Validation - -Keep sections short—200-300 words maximum. After each section of output, pause to validate understanding: - -- "Does this match what you had in mind?" -- "Any adjustments before we continue?" -- "Is this the direction you want to go?" - -This prevents wasted effort on misaligned designs. - -## Anti-Patterns to Avoid - -| Anti-Pattern | Better Approach | -|--------------|-----------------| -| Asking 5 questions at once | Ask one at a time | -| Jumping to implementation details | Stay focused on WHAT, not HOW | -| Proposing overly complex solutions | Start simple, add complexity only if needed | -| Ignoring existing codebase patterns | Research what exists first | -| Making assumptions without validating | State assumptions explicitly and confirm | -| Creating lengthy design documents | Keep it concise—details go in the plan | - -## Microservice Mode - -When working in a multi-service monorepo with focused services active: - -- **Scope questions** to the focused services during Phase 1 -- **Include a `## Services` section** in the brainstorm document (Phase 3) listing affected services and their roles -- **Keep brainstorm as a single document** even for cross-service features — splitting brainstorms across files makes them harder to read -- **Pass `<focus_context>` block** to any sub-agents spawned during brainstorm - -The Services section enables `/workflows:plan` to auto-detect scope and generate per-service plan files. - -## Integration with Planning - -Brainstorming answers **WHAT** to build: -- Requirements and acceptance criteria -- Chosen approach and rationale -- Key decisions and trade-offs - -Planning answers **HOW** to build it: -- Implementation steps and file changes -- Technical details and code patterns -- Testing strategy and verification - -When brainstorm output exists, `/workflows:plan` should detect it and use it as input, skipping its own idea refinement phase. diff --git a/skills/compound-docs/SKILL.md b/skills/compound-docs/SKILL.md deleted file mode 100644 index fcfedd1..0000000 --- a/skills/compound-docs/SKILL.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -name: compound-docs -description: Capture solved problems as categorized documentation with YAML frontmatter for fast lookup -model: opus -disable-model-invocation: true -allowed-tools: - - Read - - Write - - Bash - - Grep -preconditions: - - Problem has been solved (not in-progress) - - Solution has been verified working ---- - -# compound-docs - -**Purpose:** Capture solved problems as one markdown file per problem in `docs/solutions/{category}/` with validated YAML frontmatter for search. - -## When to Use - -Triggers on confirmation phrases: "that worked", "it's fixed", "working now", "problem solved", "that did it". Or `/compound`. - -**Only for non-trivial problems.** Skip typos, obvious syntax errors, trivial fixes. - -## Process (7 steps) - -Full detail in [references/process.md](./references/process.md). Summary: - -1. **Detect confirmation** — user signals the problem is solved -2. **Gather context** — module, symptom, attempts, root cause, solution, prevention. If critical info missing, ASK and WAIT. -3. **Check existing docs** — `grep -r` in `docs/solutions/`. If match, present options (new + xref / update / other), WAIT. -4. **Generate filename** — `[symptom]-[module]-[YYYYMMDD].md` -5. **Validate YAML schema** — against [references/yaml-schema.md](./references/yaml-schema.md). BLOCKING: do not proceed if invalid. -6. **Create doc** — from [assets/resolution-template.md](./assets/resolution-template.md). Microservice-aware path: `{service}/docs/solutions/{category}/` or root `docs/solutions/{category}/`. -7. **Cross-reference & pattern detection** — link related docs, flag critical patterns in decision menu (never auto-promote). - -## Decision Menu After Capture - -Present and WAIT: - -``` -✓ Solution documented -File: docs/solutions/[category]/[filename].md - -What's next? -1. Continue workflow (recommended) -2. Add to Required Reading (critical-patterns.md) -3. Link related issues -4. Add to existing skill (e.g., django-patterns) -5. Create new skill -6. View documentation -7. Other -``` - -**Option 2 (Required Reading):** extract pattern as `❌ WRONG` vs `✅ CORRECT`, append to `docs/solutions/patterns/critical-patterns.md` using [assets/critical-pattern-template.md](./assets/critical-pattern-template.md), add cross-ref back. Confirm: "✓ Added to Required Reading. All subagents will see this pattern before code generation." - -**Option 3 (Link related):** prompt for target doc, add xref to both. - -**Option 4 (Add to existing skill):** prompt for skill, update appropriate reference file (resources.md / patterns.md / examples.md). - -**Option 5 (Create new skill):** prompt for name, run `python3 .claude/skills/skill-creator/scripts/init_skill.py [name]`, seed with this solution. - -## Success Criteria - -- YAML validated against schema (enums exact) -- File at `docs/solutions/[category]/[filename].md` -- Code examples included -- Cross-references added where applicable -- Decision menu presented and action confirmed - -## Execution Guardrails - -**MUST:** validate YAML (blocking), extract exact error messages, include code examples, `mkdir -p` before write, ask and wait when critical context is missing. - -**MUST NOT:** skip YAML validation, use vague descriptions, omit code or cross-references. - -## Reference files - -- [references/process.md](./references/process.md) — full 7-step detail with validation gates -- [references/yaml-schema.md](./references/yaml-schema.md) — frontmatter enums, category mapping -- [references/example.md](./references/example.md) — walkthrough + quality guidelines + error handling -- [assets/resolution-template.md](./assets/resolution-template.md) — doc body template -- [assets/critical-pattern-template.md](./assets/critical-pattern-template.md) — critical-pattern entry template -- [schema.yaml](./schema.yaml) — validation schema - -## Integration - -**Invoked by:** `/compound` command; manual after a fix is confirmed; auto-trigger on confirmation phrases. -**Invokes:** none (terminal skill). -**Handoff:** all context must be in conversation history before invocation. diff --git a/skills/compound-docs/assets/critical-pattern-template.md b/skills/compound-docs/assets/critical-pattern-template.md deleted file mode 100644 index 48d1b17..0000000 --- a/skills/compound-docs/assets/critical-pattern-template.md +++ /dev/null @@ -1,34 +0,0 @@ -# Critical Pattern Template - -Use this template when adding a pattern to `docs/solutions/patterns/critical-patterns.md`: - ---- - -## N. [Pattern Name] (ALWAYS REQUIRED) - -### ❌ WRONG ([Will cause X error]) -```[language] -[code showing wrong approach] -``` - -### ✅ CORRECT -```[language] -[code showing correct approach] -``` - -**Why:** [Technical explanation of why this is required] - -**Placement/Context:** [When this applies] - -**Documented in:** `docs/solutions/[category]/[filename].md` - ---- - -**Instructions:** -1. Replace N with the next pattern number -2. Replace [Pattern Name] with descriptive title -3. Fill in WRONG example with code that causes the problem -4. Fill in CORRECT example with the solution -5. Explain the technical reason in "Why" -6. Clarify when this pattern applies in "Placement/Context" -7. Link to the full troubleshooting doc where this was originally solved diff --git a/skills/compound-docs/assets/resolution-template.md b/skills/compound-docs/assets/resolution-template.md deleted file mode 100644 index 9211649..0000000 --- a/skills/compound-docs/assets/resolution-template.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -module: [Module name or "System" for system-wide] -date: [YYYY-MM-DD] -problem_type: [build_error|test_failure|runtime_error|performance_issue|database_issue|security_issue|ui_bug|integration_issue|logic_error] -component: [django_model|django_view|django_serializer|django_template|fastapi_endpoint|sqlalchemy_model|pydantic_model|service_layer|celery_task|database|middleware|api_client|authentication|payments] -symptoms: - - [Observable symptom 1 - specific error message or behavior] - - [Observable symptom 2 - what user actually saw/experienced] -root_cause: [missing_relationship|missing_prefetch|missing_index|wrong_api|queryset_issue|async_issue|task_timing|memory_leak|config_error|logic_error|test_isolation|missing_validation|missing_permission] -python_version: [3.12 - optional] -framework_version: [Django 5.0.2 - optional] -resolution_type: [code_fix|migration|config_change|test_fix|dependency_update|environment_setup] -severity: [critical|high|medium|low] -tags: [keyword1, keyword2, keyword3] ---- - -# Troubleshooting: [Clear Problem Title] - -## Problem -[1-2 sentence clear description of the issue and what the user experienced] - -## Environment -- Module: [Name or "System-wide"] -- Python Version: [e.g., 3.12] -- Framework: [e.g., Django 5.0.2, FastAPI 0.109.0] -- Affected Component: [e.g., "Order model", "Payment serializer", "Auth middleware"] -- Date: [YYYY-MM-DD when this was solved] - -## Symptoms -- [Observable symptom 1 - what the user saw/experienced] -- [Observable symptom 2 - error messages, visual issues, unexpected behavior] -- [Continue as needed - be specific] - -## What Didn't Work - -**Attempted Solution 1:** [Description of what was tried] -- **Why it failed:** [Technical reason this didn't solve the problem] - -**Attempted Solution 2:** [Description of second attempt] -- **Why it failed:** [Technical reason] - -[Continue for all significant attempts that DIDN'T work] - -[If nothing else was attempted first, write:] -**Direct solution:** The problem was identified and fixed on the first attempt. - -## Solution - -[The actual fix that worked - provide specific details] - -**Code changes** (if applicable): -```python -# Before (broken): -[Show the problematic code] - -# After (fixed): -[Show the corrected code with explanation] -``` - -**Database migration** (if applicable): -```python -# Migration change: -[Show what was changed in the migration] -``` - -**Commands run** (if applicable): -```bash -# Steps taken to fix: -[Commands or actions] -``` - -## Why This Works - -[Technical explanation of:] -1. What was the ROOT CAUSE of the problem? -2. Why does the solution address this root cause? -3. What was the underlying issue (API misuse, configuration error, framework version issue, etc.)? - -[Be detailed enough that future developers understand the "why", not just the "what"] - -## Prevention - -[How to avoid this problem in future development:] -- [Specific coding practice, check, or pattern to follow] -- [What to watch out for] -- [How to catch this early] - -## Related Issues - -[If any similar problems exist in docs/solutions/, link to them:] -- See also: [another-related-issue.md](../category/another-related-issue.md) -- Similar to: [related-problem.md](../category/related-problem.md) - -[If no related issues, write:] -No related issues documented yet. diff --git a/skills/compound-docs/references/example.md b/skills/compound-docs/references/example.md deleted file mode 100644 index e6194ae..0000000 --- a/skills/compound-docs/references/example.md +++ /dev/null @@ -1,75 +0,0 @@ -# Example Scenario - -**User:** "That worked! The N+1 query is fixed." - -Skill activates: - -1. **Detect:** "That worked!" triggers auto-invoke. -2. **Gather:** - - Module: Order Processing - - Symptom: Order listing taking >5 seconds, N+1 query loading order items - - Failed attempts: Added pagination (didn't help), checked Celery task performance - - Solution: `select_related('customer')` + `prefetch_related('items')` on Order queryset - - Root cause: Missing eager loading → separate DB query per order item -3. **Check existing:** None found. -4. **Filename:** `n-plus-one-order-listing-OrderProcessing-20260401.md` -5. **Validate YAML:** - ```yaml - module: Order Processing - date: 2026-04-01 - problem_type: performance_issue - component: django_queryset - symptoms: - - "N+1 query when loading order items" - - "Order listing taking >5 seconds" - root_cause: missing_prefetch - severity: high - tags: [n-plus-one, select-related, prefetch-related, performance] - ``` -6. **Create:** `docs/solutions/performance-issues/n-plus-one-order-listing-OrderProcessing-20260401.md` -7. **Cross-reference:** none needed. - -**Output:** - -``` -✓ Solution documented - -File created: -- docs/solutions/performance-issues/n-plus-one-order-listing-OrderProcessing-20260401.md - -What's next? -1. Continue workflow (recommended) -2. Add to Required Reading -3. Link related issues -4. Add to existing skill -5. Create new skill -6. View documentation -7. Other -``` - -# Quality Guidelines - -**Good docs have:** -- Exact error messages (copy-paste) -- Specific file:line references -- Observable symptoms (what you saw, not interpretations) -- Failed attempts documented -- Technical "why" not just "what" -- Before/after code examples -- Prevention guidance -- Cross-references - -**Avoid:** -- Vague descriptions ("something was wrong") -- Missing technical details ("fixed the code") -- No version / file context -- Code dumps without explanation -- No prevention guidance -- No cross-references - -# Error Handling - -- **Missing context:** Ask user, don't proceed. -- **YAML validation failure:** Show errors, request corrected values, BLOCK until valid. -- **Similar issue ambiguity:** Present matches, let user pick new/update/link. -- **Module not documented:** Warn but don't block. Suggest adding to module docs. diff --git a/skills/compound-docs/references/process.md b/skills/compound-docs/references/process.md deleted file mode 100644 index c8ca04f..0000000 --- a/skills/compound-docs/references/process.md +++ /dev/null @@ -1,106 +0,0 @@ -# 7-Step Documentation Process - -## Step 1 — Detect Confirmation - -Auto-invoke on: "that worked", "it's fixed", "working now", "problem solved", "that did it". -Manual: `/doc-fix`. - -**Only for non-trivial problems:** -- Multiple investigation attempts needed -- Tricky debugging -- Non-obvious solution -- Future sessions would benefit - -**Skip:** typos, obvious syntax errors, trivial fixes. - -## Step 2 — Gather Context - -**Required:** -- Module name -- Symptom (exact error messages) -- Investigation attempts (what didn't work and why) -- Root cause (technical explanation) -- Solution (code/config changes) -- Prevention (how to avoid) - -**Environment:** Python/framework version, environment (local/staging/production), OS, file:line refs. - -**BLOCKING:** If critical context is missing (module, exact error, stage, resolution), ask user and WAIT before Step 3: - -``` -I need a few details to document this properly: -1. Which module had this issue? -2. What was the exact error message or symptom? -3. What environment was this in? -``` - -## Step 3 — Check Existing Docs - -```bash -grep -r "exact error phrase" docs/solutions/ -ls docs/solutions/[category]/ -``` - -If similar issue found, present: -``` -Found similar issue: docs/solutions/[path] -1. Create new doc with cross-reference (recommended) -2. Update existing doc (only if same root cause) -3. Other -``` - -WAIT for user response. Otherwise proceed to Step 4. - -## Step 4 — Generate Filename - -Format: `[sanitized-symptom]-[module]-[YYYYMMDD].md` - -Rules: lowercase, hyphens for spaces, strip specials, < 80 chars. - -Examples: -- `missing-prefetch-OrderProcessing-20260401.md` -- `parameter-not-saving-state-EmailProcessing-20260401.md` - -## Step 5 — Validate YAML Schema (BLOCKING) - -Validate frontmatter against enums in [yaml-schema.md](./yaml-schema.md). - -On failure: -``` -❌ YAML validation failed -- problem_type: must be one of schema enums -- severity: must be one of [critical, high, medium, low] -- symptoms: must be array with 1-5 items -``` - -Do NOT proceed to Step 6 until valid. - -## Step 6 — Create Documentation - -Determine `category` from `problem_type` (mapping in [yaml-schema.md](./yaml-schema.md)). - -**Path rules (microservice mode):** -- Single service: `{service}/docs/solutions/${CATEGORY}/${FILENAME}` — add `service: [name]` to frontmatter -- Cross-service or no service context: `docs/solutions/${CATEGORY}/${FILENAME}` — add `services: [service-a, service-b]` - -```bash -mkdir -p "$(dirname ${DOC_PATH})" -# Populate using assets/resolution-template.md + context + validated YAML -``` - -## Step 7 — Cross-Reference & Pattern Detection - -If similar issues found in Step 3, add "See also" links to both docs. - -If pattern seen 3+ times, append to `docs/solutions/patterns/common-solutions.md`: -```markdown -## [Pattern Name] -**Common symptom:** ... -**Root cause:** ... -**Solution pattern:** ... -**Examples:** [docs...] -``` - -**Critical pattern indicators** (severity critical, affects multiple modules or foundational components, non-obvious solution): note in decision menu Option 2 — never auto-promote. - -When user selects Option 2, use [critical-pattern-template.md](../assets/critical-pattern-template.md). diff --git a/skills/compound-docs/references/yaml-schema.md b/skills/compound-docs/references/yaml-schema.md deleted file mode 100644 index 62b3bf0..0000000 --- a/skills/compound-docs/references/yaml-schema.md +++ /dev/null @@ -1,67 +0,0 @@ -# YAML Frontmatter Schema - -**See `schema.yaml` in the skill root for the complete schema specification.** - -## Required Fields - -- **module** (string): Module name (e.g., "OrderProcessing") or "System" for system-wide issues -- **date** (string): ISO 8601 date (YYYY-MM-DD) -- **problem_type** (enum): One of [build_error, test_failure, runtime_error, performance_issue, database_issue, security_issue, ui_bug, integration_issue, logic_error, developer_experience, workflow_issue, best_practice, documentation_gap] -- **component** (enum): One of [django_model, django_view, django_serializer, django_template, fastapi_endpoint, sqlalchemy_model, pydantic_model, service_layer, celery_task, database, middleware, api_client, authentication, payments, development_workflow, testing_framework, documentation, tooling] -- **symptoms** (array): 1-5 specific observable symptoms -- **root_cause** (enum): One of [missing_relationship, missing_prefetch, missing_index, wrong_api, queryset_issue, async_issue, task_timing, memory_leak, config_error, logic_error, test_isolation, missing_validation, missing_permission, missing_workflow_step, inadequate_documentation, missing_tooling, incomplete_setup] -- **resolution_type** (enum): One of [code_fix, migration, config_change, test_fix, dependency_update, environment_setup, workflow_improvement, documentation_update, tooling_addition, fixture_update] -- **severity** (enum): One of [critical, high, medium, low] - -## Optional Fields - -- **python_version** (string): Python version in X.Y or X.Y.Z format -- **framework_version** (string): Framework version (e.g., "Django 5.0.2") -- **tags** (array): Searchable keywords (lowercase, hyphen-separated) - -## Validation Rules - -1. All required fields must be present -2. Enum fields must match allowed values exactly (case-sensitive) -3. symptoms must be YAML array with 1-5 items -4. date must match YYYY-MM-DD format -5. python_version (if provided) must match X.Y or X.Y.Z format -6. tags should be lowercase, hyphen-separated - -## Example - -```yaml ---- -module: Order Processing -date: 2026-04-01 -problem_type: performance_issue -component: django_model -symptoms: - - "N+1 query when loading order items" - - "Order listing taking >5 seconds" -root_cause: missing_prefetch -python_version: 3.12 -framework_version: Django 5.0.2 -resolution_type: code_fix -severity: high -tags: [n-plus-one, select-related, prefetch-related, performance] ---- -``` - -## Category Mapping - -Based on `problem_type`, documentation is filed in: - -- **build_error** → `docs/solutions/build-errors/` -- **test_failure** → `docs/solutions/test-failures/` -- **runtime_error** → `docs/solutions/runtime-errors/` -- **performance_issue** → `docs/solutions/performance-issues/` -- **database_issue** → `docs/solutions/database-issues/` -- **security_issue** → `docs/solutions/security-issues/` -- **ui_bug** → `docs/solutions/ui-bugs/` -- **integration_issue** → `docs/solutions/integration-issues/` -- **logic_error** → `docs/solutions/logic-errors/` -- **developer_experience** → `docs/solutions/developer-experience/` -- **workflow_issue** → `docs/solutions/workflow-issues/` -- **best_practice** → `docs/solutions/best-practices/` -- **documentation_gap** → `docs/solutions/documentation-gaps/` diff --git a/skills/compound-docs/schema.yaml b/skills/compound-docs/schema.yaml deleted file mode 100644 index eee80eb..0000000 --- a/skills/compound-docs/schema.yaml +++ /dev/null @@ -1,182 +0,0 @@ -# Solution Documentation Schema -# This schema MUST be validated before writing any documentation file - -required_fields: - module: - type: string - description: "Module/area of the project (e.g., 'Order Processing', 'Authentication', 'Payment Service')" - examples: - - "Order Processing" - - "Authentication" - - "Payment Service" - - "Email Processing" - - date: - type: string - pattern: '^\d{4}-\d{2}-\d{2}$' - description: "Date when this problem was solved (YYYY-MM-DD)" - - problem_type: - type: enum - values: - - build_error # Package, dependency, compilation errors - - test_failure # Test failures, flaky tests - - runtime_error # Exceptions, crashes during execution - - performance_issue # Slow queries, memory issues, N+1 queries - - database_issue # Migration, query, schema problems - - security_issue # Authentication, authorization, XSS, SQL injection - - ui_bug # Frontend, template, static file issues - - integration_issue # External service, API integration problems - - logic_error # Business logic bugs - - developer_experience # DX issues: workflow, tooling, seed data, dev setup - - workflow_issue # Development process, missing steps, unclear practices - - best_practice # Documenting patterns and practices to follow - - documentation_gap # Missing or inadequate documentation - description: "Primary category of the problem" - - component: - type: enum - values: - - django_model # Django ORM models - - django_view # Django views (function or class-based) - - django_serializer # DRF serializers - - django_template # Django templates - - fastapi_endpoint # FastAPI route handlers - - sqlalchemy_model # SQLAlchemy models - - pydantic_model # Pydantic schemas/models - - service_layer # Service classes, business logic - - celery_task # Celery/background tasks - - database # PostgreSQL, migrations, schema - - middleware # Django/FastAPI middleware - - api_client # External API integrations - - authentication # Auth, permissions, JWT - - payments # Stripe, billing - - development_workflow # Dev process, seed data, tooling - - testing_framework # Test setup, fixtures, conftest - - documentation # README, guides, inline docs - - tooling # Scripts, management commands, CLI tools - description: "Project component involved" - - symptoms: - type: array[string] - min_items: 1 - max_items: 5 - description: "Observable symptoms (error messages, visual issues, crashes)" - examples: - - "N+1 query detected in order listing" - - "Serializer returning stale cached data" - - "Celery task silently failing after retry" - - root_cause: - type: enum - values: - - missing_relationship # Incorrect model relationships - - missing_prefetch # Missing select_related/prefetch_related (N+1) - - missing_index # Database performance issue - - wrong_api # Using deprecated/incorrect framework API - - queryset_issue # Incorrect queryset filtering or annotation - - async_issue # Async/await misuse, event loop problems - - task_timing # Celery/background task timing or ordering - - memory_leak # Memory leak or excessive allocation - - config_error # Configuration or environment issue - - logic_error # Algorithm/business logic bug - - test_isolation # Test isolation or fixture issue - - missing_validation # Missing model/serializer validation - - missing_permission # Authorization check missing - - missing_workflow_step # Skipped or undocumented workflow step - - inadequate_documentation # Missing or unclear documentation - - missing_tooling # Lacking helper scripts or automation - - incomplete_setup # Missing seed data, fixtures, or config - description: "Fundamental cause of the problem" - - resolution_type: - type: enum - values: - - code_fix # Fixed by changing source code - - migration # Fixed by database migration - - config_change # Fixed by changing configuration - - test_fix # Fixed by correcting tests - - dependency_update # Fixed by updating package/dependency - - environment_setup # Fixed by environment configuration - - workflow_improvement # Improved development workflow or process - - documentation_update # Added or updated documentation - - tooling_addition # Added helper script or automation - - fixture_update # Updated test fixtures or seed data - description: "Type of fix applied" - - severity: - type: enum - values: - - critical # Blocks production or development (build fails, data loss) - - high # Impairs core functionality (feature broken, security issue) - - medium # Affects specific feature (UI broken, performance impact) - - low # Minor issue or edge case - description: "Impact severity" - -optional_fields: - python_version: - type: string - pattern: '^\d+\.\d+(\.\d+)?$' - description: "Python version where this was encountered (e.g., '3.12')" - - framework_version: - type: string - description: "Framework version (e.g., 'Django 5.0.2', 'FastAPI 0.109.0')" - - related_components: - type: array[string] - description: "Other components that interact with this issue" - - tags: - type: array[string] - max_items: 8 - description: "Searchable keywords (lowercase, hyphen-separated)" - examples: - - "n-plus-one" - - "select-related" - - "test-isolation" - - "celery-retry" - -validation_rules: - - "module must be a valid project module name" - - "date must be in YYYY-MM-DD format" - - "problem_type must match one of the enum values" - - "component must match one of the enum values" - - "symptoms must be specific and observable (not vague)" - - "root_cause must be the ACTUAL cause, not a symptom" - - "resolution_type must match one of the enum values" - - "severity must match one of the enum values" - - "tags should be lowercase, hyphen-separated" - -# Example valid front matter: -# --- -# module: Order Processing -# date: 2026-04-01 -# problem_type: performance_issue -# component: django_model -# symptoms: -# - N+1 query when loading order items -# - Order listing taking >5 seconds -# root_cause: missing_prefetch -# python_version: 3.12 -# framework_version: Django 5.0.2 -# resolution_type: code_fix -# severity: high -# tags: [n-plus-one, select-related, prefetch-related, performance] -# --- -# -# Example DX issue front matter: -# --- -# module: Development Workflow -# date: 2026-04-01 -# problem_type: developer_experience -# component: development_workflow -# symptoms: -# - No example data for new feature in development -# - Management command doesn't demonstrate new capabilities -# root_cause: incomplete_setup -# python_version: 3.12 -# resolution_type: fixture_update -# severity: low -# tags: [fixtures, dx, workflow] -# --- diff --git a/skills/create-agent-skills/SKILL.md b/skills/create-agent-skills/SKILL.md deleted file mode 100644 index 2468ab6..0000000 --- a/skills/create-agent-skills/SKILL.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -name: create-agent-skills -description: Expert guidance for creating Claude Code skills and slash commands. Use when working with SKILL.md files, authoring new skills, improving existing skills, creating slash commands, or understanding skill structure and best practices. -model: opus ---- - -# Creating Skills & Commands - -Authoring guide for Claude Code skills following the [official spec](https://code.claude.com/docs/en/skills). - -## Commands and Skills Are The Same Thing - -Custom slash commands have been merged into skills. `.claude/commands/review.md` and `.claude/skills/review/SKILL.md` both create `/review`. If both exist with the same name, the **skill takes precedence**. - -**Command file** (`commands/name.md`): simple, single-file workflow, no supporting files, task-oriented (deploy, commit, triage). - -**Skill directory** (`skills/name/SKILL.md`): supporting files (references/scripts/assets), background knowledge Claude should auto-load, complex enough for progressive disclosure. - -Both use the same YAML frontmatter and markdown format. - -## Frontmatter Reference - -All fields optional; only `description` is recommended. - -| Field | Description | -|-------|-------------| -| `name` | Display name. Lowercase letters, numbers, hyphens (max 64). Defaults to dir name. | -| `description` | What + when. Used for auto-discovery. Max 1024 chars. | -| `argument-hint` | Autocomplete hint. Ex: `[issue-number]` | -| `disable-model-invocation` | `true` → only user can invoke. Use for side-effect workflows (`/deploy`, `/commit`). | -| `user-invocable` | `false` → hidden from `/` menu. Use for background knowledge. | -| `allowed-tools` | Pre-approved tools. Ex: `Read, Bash(git *)` | -| `model` | `haiku` / `sonnet` / `opus` | -| `effort` | `low` / `medium` / `high` / `xhigh` / `max` | -| `context` | `fork` → run in isolated subagent context | -| `agent` | Subagent type when `context: fork` (`Explore`, `Plan`, `general-purpose`, custom) | -| `paths` | Glob(s) that gate auto-activation | -| `hooks` | Skill-scoped lifecycle hooks | - -### Invocation control - -| Frontmatter | User | Claude | Loaded when | -|-------------|------|--------|-------------| -| (default) | Yes | Yes | Description always in context; body on invocation | -| `disable-model-invocation: true` | Yes | No | Only when user invokes | -| `user-invocable: false` | No | Yes | Description always in context; body when relevant | - -## Dynamic Features - -- **Arguments:** `$ARGUMENTS`, `$ARGUMENTS[N]`, shorthand `$0`, `$1`. If `$ARGUMENTS` not in content, args appended automatically. -- **Dynamic context injection:** `` !`command` `` runs the shell command before Claude sees content, and the output is inserted inline (e.g. `!\`gh pr diff\``). -- **Fork context:** `context: fork` + `agent: Explore` runs the skill as a subagent prompt — no conversation history. - -## Progressive Disclosure - -Keep SKILL.md under 500 lines. Split detailed content: - -``` -my-skill/ -├── SKILL.md # Entry (required): overview + navigation -├── references/ -│ └── spec.md # Detailed docs (loaded when needed) -├── assets/ -│ └── template.md # Templates / examples -└── scripts/ - └── helper.py # Executed, not loaded -``` - -Link from SKILL.md: `See [references/spec.md](./references/spec.md).` Keep references **one level deep**. - -## What Would You Like To Do? - -1. **Create new skill** → [workflows/create-new-skill.md](./workflows/create-new-skill.md) -2. **Create new command** → [workflows/simple-skill.md](./workflows/simple-skill.md) -3. **Create router skill (delegates to sub-workflows)** → [workflows/router-skill.md](./workflows/router-skill.md) -4. **Audit existing skill** → [workflows/audit-skill.md](./workflows/audit-skill.md) -5. **Add component** — reference / script / template / workflow: - - [workflows/add-reference.md](./workflows/add-reference.md) - - [workflows/add-script.md](./workflows/add-script.md) - - [workflows/add-template.md](./workflows/add-template.md) - - [workflows/add-workflow.md](./workflows/add-workflow.md) -6. **Upgrade to router** → [workflows/upgrade-to-router.md](./workflows/upgrade-to-router.md) -7. **Verify a skill works** → [workflows/verify-skill.md](./workflows/verify-skill.md) -8. **Get guidance** → [workflows/get-guidance.md](./workflows/get-guidance.md) -9. **Create domain expertise skill** → [workflows/create-domain-expertise-skill.md](./workflows/create-domain-expertise-skill.md) - -## Effective Descriptions - -Include both **what** and **when**. - -Good: `Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDFs, forms, or document extraction.` - -Bad: `Helps with documents.` - -## Audit Checklist - -- [ ] YAML frontmatter (name + description) -- [ ] Description includes trigger keywords and is specific -- [ ] Standard markdown headings (not XML tags) -- [ ] SKILL.md under 500 lines -- [ ] `disable-model-invocation: true` if it has side effects -- [ ] `allowed-tools` set if specific tools needed -- [ ] References one level deep, properly linked -- [ ] Examples are concrete, not abstract -- [ ] `model` set (haiku / sonnet / opus) -- [ ] Tested with real usage - -## Anti-Patterns - -- **XML tags in body** — use standard markdown headings -- **Vague descriptions** — be specific with trigger keywords -- **Deep nesting** — keep references one level from SKILL.md -- **Missing invocation control** — side-effect workflows need `disable-model-invocation: true` -- **Too many options** — provide a default with escape hatch -- **Punting to Claude** — scripts should handle errors explicitly - -## Reference Files - -**Spec & fundamentals** -- [references/official-spec.md](./references/official-spec.md) -- [references/best-practices.md](./references/best-practices.md) -- [references/core-principles.md](./references/core-principles.md) -- [references/skill-structure.md](./references/skill-structure.md) -- [references/recommended-structure.md](./references/recommended-structure.md) -- [references/be-clear-and-direct.md](./references/be-clear-and-direct.md) - -**Patterns & techniques** -- [references/common-patterns.md](./references/common-patterns.md) -- [references/iteration-and-testing.md](./references/iteration-and-testing.md) -- [references/workflows-and-validation.md](./references/workflows-and-validation.md) -- [references/executable-code.md](./references/executable-code.md) -- [references/using-scripts.md](./references/using-scripts.md) -- [references/using-templates.md](./references/using-templates.md) -- [references/api-security.md](./references/api-security.md) - -## Sources - -- [Extend Claude with skills](https://code.claude.com/docs/en/skills) -- [anthropics/skills](https://github.com/anthropics/skills) diff --git a/skills/create-agent-skills/references/api-security.md b/skills/create-agent-skills/references/api-security.md deleted file mode 100644 index 08ced5f..0000000 --- a/skills/create-agent-skills/references/api-security.md +++ /dev/null @@ -1,226 +0,0 @@ -<overview> -When building skills that make API calls requiring credentials (API keys, tokens, secrets), follow this protocol to prevent credentials from appearing in chat. -</overview> - -<the_problem> -Raw curl commands with environment variables expose credentials: - -```bash -# ❌ BAD - API key visible in chat -curl -H "Authorization: Bearer $API_KEY" https://api.example.com/data -``` - -When Claude executes this, the full command with expanded `$API_KEY` appears in the conversation. -</the_problem> - -<the_solution> -Use `~/.claude/scripts/secure-api.sh` - a wrapper that loads credentials internally. - -<for_supported_services> -```bash -# ✅ GOOD - No credentials visible -~/.claude/scripts/secure-api.sh <service> <operation> [args] - -# Examples: -~/.claude/scripts/secure-api.sh facebook list-campaigns -~/.claude/scripts/secure-api.sh ghl search-contact "email@example.com" -``` -</for_supported_services> - -<adding_new_services> -When building a new skill that requires API calls: - -1. **Add operations to the wrapper** (`~/.claude/scripts/secure-api.sh`): - -```bash -case "$SERVICE" in - yourservice) - case "$OPERATION" in - list-items) - curl -s -G \ - -H "Authorization: Bearer $YOUR_API_KEY" \ - "https://api.yourservice.com/items" - ;; - get-item) - ITEM_ID=$1 - curl -s -G \ - -H "Authorization: Bearer $YOUR_API_KEY" \ - "https://api.yourservice.com/items/$ITEM_ID" - ;; - *) - echo "Unknown operation: $OPERATION" >&2 - exit 1 - ;; - esac - ;; -esac -``` - -2. **Add profile support to the wrapper** (if service needs multiple accounts): - -```bash -# In secure-api.sh, add to profile remapping section: -yourservice) - SERVICE_UPPER="YOURSERVICE" - YOURSERVICE_API_KEY=$(eval echo \$${SERVICE_UPPER}_${PROFILE_UPPER}_API_KEY) - YOURSERVICE_ACCOUNT_ID=$(eval echo \$${SERVICE_UPPER}_${PROFILE_UPPER}_ACCOUNT_ID) - ;; -``` - -3. **Add credential placeholders to `~/.claude/.env`** using profile naming: - -```bash -# Check if entries already exist -grep -q "YOURSERVICE_MAIN_API_KEY=" ~/.claude/.env 2>/dev/null || \ - echo -e "\n# Your Service - Main profile\nYOURSERVICE_MAIN_API_KEY=\nYOURSERVICE_MAIN_ACCOUNT_ID=" >> ~/.claude/.env - -echo "Added credential placeholders to ~/.claude/.env - user needs to fill them in" -``` - -4. **Document profile workflow in your SKILL.md**: - -```markdown -## Profile Selection Workflow - -**CRITICAL:** Always use profile selection to prevent using wrong account credentials. - -### When user requests YourService operation: - -1. **Check for saved profile:** - ```bash - ~/.claude/scripts/profile-state get yourservice - ``` - -2. **If no profile saved, discover available profiles:** - ```bash - ~/.claude/scripts/list-profiles yourservice - ``` - -3. **If only ONE profile:** Use it automatically and announce: - ``` - "Using YourService profile 'main' to list items..." - ``` - -4. **If MULTIPLE profiles:** Ask user which one: - ``` - "Which YourService profile: main, clienta, or clientb?" - ``` - -5. **Save user's selection:** - ```bash - ~/.claude/scripts/profile-state set yourservice <selected_profile> - ``` - -6. **Always announce which profile before calling API:** - ``` - "Using YourService profile 'main' to list items..." - ``` - -7. **Make API call with profile:** - ```bash - ~/.claude/scripts/secure-api.sh yourservice:<profile> list-items - ``` - -## Secure API Calls - -All API calls use profile syntax: - -```bash -~/.claude/scripts/secure-api.sh yourservice:<profile> <operation> [args] - -# Examples: -~/.claude/scripts/secure-api.sh yourservice:main list-items -~/.claude/scripts/secure-api.sh yourservice:main get-item <ITEM_ID> -``` - -**Profile persists for session:** Once selected, use same profile for subsequent operations unless user explicitly changes it. -``` -</adding_new_services> -</the_solution> - -<pattern_guidelines> -<simple_get_requests> -```bash -curl -s -G \ - -H "Authorization: Bearer $API_KEY" \ - "https://api.example.com/endpoint" -``` -</simple_get_requests> - -<post_with_json_body> -```bash -ITEM_ID=$1 -curl -s -X POST \ - -H "Authorization: Bearer $API_KEY" \ - -H "Content-Type: application/json" \ - -d @- \ - "https://api.example.com/items/$ITEM_ID" -``` - -Usage: -```bash -echo '{"name":"value"}' | ~/.claude/scripts/secure-api.sh service create-item -``` -</post_with_json_body> - -<post_with_form_data> -```bash -curl -s -X POST \ - -F "field1=value1" \ - -F "field2=value2" \ - -F "access_token=$API_TOKEN" \ - "https://api.example.com/endpoint" -``` -</post_with_form_data> -</pattern_guidelines> - -<credential_storage> -**Location:** `~/.claude/.env` (global for all skills, accessible from any directory) - -**Format:** -```bash -# Service credentials -SERVICE_API_KEY=your-key-here -SERVICE_ACCOUNT_ID=account-id-here - -# Another service -OTHER_API_TOKEN=token-here -OTHER_BASE_URL=https://api.other.com -``` - -**Loading in script:** -```bash -set -a -source ~/.claude/.env 2>/dev/null || { echo "Error: ~/.claude/.env not found" >&2; exit 1; } -set +a -``` -</credential_storage> - -<best_practices> -1. **Never use raw curl with `$VARIABLE` in skill examples** - always use the wrapper -2. **Add all operations to the wrapper** - don't make users figure out curl syntax -3. **Auto-create credential placeholders** - add empty fields to `~/.claude/.env` immediately when creating the skill -4. **Keep credentials in `~/.claude/.env`** - one central location, works everywhere -5. **Document each operation** - show examples in SKILL.md -6. **Handle errors gracefully** - check for missing env vars, show helpful error messages -</best_practices> - -<testing> -Test the wrapper without exposing credentials: - -```bash -# This command appears in chat -~/.claude/scripts/secure-api.sh facebook list-campaigns - -# But API keys never appear - they're loaded inside the script -``` - -Verify credentials are loaded: -```bash -# Check .env exists -ls -la ~/.claude/.env - -# Check specific variables (without showing values) -grep -q "YOUR_API_KEY=" ~/.claude/.env && echo "API key configured" || echo "API key missing" -``` -</testing> diff --git a/skills/create-agent-skills/references/be-clear-and-direct.md b/skills/create-agent-skills/references/be-clear-and-direct.md deleted file mode 100644 index 38078e4..0000000 --- a/skills/create-agent-skills/references/be-clear-and-direct.md +++ /dev/null @@ -1,531 +0,0 @@ -<golden_rule> -Show your skill to someone with minimal context and ask them to follow the instructions. If they're confused, Claude will likely be too. -</golden_rule> - -<overview> -Clarity and directness are fundamental to effective skill authoring. Clear instructions reduce errors, improve execution quality, and minimize token waste. -</overview> - -<guidelines> -<contextual_information> -Give Claude contextual information that frames the task: - -- What the task results will be used for -- What audience the output is meant for -- What workflow the task is part of -- The end goal or what successful completion looks like - -Context helps Claude make better decisions and produce more appropriate outputs. - -<example> -```xml -<context> -This analysis will be presented to investors who value transparency and actionable insights. Focus on financial metrics and clear recommendations. -</context> -``` -</example> -</contextual_information> - -<specificity> -Be specific about what you want Claude to do. If you want code only and nothing else, say so. - -**Vague**: "Help with the report" -**Specific**: "Generate a markdown report with three sections: Executive Summary, Key Findings, Recommendations" - -**Vague**: "Process the data" -**Specific**: "Extract customer names and email addresses from the CSV file, removing duplicates, and save to JSON format" - -Specificity eliminates ambiguity and reduces iteration cycles. -</specificity> - -<sequential_steps> -Provide instructions as sequential steps. Use numbered lists or bullet points. - -```xml -<workflow> -1. Extract data from source file -2. Transform to target format -3. Validate transformation -4. Save to output file -5. Verify output correctness -</workflow> -``` - -Sequential steps create clear expectations and reduce the chance Claude skips important operations. -</sequential_steps> -</guidelines> - -<example_comparison> -<unclear_example> -```xml -<quick_start> -Please remove all personally identifiable information from these customer feedback messages: {{FEEDBACK_DATA}} -</quick_start> -``` - -**Problems**: -- What counts as PII? -- What should replace PII? -- What format should the output be? -- What if no PII is found? -- Should product names be redacted? -</unclear_example> - -<clear_example> -```xml -<objective> -Anonymize customer feedback for quarterly review presentation. -</objective> - -<quick_start> -<instructions> -1. Replace all customer names with "CUSTOMER_[ID]" (e.g., "Jane Doe" → "CUSTOMER_001") -2. Replace email addresses with "EMAIL_[ID]@example.com" -3. Redact phone numbers as "PHONE_[ID]" -4. If a message mentions a specific product (e.g., "AcmeCloud"), leave it intact -5. If no PII is found, copy the message verbatim -6. Output only the processed messages, separated by "---" -</instructions> - -Data to process: {{FEEDBACK_DATA}} -</quick_start> - -<success_criteria> -- All customer names replaced with IDs -- All emails and phones redacted -- Product names preserved -- Output format matches specification -</success_criteria> -``` - -**Why this is better**: -- States the purpose (quarterly review) -- Provides explicit step-by-step rules -- Defines output format clearly -- Specifies edge cases (product names, no PII found) -- Defines success criteria -</clear_example> -</example_comparison> - -<key_differences> -The clear version: -- States the purpose (quarterly review) -- Provides explicit step-by-step rules -- Defines output format -- Specifies edge cases (product names, no PII found) -- Includes success criteria - -The unclear version leaves all these decisions to Claude, increasing the chance of misalignment with expectations. -</key_differences> - -<show_dont_just_tell> -<principle> -When format matters, show an example rather than just describing it. -</principle> - -<telling_example> -```xml -<commit_messages> -Generate commit messages in conventional format with type, scope, and description. -</commit_messages> -``` -</telling_example> - -<showing_example> -```xml -<commit_message_format> -Generate commit messages following these examples: - -<example number="1"> -<input>Added user authentication with JWT tokens</input> -<output> -``` -feat(auth): implement JWT-based authentication - -Add login endpoint and token validation middleware -``` -</output> -</example> - -<example number="2"> -<input>Fixed bug where dates displayed incorrectly in reports</input> -<output> -``` -fix(reports): correct date formatting in timezone conversion - -Use UTC timestamps consistently across report generation -``` -</output> -</example> - -Follow this style: type(scope): brief description, then detailed explanation. -</commit_message_format> -``` -</showing_example> - -<why_showing_works> -Examples communicate nuances that text descriptions can't: -- Exact formatting (spacing, capitalization, punctuation) -- Tone and style -- Level of detail -- Pattern across multiple cases - -Claude learns patterns from examples more reliably than from descriptions. -</why_showing_works> -</show_dont_just_tell> - -<avoid_ambiguity> -<principle> -Eliminate words and phrases that create ambiguity or leave decisions open. -</principle> - -<ambiguous_phrases> -❌ **"Try to..."** - Implies optional -✅ **"Always..."** or **"Never..."** - Clear requirement - -❌ **"Should probably..."** - Unclear obligation -✅ **"Must..."** or **"May optionally..."** - Clear obligation level - -❌ **"Generally..."** - When are exceptions allowed? -✅ **"Always... except when..."** - Clear rule with explicit exceptions - -❌ **"Consider..."** - Should Claude always do this or only sometimes? -✅ **"If X, then Y"** or **"Always..."** - Clear conditions -</ambiguous_phrases> - -<example> -❌ **Ambiguous**: -```xml -<validation> -You should probably validate the output and try to fix any errors. -</validation> -``` - -✅ **Clear**: -```xml -<validation> -Always validate output before proceeding: - -```bash -python scripts/validate.py output_dir/ -``` - -If validation fails, fix errors and re-validate. Only proceed when validation passes with zero errors. -</validation> -``` -</example> -</avoid_ambiguity> - -<define_edge_cases> -<principle> -Anticipate edge cases and define how to handle them. Don't leave Claude guessing. -</principle> - -<without_edge_cases> -```xml -<quick_start> -Extract email addresses from the text file and save to a JSON array. -</quick_start> -``` - -**Questions left unanswered**: -- What if no emails are found? -- What if the same email appears multiple times? -- What if emails are malformed? -- What JSON format exactly? -</without_edge_cases> - -<with_edge_cases> -```xml -<quick_start> -Extract email addresses from the text file and save to a JSON array. - -<edge_cases> -- **No emails found**: Save empty array `[]` -- **Duplicate emails**: Keep only unique emails -- **Malformed emails**: Skip invalid formats, log to stderr -- **Output format**: Array of strings, one email per element -</edge_cases> - -<example_output> -```json -[ - "user1@example.com", - "user2@example.com" -] -``` -</example_output> -</quick_start> -``` -</with_edge_cases> -</define_edge_cases> - -<output_format_specification> -<principle> -When output format matters, specify it precisely. Show examples. -</principle> - -<vague_format> -```xml -<output> -Generate a report with the analysis results. -</output> -``` -</vague_format> - -<specific_format> -```xml -<output_format> -Generate a markdown report with this exact structure: - -```markdown -# Analysis Report: [Title] - -## Executive Summary -[1-2 paragraphs summarizing key findings] - -## Key Findings -- Finding 1 with supporting data -- Finding 2 with supporting data -- Finding 3 with supporting data - -## Recommendations -1. Specific actionable recommendation -2. Specific actionable recommendation - -## Appendix -[Raw data and detailed calculations] -``` - -**Requirements**: -- Use exactly these section headings -- Executive summary must be 1-2 paragraphs -- List 3-5 key findings -- Provide 2-4 recommendations -- Include appendix with source data -</output_format> -``` -</specific_format> -</output_format_specification> - -<decision_criteria> -<principle> -When Claude must make decisions, provide clear criteria. -</principle> - -<no_criteria> -```xml -<workflow> -Analyze the data and decide which visualization to use. -</workflow> -``` - -**Problem**: What factors should guide this decision? -</no_criteria> - -<with_criteria> -```xml -<workflow> -Analyze the data and select appropriate visualization: - -<decision_criteria> -**Use bar chart when**: -- Comparing quantities across categories -- Fewer than 10 categories -- Exact values matter - -**Use line chart when**: -- Showing trends over time -- Continuous data -- Pattern recognition matters more than exact values - -**Use scatter plot when**: -- Showing relationship between two variables -- Looking for correlations -- Individual data points matter -</decision_criteria> -</workflow> -``` - -**Benefits**: Claude has objective criteria for making the decision rather than guessing. -</with_criteria> -</decision_criteria> - -<constraints_and_requirements> -<principle> -Clearly separate "must do" from "nice to have" from "must not do". -</principle> - -<unclear_requirements> -```xml -<requirements> -The report should include financial data, customer metrics, and market analysis. It would be good to have visualizations. Don't make it too long. -</requirements> -``` - -**Problems**: -- Are all three content types required? -- Are visualizations optional or required? -- How long is "too long"? -</unclear_requirements> - -<clear_requirements> -```xml -<requirements> -<must_have> -- Financial data (revenue, costs, profit margins) -- Customer metrics (acquisition, retention, lifetime value) -- Market analysis (competition, trends, opportunities) -- Maximum 5 pages -</must_have> - -<nice_to_have> -- Charts and visualizations -- Industry benchmarks -- Future projections -</nice_to_have> - -<must_not> -- Include confidential customer names -- Exceed 5 pages -- Use technical jargon without definitions -</must_not> -</requirements> -``` - -**Benefits**: Clear priorities and constraints prevent misalignment. -</clear_requirements> -</constraints_and_requirements> - -<success_criteria> -<principle> -Define what success looks like. How will Claude know it succeeded? -</principle> - -<without_success_criteria> -```xml -<objective> -Process the CSV file and generate a report. -</objective> -``` - -**Problem**: When is this task complete? What defines success? -</without_success_criteria> - -<with_success_criteria> -```xml -<objective> -Process the CSV file and generate a summary report. -</objective> - -<success_criteria> -- All rows in CSV successfully parsed -- No data validation errors -- Report generated with all required sections -- Report saved to output/report.md -- Output file is valid markdown -- Process completes without errors -</success_criteria> -``` - -**Benefits**: Clear completion criteria eliminate ambiguity about when the task is done. -</with_success_criteria> -</success_criteria> - -<testing_clarity> -<principle> -Test your instructions by asking: "Could I hand these instructions to a junior developer and expect correct results?" -</principle> - -<testing_process> -1. Read your skill instructions -2. Remove context only you have (project knowledge, unstated assumptions) -3. Identify ambiguous terms or vague requirements -4. Add specificity where needed -5. Test with someone who doesn't have your context -6. Iterate based on their questions and confusion - -If a human with minimal context struggles, Claude will too. -</testing_process> -</testing_clarity> - -<practical_examples> -<example domain="data_processing"> -❌ **Unclear**: -```xml -<quick_start> -Clean the data and remove bad entries. -</quick_start> -``` - -✅ **Clear**: -```xml -<quick_start> -<data_cleaning> -1. Remove rows where required fields (name, email, date) are empty -2. Standardize date format to YYYY-MM-DD -3. Remove duplicate entries based on email address -4. Validate email format (must contain @ and domain) -5. Save cleaned data to output/cleaned_data.csv -</data_cleaning> - -<success_criteria> -- No empty required fields -- All dates in YYYY-MM-DD format -- No duplicate emails -- All emails valid format -- Output file created successfully -</success_criteria> -</quick_start> -``` -</example> - -<example domain="code_generation"> -❌ **Unclear**: -```xml -<quick_start> -Write a function to process user input. -</quick_start> -``` - -✅ **Clear**: -```xml -<quick_start> -<function_specification> -Write a Python function with this signature: - -```python -def process_user_input(raw_input: str) -> dict: - """ - Validate and parse user input. - - Args: - raw_input: Raw string from user (format: "name:email:age") - - Returns: - dict with keys: name (str), email (str), age (int) - - Raises: - ValueError: If input format is invalid - """ -``` - -**Requirements**: -- Split input on colon delimiter -- Validate email contains @ and domain -- Convert age to integer, raise ValueError if not numeric -- Return dictionary with specified keys -- Include docstring and type hints -</function_specification> - -<success_criteria> -- Function signature matches specification -- All validation checks implemented -- Proper error handling for invalid input -- Type hints included -- Docstring included -</success_criteria> -</quick_start> -``` -</example> -</practical_examples> diff --git a/skills/create-agent-skills/references/best-practices.md b/skills/create-agent-skills/references/best-practices.md deleted file mode 100644 index 23c7639..0000000 --- a/skills/create-agent-skills/references/best-practices.md +++ /dev/null @@ -1,404 +0,0 @@ -# Skill Authoring Best Practices - -Source: [platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices) - -## Core Principles - -### Concise is Key - -The context window is a public good. Your Skill shares the context window with everything else Claude needs to know. - -**Default assumption**: Claude is already very smart. Only add context Claude doesn't already have. - -Challenge each piece of information: -- "Does Claude really need this explanation?" -- "Can I assume Claude knows this?" -- "Does this paragraph justify its token cost?" - -**Good example (concise, ~50 tokens):** -```markdown -## Extract PDF text - -Use pdfplumber for text extraction: - -```python -import pdfplumber -with pdfplumber.open("file.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` -``` - -**Bad example (too verbose, ~150 tokens):** -```markdown -## Extract PDF text - -PDF (Portable Document Format) files are a common file format that contains -text, images, and other content. To extract text from a PDF, you'll need to -use a library. There are many libraries available... -``` - -### Set Appropriate Degrees of Freedom - -Match specificity to task fragility and variability. - -**High freedom** (multiple valid approaches): -```markdown -## Code review process - -1. Analyze the code structure and organization -2. Check for potential bugs or edge cases -3. Suggest improvements for readability -4. Verify adherence to project conventions -``` - -**Medium freedom** (preferred pattern with variation): -```markdown -## Generate report - -Use this template and customize as needed: - -```python -def generate_report(data, format="markdown"): - # Process data - # Generate output in specified format -``` -``` - -**Low freedom** (fragile, exact sequence required): -```markdown -## Database migration - -Run exactly this script: - -```bash -python scripts/migrate.py --verify --backup -``` - -Do not modify the command or add flags. -``` - -### Test With All Models - -Skills act as additions to models. Test with Haiku, Sonnet, and Opus. - -- **Haiku**: Does the Skill provide enough guidance? -- **Sonnet**: Is the Skill clear and efficient? -- **Opus**: Does the Skill avoid over-explaining? - -## Naming Conventions - -Use **gerund form** (verb + -ing) for Skill names: - -**Good:** -- `processing-pdfs` -- `analyzing-spreadsheets` -- `managing-databases` -- `testing-code` -- `writing-documentation` - -**Acceptable alternatives:** -- Noun phrases: `pdf-processing`, `spreadsheet-analysis` -- Action-oriented: `process-pdfs`, `analyze-spreadsheets` - -**Avoid:** -- Vague: `helper`, `utils`, `tools` -- Generic: `documents`, `data`, `files` -- Reserved: `anthropic-*`, `claude-*` - -## Writing Effective Descriptions - -**Always write in third person.** The description is injected into the system prompt. - -**Be specific and include key terms:** - -```yaml -# PDF Processing skill -description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. - -# Excel Analysis skill -description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files. - -# Git Commit Helper skill -description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes. -``` - -**Avoid vague descriptions:** -```yaml -description: Helps with documents # Too vague! -description: Processes data # Too generic! -description: Does stuff with files # Useless! -``` - -## Progressive Disclosure Patterns - -### Pattern 1: High-level guide with references - -```markdown ---- -name: pdf-processing -description: Extracts text and tables from PDF files, fills forms, merges documents. ---- - -# PDF Processing - -## Quick start - -```python -import pdfplumber -with pdfplumber.open("file.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` - -## Advanced features - -**Form filling**: See [FORMS.md](FORMS.md) -**API reference**: See [REFERENCE.md](REFERENCE.md) -**Examples**: See [EXAMPLES.md](EXAMPLES.md) -``` - -### Pattern 2: Domain-specific organization - -``` -bigquery-skill/ -├── SKILL.md (overview and navigation) -└── reference/ - ├── finance.md (revenue, billing) - ├── sales.md (opportunities, pipeline) - ├── product.md (API usage, features) - └── marketing.md (campaigns, attribution) -``` - -### Pattern 3: Conditional details - -```markdown -# DOCX Processing - -## Creating documents - -Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md). - -## Editing documents - -For simple edits, modify the XML directly. - -**For tracked changes**: See [REDLINING.md](REDLINING.md) -**For OOXML details**: See [OOXML.md](OOXML.md) -``` - -## Keep References One Level Deep - -Claude may partially read files when they're referenced from other referenced files. - -**Bad (too deep):** -```markdown -# SKILL.md -See [advanced.md](advanced.md)... - -# advanced.md -See [details.md](details.md)... - -# details.md -Here's the actual information... -``` - -**Good (one level deep):** -```markdown -# SKILL.md - -**Basic usage**: [in SKILL.md] -**Advanced features**: See [advanced.md](advanced.md) -**API reference**: See [reference.md](reference.md) -**Examples**: See [examples.md](examples.md) -``` - -## Workflows and Feedback Loops - -### Workflow with Checklist - -```markdown -## Research synthesis workflow - -Copy this checklist: - -``` -- [ ] Step 1: Read all source documents -- [ ] Step 2: Identify key themes -- [ ] Step 3: Cross-reference claims -- [ ] Step 4: Create structured summary -- [ ] Step 5: Verify citations -``` - -**Step 1: Read all source documents** - -Review each document in `sources/`. Note main arguments. -... -``` - -### Feedback Loop Pattern - -```markdown -## Document editing process - -1. Make your edits to `word/document.xml` -2. **Validate immediately**: `python scripts/validate.py unpacked_dir/` -3. If validation fails: - - Review the error message - - Fix the issues - - Run validation again -4. **Only proceed when validation passes** -5. Rebuild: `python scripts/pack.py unpacked_dir/ output.docx` -``` - -## Common Patterns - -### Template Pattern - -```markdown -## Report structure - -Use this template: - -```markdown -# [Analysis Title] - -## Executive summary -[One-paragraph overview] - -## Key findings -- Finding 1 with supporting data -- Finding 2 with supporting data - -## Recommendations -1. Specific actionable recommendation -2. Specific actionable recommendation -``` -``` - -### Examples Pattern - -```markdown -## Commit message format - -**Example 1:** -Input: Added user authentication with JWT tokens -Output: -``` -feat(auth): implement JWT-based authentication - -Add login endpoint and token validation middleware -``` - -**Example 2:** -Input: Fixed bug where dates displayed incorrectly -Output: -``` -fix(reports): correct date formatting in timezone conversion -``` -``` - -### Conditional Workflow Pattern - -```markdown -## Document modification - -1. Determine the modification type: - - **Creating new content?** → Follow "Creation workflow" - **Editing existing?** → Follow "Editing workflow" - -2. Creation workflow: - - Use docx-js library - - Build document from scratch - -3. Editing workflow: - - Unpack existing document - - Modify XML directly - - Validate after each change -``` - -## Content Guidelines - -### Avoid Time-Sensitive Information - -**Bad:** -```markdown -If you're doing this before August 2025, use the old API. -``` - -**Good:** -```markdown -## Current method - -Use the v2 API endpoint: `api.example.com/v2/messages` - -## Old patterns - -<details> -<summary>Legacy v1 API (deprecated 2025-08)</summary> -The v1 API used: `api.example.com/v1/messages` -</details> -``` - -### Use Consistent Terminology - -**Good - Consistent:** -- Always "API endpoint" -- Always "field" -- Always "extract" - -**Bad - Inconsistent:** -- Mix "API endpoint", "URL", "API route", "path" -- Mix "field", "box", "element", "control" - -## Anti-Patterns to Avoid - -### Windows-Style Paths - -- **Good**: `scripts/helper.py`, `reference/guide.md` -- **Avoid**: `scripts\helper.py`, `reference\guide.md` - -### Too Many Options - -**Bad:** -```markdown -You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or... -``` - -**Good:** -```markdown -Use pdfplumber for text extraction: -```python -import pdfplumber -``` - -For scanned PDFs requiring OCR, use pdf2image with pytesseract instead. -``` - -## Checklist for Effective Skills - -### Core Quality -- [ ] Description is specific and includes key terms -- [ ] Description includes both what and when -- [ ] SKILL.md body under 500 lines -- [ ] Additional details in separate files -- [ ] No time-sensitive information -- [ ] Consistent terminology -- [ ] Examples are concrete -- [ ] References one level deep -- [ ] Progressive disclosure used appropriately -- [ ] Workflows have clear steps - -### Code and Scripts -- [ ] Scripts handle errors explicitly -- [ ] No "voodoo constants" (all values justified) -- [ ] Required packages listed -- [ ] Scripts have clear documentation -- [ ] No Windows-style paths -- [ ] Validation steps for critical operations -- [ ] Feedback loops for quality-critical tasks - -### Testing -- [ ] At least three test scenarios -- [ ] Tested with Haiku, Sonnet, and Opus -- [ ] Tested with real usage scenarios -- [ ] Team feedback incorporated diff --git a/skills/create-agent-skills/references/common-patterns.md b/skills/create-agent-skills/references/common-patterns.md deleted file mode 100644 index 4f184f7..0000000 --- a/skills/create-agent-skills/references/common-patterns.md +++ /dev/null @@ -1,595 +0,0 @@ -<overview> -This reference documents common patterns for skill authoring, including templates, examples, terminology consistency, and anti-patterns. All patterns use pure XML structure. -</overview> - -<template_pattern> -<description> -Provide templates for output format. Match the level of strictness to your needs. -</description> - -<strict_requirements> -Use when output format must be exact and consistent: - -```xml -<report_structure> -ALWAYS use this exact template structure: - -```markdown -# [Analysis Title] - -## Executive summary -[One-paragraph overview of key findings] - -## Key findings -- Finding 1 with supporting data -- Finding 2 with supporting data -- Finding 3 with supporting data - -## Recommendations -1. Specific actionable recommendation -2. Specific actionable recommendation -``` -</report_structure> -``` - -**When to use**: Compliance reports, standardized formats, automated processing -</strict_requirements> - -<flexible_guidance> -Use when Claude should adapt the format based on context: - -```xml -<report_structure> -Here is a sensible default format, but use your best judgment: - -```markdown -# [Analysis Title] - -## Executive summary -[Overview] - -## Key findings -[Adapt sections based on what you discover] - -## Recommendations -[Tailor to the specific context] -``` - -Adjust sections as needed for the specific analysis type. -</report_structure> -``` - -**When to use**: Exploratory analysis, context-dependent formatting, creative tasks -</flexible_guidance> -</template_pattern> - -<examples_pattern> -<description> -For skills where output quality depends on seeing examples, provide input/output pairs. -</description> - -<commit_messages_example> -```xml -<objective> -Generate commit messages following conventional commit format. -</objective> - -<commit_message_format> -Generate commit messages following these examples: - -<example number="1"> -<input>Added user authentication with JWT tokens</input> -<output> -``` -feat(auth): implement JWT-based authentication - -Add login endpoint and token validation middleware -``` -</output> -</example> - -<example number="2"> -<input>Fixed bug where dates displayed incorrectly in reports</input> -<output> -``` -fix(reports): correct date formatting in timezone conversion - -Use UTC timestamps consistently across report generation -``` -</output> -</example> - -Follow this style: type(scope): brief description, then detailed explanation. -</commit_message_format> -``` -</commit_messages_example> - -<when_to_use> -- Output format has nuances that text explanations can't capture -- Pattern recognition is easier than rule following -- Examples demonstrate edge cases -- Multi-shot learning improves quality -</when_to_use> -</examples_pattern> - -<consistent_terminology> -<principle> -Choose one term and use it throughout the skill. Inconsistent terminology confuses Claude and reduces execution quality. -</principle> - -<good_example> -Consistent usage: -- Always "API endpoint" (not mixing with "URL", "API route", "path") -- Always "field" (not mixing with "box", "element", "control") -- Always "extract" (not mixing with "pull", "get", "retrieve") - -```xml -<objective> -Extract data from API endpoints using field mappings. -</objective> - -<quick_start> -1. Identify the API endpoint -2. Map response fields to your schema -3. Extract field values -</quick_start> -``` -</good_example> - -<bad_example> -Inconsistent usage creates confusion: - -```xml -<objective> -Pull data from API routes using element mappings. -</objective> - -<quick_start> -1. Identify the URL -2. Map response boxes to your schema -3. Retrieve control values -</quick_start> -``` - -Claude must now interpret: Are "API routes" and "URLs" the same? Are "fields", "boxes", "elements", and "controls" the same? -</bad_example> - -<implementation> -1. Choose terminology early in skill development -2. Document key terms in `<objective>` or `<context>` -3. Use find/replace to enforce consistency -4. Review reference files for consistent usage -</implementation> -</consistent_terminology> - -<provide_default_with_escape_hatch> -<principle> -Provide a default approach with an escape hatch for special cases, not a list of alternatives. Too many options paralyze decision-making. -</principle> - -<good_example> -Clear default with escape hatch: - -```xml -<quick_start> -Use pdfplumber for text extraction: - -```python -import pdfplumber -with pdfplumber.open("file.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` - -For scanned PDFs requiring OCR, use pdf2image with pytesseract instead. -</quick_start> -``` -</good_example> - -<bad_example> -Too many options creates decision paralysis: - -```xml -<quick_start> -You can use any of these libraries: - -- **pypdf**: Good for basic extraction -- **pdfplumber**: Better for tables -- **PyMuPDF**: Faster but more complex -- **pdf2image**: For scanned documents -- **pdfminer**: Low-level control -- **tabula-py**: Table-focused - -Choose based on your needs. -</quick_start> -``` - -Claude must now research and compare all options before starting. This wastes tokens and time. -</bad_example> - -<implementation> -1. Recommend ONE default approach -2. Explain when to use the default (implied: most of the time) -3. Add ONE escape hatch for edge cases -4. Link to advanced reference if multiple alternatives truly needed -</implementation> -</provide_default_with_escape_hatch> - -<anti_patterns> -<description> -Common mistakes to avoid when authoring skills. -</description> - -<pitfall name="markdown_headings_in_body"> -❌ **BAD**: Using markdown headings in skill body: - -```markdown -# PDF Processing - -## Quick start -Extract text with pdfplumber... - -## Advanced features -Form filling requires additional setup... -``` - -✅ **GOOD**: Using pure XML structure: - -```xml -<objective> -PDF processing with text extraction, form filling, and merging capabilities. -</objective> - -<quick_start> -Extract text with pdfplumber... -</quick_start> - -<advanced_features> -Form filling requires additional setup... -</advanced_features> -``` - -**Why it matters**: XML provides semantic meaning, reliable parsing, and token efficiency. -</pitfall> - -<pitfall name="vague_descriptions"> -❌ **BAD**: -```yaml -description: Helps with documents -``` - -✅ **GOOD**: -```yaml -description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. -``` - -**Why it matters**: Vague descriptions prevent Claude from discovering and using the skill appropriately. -</pitfall> - -<pitfall name="inconsistent_pov"> -❌ **BAD**: -```yaml -description: I can help you process Excel files and generate reports -``` - -✅ **GOOD**: -```yaml -description: Processes Excel files and generates reports. Use when analyzing spreadsheets or .xlsx files. -``` - -**Why it matters**: Skills must use third person. First/second person breaks the skill metadata pattern. -</pitfall> - -<pitfall name="wrong_naming_convention"> -❌ **BAD**: Directory name doesn't match skill name or verb-noun convention: -- Directory: `facebook-ads`, Name: `facebook-ads-manager` -- Directory: `stripe-integration`, Name: `stripe` -- Directory: `helper-scripts`, Name: `helper` - -✅ **GOOD**: Consistent verb-noun convention: -- Directory: `manage-facebook-ads`, Name: `manage-facebook-ads` -- Directory: `setup-stripe-payments`, Name: `setup-stripe-payments` -- Directory: `process-pdfs`, Name: `process-pdfs` - -**Why it matters**: Consistency in naming makes skills discoverable and predictable. -</pitfall> - -<pitfall name="too_many_options"> -❌ **BAD**: -```xml -<quick_start> -You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or pdfminer, or tabula-py... -</quick_start> -``` - -✅ **GOOD**: -```xml -<quick_start> -Use pdfplumber for text extraction: - -```python -import pdfplumber -``` - -For scanned PDFs requiring OCR, use pdf2image with pytesseract instead. -</quick_start> -``` - -**Why it matters**: Decision paralysis. Provide one default approach with escape hatch for special cases. -</pitfall> - -<pitfall name="deeply_nested_references"> -❌ **BAD**: References nested multiple levels: -``` -SKILL.md → advanced.md → details.md → examples.md -``` - -✅ **GOOD**: References one level deep from SKILL.md: -``` -SKILL.md → advanced.md -SKILL.md → details.md -SKILL.md → examples.md -``` - -**Why it matters**: Claude may only partially read deeply nested files. Keep references one level deep from SKILL.md. -</pitfall> - -<pitfall name="windows_paths"> -❌ **BAD**: -```xml -<reference_guides> -See scripts\validate.py for validation -</reference_guides> -``` - -✅ **GOOD**: -```xml -<reference_guides> -See scripts/validate.py for validation -</reference_guides> -``` - -**Why it matters**: Always use forward slashes for cross-platform compatibility. -</pitfall> - -<pitfall name="dynamic_context_and_file_reference_execution"> -**Problem**: When showing examples of dynamic context syntax (exclamation mark + backticks) or file references (@ prefix), the skill loader executes these during skill loading. - -❌ **BAD** - These execute during skill load: -```xml -<examples> -Load current status with: !`git status` -Review dependencies in: @package.json -</examples> -``` - -✅ **GOOD** - Add space to prevent execution: -```xml -<examples> -Load current status with: ! `git status` (remove space before backtick in actual usage) -Review dependencies in: @ package.json (remove space after @ in actual usage) -</examples> -``` - -**When this applies**: -- Skills that teach users about dynamic context (slash commands, prompts) -- Any documentation showing the exclamation mark prefix syntax or @ file references -- Skills with example commands or file paths that shouldn't execute during loading - -**Why it matters**: Without the space, these execute during skill load, causing errors or unwanted file reads. -</pitfall> - -<pitfall name="missing_required_tags"> -❌ **BAD**: Missing required tags: -```xml -<quick_start> -Use this tool for processing... -</quick_start> -``` - -✅ **GOOD**: All required tags present: -```xml -<objective> -Process data files with validation and transformation. -</objective> - -<quick_start> -Use this tool for processing... -</quick_start> - -<success_criteria> -- Input file successfully processed -- Output file validates without errors -- Transformation applied correctly -</success_criteria> -``` - -**Why it matters**: Every skill must have `<objective>`, `<quick_start>`, and `<success_criteria>` (or `<when_successful>`). -</pitfall> - -<pitfall name="hybrid_xml_markdown"> -❌ **BAD**: Mixing XML tags with markdown headings: -```markdown -<objective> -PDF processing capabilities -</objective> - -## Quick start - -Extract text with pdfplumber... - -## Advanced features - -Form filling... -``` - -✅ **GOOD**: Pure XML throughout: -```xml -<objective> -PDF processing capabilities -</objective> - -<quick_start> -Extract text with pdfplumber... -</quick_start> - -<advanced_features> -Form filling... -</advanced_features> -``` - -**Why it matters**: Consistency in structure. Either use pure XML or pure markdown (prefer XML). -</pitfall> - -<pitfall name="unclosed_xml_tags"> -❌ **BAD**: Forgetting to close XML tags: -```xml -<objective> -Process PDF files - -<quick_start> -Use pdfplumber... -</quick_start> -``` - -✅ **GOOD**: Properly closed tags: -```xml -<objective> -Process PDF files -</objective> - -<quick_start> -Use pdfplumber... -</quick_start> -``` - -**Why it matters**: Unclosed tags break XML parsing and create ambiguous boundaries. -</pitfall> -</anti_patterns> - -<progressive_disclosure_pattern> -<description> -Keep SKILL.md concise by linking to detailed reference files. Claude loads reference files only when needed. -</description> - -<implementation> -```xml -<objective> -Manage Facebook Ads campaigns, ad sets, and ads via the Marketing API. -</objective> - -<quick_start> -<basic_operations> -See [basic-operations.md](basic-operations.md) for campaign creation and management. -</basic_operations> -</quick_start> - -<advanced_features> -**Custom audiences**: See [audiences.md](audiences.md) -**Conversion tracking**: See [conversions.md](conversions.md) -**Budget optimization**: See [budgets.md](budgets.md) -**API reference**: See [api-reference.md](api-reference.md) -</advanced_features> -``` - -**Benefits**: -- SKILL.md stays under 500 lines -- Claude only reads relevant reference files -- Token usage scales with task complexity -- Easier to maintain and update -</implementation> -</progressive_disclosure_pattern> - -<validation_pattern> -<description> -For skills with validation steps, make validation scripts verbose and specific. -</description> - -<implementation> -```xml -<validation> -After making changes, validate immediately: - -```bash -python scripts/validate.py output_dir/ -``` - -If validation fails, fix errors before continuing. Validation errors include: - -- **Field not found**: "Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" -- **Type mismatch**: "Field 'order_total' expects number, got string" -- **Missing required field**: "Required field 'customer_name' is missing" - -Only proceed when validation passes with zero errors. -</validation> -``` - -**Why verbose errors help**: -- Claude can fix issues without guessing -- Specific error messages reduce iteration cycles -- Available options shown in error messages -</implementation> -</validation_pattern> - -<checklist_pattern> -<description> -For complex multi-step workflows, provide a checklist Claude can copy and track progress. -</description> - -<implementation> -```xml -<workflow> -Copy this checklist and check off items as you complete them: - -``` -Task Progress: -- [ ] Step 1: Analyze the form (run analyze_form.py) -- [ ] Step 2: Create field mapping (edit fields.json) -- [ ] Step 3: Validate mapping (run validate_fields.py) -- [ ] Step 4: Fill the form (run fill_form.py) -- [ ] Step 5: Verify output (run verify_output.py) -``` - -<step_1> -**Analyze the form** - -Run: `python scripts/analyze_form.py input.pdf` - -This extracts form fields and their locations, saving to `fields.json`. -</step_1> - -<step_2> -**Create field mapping** - -Edit `fields.json` to add values for each field. -</step_2> - -<step_3> -**Validate mapping** - -Run: `python scripts/validate_fields.py fields.json` - -Fix any validation errors before continuing. -</step_3> - -<step_4> -**Fill the form** - -Run: `python scripts/fill_form.py input.pdf fields.json output.pdf` -</step_4> - -<step_5> -**Verify output** - -Run: `python scripts/verify_output.py output.pdf` - -If verification fails, return to Step 2. -</step_5> -</workflow> -``` - -**Benefits**: -- Clear progress tracking -- Prevents skipping steps -- Easy to resume after interruption -</implementation> -</checklist_pattern> diff --git a/skills/create-agent-skills/references/core-principles.md b/skills/create-agent-skills/references/core-principles.md deleted file mode 100644 index 35313e4..0000000 --- a/skills/create-agent-skills/references/core-principles.md +++ /dev/null @@ -1,437 +0,0 @@ -<overview> -Core principles guide skill authoring decisions. These principles ensure skills are efficient, effective, and maintainable across different models and use cases. -</overview> - -<xml_structure_principle> -<description> -Skills use pure XML structure for consistent parsing, efficient token usage, and improved Claude performance. -</description> - -<why_xml> -<consistency> -XML enforces consistent structure across all skills. All skills use the same tag names for the same purposes: -- `<objective>` always defines what the skill does -- `<quick_start>` always provides immediate guidance -- `<success_criteria>` always defines completion - -This consistency makes skills predictable and easier to maintain. -</consistency> - -<parseability> -XML provides unambiguous boundaries and semantic meaning. Claude can reliably: -- Identify section boundaries (where content starts and ends) -- Understand content purpose (what role each section plays) -- Skip irrelevant sections (progressive disclosure) -- Parse programmatically (validation tools can check structure) - -Markdown headings are just visual formatting. Claude must infer meaning from heading text, which is less reliable. -</parseability> - -<token_efficiency> -XML tags are more efficient than markdown headings: - -**Markdown headings**: -```markdown -## Quick start -## Workflow -## Advanced features -## Success criteria -``` -Total: ~20 tokens, no semantic meaning to Claude - -**XML tags**: -```xml -<quick_start> -<workflow> -<advanced_features> -<success_criteria> -``` -Total: ~15 tokens, semantic meaning built-in - -Savings compound across all skills in the ecosystem. -</token_efficiency> - -<claude_performance> -Claude performs better with pure XML because: -- Unambiguous section boundaries reduce parsing errors -- Semantic tags convey intent directly (no inference needed) -- Nested tags create clear hierarchies -- Consistent structure across skills reduces cognitive load -- Progressive disclosure works more reliably - -Pure XML structure is not just a style preference—it's a performance optimization. -</claude_performance> -</why_xml> - -<critical_rule> -**Remove ALL markdown headings (#, ##, ###) from skill body content.** Replace with semantic XML tags. Keep markdown formatting WITHIN content (bold, italic, lists, code blocks, links). -</critical_rule> - -<required_tags> -Every skill MUST have: -- `<objective>` - What the skill does and why it matters -- `<quick_start>` - Immediate, actionable guidance -- `<success_criteria>` or `<when_successful>` - How to know it worked - -See [use-xml-tags.md](use-xml-tags.md) for conditional tags and intelligence rules. -</required_tags> -</xml_structure_principle> - -<conciseness_principle> -<description> -The context window is shared. Your skill shares it with the system prompt, conversation history, other skills' metadata, and the actual request. -</description> - -<guidance> -Only add context Claude doesn't already have. Challenge each piece of information: -- "Does Claude really need this explanation?" -- "Can I assume Claude knows this?" -- "Does this paragraph justify its token cost?" - -Assume Claude is smart. Don't explain obvious concepts. -</guidance> - -<concise_example> -**Concise** (~50 tokens): -```xml -<quick_start> -Extract PDF text with pdfplumber: - -```python -import pdfplumber - -with pdfplumber.open("file.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` -</quick_start> -``` - -**Verbose** (~150 tokens): -```xml -<quick_start> -PDF files are a common file format used for documents. To extract text from them, we'll use a Python library called pdfplumber. First, you'll need to import the library, then open the PDF file using the open method, and finally extract the text from each page. Here's how to do it: - -```python -import pdfplumber - -with pdfplumber.open("file.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` - -This code opens the PDF and extracts text from the first page. -</quick_start> -``` - -The concise version assumes Claude knows what PDFs are, understands Python imports, and can read code. All those assumptions are correct. -</concise_example> - -<when_to_elaborate> -Add explanation when: -- Concept is domain-specific (not general programming knowledge) -- Pattern is non-obvious or counterintuitive -- Context affects behavior in subtle ways -- Trade-offs require judgment - -Don't add explanation for: -- Common programming concepts (loops, functions, imports) -- Standard library usage (reading files, making HTTP requests) -- Well-known tools (git, npm, pip) -- Obvious next steps -</when_to_elaborate> -</conciseness_principle> - -<degrees_of_freedom_principle> -<description> -Match the level of specificity to the task's fragility and variability. Give Claude more freedom for creative tasks, less freedom for fragile operations. -</description> - -<high_freedom> -<when> -- Multiple approaches are valid -- Decisions depend on context -- Heuristics guide the approach -- Creative solutions welcome -</when> - -<example> -```xml -<objective> -Review code for quality, bugs, and maintainability. -</objective> - -<workflow> -1. Analyze the code structure and organization -2. Check for potential bugs or edge cases -3. Suggest improvements for readability and maintainability -4. Verify adherence to project conventions -</workflow> - -<success_criteria> -- All major issues identified -- Suggestions are actionable and specific -- Review balances praise and criticism -</success_criteria> -``` - -Claude has freedom to adapt the review based on what the code needs. -</example> -</high_freedom> - -<medium_freedom> -<when> -- A preferred pattern exists -- Some variation is acceptable -- Configuration affects behavior -- Template can be adapted -</when> - -<example> -```xml -<objective> -Generate reports with customizable format and sections. -</objective> - -<report_template> -Use this template and customize as needed: - -```python -def generate_report(data, format="markdown", include_charts=True): - # Process data - # Generate output in specified format - # Optionally include visualizations -``` -</report_template> - -<success_criteria> -- Report includes all required sections -- Format matches user preference -- Data accurately represented -</success_criteria> -``` - -Claude can customize the template based on requirements. -</example> -</medium_freedom> - -<low_freedom> -<when> -- Operations are fragile and error-prone -- Consistency is critical -- A specific sequence must be followed -- Deviation causes failures -</when> - -<example> -```xml -<objective> -Run database migration with exact sequence to prevent data loss. -</objective> - -<workflow> -Run exactly this script: - -```bash -python scripts/migrate.py --verify --backup -``` - -**Do not modify the command or add additional flags.** -</workflow> - -<success_criteria> -- Migration completes without errors -- Backup created before migration -- Verification confirms data integrity -</success_criteria> -``` - -Claude must follow the exact command with no variation. -</example> -</low_freedom> - -<matching_specificity> -The key is matching specificity to fragility: - -- **Fragile operations** (database migrations, payment processing, security): Low freedom, exact instructions -- **Standard operations** (API calls, file processing, data transformation): Medium freedom, preferred pattern with flexibility -- **Creative operations** (code review, content generation, analysis): High freedom, heuristics and principles - -Mismatched specificity causes problems: -- Too much freedom on fragile tasks → errors and failures -- Too little freedom on creative tasks → rigid, suboptimal outputs -</matching_specificity> -</degrees_of_freedom_principle> - -<model_testing_principle> -<description> -Skills act as additions to models, so effectiveness depends on the underlying model. What works for Opus might need more detail for Haiku. -</description> - -<testing_across_models> -Test your skill with all models you plan to use: - -<haiku_testing> -**Claude Haiku** (fast, economical) - -Questions to ask: -- Does the skill provide enough guidance? -- Are examples clear and complete? -- Do implicit assumptions become explicit? -- Does Haiku need more structure? - -Haiku benefits from: -- More explicit instructions -- Complete examples (no partial code) -- Clear success criteria -- Step-by-step workflows -</haiku_testing> - -<sonnet_testing> -**Claude Sonnet** (balanced) - -Questions to ask: -- Is the skill clear and efficient? -- Does it avoid over-explanation? -- Are workflows well-structured? -- Does progressive disclosure work? - -Sonnet benefits from: -- Balanced detail level -- XML structure for clarity -- Progressive disclosure -- Concise but complete guidance -</sonnet_testing> - -<opus_testing> -**Claude Opus** (powerful reasoning) - -Questions to ask: -- Does the skill avoid over-explaining? -- Can Opus infer obvious steps? -- Are constraints clear? -- Is context minimal but sufficient? - -Opus benefits from: -- Concise instructions -- Principles over procedures -- High degrees of freedom -- Trust in reasoning capabilities -</opus_testing> -</testing_across_models> - -<balancing_across_models> -Aim for instructions that work well across all target models: - -**Good balance**: -```xml -<quick_start> -Use pdfplumber for text extraction: - -```python -import pdfplumber -with pdfplumber.open("file.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` - -For scanned PDFs requiring OCR, use pdf2image with pytesseract instead. -</quick_start> -``` - -This works for all models: -- Haiku gets complete working example -- Sonnet gets clear default with escape hatch -- Opus gets enough context without over-explanation - -**Too minimal for Haiku**: -```xml -<quick_start> -Use pdfplumber for text extraction. -</quick_start> -``` - -**Too verbose for Opus**: -```xml -<quick_start> -PDF files are documents that contain text. To extract that text, we use a library called pdfplumber. First, import the library at the top of your Python file. Then, open the PDF file using the pdfplumber.open() method. This returns a PDF object. Access the pages attribute to get a list of pages. Each page has an extract_text() method that returns the text content... -</quick_start> -``` -</balancing_across_models> - -<iterative_improvement> -1. Start with medium detail level -2. Test with target models -3. Observe where models struggle or succeed -4. Adjust based on actual performance -5. Re-test and iterate - -Don't optimize for one model. Find the balance that works across your target models. -</iterative_improvement> -</model_testing_principle> - -<progressive_disclosure_principle> -<description> -SKILL.md serves as an overview. Reference files contain details. Claude loads reference files only when needed. -</description> - -<token_efficiency> -Progressive disclosure keeps token usage proportional to task complexity: - -- Simple task: Load SKILL.md only (~500 tokens) -- Medium task: Load SKILL.md + one reference (~1000 tokens) -- Complex task: Load SKILL.md + multiple references (~2000 tokens) - -Without progressive disclosure, every task loads all content regardless of need. -</token_efficiency> - -<implementation> -- Keep SKILL.md under 500 lines -- Split detailed content into reference files -- Keep references one level deep from SKILL.md -- Link to references from relevant sections -- Use descriptive reference file names - -See [skill-structure.md](skill-structure.md) for progressive disclosure patterns. -</implementation> -</progressive_disclosure_principle> - -<validation_principle> -<description> -Validation scripts are force multipliers. They catch errors that Claude might miss and provide actionable feedback. -</description> - -<characteristics> -Good validation scripts: -- Provide verbose, specific error messages -- Show available valid options when something is invalid -- Pinpoint exact location of problems -- Suggest actionable fixes -- Are deterministic and reliable - -See [workflows-and-validation.md](workflows-and-validation.md) for validation patterns. -</characteristics> -</validation_principle> - -<principle_summary> -<xml_structure> -Use pure XML structure for consistency, parseability, and Claude performance. Required tags: objective, quick_start, success_criteria. -</xml_structure> - -<conciseness> -Only add context Claude doesn't have. Assume Claude is smart. Challenge every piece of content. -</conciseness> - -<degrees_of_freedom> -Match specificity to fragility. High freedom for creative tasks, low freedom for fragile operations, medium for standard work. -</degrees_of_freedom> - -<model_testing> -Test with all target models. Balance detail level to work across Haiku, Sonnet, and Opus. -</model_testing> - -<progressive_disclosure> -Keep SKILL.md concise. Split details into reference files. Load reference files only when needed. -</progressive_disclosure> - -<validation> -Make validation scripts verbose and specific. Catch errors early with actionable feedback. -</validation> -</principle_summary> diff --git a/skills/create-agent-skills/references/executable-code.md b/skills/create-agent-skills/references/executable-code.md deleted file mode 100644 index 4c9273a..0000000 --- a/skills/create-agent-skills/references/executable-code.md +++ /dev/null @@ -1,175 +0,0 @@ -<when_to_use_scripts> -Even if Claude could write a script, pre-made scripts offer advantages: -- More reliable than generated code -- Save tokens (no need to include code in context) -- Save time (no code generation required) -- Ensure consistency across uses - -<execution_vs_reference> -Make clear whether Claude should: -- **Execute the script** (most common): "Run `analyze_form.py` to extract fields" -- **Read it as reference** (for complex logic): "See `analyze_form.py` for the extraction algorithm" - -For most utility scripts, execution is preferred. -</execution_vs_reference> - -<how_scripts_work> -When Claude executes a script via bash: -1. Script code never enters context window -2. Only script output consumes tokens -3. Far more efficient than having Claude generate equivalent code -</how_scripts_work> -</when_to_use_scripts> - -<file_organization> -<scripts_directory> -**Best practice**: Place all executable scripts in a `scripts/` subdirectory within the skill folder. - -``` -skill-name/ -├── SKILL.md -├── scripts/ -│ ├── main_utility.py -│ ├── helper_script.py -│ └── validator.py -└── references/ - └── api-docs.md -``` - -**Benefits**: -- Keeps skill root clean and organized -- Clear separation between documentation and executable code -- Consistent pattern across all skills -- Easy to reference: `python scripts/script_name.py` - -**Reference pattern**: In SKILL.md, reference scripts using the `scripts/` path: - -```bash -python ~/.claude/skills/skill-name/scripts/analyze.py input.har -``` -</scripts_directory> -</file_organization> - -<utility_scripts_pattern> -<example> -## Utility scripts - -**analyze_form.py**: Extract all form fields from PDF - -```bash -python scripts/analyze_form.py input.pdf > fields.json -``` - -Output format: -```json -{ - "field_name": { "type": "text", "x": 100, "y": 200 }, - "signature": { "type": "sig", "x": 150, "y": 500 } -} -``` - -**validate_boxes.py**: Check for overlapping bounding boxes - -```bash -python scripts/validate_boxes.py fields.json -# Returns: "OK" or lists conflicts -``` - -**fill_form.py**: Apply field values to PDF - -```bash -python scripts/fill_form.py input.pdf fields.json output.pdf -``` -</example> -</utility_scripts_pattern> - -<solve_dont_punt> -Handle error conditions rather than punting to Claude. - -<example type="good"> -```python -def process_file(path): - """Process a file, creating it if it doesn't exist.""" - try: - with open(path) as f: - return f.read() - except FileNotFoundError: - print(f"File {path} not found, creating default") - with open(path, 'w') as f: - f.write('') - return '' - except PermissionError: - print(f"Cannot access {path}, using default") - return '' -``` -</example> - -<example type="bad"> -```python -def process_file(path): - # Just fail and let Claude figure it out - return open(path).read() -``` -</example> - -<configuration_values> -Document configuration parameters to avoid "voodoo constants": - -<example type="good"> -```python -# HTTP requests typically complete within 30 seconds -REQUEST_TIMEOUT = 30 - -# Three retries balances reliability vs speed -MAX_RETRIES = 3 -``` -</example> - -<example type="bad"> -```python -TIMEOUT = 47 # Why 47? -RETRIES = 5 # Why 5? -``` -</example> -</configuration_values> -</solve_dont_punt> - -<package_dependencies> -<runtime_constraints> -Skills run in code execution environment with platform-specific limitations: -- **claude.ai**: Can install packages from npm and PyPI -- **Anthropic API**: No network access and no runtime package installation -</runtime_constraints> - -<guidance> -List required packages in your SKILL.md and verify they're available. - -<example type="good"> -Install required package: `pip install pypdf` - -Then use it: - -```python -from pypdf import PdfReader -reader = PdfReader("file.pdf") -``` -</example> - -<example type="bad"> -"Use the pdf library to process the file." -</example> -</guidance> -</package_dependencies> - -<mcp_tool_references> -If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names. - -<format>ServerName:tool_name</format> - -<examples> -- Use the BigQuery:bigquery_schema tool to retrieve table schemas. -- Use the GitHub:create_issue tool to create issues. -</examples> - -Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available. -</mcp_tool_references> diff --git a/skills/create-agent-skills/references/iteration-and-testing.md b/skills/create-agent-skills/references/iteration-and-testing.md deleted file mode 100644 index 5d41d53..0000000 --- a/skills/create-agent-skills/references/iteration-and-testing.md +++ /dev/null @@ -1,474 +0,0 @@ -<overview> -Skills improve through iteration and testing. This reference covers evaluation-driven development, Claude A/B testing patterns, and XML structure validation during testing. -</overview> - -<evaluation_driven_development> -<principle> -Create evaluations BEFORE writing extensive documentation. This ensures your skill solves real problems rather than documenting imagined ones. -</principle> - -<workflow> -<step_1> -**Identify gaps**: Run Claude on representative tasks without a skill. Document specific failures or missing context. -</step_1> - -<step_2> -**Create evaluations**: Build three scenarios that test these gaps. -</step_2> - -<step_3> -**Establish baseline**: Measure Claude's performance without the skill. -</step_3> - -<step_4> -**Write minimal instructions**: Create just enough content to address the gaps and pass evaluations. -</step_4> - -<step_5> -**Iterate**: Execute evaluations, compare against baseline, and refine. -</step_5> -</workflow> - -<evaluation_structure> -```json -{ - "skills": ["pdf-processing"], - "query": "Extract all text from this PDF file and save it to output.txt", - "files": ["test-files/document.pdf"], - "expected_behavior": [ - "Successfully reads the PDF file using appropriate library", - "Extracts text content from all pages without missing any", - "Saves extracted text to output.txt in clear, readable format" - ] -} -``` -</evaluation_structure> - -<why_evaluations_first> -- Prevents documenting imagined problems -- Forces clarity about what success looks like -- Provides objective measurement of skill effectiveness -- Keeps skill focused on actual needs -- Enables quantitative improvement tracking -</why_evaluations_first> -</evaluation_driven_development> - -<iterative_development_with_claude> -<principle> -The most effective skill development uses Claude itself. Work with "Claude A" (expert who helps refine) to create skills used by "Claude B" (agent executing tasks). -</principle> - -<creating_skills> -<workflow> -<step_1> -**Complete task without skill**: Work through problem with Claude A, noting what context you repeatedly provide. -</step_1> - -<step_2> -**Ask Claude A to create skill**: "Create a skill that captures this pattern we just used" -</step_2> - -<step_3> -**Review for conciseness**: Remove unnecessary explanations. -</step_3> - -<step_4> -**Improve architecture**: Organize content with progressive disclosure. -</step_4> - -<step_5> -**Test with Claude B**: Use fresh instance to test on real tasks. -</step_5> - -<step_6> -**Iterate based on observation**: Return to Claude A with specific issues observed. -</step_6> -</workflow> - -<insight> -Claude models understand skill format natively. Simply ask Claude to create a skill and it will generate properly structured SKILL.md content. -</insight> -</creating_skills> - -<improving_skills> -<workflow> -<step_1> -**Use skill in real workflows**: Give Claude B actual tasks. -</step_1> - -<step_2> -**Observe behavior**: Where does it struggle, succeed, or make unexpected choices? -</step_2> - -<step_3> -**Return to Claude A**: Share observations and current SKILL.md. -</step_3> - -<step_4> -**Review suggestions**: Claude A might suggest reorganization, stronger language, or workflow restructuring. -</step_4> - -<step_5> -**Apply and test**: Update skill and test again. -</step_5> - -<step_6> -**Repeat**: Continue based on real usage, not assumptions. -</step_6> -</workflow> - -<what_to_watch_for> -- **Unexpected exploration paths**: Structure might not be intuitive -- **Missed connections**: Links might need to be more explicit -- **Overreliance on sections**: Consider moving frequently-read content to main SKILL.md -- **Ignored content**: Poorly signaled or unnecessary files -- **Critical metadata**: The name and description in your skill's metadata are critical for discovery -</what_to_watch_for> -</improving_skills> -</iterative_development_with_claude> - -<model_testing> -<principle> -Test with all models you plan to use. Different models have different strengths and need different levels of detail. -</principle> - -<haiku_testing> -**Claude Haiku** (fast, economical) - -Questions to ask: -- Does the skill provide enough guidance? -- Are examples clear and complete? -- Do implicit assumptions become explicit? -- Does Haiku need more structure? - -Haiku benefits from: -- More explicit instructions -- Complete examples (no partial code) -- Clear success criteria -- Step-by-step workflows -</haiku_testing> - -<sonnet_testing> -**Claude Sonnet** (balanced) - -Questions to ask: -- Is the skill clear and efficient? -- Does it avoid over-explanation? -- Are workflows well-structured? -- Does progressive disclosure work? - -Sonnet benefits from: -- Balanced detail level -- XML structure for clarity -- Progressive disclosure -- Concise but complete guidance -</sonnet_testing> - -<opus_testing> -**Claude Opus** (powerful reasoning) - -Questions to ask: -- Does the skill avoid over-explaining? -- Can Opus infer obvious steps? -- Are constraints clear? -- Is context minimal but sufficient? - -Opus benefits from: -- Concise instructions -- Principles over procedures -- High degrees of freedom -- Trust in reasoning capabilities -</opus_testing> - -<balancing_across_models> -What works for Opus might need more detail for Haiku. Aim for instructions that work well across all target models. Find the balance that serves your target audience. - -See [core-principles.md](core-principles.md) for model testing examples. -</balancing_across_models> -</model_testing> - -<xml_structure_validation> -<principle> -During testing, validate that your skill's XML structure is correct and complete. -</principle> - -<validation_checklist> -After updating a skill, verify: - -<required_tags_present> -- ✅ `<objective>` tag exists and defines what skill does -- ✅ `<quick_start>` tag exists with immediate guidance -- ✅ `<success_criteria>` or `<when_successful>` tag exists -</required_tags_present> - -<no_markdown_headings> -- ✅ No `#`, `##`, or `###` headings in skill body -- ✅ All sections use XML tags instead -- ✅ Markdown formatting within tags is preserved (bold, italic, lists, code blocks) -</no_markdown_headings> - -<proper_xml_nesting> -- ✅ All XML tags properly closed -- ✅ Nested tags have correct hierarchy -- ✅ No unclosed tags -</proper_xml_nesting> - -<conditional_tags_appropriate> -- ✅ Conditional tags match skill complexity -- ✅ Simple skills use required tags only -- ✅ Complex skills add appropriate conditional tags -- ✅ No over-engineering or under-specifying -</conditional_tags_appropriate> - -<reference_files_check> -- ✅ Reference files also use pure XML structure -- ✅ Links to reference files are correct -- ✅ References are one level deep from SKILL.md -</reference_files_check> -</validation_checklist> - -<testing_xml_during_iteration> -When iterating on a skill: - -1. Make changes to XML structure -2. **Validate XML structure** (check tags, nesting, completeness) -3. Test with Claude on representative tasks -4. Observe if XML structure aids or hinders Claude's understanding -5. Iterate structure based on actual performance -</testing_xml_during_iteration> -</xml_structure_validation> - -<observation_based_iteration> -<principle> -Iterate based on what you observe, not what you assume. Real usage reveals issues assumptions miss. -</principle> - -<observation_categories> -<what_claude_reads> -Which sections does Claude actually read? Which are ignored? This reveals: -- Relevance of content -- Effectiveness of progressive disclosure -- Whether section names are clear -</what_claude_reads> - -<where_claude_struggles> -Which tasks cause confusion or errors? This reveals: -- Missing context -- Unclear instructions -- Insufficient examples -- Ambiguous requirements -</where_claude_struggles> - -<where_claude_succeeds> -Which tasks go smoothly? This reveals: -- Effective patterns -- Good examples -- Clear instructions -- Appropriate detail level -</where_claude_succeeds> - -<unexpected_behaviors> -What does Claude do that surprises you? This reveals: -- Unstated assumptions -- Ambiguous phrasing -- Missing constraints -- Alternative interpretations -</unexpected_behaviors> -</observation_categories> - -<iteration_pattern> -1. **Observe**: Run Claude on real tasks with current skill -2. **Document**: Note specific issues, not general feelings -3. **Hypothesize**: Why did this issue occur? -4. **Fix**: Make targeted changes to address specific issues -5. **Test**: Verify fix works on same scenario -6. **Validate**: Ensure fix doesn't break other scenarios -7. **Repeat**: Continue with next observed issue -</iteration_pattern> -</observation_based_iteration> - -<progressive_refinement> -<principle> -Skills don't need to be perfect initially. Start minimal, observe usage, add what's missing. -</principle> - -<initial_version> -Start with: -- Valid YAML frontmatter -- Required XML tags: objective, quick_start, success_criteria -- Minimal working example -- Basic success criteria - -Skip initially: -- Extensive examples -- Edge case documentation -- Advanced features -- Detailed reference files -</initial_version> - -<iteration_additions> -Add through iteration: -- Examples when patterns aren't clear from description -- Edge cases when observed in real usage -- Advanced features when users need them -- Reference files when SKILL.md approaches 500 lines -- Validation scripts when errors are common -</iteration_additions> - -<benefits> -- Faster to initial working version -- Additions solve real needs, not imagined ones -- Keeps skills focused and concise -- Progressive disclosure emerges naturally -- Documentation stays aligned with actual usage -</benefits> -</progressive_refinement> - -<testing_discovery> -<principle> -Test that Claude can discover and use your skill when appropriate. -</principle> - -<discovery_testing> -<test_description> -Test if Claude loads your skill when it should: - -1. Start fresh conversation (Claude B) -2. Ask question that should trigger skill -3. Check if skill was loaded -4. Verify skill was used appropriately -</test_description> - -<description_quality> -If skill isn't discovered: -- Check description includes trigger keywords -- Verify description is specific, not vague -- Ensure description explains when to use skill -- Test with different phrasings of the same request - -The description is Claude's primary discovery mechanism. -</description_quality> -</discovery_testing> -</testing_discovery> - -<common_iteration_patterns> -<pattern name="too_verbose"> -**Observation**: Skill works but uses lots of tokens - -**Fix**: -- Remove obvious explanations -- Assume Claude knows common concepts -- Use examples instead of lengthy descriptions -- Move advanced content to reference files -</pattern> - -<pattern name="too_minimal"> -**Observation**: Claude makes incorrect assumptions or misses steps - -**Fix**: -- Add explicit instructions where assumptions fail -- Provide complete working examples -- Define edge cases -- Add validation steps -</pattern> - -<pattern name="poor_discovery"> -**Observation**: Skill exists but Claude doesn't load it when needed - -**Fix**: -- Improve description with specific triggers -- Add relevant keywords -- Test description against actual user queries -- Make description more specific about use cases -</pattern> - -<pattern name="unclear_structure"> -**Observation**: Claude reads wrong sections or misses relevant content - -**Fix**: -- Use clearer XML tag names -- Reorganize content hierarchy -- Move frequently-needed content earlier -- Add explicit links to relevant sections -</pattern> - -<pattern name="incomplete_examples"> -**Observation**: Claude produces outputs that don't match expected pattern - -**Fix**: -- Add more examples showing pattern -- Make examples more complete -- Show edge cases in examples -- Add anti-pattern examples (what not to do) -</pattern> -</common_iteration_patterns> - -<iteration_velocity> -<principle> -Small, frequent iterations beat large, infrequent rewrites. -</principle> - -<fast_iteration> -**Good approach**: -1. Make one targeted change -2. Test on specific scenario -3. Verify improvement -4. Commit change -5. Move to next issue - -Total time: Minutes per iteration -Iterations per day: 10-20 -Learning rate: High -</fast_iteration> - -<slow_iteration> -**Problematic approach**: -1. Accumulate many issues -2. Make large refactor -3. Test everything at once -4. Debug multiple issues simultaneously -5. Hard to know what fixed what - -Total time: Hours per iteration -Iterations per day: 1-2 -Learning rate: Low -</slow_iteration> - -<benefits_of_fast_iteration> -- Isolate cause and effect -- Build pattern recognition faster -- Less wasted work from wrong directions -- Easier to revert if needed -- Maintains momentum -</benefits_of_fast_iteration> -</iteration_velocity> - -<success_metrics> -<principle> -Define how you'll measure if the skill is working. Quantify success. -</principle> - -<objective_metrics> -- **Success rate**: Percentage of tasks completed correctly -- **Token usage**: Average tokens consumed per task -- **Iteration count**: How many tries to get correct output -- **Error rate**: Percentage of tasks with errors -- **Discovery rate**: How often skill loads when it should -</objective_metrics> - -<subjective_metrics> -- **Output quality**: Does output meet requirements? -- **Appropriate detail**: Too verbose or too minimal? -- **Claude confidence**: Does Claude seem uncertain? -- **User satisfaction**: Does skill solve the actual problem? -</subjective_metrics> - -<tracking_improvement> -Compare metrics before and after changes: -- Baseline: Measure without skill -- Initial: Measure with first version -- Iteration N: Measure after each change - -Track which changes improve which metrics. Double down on effective patterns. -</tracking_improvement> -</success_metrics> diff --git a/skills/create-agent-skills/references/official-spec.md b/skills/create-agent-skills/references/official-spec.md deleted file mode 100644 index d04fbf7..0000000 --- a/skills/create-agent-skills/references/official-spec.md +++ /dev/null @@ -1,134 +0,0 @@ -# Official Skill Specification (2026) - -Source: [code.claude.com/docs/en/skills](https://code.claude.com/docs/en/skills) - -## Commands and Skills Are Merged - -Custom slash commands have been merged into skills. A file at `.claude/commands/review.md` and a skill at `.claude/skills/review/SKILL.md` both create `/review` and work the same way. Existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to control invocation, and automatic context loading. - -If a skill and a command share the same name, the skill takes precedence. - -## SKILL.md File Structure - -Every skill requires a `SKILL.md` file with YAML frontmatter followed by standard markdown instructions. - -```markdown ---- -name: your-skill-name -description: What it does and when to use it ---- - -# Your Skill Name - -## Instructions -Clear, step-by-step guidance. - -## Examples -Concrete examples of using this skill. -``` - -## Complete Frontmatter Reference - -All fields are optional. Only `description` is recommended. - -| Field | Required | Description | -|-------|----------|-------------| -| `name` | No | Display name. Lowercase letters, numbers, hyphens only (max 64 chars). Defaults to directory name if omitted. | -| `description` | Recommended | What it does AND when to use it (max 1024 chars). Claude uses this to decide when to apply the skill. | -| `argument-hint` | No | Hint shown during autocomplete. Example: `[issue-number]` or `[filename] [format]` | -| `disable-model-invocation` | No | Set `true` to prevent Claude from auto-loading. Use for manual workflows. Default: `false` | -| `user-invocable` | No | Set `false` to hide from `/` menu. Use for background knowledge. Default: `true` | -| `allowed-tools` | No | Tools Claude can use without permission prompts. Example: `Read, Bash(git *)` | -| `model` | No | Model to use: `haiku`, `sonnet`, or `opus` | -| `context` | No | Set `fork` to run in isolated subagent context | -| `agent` | No | Subagent type when `context: fork`. Options: `Explore`, `Plan`, `general-purpose`, or custom agent name | -| `hooks` | No | Hooks scoped to this skill's lifecycle | - -## Invocation Control - -| Frontmatter | User can invoke | Claude can invoke | When loaded into context | -|-------------|----------------|-------------------|--------------------------| -| (default) | Yes | Yes | Description always in context, full skill loads when invoked | -| `disable-model-invocation: true` | Yes | No | Description not in context, full skill loads when you invoke | -| `user-invocable: false` | No | Yes | Description always in context, full skill loads when invoked | - -## Skill Locations & Priority - -``` -Enterprise (highest priority) → Personal → Project → Plugin (lowest priority) -``` - -| Type | Path | Applies to | -|------|------|-----------| -| Enterprise | See managed settings | All users in organization | -| Personal | `~/.claude/skills/<name>/SKILL.md` | You, across all projects | -| Project | `.claude/skills/<name>/SKILL.md` | Anyone working in repository | -| Plugin | `<plugin>/skills/<name>/SKILL.md` | Where plugin is enabled | - -Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict with other levels. - -## How Skills Work - -1. **Discovery**: Claude loads only name and description at startup (2% of context window budget) -2. **Activation**: When your request matches a skill's description, Claude loads the full content -3. **Execution**: Claude follows the skill's instructions - -## String Substitutions - -| Variable | Description | -|----------|-------------| -| `$ARGUMENTS` | All arguments passed when invoking | -| `$ARGUMENTS[N]` | Specific argument by 0-based index | -| `$N` | Shorthand for `$ARGUMENTS[N]` | -| `${CLAUDE_SESSION_ID}` | Current session ID | - -## Dynamic Context Injection - -The `` !`command` `` syntax runs shell commands before content is sent to Claude: - -```markdown -## Context -- Current branch: !`git branch --show-current` -- PR diff: !`gh pr diff` -``` - -Commands execute immediately and their output replaces the placeholder. Claude only sees the final result. - -## Progressive Disclosure - -``` -my-skill/ -├── SKILL.md # Entry point (required) -├── reference.md # Detailed docs (loaded when needed) -├── examples.md # Usage examples (loaded when needed) -└── scripts/ - └── helper.py # Utility script (executed, not loaded) -``` - -Keep SKILL.md under 500 lines. Link to supporting files: -```markdown -For API details, see [reference.md](reference.md). -``` - -## Running in a Subagent - -Add `context: fork` to run in isolation: - -```yaml ---- -name: deep-research -description: Research a topic thoroughly -context: fork -agent: Explore ---- - -Research $ARGUMENTS thoroughly... -``` - -The skill content becomes the subagent's prompt. It won't have access to conversation history. - -## Distribution - -- **Project skills**: Commit `.claude/skills/` to version control -- **Plugins**: Add `skills/` directory to plugin -- **Enterprise**: Deploy organization-wide through managed settings diff --git a/skills/create-agent-skills/references/recommended-structure.md b/skills/create-agent-skills/references/recommended-structure.md deleted file mode 100644 index d39a1d6..0000000 --- a/skills/create-agent-skills/references/recommended-structure.md +++ /dev/null @@ -1,168 +0,0 @@ -# Recommended Skill Structure - -The optimal structure for complex skills separates routing, workflows, and knowledge. - -<structure> -``` -skill-name/ -├── SKILL.md # Router + essential principles (unavoidable) -├── workflows/ # Step-by-step procedures (how) -│ ├── workflow-a.md -│ ├── workflow-b.md -│ └── ... -└── references/ # Domain knowledge (what) - ├── reference-a.md - ├── reference-b.md - └── ... -``` -</structure> - -<why_this_works> -## Problems This Solves - -**Problem 1: Context gets skipped** -When important principles are in a separate file, Claude may not read them. -**Solution:** Put essential principles directly in SKILL.md. They load automatically. - -**Problem 2: Wrong context loaded** -A "build" task loads debugging references. A "debug" task loads build references. -**Solution:** Intake question determines intent → routes to specific workflow → workflow specifies which references to read. - -**Problem 3: Monolithic skills are overwhelming** -500+ lines of mixed content makes it hard to find relevant parts. -**Solution:** Small router (SKILL.md) + focused workflows + reference library. - -**Problem 4: Procedures mixed with knowledge** -"How to do X" mixed with "What X means" creates confusion. -**Solution:** Workflows are procedures (steps). References are knowledge (patterns, examples). -</why_this_works> - -<skill_md_template> -## SKILL.md Template - -```markdown ---- -name: skill-name -description: What it does and when to use it. ---- - -<essential_principles> -## How This Skill Works - -[Inline principles that apply to ALL workflows. Cannot be skipped.] - -### Principle 1: [Name] -[Brief explanation] - -### Principle 2: [Name] -[Brief explanation] -</essential_principles> - -<intake> -**Ask the user:** - -What would you like to do? -1. [Option A] -2. [Option B] -3. [Option C] -4. Something else - -**Wait for response before proceeding.** -</intake> - -<routing> -| Response | Workflow | -|----------|----------| -| 1, "keyword", "keyword" | `workflows/option-a.md` | -| 2, "keyword", "keyword" | `workflows/option-b.md` | -| 3, "keyword", "keyword" | `workflows/option-c.md` | -| 4, other | Clarify, then select | - -**After reading the workflow, follow it exactly.** -</routing> - -<reference_index> -All domain knowledge in `references/`: - -**Category A:** file-a.md, file-b.md -**Category B:** file-c.md, file-d.md -</reference_index> - -<workflows_index> -| Workflow | Purpose | -|----------|---------| -| option-a.md | [What it does] | -| option-b.md | [What it does] | -| option-c.md | [What it does] | -</workflows_index> -``` -</skill_md_template> - -<workflow_template> -## Workflow Template - -```markdown -# Workflow: [Name] - -<required_reading> -**Read these reference files NOW:** -1. references/relevant-file.md -2. references/another-file.md -</required_reading> - -<process> -## Step 1: [Name] -[What to do] - -## Step 2: [Name] -[What to do] - -## Step 3: [Name] -[What to do] -</process> - -<success_criteria> -This workflow is complete when: -- [ ] Criterion 1 -- [ ] Criterion 2 -- [ ] Criterion 3 -</success_criteria> -``` -</workflow_template> - -<when_to_use_this_pattern> -## When to Use This Pattern - -**Use router + workflows + references when:** -- Multiple distinct workflows (build vs debug vs ship) -- Different workflows need different references -- Essential principles must not be skipped -- Skill has grown beyond 200 lines - -**Use simple single-file skill when:** -- One workflow -- Small reference set -- Under 200 lines total -- No essential principles to enforce -</when_to_use_this_pattern> - -<key_insight> -## The Key Insight - -**SKILL.md is always loaded. Use this guarantee.** - -Put unavoidable content in SKILL.md: -- Essential principles -- Intake question -- Routing logic - -Put workflow-specific content in workflows/: -- Step-by-step procedures -- Required references for that workflow -- Success criteria for that workflow - -Put reusable knowledge in references/: -- Patterns and examples -- Technical details -- Domain expertise -</key_insight> diff --git a/skills/create-agent-skills/references/skill-structure.md b/skills/create-agent-skills/references/skill-structure.md deleted file mode 100644 index ab8c248..0000000 --- a/skills/create-agent-skills/references/skill-structure.md +++ /dev/null @@ -1,152 +0,0 @@ -# Skill Structure Reference - -Skills have three structural components: YAML frontmatter (metadata), standard markdown body (content), and progressive disclosure (file organization). - -## Body Format - -Use **standard markdown headings** for structure. Keep markdown formatting within content (bold, italic, lists, code blocks, links). - -```markdown ---- -name: my-skill -description: What it does and when to use it ---- - -# Skill Name - -## Quick Start -Immediate actionable guidance... - -## Instructions -Step-by-step procedures... - -## Examples -Concrete usage examples... - -## Guidelines -Rules and constraints... -``` - -## Recommended Sections - -Every skill should have: - -- **Quick Start** - Immediate, actionable guidance (minimal working example) -- **Instructions** - Core step-by-step guidance -- **Success Criteria** - How to know it worked - -Add based on complexity: - -- **Context** - Background/situational information -- **Workflow** - Multi-step procedures -- **Examples** - Concrete input/output pairs -- **Advanced Features** - Deep-dive topics (link to reference files) -- **Anti-Patterns** - Common mistakes to avoid -- **Guidelines** - Rules and constraints - -## YAML Frontmatter - -### Required/Recommended Fields - -```yaml ---- -name: skill-name-here -description: What it does and when to use it (specific triggers included) ---- -``` - -### Name Field - -**Validation rules:** -- Maximum 64 characters -- Lowercase letters, numbers, hyphens only -- Must match directory name -- No reserved words: "anthropic", "claude" - -**Examples:** -- `triage-prs` -- `deploy-production` -- `review-code` -- `setup-stripe-payments` - -**Avoid:** `helper`, `utils`, `tools`, generic names - -### Description Field - -**Validation rules:** -- Maximum 1024 characters -- Include what it does AND when to use it -- Third person voice - -**Good:** -```yaml -description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. -``` - -**Bad:** -```yaml -description: Helps with documents -``` - -### Optional Fields - -| Field | Description | -|-------|-------------| -| `argument-hint` | Usage hints. Example: `[issue-number]` | -| `disable-model-invocation` | `true` to prevent auto-loading. Use for side-effect workflows. | -| `user-invocable` | `false` to hide from `/` menu. Use for background knowledge. | -| `allowed-tools` | Tools without permission prompts. Example: `Read, Bash(git *)` | -| `model` | `haiku`, `sonnet`, or `opus` | -| `context` | `fork` for isolated subagent execution | -| `agent` | Subagent type: `Explore`, `Plan`, `general-purpose`, or custom | - -## Naming Conventions - -Use descriptive names that indicate purpose: - -| Pattern | Examples | -|---------|----------| -| Action-oriented | `triage-prs`, `deploy-production`, `review-code` | -| Domain-specific | `setup-stripe-payments`, `manage-facebook-ads` | -| Descriptive | `git-worktree`, `frontend-design`, `django-patterns` | - -## Progressive Disclosure - -Keep SKILL.md under 500 lines. Split into reference files: - -``` -my-skill/ -├── SKILL.md # Entry point (required, overview + navigation) -├── reference.md # Detailed docs (loaded when needed) -├── examples.md # Usage examples (loaded when needed) -└── scripts/ - └── helper.py # Utility script (executed, not loaded) -``` - -**Rules:** -- Keep references one level deep from SKILL.md -- Add table of contents to reference files over 100 lines -- Use forward slashes in paths: `scripts/helper.py` -- Name files descriptively: `form_validation_rules.md` not `doc2.md` - -## Validation Checklist - -Before finalizing: - -- [ ] YAML frontmatter valid (name matches directory, description specific) -- [ ] Uses standard markdown headings (not XML tags) -- [ ] Has Quick Start, Instructions, and Success Criteria sections -- [ ] `disable-model-invocation: true` if skill has side effects -- [ ] SKILL.md under 500 lines -- [ ] Reference files linked properly from SKILL.md -- [ ] File paths use forward slashes -- [ ] Tested with real usage - -## Anti-Patterns - -- **XML tags in body** - Use standard markdown headings -- **Vague descriptions** - Be specific with trigger keywords -- **Deep nesting** - Keep references one level from SKILL.md -- **Missing invocation control** - Side-effect workflows need `disable-model-invocation: true` -- **Inconsistent naming** - Directory name must match `name` field -- **Windows paths** - Always use forward slashes diff --git a/skills/create-agent-skills/references/using-scripts.md b/skills/create-agent-skills/references/using-scripts.md deleted file mode 100644 index 5d8747c..0000000 --- a/skills/create-agent-skills/references/using-scripts.md +++ /dev/null @@ -1,113 +0,0 @@ -# Using Scripts in Skills - -<purpose> -Scripts are executable code that Claude runs as-is rather than regenerating each time. They ensure reliable, error-free execution of repeated operations. -</purpose> - -<when_to_use> -Use scripts when: -- The same code runs across multiple skill invocations -- Operations are error-prone when rewritten from scratch -- Complex shell commands or API interactions are involved -- Consistency matters more than flexibility - -Common script types: -- **Deployment** - Deploy to Vercel, publish packages, push releases -- **Setup** - Initialize projects, install dependencies, configure environments -- **API calls** - Authenticated requests, webhook handlers, data fetches -- **Data processing** - Transform files, batch operations, migrations -- **Build processes** - Compile, bundle, test runners -</when_to_use> - -<script_structure> -Scripts live in `scripts/` within the skill directory: - -``` -skill-name/ -├── SKILL.md -├── workflows/ -├── references/ -├── templates/ -└── scripts/ - ├── deploy.sh - ├── setup.py - └── fetch-data.ts -``` - -A well-structured script includes: -1. Clear purpose comment at top -2. Input validation -3. Error handling -4. Idempotent operations where possible -5. Clear output/feedback -</script_structure> - -<script_example> -```bash -#!/bin/bash -# deploy.sh - Deploy project to Vercel -# Usage: ./deploy.sh [environment] -# Environments: preview (default), production - -set -euo pipefail - -ENVIRONMENT="${1:-preview}" - -# Validate environment -if [[ "$ENVIRONMENT" != "preview" && "$ENVIRONMENT" != "production" ]]; then - echo "Error: Environment must be 'preview' or 'production'" - exit 1 -fi - -echo "Deploying to $ENVIRONMENT..." - -if [[ "$ENVIRONMENT" == "production" ]]; then - vercel --prod -else - vercel -fi - -echo "Deployment complete." -``` -</script_example> - -<workflow_integration> -Workflows reference scripts like this: - -```xml -<process> -## Step 5: Deploy - -1. Ensure all tests pass -2. Run `scripts/deploy.sh production` -3. Verify deployment succeeded -4. Update user with deployment URL -</process> -``` - -The workflow tells Claude WHEN to run the script. The script handles HOW the operation executes. -</workflow_integration> - -<best_practices> -**Do:** -- Make scripts idempotent (safe to run multiple times) -- Include clear usage comments -- Validate inputs before executing -- Provide meaningful error messages -- Use `set -euo pipefail` in bash scripts - -**Don't:** -- Hardcode secrets or credentials (use environment variables) -- Create scripts for one-off operations -- Skip error handling -- Make scripts do too many unrelated things -- Forget to make scripts executable (`chmod +x`) -</best_practices> - -<security_considerations> -- Never embed API keys, tokens, or secrets in scripts -- Use environment variables for sensitive configuration -- Validate and sanitize any user-provided inputs -- Be cautious with scripts that delete or modify data -- Consider adding `--dry-run` options for destructive operations -</security_considerations> diff --git a/skills/create-agent-skills/references/using-templates.md b/skills/create-agent-skills/references/using-templates.md deleted file mode 100644 index 6afe577..0000000 --- a/skills/create-agent-skills/references/using-templates.md +++ /dev/null @@ -1,112 +0,0 @@ -# Using Templates in Skills - -<purpose> -Templates are reusable output structures that Claude copies and fills in. They ensure consistent, high-quality outputs without regenerating structure each time. -</purpose> - -<when_to_use> -Use templates when: -- Output should have consistent structure across invocations -- The structure matters more than creative generation -- Filling placeholders is more reliable than blank-page generation -- Users expect predictable, professional-looking outputs - -Common template types: -- **Plans** - Project plans, implementation plans, migration plans -- **Specifications** - Technical specs, feature specs, API specs -- **Documents** - Reports, proposals, summaries -- **Configurations** - Config files, settings, environment setups -- **Scaffolds** - File structures, boilerplate code -</when_to_use> - -<template_structure> -Templates live in `templates/` within the skill directory: - -``` -skill-name/ -├── SKILL.md -├── workflows/ -├── references/ -└── templates/ - ├── plan-template.md - ├── spec-template.md - └── report-template.md -``` - -A template file contains: -1. Clear section markers -2. Placeholder indicators (use `{{placeholder}}` or `[PLACEHOLDER]`) -3. Inline guidance for what goes where -4. Example content where helpful -</template_structure> - -<template_example> -```markdown -# {{PROJECT_NAME}} Implementation Plan - -## Overview -{{1-2 sentence summary of what this plan covers}} - -## Goals -- {{Primary goal}} -- {{Secondary goals...}} - -## Scope -**In scope:** -- {{What's included}} - -**Out of scope:** -- {{What's explicitly excluded}} - -## Phases - -### Phase 1: {{Phase name}} -**Duration:** {{Estimated duration}} -**Deliverables:** -- {{Deliverable 1}} -- {{Deliverable 2}} - -### Phase 2: {{Phase name}} -... - -## Success Criteria -- [ ] {{Measurable criterion 1}} -- [ ] {{Measurable criterion 2}} - -## Risks -| Risk | Likelihood | Impact | Mitigation | -|------|------------|--------|------------| -| {{Risk}} | {{H/M/L}} | {{H/M/L}} | {{Strategy}} | -``` -</template_example> - -<workflow_integration> -Workflows reference templates like this: - -```xml -<process> -## Step 3: Generate Plan - -1. Read `templates/plan-template.md` -2. Copy the template structure -3. Fill each placeholder based on gathered requirements -4. Review for completeness -</process> -``` - -The workflow tells Claude WHEN to use the template. The template provides WHAT structure to produce. -</workflow_integration> - -<best_practices> -**Do:** -- Keep templates focused on structure, not content -- Use clear placeholder syntax consistently -- Include brief inline guidance where sections might be ambiguous -- Make templates complete but minimal - -**Don't:** -- Put excessive example content that might be copied verbatim -- Create templates for outputs that genuinely need creative generation -- Over-constrain with too many required sections -- Forget to update templates when requirements change -</best_practices> diff --git a/skills/create-agent-skills/references/workflows-and-validation.md b/skills/create-agent-skills/references/workflows-and-validation.md deleted file mode 100644 index d3fef63..0000000 --- a/skills/create-agent-skills/references/workflows-and-validation.md +++ /dev/null @@ -1,510 +0,0 @@ -<overview> -This reference covers patterns for complex workflows, validation loops, and feedback cycles in skill authoring. All patterns use pure XML structure. -</overview> - -<complex_workflows> -<principle> -Break complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist. -</principle> - -<pdf_forms_example> -```xml -<objective> -Fill PDF forms with validated data from JSON field mappings. -</objective> - -<workflow> -Copy this checklist and check off items as you complete them: - -``` -Task Progress: -- [ ] Step 1: Analyze the form (run analyze_form.py) -- [ ] Step 2: Create field mapping (edit fields.json) -- [ ] Step 3: Validate mapping (run validate_fields.py) -- [ ] Step 4: Fill the form (run fill_form.py) -- [ ] Step 5: Verify output (run verify_output.py) -``` - -<step_1> -**Analyze the form** - -Run: `python scripts/analyze_form.py input.pdf` - -This extracts form fields and their locations, saving to `fields.json`. -</step_1> - -<step_2> -**Create field mapping** - -Edit `fields.json` to add values for each field. -</step_2> - -<step_3> -**Validate mapping** - -Run: `python scripts/validate_fields.py fields.json` - -Fix any validation errors before continuing. -</step_3> - -<step_4> -**Fill the form** - -Run: `python scripts/fill_form.py input.pdf fields.json output.pdf` -</step_4> - -<step_5> -**Verify output** - -Run: `python scripts/verify_output.py output.pdf` - -If verification fails, return to Step 2. -</step_5> -</workflow> -``` -</pdf_forms_example> - -<when_to_use> -Use checklist pattern when: -- Workflow has 5+ sequential steps -- Steps must be completed in order -- Progress tracking helps prevent errors -- Easy resumption after interruption is valuable -</when_to_use> -</complex_workflows> - -<feedback_loops> -<validate_fix_repeat_pattern> -<principle> -Run validator → fix errors → repeat. This pattern greatly improves output quality. -</principle> - -<document_editing_example> -```xml -<objective> -Edit OOXML documents with XML validation at each step. -</objective> - -<editing_process> -<step_1> -Make your edits to `word/document.xml` -</step_1> - -<step_2> -**Validate immediately**: `python ooxml/scripts/validate.py unpacked_dir/` -</step_2> - -<step_3> -If validation fails: -- Review the error message carefully -- Fix the issues in the XML -- Run validation again -</step_3> - -<step_4> -**Only proceed when validation passes** -</step_4> - -<step_5> -Rebuild: `python ooxml/scripts/pack.py unpacked_dir/ output.docx` -</step_5> - -<step_6> -Test the output document -</step_6> -</editing_process> - -<validation> -Never skip validation. Catching errors early prevents corrupted output files. -</validation> -``` -</document_editing_example> - -<why_it_works> -- Catches errors early before changes are applied -- Machine-verifiable with objective verification -- Plan can be iterated without touching originals -- Reduces total iteration cycles -</why_it_works> -</validate_fix_repeat_pattern> - -<plan_validate_execute_pattern> -<principle> -When Claude performs complex, open-ended tasks, create a plan in a structured format, validate it, then execute. - -Workflow: analyze → **create plan file** → **validate plan** → execute → verify -</principle> - -<batch_update_example> -```xml -<objective> -Apply batch updates to spreadsheet with plan validation. -</objective> - -<workflow> -<plan_phase> -<step_1> -Analyze the spreadsheet and requirements -</step_1> - -<step_2> -Create `changes.json` with all planned updates -</step_2> -</plan_phase> - -<validation_phase> -<step_3> -Validate the plan: `python scripts/validate_changes.py changes.json` -</step_3> - -<step_4> -If validation fails: -- Review error messages -- Fix issues in changes.json -- Validate again -</step_4> - -<step_5> -Only proceed when validation passes -</step_5> -</validation_phase> - -<execution_phase> -<step_6> -Apply changes: `python scripts/apply_changes.py changes.json` -</step_6> - -<step_7> -Verify output -</step_7> -</execution_phase> -</workflow> - -<success_criteria> -- Plan validation passes with zero errors -- All changes applied successfully -- Output verification confirms expected results -</success_criteria> -``` -</batch_update_example> - -<implementation_tip> -Make validation scripts verbose with specific error messages: - -**Good error message**: -"Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" - -**Bad error message**: -"Invalid field" - -Specific errors help Claude fix issues without guessing. -</implementation_tip> - -<when_to_use> -Use plan-validate-execute when: -- Operations are complex and error-prone -- Changes are irreversible or difficult to undo -- Planning can be validated independently -- Catching errors early saves significant time -</when_to_use> -</plan_validate_execute_pattern> -</feedback_loops> - -<conditional_workflows> -<principle> -Guide Claude through decision points with clear branching logic. -</principle> - -<document_modification_example> -```xml -<objective> -Modify DOCX files using appropriate method based on task type. -</objective> - -<workflow> -<decision_point_1> -Determine the modification type: - -**Creating new content?** → Follow "Creation workflow" -**Editing existing content?** → Follow "Editing workflow" -</decision_point_1> - -<creation_workflow> -<objective>Build documents from scratch</objective> - -<steps> -1. Use docx-js library -2. Build document from scratch -3. Export to .docx format -</steps> -</creation_workflow> - -<editing_workflow> -<objective>Modify existing documents</objective> - -<steps> -1. Unpack existing document -2. Modify XML directly -3. Validate after each change -4. Repack when complete -</steps> -</editing_workflow> -</workflow> - -<success_criteria> -- Correct workflow chosen based on task type -- All steps in chosen workflow completed -- Output file validated and verified -</success_criteria> -``` -</document_modification_example> - -<when_to_use> -Use conditional workflows when: -- Different task types require different approaches -- Decision points are clear and well-defined -- Workflows are mutually exclusive -- Guiding Claude to correct path improves outcomes -</when_to_use> -</conditional_workflows> - -<validation_scripts> -<principles> -Validation scripts are force multipliers. They catch errors that Claude might miss and provide actionable feedback for fixing issues. -</principles> - -<characteristics_of_good_validation> -<verbose_errors> -**Good**: "Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" - -**Bad**: "Invalid field" - -Verbose errors help Claude fix issues in one iteration instead of multiple rounds of guessing. -</verbose_errors> - -<specific_feedback> -**Good**: "Line 47: Expected closing tag `</paragraph>` but found `</section>`" - -**Bad**: "XML syntax error" - -Specific feedback pinpoints exact location and nature of the problem. -</specific_feedback> - -<actionable_suggestions> -**Good**: "Required field 'customer_name' is missing. Add: {\"customer_name\": \"value\"}" - -**Bad**: "Missing required field" - -Actionable suggestions show Claude exactly what to fix. -</actionable_suggestions> - -<available_options> -When validation fails, show available valid options: - -**Good**: "Invalid status 'pending_review'. Valid statuses: active, paused, archived" - -**Bad**: "Invalid status" - -Showing valid options eliminates guesswork. -</available_options> -</characteristics_of_good_validation> - -<implementation_pattern> -```xml -<validation> -After making changes, validate immediately: - -```bash -python scripts/validate.py output_dir/ -``` - -If validation fails, fix errors before continuing. Validation errors include: - -- **Field not found**: "Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" -- **Type mismatch**: "Field 'order_total' expects number, got string" -- **Missing required field**: "Required field 'customer_name' is missing" -- **Invalid value**: "Invalid status 'pending_review'. Valid statuses: active, paused, archived" - -Only proceed when validation passes with zero errors. -</validation> -``` -</implementation_pattern> - -<benefits> -- Catches errors before they propagate -- Reduces iteration cycles -- Provides learning feedback -- Makes debugging deterministic -- Enables confident execution -</benefits> -</validation_scripts> - -<iterative_refinement> -<principle> -Many workflows benefit from iteration: generate → validate → refine → validate → finalize. -</principle> - -<implementation_example> -```xml -<objective> -Generate reports with iterative quality improvement. -</objective> - -<workflow> -<iteration_1> -**Generate initial draft** - -Create report based on data and requirements. -</iteration_1> - -<iteration_2> -**Validate draft** - -Run: `python scripts/validate_report.py draft.md` - -Fix any structural issues, missing sections, or data errors. -</iteration_2> - -<iteration_3> -**Refine content** - -Improve clarity, add supporting data, enhance visualizations. -</iteration_3> - -<iteration_4> -**Final validation** - -Run: `python scripts/validate_report.py final.md` - -Ensure all quality criteria met. -</iteration_4> - -<iteration_5> -**Finalize** - -Export to final format and deliver. -</iteration_5> -</workflow> - -<success_criteria> -- Final validation passes with zero errors -- All quality criteria met -- Report ready for delivery -</success_criteria> -``` -</implementation_example> - -<when_to_use> -Use iterative refinement when: -- Quality improves with multiple passes -- Validation provides actionable feedback -- Time permits iteration -- Perfect output matters more than speed -</when_to_use> -</iterative_refinement> - -<checkpoint_pattern> -<principle> -For long workflows, add checkpoints where Claude can pause and verify progress before continuing. -</principle> - -<implementation_example> -```xml -<workflow> -<phase_1> -**Data collection** (Steps 1-3) - -1. Extract data from source -2. Transform to target format -3. **CHECKPOINT**: Verify data completeness - -Only continue if checkpoint passes. -</phase_1> - -<phase_2> -**Data processing** (Steps 4-6) - -4. Apply business rules -5. Validate transformations -6. **CHECKPOINT**: Verify processing accuracy - -Only continue if checkpoint passes. -</phase_2> - -<phase_3> -**Output generation** (Steps 7-9) - -7. Generate output files -8. Validate output format -9. **CHECKPOINT**: Verify final output - -Proceed to delivery only if checkpoint passes. -</phase_3> -</workflow> - -<checkpoint_validation> -At each checkpoint: -1. Run validation script -2. Review output for correctness -3. Verify no errors or warnings -4. Only proceed when validation passes -</checkpoint_validation> -``` -</implementation_example> - -<benefits> -- Prevents cascading errors -- Easier to diagnose issues -- Clear progress indicators -- Natural pause points for review -- Reduces wasted work from early errors -</benefits> -</checkpoint_pattern> - -<error_recovery> -<principle> -Design workflows with clear error recovery paths. Claude should know what to do when things go wrong. -</principle> - -<implementation_example> -```xml -<workflow> -<normal_path> -1. Process input file -2. Validate output -3. Save results -</normal_path> - -<error_recovery> -**If validation fails in step 2:** -- Review validation errors -- Check if input file is corrupted → Return to step 1 with different input -- Check if processing logic failed → Fix logic, return to step 1 -- Check if output format wrong → Fix format, return to step 2 - -**If save fails in step 3:** -- Check disk space -- Check file permissions -- Check file path validity -- Retry save with corrected conditions -</error_recovery> - -<escalation> -**If error persists after 3 attempts:** -- Document the error with full context -- Save partial results if available -- Report issue to user with diagnostic information -</escalation> -</workflow> -``` -</implementation_example> - -<when_to_use> -Include error recovery when: -- Workflows interact with external systems -- File operations could fail -- Network calls could timeout -- User input could be invalid -- Errors are recoverable -</when_to_use> -</error_recovery> diff --git a/skills/create-agent-skills/templates/router-skill.md b/skills/create-agent-skills/templates/router-skill.md deleted file mode 100644 index b2dc762..0000000 --- a/skills/create-agent-skills/templates/router-skill.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -name: {{SKILL_NAME}} -description: {{What it does}} Use when {{trigger conditions}}. ---- - -<essential_principles> -## {{Core Concept}} - -{{Principles that ALWAYS apply, regardless of which workflow runs}} - -### 1. {{First principle}} -{{Explanation}} - -### 2. {{Second principle}} -{{Explanation}} - -### 3. {{Third principle}} -{{Explanation}} -</essential_principles> - -<intake> -**Ask the user:** - -What would you like to do? -1. {{First option}} -2. {{Second option}} -3. {{Third option}} - -**Wait for response before proceeding.** -</intake> - -<routing> -| Response | Workflow | -|----------|----------| -| 1, "{{keywords}}" | `workflows/{{first-workflow}}.md` | -| 2, "{{keywords}}" | `workflows/{{second-workflow}}.md` | -| 3, "{{keywords}}" | `workflows/{{third-workflow}}.md` | - -**After reading the workflow, follow it exactly.** -</routing> - -<quick_reference> -## {{Skill Name}} Quick Reference - -{{Brief reference information always useful to have visible}} -</quick_reference> - -<reference_index> -## Domain Knowledge - -All in `references/`: -- {{reference-1.md}} - {{purpose}} -- {{reference-2.md}} - {{purpose}} -</reference_index> - -<workflows_index> -## Workflows - -All in `workflows/`: - -| Workflow | Purpose | -|----------|---------| -| {{first-workflow}}.md | {{purpose}} | -| {{second-workflow}}.md | {{purpose}} | -| {{third-workflow}}.md | {{purpose}} | -</workflows_index> - -<success_criteria> -A well-executed {{skill name}}: -- {{First criterion}} -- {{Second criterion}} -- {{Third criterion}} -</success_criteria> diff --git a/skills/create-agent-skills/templates/simple-skill.md b/skills/create-agent-skills/templates/simple-skill.md deleted file mode 100644 index 6678fa7..0000000 --- a/skills/create-agent-skills/templates/simple-skill.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: {{SKILL_NAME}} -description: {{What it does}} Use when {{trigger conditions}}. ---- - -<objective> -{{Clear statement of what this skill accomplishes}} -</objective> - -<quick_start> -{{Immediate actionable guidance - what Claude should do first}} -</quick_start> - -<process> -## Step 1: {{First action}} - -{{Instructions for step 1}} - -## Step 2: {{Second action}} - -{{Instructions for step 2}} - -## Step 3: {{Third action}} - -{{Instructions for step 3}} -</process> - -<success_criteria> -{{Skill name}} is complete when: -- [ ] {{First success criterion}} -- [ ] {{Second success criterion}} -- [ ] {{Third success criterion}} -</success_criteria> diff --git a/skills/create-agent-skills/workflows/add-reference.md b/skills/create-agent-skills/workflows/add-reference.md deleted file mode 100644 index 4a26adb..0000000 --- a/skills/create-agent-skills/workflows/add-reference.md +++ /dev/null @@ -1,96 +0,0 @@ -# Workflow: Add a Reference to Existing Skill - -<required_reading> -**Read these reference files NOW:** -1. references/recommended-structure.md -2. references/skill-structure.md -</required_reading> - -<process> -## Step 1: Select the Skill - -```bash -ls ~/.claude/skills/ -``` - -Present numbered list, ask: "Which skill needs a new reference?" - -## Step 2: Analyze Current Structure - -```bash -cat ~/.claude/skills/{skill-name}/SKILL.md -ls ~/.claude/skills/{skill-name}/references/ 2>/dev/null -``` - -Determine: -- **Has references/ folder?** → Good, can add directly -- **Simple skill?** → May need to create references/ first -- **What references exist?** → Understand the knowledge landscape - -Report current references to user. - -## Step 3: Gather Reference Requirements - -Ask: -- What knowledge should this reference contain? -- Which workflows will use it? -- Is this reusable across workflows or specific to one? - -**If specific to one workflow** → Consider putting it inline in that workflow instead. - -## Step 4: Create the Reference File - -Create `references/{reference-name}.md`: - -Use semantic XML tags to structure the content: -```xml -<overview> -Brief description of what this reference covers -</overview> - -<patterns> -## Common Patterns -[Reusable patterns, examples, code snippets] -</patterns> - -<guidelines> -## Guidelines -[Best practices, rules, constraints] -</guidelines> - -<examples> -## Examples -[Concrete examples with explanation] -</examples> -``` - -## Step 5: Update SKILL.md - -Add the new reference to `<reference_index>`: -```markdown -**Category:** existing.md, new-reference.md -``` - -## Step 6: Update Workflows That Need It - -For each workflow that should use this reference: - -1. Read the workflow file -2. Add to its `<required_reading>` section -3. Verify the workflow still makes sense with this addition - -## Step 7: Verify - -- [ ] Reference file exists and is well-structured -- [ ] Reference is in SKILL.md reference_index -- [ ] Relevant workflows have it in required_reading -- [ ] No broken references -</process> - -<success_criteria> -Reference addition is complete when: -- [ ] Reference file created with useful content -- [ ] Added to reference_index in SKILL.md -- [ ] Relevant workflows updated to read it -- [ ] Content is reusable (not workflow-specific) -</success_criteria> diff --git a/skills/create-agent-skills/workflows/add-script.md b/skills/create-agent-skills/workflows/add-script.md deleted file mode 100644 index fb77806..0000000 --- a/skills/create-agent-skills/workflows/add-script.md +++ /dev/null @@ -1,93 +0,0 @@ -# Workflow: Add a Script to a Skill - -<required_reading> -**Read these reference files NOW:** -1. references/using-scripts.md -</required_reading> - -<process> -## Step 1: Identify the Skill - -Ask (if not already provided): -- Which skill needs a script? -- What operation should the script perform? - -## Step 2: Analyze Script Need - -Confirm this is a good script candidate: -- [ ] Same code runs across multiple invocations -- [ ] Operation is error-prone when rewritten -- [ ] Consistency matters more than flexibility - -If not a good fit, suggest alternatives (inline code in workflow, reference examples). - -## Step 3: Create Scripts Directory - -```bash -mkdir -p ~/.claude/skills/{skill-name}/scripts -``` - -## Step 4: Design Script - -Gather requirements: -- What inputs does the script need? -- What should it output or accomplish? -- What errors might occur? -- Should it be idempotent? - -Choose language: -- **bash** - Shell operations, file manipulation, CLI tools -- **python** - Data processing, API calls, complex logic -- **node/ts** - JavaScript ecosystem, async operations - -## Step 5: Write Script File - -Create `scripts/{script-name}.{ext}` with: -- Purpose comment at top -- Usage instructions -- Input validation -- Error handling -- Clear output/feedback - -For bash scripts: -```bash -#!/bin/bash -set -euo pipefail -``` - -## Step 6: Make Executable (if bash) - -```bash -chmod +x ~/.claude/skills/{skill-name}/scripts/{script-name}.sh -``` - -## Step 7: Update Workflow to Use Script - -Find the workflow that needs this operation. Add: -```xml -<process> -... -N. Run `scripts/{script-name}.sh [arguments]` -N+1. Verify operation succeeded -... -</process> -``` - -## Step 8: Test - -Invoke the skill workflow and verify: -- Script runs at the right step -- Inputs are passed correctly -- Errors are handled gracefully -- Output matches expectations -</process> - -<success_criteria> -Script is complete when: -- [ ] scripts/ directory exists -- [ ] Script file has proper structure (comments, validation, error handling) -- [ ] Script is executable (if bash) -- [ ] At least one workflow references the script -- [ ] No hardcoded secrets or credentials -- [ ] Tested with real invocation -</success_criteria> diff --git a/skills/create-agent-skills/workflows/add-template.md b/skills/create-agent-skills/workflows/add-template.md deleted file mode 100644 index 8481a2c..0000000 --- a/skills/create-agent-skills/workflows/add-template.md +++ /dev/null @@ -1,74 +0,0 @@ -# Workflow: Add a Template to a Skill - -<required_reading> -**Read these reference files NOW:** -1. references/using-templates.md -</required_reading> - -<process> -## Step 1: Identify the Skill - -Ask (if not already provided): -- Which skill needs a template? -- What output does this template structure? - -## Step 2: Analyze Template Need - -Confirm this is a good template candidate: -- [ ] Output has consistent structure across uses -- [ ] Structure matters more than creative generation -- [ ] Filling placeholders is more reliable than blank-page generation - -If not a good fit, suggest alternatives (workflow guidance, reference examples). - -## Step 3: Create Templates Directory - -```bash -mkdir -p ~/.claude/skills/{skill-name}/templates -``` - -## Step 4: Design Template Structure - -Gather requirements: -- What sections does the output need? -- What information varies between uses? (→ placeholders) -- What stays constant? (→ static structure) - -## Step 5: Write Template File - -Create `templates/{template-name}.md` with: -- Clear section markers -- `{{PLACEHOLDER}}` syntax for variable content -- Brief inline guidance where helpful -- Minimal example content - -## Step 6: Update Workflow to Use Template - -Find the workflow that produces this output. Add: -```xml -<process> -... -N. Read `templates/{template-name}.md` -N+1. Copy template structure -N+2. Fill each placeholder based on gathered context -... -</process> -``` - -## Step 7: Test - -Invoke the skill workflow and verify: -- Template is read at the right step -- All placeholders get filled appropriately -- Output structure matches template -- No placeholders left unfilled -</process> - -<success_criteria> -Template is complete when: -- [ ] templates/ directory exists -- [ ] Template file has clear structure with placeholders -- [ ] At least one workflow references the template -- [ ] Workflow instructions explain when/how to use template -- [ ] Tested with real invocation -</success_criteria> diff --git a/skills/create-agent-skills/workflows/add-workflow.md b/skills/create-agent-skills/workflows/add-workflow.md deleted file mode 100644 index f53e9cf..0000000 --- a/skills/create-agent-skills/workflows/add-workflow.md +++ /dev/null @@ -1,120 +0,0 @@ -# Workflow: Add a Workflow to Existing Skill - -<required_reading> -**Read these reference files NOW:** -1. references/recommended-structure.md -2. references/workflows-and-validation.md -</required_reading> - -<process> -## Step 1: Select the Skill - -**DO NOT use AskUserQuestion** - there may be many skills. - -```bash -ls ~/.claude/skills/ -``` - -Present numbered list, ask: "Which skill needs a new workflow?" - -## Step 2: Analyze Current Structure - -Read the skill: -```bash -cat ~/.claude/skills/{skill-name}/SKILL.md -ls ~/.claude/skills/{skill-name}/workflows/ 2>/dev/null -``` - -Determine: -- **Simple skill?** → May need to upgrade to router pattern first -- **Already has workflows/?** → Good, can add directly -- **What workflows exist?** → Avoid duplication - -Report current structure to user. - -## Step 3: Gather Workflow Requirements - -Ask using AskUserQuestion or direct question: -- What should this workflow do? -- When would someone use it vs existing workflows? -- What references would it need? - -## Step 4: Upgrade to Router Pattern (if needed) - -**If skill is currently simple (no workflows/):** - -Ask: "This skill needs to be upgraded to the router pattern first. Should I restructure it?" - -If yes: -1. Create workflows/ directory -2. Move existing process content to workflows/main.md -3. Rewrite SKILL.md as router with intake + routing -4. Verify structure works before proceeding - -## Step 5: Create the Workflow File - -Create `workflows/{workflow-name}.md`: - -```markdown -# Workflow: {Workflow Name} - -<required_reading> -**Read these reference files NOW:** -1. references/{relevant-file}.md -</required_reading> - -<process> -## Step 1: {First Step} -[What to do] - -## Step 2: {Second Step} -[What to do] - -## Step 3: {Third Step} -[What to do] -</process> - -<success_criteria> -This workflow is complete when: -- [ ] Criterion 1 -- [ ] Criterion 2 -- [ ] Criterion 3 -</success_criteria> -``` - -## Step 6: Update SKILL.md - -Add the new workflow to: - -1. **Intake question** - Add new option -2. **Routing table** - Map option to workflow file -3. **Workflows index** - Add to the list - -## Step 7: Create References (if needed) - -If the workflow needs domain knowledge that doesn't exist: -1. Create `references/{reference-name}.md` -2. Add to reference_index in SKILL.md -3. Reference it in the workflow's required_reading - -## Step 8: Test - -Invoke the skill: -- Does the new option appear in intake? -- Does selecting it route to the correct workflow? -- Does the workflow load the right references? -- Does the workflow execute correctly? - -Report results to user. -</process> - -<success_criteria> -Workflow addition is complete when: -- [ ] Skill upgraded to router pattern (if needed) -- [ ] Workflow file created with required_reading, process, success_criteria -- [ ] SKILL.md intake updated with new option -- [ ] SKILL.md routing updated -- [ ] SKILL.md workflows_index updated -- [ ] Any needed references created -- [ ] Tested and working -</success_criteria> diff --git a/skills/create-agent-skills/workflows/audit-skill.md b/skills/create-agent-skills/workflows/audit-skill.md deleted file mode 100644 index 364f78e..0000000 --- a/skills/create-agent-skills/workflows/audit-skill.md +++ /dev/null @@ -1,138 +0,0 @@ -# Workflow: Audit a Skill - -<required_reading> -**Read these reference files NOW:** -1. references/recommended-structure.md -2. references/skill-structure.md -3. references/use-xml-tags.md -</required_reading> - -<process> -## Step 1: List Available Skills - -**DO NOT use AskUserQuestion** - there may be many skills. - -Enumerate skills in chat as numbered list: -```bash -ls ~/.claude/skills/ -``` - -Present as: -``` -Available skills: -1. create-agent-skills -2. build-macos-apps -3. manage-stripe -... -``` - -Ask: "Which skill would you like to audit? (enter number or name)" - -## Step 2: Read the Skill - -After user selects, read the full skill structure: -```bash -# Read main file -cat ~/.claude/skills/{skill-name}/SKILL.md - -# Check for workflows and references -ls ~/.claude/skills/{skill-name}/ -ls ~/.claude/skills/{skill-name}/workflows/ 2>/dev/null -ls ~/.claude/skills/{skill-name}/references/ 2>/dev/null -``` - -## Step 3: Run Audit Checklist - -Evaluate against each criterion: - -### YAML Frontmatter -- [ ] Has `name:` field (lowercase-with-hyphens) -- [ ] Name matches directory name -- [ ] Has `description:` field -- [ ] Description says what it does AND when to use it -- [ ] Description is third person ("Use when...") - -### Structure -- [ ] SKILL.md under 500 lines -- [ ] Pure XML structure (no markdown headings # in body) -- [ ] All XML tags properly closed -- [ ] Has required tags: objective OR essential_principles -- [ ] Has success_criteria - -### Router Pattern (if complex skill) -- [ ] Essential principles inline in SKILL.md (not in separate file) -- [ ] Has intake question -- [ ] Has routing table -- [ ] All referenced workflow files exist -- [ ] All referenced reference files exist - -### Workflows (if present) -- [ ] Each has required_reading section -- [ ] Each has process section -- [ ] Each has success_criteria section -- [ ] Required reading references exist - -### Content Quality -- [ ] Principles are actionable (not vague platitudes) -- [ ] Steps are specific (not "do the thing") -- [ ] Success criteria are verifiable -- [ ] No redundant content across files - -## Step 4: Generate Report - -Present findings as: - -``` -## Audit Report: {skill-name} - -### ✅ Passing -- [list passing items] - -### ⚠️ Issues Found -1. **[Issue name]**: [Description] - → Fix: [Specific action] - -2. **[Issue name]**: [Description] - → Fix: [Specific action] - -### 📊 Score: X/Y criteria passing -``` - -## Step 5: Offer Fixes - -If issues found, ask: -"Would you like me to fix these issues?" - -Options: -1. **Fix all** - Apply all recommended fixes -2. **Fix one by one** - Review each fix before applying -3. **Just the report** - No changes needed - -If fixing: -- Make each change -- Verify file validity after each change -- Report what was fixed -</process> - -<audit_anti_patterns> -## Common Anti-Patterns to Flag - -**Skippable principles**: Essential principles in separate file instead of inline -**Monolithic skill**: Single file over 500 lines -**Mixed concerns**: Procedures and knowledge in same file -**Vague steps**: "Handle the error appropriately" -**Untestable criteria**: "User is satisfied" -**Markdown headings in body**: Using # instead of XML tags -**Missing routing**: Complex skill without intake/routing -**Broken references**: Files mentioned but don't exist -**Redundant content**: Same information in multiple places -</audit_anti_patterns> - -<success_criteria> -Audit is complete when: -- [ ] Skill fully read and analyzed -- [ ] All checklist items evaluated -- [ ] Report presented to user -- [ ] Fixes applied (if requested) -- [ ] User has clear picture of skill health -</success_criteria> diff --git a/skills/create-agent-skills/workflows/create-domain-expertise-skill.md b/skills/create-agent-skills/workflows/create-domain-expertise-skill.md deleted file mode 100644 index 8eaed0c..0000000 --- a/skills/create-agent-skills/workflows/create-domain-expertise-skill.md +++ /dev/null @@ -1,605 +0,0 @@ -# Workflow: Create Exhaustive Domain Expertise Skill - -<objective> -Build a comprehensive execution skill that does real work in a specific domain. Domain expertise skills are full-featured build skills with exhaustive domain knowledge in references, complete workflows for the full lifecycle (build → debug → optimize → ship), and can be both invoked directly by users AND loaded by other skills (like create-plans) for domain knowledge. -</objective> - -<critical_distinction> -**Regular skill:** "Do one specific task" -**Domain expertise skill:** "Do EVERYTHING in this domain, with complete practitioner knowledge" - -Examples: -- `expertise/macos-apps` - Build macOS apps from scratch through shipping -- `expertise/python-games` - Build complete Python games with full game dev lifecycle -- `expertise/rust-systems` - Build Rust systems programs with exhaustive systems knowledge -- `expertise/web-scraping` - Build scrapers, handle all edge cases, deploy at scale - -Domain expertise skills: -- ✅ Execute tasks (build, debug, optimize, ship) -- ✅ Have comprehensive domain knowledge in references -- ✅ Are invoked directly by users ("build a macOS app") -- ✅ Can be loaded by other skills (create-plans reads references for planning) -- ✅ Cover the FULL lifecycle, not just getting started -</critical_distinction> - -<required_reading> -**Read these reference files NOW:** -1. references/recommended-structure.md -2. references/core-principles.md -3. references/use-xml-tags.md -</required_reading> - -<process> -## Step 1: Identify Domain - -Ask user what domain expertise to build: - -**Example domains:** -- macOS/iOS app development -- Python game development -- Rust systems programming -- Machine learning / AI -- Web scraping and automation -- Data engineering pipelines -- Audio processing / DSP -- 3D graphics / shaders -- Unity/Unreal game development -- Embedded systems - -Get specific: "Python games" or "Python games with Pygame specifically"? - -## Step 2: Confirm Target Location - -Explain: -``` -Domain expertise skills go in: ~/.claude/skills/expertise/{domain-name}/ - -These are comprehensive BUILD skills that: -- Execute tasks (build, debug, optimize, ship) -- Contain exhaustive domain knowledge -- Can be invoked directly by users -- Can be loaded by other skills for domain knowledge - -Name suggestion: {suggested-name} -Location: ~/.claude/skills/expertise/{suggested-name}/ -``` - -Confirm or adjust name. - -## Step 3: Identify Workflows - -Domain expertise skills cover the FULL lifecycle. Identify what workflows are needed. - -**Common workflows for most domains:** -1. **build-new-{thing}.md** - Create from scratch -2. **add-feature.md** - Extend existing {thing} -3. **debug-{thing}.md** - Find and fix bugs -4. **write-tests.md** - Test for correctness -5. **optimize-performance.md** - Profile and speed up -6. **ship-{thing}.md** - Deploy/distribute - -**Domain-specific workflows:** -- Games: `implement-game-mechanic.md`, `add-audio.md`, `polish-ui.md` -- Web apps: `setup-auth.md`, `add-api-endpoint.md`, `setup-database.md` -- Systems: `optimize-memory.md`, `profile-cpu.md`, `cross-compile.md` - -Each workflow = one complete task type that users actually do. - -## Step 4: Exhaustive Research Phase - -**CRITICAL:** This research must be comprehensive, not superficial. - -### Research Strategy - -Run multiple web searches to ensure coverage: - -**Search 1: Current ecosystem** -- "best {domain} libraries 2024 2025 2026" -- "popular {domain} frameworks comparison" -- "{domain} tech stack recommendations" - -**Search 2: Architecture patterns** -- "{domain} architecture patterns" -- "{domain} best practices design patterns" -- "how to structure {domain} projects" - -**Search 3: Lifecycle and tooling** -- "{domain} development workflow" -- "{domain} testing debugging best practices" -- "{domain} deployment distribution" - -**Search 4: Common pitfalls** -- "{domain} common mistakes avoid" -- "{domain} anti-patterns" -- "what not to do {domain}" - -**Search 5: Real-world usage** -- "{domain} production examples GitHub" -- "{domain} case studies" -- "successful {domain} projects" - -### Verification Requirements - -For EACH major library/tool/pattern found: -- **Check recency:** When was it last updated? -- **Check adoption:** Is it actively maintained? Community size? -- **Check alternatives:** What else exists? When to use each? -- **Check deprecation:** Is anything being replaced? - -**Red flags for outdated content:** -- Articles from before 2023 (unless fundamental concepts) -- Abandoned libraries (no commits in 12+ months) -- Deprecated APIs or patterns -- "This used to be popular but..." - -### Documentation Sources - -Use Context7 MCP when available: -``` -mcp__context7__resolve-library-id: {library-name} -mcp__context7__get-library-docs: {library-id} -``` - -Focus on official docs, not tutorials. - -## Step 5: Organize Knowledge Into Domain Areas - -Structure references by domain concerns, NOT by arbitrary categories. - -**For game development example:** -``` -references/ -├── architecture.md # ECS, component-based, state machines -├── libraries.md # Pygame, Arcade, Panda3D (when to use each) -├── graphics-rendering.md # 2D/3D rendering, sprites, shaders -├── physics.md # Collision, physics engines -├── audio.md # Sound effects, music, spatial audio -├── input.md # Keyboard, mouse, gamepad, touch -├── ui-menus.md # HUD, menus, dialogs -├── game-loop.md # Update/render loop, fixed timestep -├── state-management.md # Game states, scene management -├── networking.md # Multiplayer, client-server, P2P -├── asset-pipeline.md # Loading, caching, optimization -├── testing-debugging.md # Unit tests, profiling, debugging tools -├── performance.md # Optimization, profiling, benchmarking -├── packaging.md # Building executables, installers -├── distribution.md # Steam, itch.io, app stores -└── anti-patterns.md # Common mistakes, what NOT to do -``` - -**For macOS app development example:** -``` -references/ -├── app-architecture.md # State management, dependency injection -├── swiftui-patterns.md # Declarative UI patterns -├── appkit-integration.md # Using AppKit with SwiftUI -├── concurrency-patterns.md # Async/await, actors, structured concurrency -├── data-persistence.md # Storage strategies -├── networking.md # URLSession, async networking -├── system-apis.md # macOS-specific frameworks -├── testing-tdd.md # Testing patterns -├── testing-debugging.md # Debugging tools and techniques -├── performance.md # Profiling, optimization -├── design-system.md # Platform conventions -├── macos-polish.md # Native feel, accessibility -├── security-code-signing.md # Signing, notarization -└── project-scaffolding.md # CLI-based setup -``` - -**For each reference file:** -- Pure XML structure -- Decision trees: "If X, use Y. If Z, use A instead." -- Comparison tables: Library vs Library (speed, features, learning curve) -- Code examples showing patterns -- "When to use" guidance -- Platform-specific considerations -- Current versions and compatibility - -## Step 6: Create SKILL.md - -Domain expertise skills use router pattern with essential principles: - -```yaml ---- -name: build-{domain-name} -description: Build {domain things} from scratch through shipping. Full lifecycle - build, debug, test, optimize, ship. {Any specific constraints like "CLI-only, no IDE"}. ---- - -<essential_principles> -## How {This Domain} Works - -{Domain-specific principles that ALWAYS apply} - -### 1. {First Principle} -{Critical practice that can't be skipped} - -### 2. {Second Principle} -{Another fundamental practice} - -### 3. {Third Principle} -{Core workflow pattern} -</essential_principles> - -<intake> -**Ask the user:** - -What would you like to do? -1. Build a new {thing} -2. Debug an existing {thing} -3. Add a feature -4. Write/run tests -5. Optimize performance -6. Ship/release -7. Something else - -**Then read the matching workflow from `workflows/` and follow it.** -</intake> - -<routing> -| Response | Workflow | -|----------|----------| -| 1, "new", "create", "build", "start" | `workflows/build-new-{thing}.md` | -| 2, "broken", "fix", "debug", "crash", "bug" | `workflows/debug-{thing}.md` | -| 3, "add", "feature", "implement", "change" | `workflows/add-feature.md` | -| 4, "test", "tests", "TDD", "coverage" | `workflows/write-tests.md` | -| 5, "slow", "optimize", "performance", "fast" | `workflows/optimize-performance.md` | -| 6, "ship", "release", "deploy", "publish" | `workflows/ship-{thing}.md` | -| 7, other | Clarify, then select workflow or references | -</routing> - -<verification_loop> -## After Every Change - -{Domain-specific verification steps} - -Example for compiled languages: -```bash -# 1. Does it build? -{build command} - -# 2. Do tests pass? -{test command} - -# 3. Does it run? -{run command} -``` - -Report to the user: -- "Build: ✓" -- "Tests: X pass, Y fail" -- "Ready for you to check [specific thing]" -</verification_loop> - -<reference_index> -## Domain Knowledge - -All in `references/`: - -**Architecture:** {list files} -**{Domain Area}:** {list files} -**{Domain Area}:** {list files} -**Development:** {list files} -**Shipping:** {list files} -</reference_index> - -<workflows_index> -## Workflows - -All in `workflows/`: - -| File | Purpose | -|------|---------| -| build-new-{thing}.md | Create new {thing} from scratch | -| debug-{thing}.md | Find and fix bugs | -| add-feature.md | Add to existing {thing} | -| write-tests.md | Write and run tests | -| optimize-performance.md | Profile and speed up | -| ship-{thing}.md | Deploy/distribute | -</workflows_index> -``` - -## Step 7: Write Workflows - -For EACH workflow identified in Step 3: - -### Workflow Template - -```markdown -# Workflow: {Workflow Name} - -<required_reading> -**Read these reference files NOW before {doing the task}:** -1. references/{relevant-file}.md -2. references/{another-relevant-file}.md -3. references/{third-relevant-file}.md -</required_reading> - -<process> -## Step 1: {First Action} - -{What to do} - -## Step 2: {Second Action} - -{What to do - actual implementation steps} - -## Step 3: {Third Action} - -{What to do} - -## Step 4: Verify - -{How to prove it works} - -```bash -{verification commands} -``` -</process> - -<anti_patterns> -Avoid: -- {Common mistake 1} -- {Common mistake 2} -- {Common mistake 3} -</anti_patterns> - -<success_criteria> -A well-{completed task}: -- {Criterion 1} -- {Criterion 2} -- {Criterion 3} -- Builds/runs without errors -- Tests pass -- Feels {native/professional/correct} -</success_criteria> -``` - -**Key workflow characteristics:** -- Starts with required_reading (which references to load) -- Contains actual implementation steps (not just "read references") -- Includes verification steps -- Has success criteria -- Documents anti-patterns - -## Step 8: Write Comprehensive References - -For EACH reference file identified in Step 5: - -### Structure Template - -```xml -<overview> -Brief introduction to this domain area -</overview> - -<options> -## Available Approaches/Libraries - -<option name="Library A"> -**When to use:** [specific scenarios] -**Strengths:** [what it's best at] -**Weaknesses:** [what it's not good for] -**Current status:** v{version}, actively maintained -**Learning curve:** [easy/medium/hard] - -```code -# Example usage -``` -</option> - -<option name="Library B"> -[Same structure] -</option> -</options> - -<decision_tree> -## Choosing the Right Approach - -**If you need [X]:** Use [Library A] -**If you need [Y]:** Use [Library B] -**If you have [constraint Z]:** Use [Library C] - -**Avoid [Library D] if:** [specific scenarios] -</decision_tree> - -<patterns> -## Common Patterns - -<pattern name="Pattern Name"> -**Use when:** [scenario] -**Implementation:** [code example] -**Considerations:** [trade-offs] -</pattern> -</patterns> - -<anti_patterns> -## What NOT to Do - -<anti_pattern name="Common Mistake"> -**Problem:** [what people do wrong] -**Why it's bad:** [consequences] -**Instead:** [correct approach] -</anti_pattern> -</anti_patterns> - -<platform_considerations> -## Platform-Specific Notes - -**Windows:** [considerations] -**macOS:** [considerations] -**Linux:** [considerations] -**Mobile:** [if applicable] -</platform_considerations> -``` - -### Quality Standards - -Each reference must include: -- **Current information** (verify dates) -- **Multiple options** (not just one library) -- **Decision guidance** (when to use each) -- **Real examples** (working code, not pseudocode) -- **Trade-offs** (no silver bullets) -- **Anti-patterns** (what NOT to do) - -### Common Reference Files - -Most domains need: -- **architecture.md** - How to structure projects -- **libraries.md** - Ecosystem overview with comparisons -- **patterns.md** - Design patterns specific to domain -- **testing-debugging.md** - How to verify correctness -- **performance.md** - Optimization strategies -- **deployment.md** - How to ship/distribute -- **anti-patterns.md** - Common mistakes consolidated - -## Step 9: Validate Completeness - -### Completeness Checklist - -Ask: "Could a user build a professional {domain thing} from scratch through shipping using just this skill?" - -**Must answer YES to:** -- [ ] All major libraries/frameworks covered? -- [ ] All architectural approaches documented? -- [ ] Complete lifecycle addressed (build → debug → test → optimize → ship)? -- [ ] Platform-specific considerations included? -- [ ] "When to use X vs Y" guidance provided? -- [ ] Common pitfalls documented? -- [ ] Current as of 2024-2026? -- [ ] Workflows actually execute tasks (not just reference knowledge)? -- [ ] Each workflow specifies which references to read? - -**Specific gaps to check:** -- [ ] Testing strategy covered? -- [ ] Debugging/profiling tools listed? -- [ ] Deployment/distribution methods documented? -- [ ] Performance optimization addressed? -- [ ] Security considerations (if applicable)? -- [ ] Asset/resource management (if applicable)? -- [ ] Networking (if applicable)? - -### Dual-Purpose Test - -Test both use cases: - -**Direct invocation:** "Can a user invoke this skill and build something?" -- Intake routes to appropriate workflow -- Workflow loads relevant references -- Workflow provides implementation steps -- Success criteria are clear - -**Knowledge reference:** "Can create-plans load references to plan a project?" -- References contain decision guidance -- All options compared -- Complete lifecycle covered -- Architecture patterns documented - -## Step 10: Create Directory and Files - -```bash -# Create structure -mkdir -p ~/.claude/skills/expertise/{domain-name} -mkdir -p ~/.claude/skills/expertise/{domain-name}/workflows -mkdir -p ~/.claude/skills/expertise/{domain-name}/references - -# Write SKILL.md -# Write all workflow files -# Write all reference files - -# Verify structure -ls -R ~/.claude/skills/expertise/{domain-name} -``` - -## Step 11: Document in create-plans - -Update `~/.claude/skills/create-plans/SKILL.md` to reference this new domain: - -Add to the domain inference table: -```markdown -| "{keyword}", "{domain term}" | expertise/{domain-name} | -``` - -So create-plans can auto-detect and offer to load it. - -## Step 12: Final Quality Check - -Review entire skill: - -**SKILL.md:** -- [ ] Name matches directory (build-{domain-name}) -- [ ] Description explains it builds things from scratch through shipping -- [ ] Essential principles inline (always loaded) -- [ ] Intake asks what user wants to do -- [ ] Routing maps to workflows -- [ ] Reference index complete and organized -- [ ] Workflows index complete - -**Workflows:** -- [ ] Each workflow starts with required_reading -- [ ] Each workflow has actual implementation steps -- [ ] Each workflow has verification steps -- [ ] Each workflow has success criteria -- [ ] Workflows cover full lifecycle (build, debug, test, optimize, ship) - -**References:** -- [ ] Pure XML structure (no markdown headings) -- [ ] Decision guidance in every file -- [ ] Current versions verified -- [ ] Code examples work -- [ ] Anti-patterns documented -- [ ] Platform considerations included - -**Completeness:** -- [ ] A professional practitioner would find this comprehensive -- [ ] No major libraries/patterns missing -- [ ] Full lifecycle covered -- [ ] Passes the "build from scratch through shipping" test -- [ ] Can be invoked directly by users -- [ ] Can be loaded by create-plans for knowledge - -</process> - -<success_criteria> -Domain expertise skill is complete when: - -- [ ] Comprehensive research completed (5+ web searches) -- [ ] All sources verified for recency (2024-2026) -- [ ] Knowledge organized by domain areas (not arbitrary) -- [ ] Essential principles in SKILL.md (always loaded) -- [ ] Intake routes to appropriate workflows -- [ ] Each workflow has required_reading + implementation steps + verification -- [ ] Each reference has decision trees and comparisons -- [ ] Anti-patterns documented throughout -- [ ] Full lifecycle covered (build → debug → test → optimize → ship) -- [ ] Platform-specific considerations included -- [ ] Located in ~/.claude/skills/expertise/{domain-name}/ -- [ ] Referenced in create-plans domain inference table -- [ ] Passes dual-purpose test: Can be invoked directly AND loaded for knowledge -- [ ] User can build something professional from scratch through shipping -</success_criteria> - -<anti_patterns> -**DON'T:** -- Copy tutorial content without verification -- Include only "getting started" material -- Skip the "when NOT to use" guidance -- Forget to check if libraries are still maintained -- Organize by document type instead of domain concerns -- Make it knowledge-only with no execution workflows -- Skip verification steps in workflows -- Include outdated content from old blog posts -- Skip decision trees and comparisons -- Create workflows that just say "read the references" - -**DO:** -- Verify everything is current -- Include complete lifecycle (build → ship) -- Provide decision guidance -- Document anti-patterns -- Make workflows execute real tasks -- Start workflows with required_reading -- Include verification in every workflow -- Make it exhaustive, not minimal -- Test both direct invocation and knowledge reference use cases -</anti_patterns> diff --git a/skills/create-agent-skills/workflows/create-new-skill.md b/skills/create-agent-skills/workflows/create-new-skill.md deleted file mode 100644 index 1b01bbb..0000000 --- a/skills/create-agent-skills/workflows/create-new-skill.md +++ /dev/null @@ -1,191 +0,0 @@ -# Workflow: Create a New Skill - -<required_reading> -**Read these reference files NOW:** -1. references/recommended-structure.md -2. references/skill-structure.md -3. references/core-principles.md -4. references/use-xml-tags.md -</required_reading> - -<process> -## Step 1: Adaptive Requirements Gathering - -**If user provided context** (e.g., "build a skill for X"): -→ Analyze what's stated, what can be inferred, what's unclear -→ Skip to asking about genuine gaps only - -**If user just invoked skill without context:** -→ Ask what they want to build - -### Using AskUserQuestion - -Ask 2-4 domain-specific questions based on actual gaps. Each question should: -- Have specific options with descriptions -- Focus on scope, complexity, outputs, boundaries -- NOT ask things obvious from context - -Example questions: -- "What specific operations should this skill handle?" (with options based on domain) -- "Should this also handle [related thing] or stay focused on [core thing]?" -- "What should the user see when successful?" - -### Decision Gate - -After initial questions, ask: -"Ready to proceed with building, or would you like me to ask more questions?" - -Options: -1. **Proceed to building** - I have enough context -2. **Ask more questions** - There are more details to clarify -3. **Let me add details** - I want to provide additional context - -## Step 2: Research Trigger (If External API) - -**When external service detected**, ask using AskUserQuestion: -"This involves [service name] API. Would you like me to research current endpoints and patterns before building?" - -Options: -1. **Yes, research first** - Fetch current documentation for accurate implementation -2. **No, proceed with general patterns** - Use common patterns without specific API research - -If research requested: -- Use Context7 MCP to fetch current library documentation -- Or use WebSearch for recent API documentation -- Focus on 2024-2026 sources -- Store findings for use in content generation - -## Step 3: Decide Structure - -**Simple skill (single workflow, <200 lines):** -→ Single SKILL.md file with all content - -**Complex skill (multiple workflows OR domain knowledge):** -→ Router pattern: -``` -skill-name/ -├── SKILL.md (router + principles) -├── workflows/ (procedures - FOLLOW) -├── references/ (knowledge - READ) -├── templates/ (output structures - COPY + FILL) -└── scripts/ (reusable code - EXECUTE) -``` - -Factors favoring router pattern: -- Multiple distinct user intents (create vs debug vs ship) -- Shared domain knowledge across workflows -- Essential principles that must not be skipped -- Skill likely to grow over time - -**Consider templates/ when:** -- Skill produces consistent output structures (plans, specs, reports) -- Structure matters more than creative generation - -**Consider scripts/ when:** -- Same code runs across invocations (deploy, setup, API calls) -- Operations are error-prone when rewritten each time - -See references/recommended-structure.md for templates. - -## Step 4: Create Directory - -```bash -mkdir -p ~/.claude/skills/{skill-name} -# If complex: -mkdir -p ~/.claude/skills/{skill-name}/workflows -mkdir -p ~/.claude/skills/{skill-name}/references -# If needed: -mkdir -p ~/.claude/skills/{skill-name}/templates # for output structures -mkdir -p ~/.claude/skills/{skill-name}/scripts # for reusable code -``` - -## Step 5: Write SKILL.md - -**Simple skill:** Write complete skill file with: -- YAML frontmatter (name, description) -- `<objective>` -- `<quick_start>` -- Content sections with pure XML -- `<success_criteria>` - -**Complex skill:** Write router with: -- YAML frontmatter -- `<essential_principles>` (inline, unavoidable) -- `<intake>` (question to ask user) -- `<routing>` (maps answers to workflows) -- `<reference_index>` and `<workflows_index>` - -## Step 6: Write Workflows (if complex) - -For each workflow: -```xml -<required_reading> -Which references to load for this workflow -</required_reading> - -<process> -Step-by-step procedure -</process> - -<success_criteria> -How to know this workflow is done -</success_criteria> -``` - -## Step 7: Write References (if needed) - -Domain knowledge that: -- Multiple workflows might need -- Doesn't change based on workflow -- Contains patterns, examples, technical details - -## Step 8: Validate Structure - -Check: -- [ ] YAML frontmatter valid -- [ ] Name matches directory (lowercase-with-hyphens) -- [ ] Description says what it does AND when to use it (third person) -- [ ] No markdown headings (#) in body - use XML tags -- [ ] Required tags present: objective, quick_start, success_criteria -- [ ] All referenced files exist -- [ ] SKILL.md under 500 lines -- [ ] XML tags properly closed - -## Step 9: Create Slash Command - -```bash -cat > ~/.claude/commands/{skill-name}.md << 'EOF' ---- -description: {Brief description} -argument-hint: [{argument hint}] -allowed-tools: Skill({skill-name}) ---- - -Invoke the {skill-name} skill for: $ARGUMENTS -EOF -``` - -## Step 10: Test - -Invoke the skill and observe: -- Does it ask the right intake question? -- Does it load the right workflow? -- Does the workflow load the right references? -- Does output match expectations? - -Iterate based on real usage, not assumptions. -</process> - -<success_criteria> -Skill is complete when: -- [ ] Requirements gathered with appropriate questions -- [ ] API research done if external service involved -- [ ] Directory structure correct -- [ ] SKILL.md has valid frontmatter -- [ ] Essential principles inline (if complex skill) -- [ ] Intake question routes to correct workflow -- [ ] All workflows have required_reading + process + success_criteria -- [ ] References contain reusable domain knowledge -- [ ] Slash command exists and works -- [ ] Tested with real invocation -</success_criteria> diff --git a/skills/create-agent-skills/workflows/get-guidance.md b/skills/create-agent-skills/workflows/get-guidance.md deleted file mode 100644 index 48f7b7d..0000000 --- a/skills/create-agent-skills/workflows/get-guidance.md +++ /dev/null @@ -1,121 +0,0 @@ -# Workflow: Get Guidance on Skill Design - -<required_reading> -**Read these reference files NOW:** -1. references/core-principles.md -2. references/recommended-structure.md -</required_reading> - -<process> -## Step 1: Understand the Problem Space - -Ask the user: -- What task or domain are you trying to support? -- Is this something you do repeatedly? -- What makes it complex enough to need a skill? - -## Step 2: Determine If a Skill Is Right - -**Create a skill when:** -- Task is repeated across multiple sessions -- Domain knowledge doesn't change frequently -- Complex enough to benefit from structure -- Would save significant time if automated - -**Don't create a skill when:** -- One-off task (just do it directly) -- Changes constantly (will be outdated quickly) -- Too simple (overhead isn't worth it) -- Better as a slash command (user-triggered, no context needed) - -Share this assessment with user. - -## Step 3: Map the Workflows - -Ask: "What are the different things someone might want to do with this skill?" - -Common patterns: -- Create / Read / Update / Delete -- Build / Debug / Ship -- Setup / Use / Troubleshoot -- Import / Process / Export - -Each distinct workflow = potential workflow file. - -## Step 4: Identify Domain Knowledge - -Ask: "What knowledge is needed regardless of which workflow?" - -This becomes references: -- API patterns -- Best practices -- Common examples -- Configuration details - -## Step 5: Draft the Structure - -Based on answers, recommend structure: - -**If 1 workflow, simple knowledge:** -``` -skill-name/ -└── SKILL.md (everything in one file) -``` - -**If 2+ workflows, shared knowledge:** -``` -skill-name/ -├── SKILL.md (router) -├── workflows/ -│ ├── workflow-a.md -│ └── workflow-b.md -└── references/ - └── shared-knowledge.md -``` - -## Step 6: Identify Essential Principles - -Ask: "What rules should ALWAYS apply, no matter which workflow?" - -These become `<essential_principles>` in SKILL.md. - -Examples: -- "Always verify before reporting success" -- "Never store credentials in code" -- "Ask before making destructive changes" - -## Step 7: Present Recommendation - -Summarize: -- Recommended structure (simple vs router pattern) -- List of workflows -- List of references -- Essential principles - -Ask: "Does this structure make sense? Ready to build it?" - -If yes → offer to switch to "Create a new skill" workflow -If no → clarify and iterate -</process> - -<decision_framework> -## Quick Decision Framework - -| Situation | Recommendation | -|-----------|----------------| -| Single task, repeat often | Simple skill | -| Multiple related tasks | Router + workflows | -| Complex domain, many patterns | Router + workflows + references | -| User-triggered, fresh context | Slash command, not skill | -| One-off task | No skill needed | -</decision_framework> - -<success_criteria> -Guidance is complete when: -- [ ] User understands if they need a skill -- [ ] Structure is recommended and explained -- [ ] Workflows are identified -- [ ] References are identified -- [ ] Essential principles are identified -- [ ] User is ready to build (or decided not to) -</success_criteria> diff --git a/skills/create-agent-skills/workflows/upgrade-to-router.md b/skills/create-agent-skills/workflows/upgrade-to-router.md deleted file mode 100644 index 26c0d11..0000000 --- a/skills/create-agent-skills/workflows/upgrade-to-router.md +++ /dev/null @@ -1,161 +0,0 @@ -# Workflow: Upgrade Skill to Router Pattern - -<required_reading> -**Read these reference files NOW:** -1. references/recommended-structure.md -2. references/skill-structure.md -</required_reading> - -<process> -## Step 1: Select the Skill - -```bash -ls ~/.claude/skills/ -``` - -Present numbered list, ask: "Which skill should be upgraded to the router pattern?" - -## Step 2: Verify It Needs Upgrading - -Read the skill: -```bash -cat ~/.claude/skills/{skill-name}/SKILL.md -ls ~/.claude/skills/{skill-name}/ -``` - -**Already a router?** (has workflows/ and intake question) -→ Tell user it's already using router pattern, offer to add workflows instead - -**Simple skill that should stay simple?** (under 200 lines, single workflow) -→ Explain that router pattern may be overkill, ask if they want to proceed anyway - -**Good candidate for upgrade:** -- Over 200 lines -- Multiple distinct use cases -- Essential principles that shouldn't be skipped -- Growing complexity - -## Step 3: Identify Components - -Analyze the current skill and identify: - -1. **Essential principles** - Rules that apply to ALL use cases -2. **Distinct workflows** - Different things a user might want to do -3. **Reusable knowledge** - Patterns, examples, technical details - -Present findings: -``` -## Analysis - -**Essential principles I found:** -- [Principle 1] -- [Principle 2] - -**Distinct workflows I identified:** -- [Workflow A]: [description] -- [Workflow B]: [description] - -**Knowledge that could be references:** -- [Reference topic 1] -- [Reference topic 2] -``` - -Ask: "Does this breakdown look right? Any adjustments?" - -## Step 4: Create Directory Structure - -```bash -mkdir -p ~/.claude/skills/{skill-name}/workflows -mkdir -p ~/.claude/skills/{skill-name}/references -``` - -## Step 5: Extract Workflows - -For each identified workflow: - -1. Create `workflows/{workflow-name}.md` -2. Add required_reading section (references it needs) -3. Add process section (steps from original skill) -4. Add success_criteria section - -## Step 6: Extract References - -For each identified reference topic: - -1. Create `references/{reference-name}.md` -2. Move relevant content from original skill -3. Structure with semantic XML tags - -## Step 7: Rewrite SKILL.md as Router - -Replace SKILL.md with router structure: - -```markdown ---- -name: {skill-name} -description: {existing description} ---- - -<essential_principles> -[Extracted principles - inline, cannot be skipped] -</essential_principles> - -<intake> -**Ask the user:** - -What would you like to do? -1. [Workflow A option] -2. [Workflow B option] -... - -**Wait for response before proceeding.** -</intake> - -<routing> -| Response | Workflow | -|----------|----------| -| 1, "keywords" | `workflows/workflow-a.md` | -| 2, "keywords" | `workflows/workflow-b.md` | -</routing> - -<reference_index> -[List all references by category] -</reference_index> - -<workflows_index> -| Workflow | Purpose | -|----------|---------| -| workflow-a.md | [What it does] | -| workflow-b.md | [What it does] | -</workflows_index> -``` - -## Step 8: Verify Nothing Was Lost - -Compare original skill content against new structure: -- [ ] All principles preserved (now inline) -- [ ] All procedures preserved (now in workflows) -- [ ] All knowledge preserved (now in references) -- [ ] No orphaned content - -## Step 9: Test - -Invoke the upgraded skill: -- Does intake question appear? -- Does each routing option work? -- Do workflows load correct references? -- Does behavior match original skill? - -Report any issues. -</process> - -<success_criteria> -Upgrade is complete when: -- [ ] workflows/ directory created with workflow files -- [ ] references/ directory created (if needed) -- [ ] SKILL.md rewritten as router -- [ ] Essential principles inline in SKILL.md -- [ ] All original content preserved -- [ ] Intake question routes correctly -- [ ] Tested and working -</success_criteria> diff --git a/skills/create-agent-skills/workflows/verify-skill.md b/skills/create-agent-skills/workflows/verify-skill.md deleted file mode 100644 index ab85743..0000000 --- a/skills/create-agent-skills/workflows/verify-skill.md +++ /dev/null @@ -1,204 +0,0 @@ -# Workflow: Verify Skill Content Accuracy - -<required_reading> -**Read these reference files NOW:** -1. references/skill-structure.md -</required_reading> - -<purpose> -Audit checks structure. **Verify checks truth.** - -Skills contain claims about external things: APIs, CLI tools, frameworks, services. These change over time. This workflow checks if a skill's content is still accurate. -</purpose> - -<process> -## Step 1: Select the Skill - -```bash -ls ~/.claude/skills/ -``` - -Present numbered list, ask: "Which skill should I verify for accuracy?" - -## Step 2: Read and Categorize - -Read the entire skill (SKILL.md + workflows/ + references/): -```bash -cat ~/.claude/skills/{skill-name}/SKILL.md -cat ~/.claude/skills/{skill-name}/workflows/*.md 2>/dev/null -cat ~/.claude/skills/{skill-name}/references/*.md 2>/dev/null -``` - -Categorize by primary dependency type: - -| Type | Examples | Verification Method | -|------|----------|---------------------| -| **API/Service** | manage-stripe, manage-gohighlevel | Context7 + WebSearch | -| **CLI Tools** | build-macos-apps (xcodebuild, swift) | Run commands | -| **Framework** | build-iphone-apps (SwiftUI, UIKit) | Context7 for docs | -| **Integration** | setup-stripe-payments | WebFetch + Context7 | -| **Pure Process** | create-agent-skills | No external deps | - -Report: "This skill is primarily [type]-based. I'll verify using [method]." - -## Step 3: Extract Verifiable Claims - -Scan skill content and extract: - -**CLI Tools mentioned:** -- Tool names (xcodebuild, swift, npm, etc.) -- Specific flags/options documented -- Expected output patterns - -**API Endpoints:** -- Service names (Stripe, Meta, etc.) -- Specific endpoints documented -- Authentication methods -- SDK versions - -**Framework Patterns:** -- Framework names (SwiftUI, React, etc.) -- Specific APIs/patterns documented -- Version-specific features - -**File Paths/Structures:** -- Expected project structures -- Config file locations - -Present: "Found X verifiable claims to check." - -## Step 4: Verify by Type - -### For CLI Tools -```bash -# Check tool exists -which {tool-name} - -# Check version -{tool-name} --version - -# Verify documented flags work -{tool-name} --help | grep "{documented-flag}" -``` - -### For API/Service Skills -Use Context7 to fetch current documentation: -``` -mcp__context7__resolve-library-id: {service-name} -mcp__context7__get-library-docs: {library-id}, topic: {relevant-topic} -``` - -Compare skill's documented patterns against current docs: -- Are endpoints still valid? -- Has authentication changed? -- Are there deprecated methods being used? - -### For Framework Skills -Use Context7: -``` -mcp__context7__resolve-library-id: {framework-name} -mcp__context7__get-library-docs: {library-id}, topic: {specific-api} -``` - -Check: -- Are documented APIs still current? -- Have patterns changed? -- Are there newer recommended approaches? - -### For Integration Skills -WebSearch for recent changes: -``` -"[service name] API changes 2026" -"[service name] breaking changes" -"[service name] deprecated endpoints" -``` - -Then Context7 for current SDK patterns. - -### For Services with Status Pages -WebFetch official docs/changelog if available. - -## Step 5: Generate Freshness Report - -Present findings: - -``` -## Verification Report: {skill-name} - -### ✅ Verified Current -- [Claim]: [Evidence it's still accurate] - -### ⚠️ May Be Outdated -- [Claim]: [What changed / newer info found] - → Current: [what docs now say] - -### ❌ Broken / Invalid -- [Claim]: [Why it's wrong] - → Fix: [What it should be] - -### ℹ️ Could Not Verify -- [Claim]: [Why verification wasn't possible] - ---- -**Overall Status:** [Fresh / Needs Updates / Significantly Stale] -**Last Verified:** [Today's date] -``` - -## Step 6: Offer Updates - -If issues found: - -"Found [N] items that need updating. Would you like me to:" - -1. **Update all** - Apply all corrections -2. **Review each** - Show each change before applying -3. **Just the report** - No changes - -If updating: -- Make changes based on verified current information -- Add verification date comment if appropriate -- Report what was updated - -## Step 7: Suggest Verification Schedule - -Based on skill type, recommend: - -| Skill Type | Recommended Frequency | -|------------|----------------------| -| API/Service | Every 1-2 months | -| Framework | Every 3-6 months | -| CLI Tools | Every 6 months | -| Pure Process | Annually | - -"This skill should be re-verified in approximately [timeframe]." -</process> - -<verification_shortcuts> -## Quick Verification Commands - -**Check if CLI tool exists and get version:** -```bash -which {tool} && {tool} --version -``` - -**Context7 pattern for any library:** -``` -1. resolve-library-id: "{library-name}" -2. get-library-docs: "{id}", topic: "{specific-feature}" -``` - -**WebSearch patterns:** -- Breaking changes: "{service} breaking changes 2026" -- Deprecations: "{service} deprecated API" -- Current best practices: "{framework} best practices 2026" -</verification_shortcuts> - -<success_criteria> -Verification is complete when: -- [ ] Skill categorized by dependency type -- [ ] Verifiable claims extracted -- [ ] Each claim checked with appropriate method -- [ ] Freshness report generated -- [ ] Updates applied (if requested) -- [ ] User knows when to re-verify -</success_criteria> diff --git a/skills/document-review/SKILL.md b/skills/document-review/SKILL.md index b0ba94d..9516df6 100644 --- a/skills/document-review/SKILL.md +++ b/skills/document-review/SKILL.md @@ -12,7 +12,7 @@ Improve brainstorm or plan documents through structured review. **If a document path is provided:** Read it, then proceed to Step 2. -**If no document is specified:** Ask which document to review, or look for the most recent brainstorm/plan in `docs/brainstorms/` or `docs/plans/`. +**If no document is specified:** Ask which document to review, or look for the most recent spec/plan in `docs/superpowers/specs/`, `docs/superpowers/plans/`, or `docs/plans/` (the last is for plans created before v3.0.0). ## Step 2: Assess diff --git a/skills/git-worktree/SKILL.md b/skills/git-worktree/SKILL.md deleted file mode 100644 index be4da8f..0000000 --- a/skills/git-worktree/SKILL.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -name: git-worktree -description: This skill manages Git worktrees for isolated parallel development. It handles creating, listing, switching, and cleaning up worktrees with a simple interactive interface, following KISS principles. -model: sonnet ---- - -# Git Worktree Manager - -Unified interface for Git worktrees — isolated parallel development via a single manager script. - -## What this skill does - -- Create worktrees from a base branch (default `main`) -- List, switch, cleanup -- Auto-manages `.gitignore` for `.worktrees/` -- Auto-copies `.env*` files from main repo - -## CRITICAL: Always use the manager script - -**NEVER call `git worktree add` directly.** The script handles setup raw git doesn't: - -1. Copies `.env`, `.env.local`, `.env.test`, etc. -2. Ensures `.worktrees` is in `.gitignore` -3. Creates consistent directory structure - -```bash -# ✅ CORRECT -bash ${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh create feature-name - -# ❌ WRONG -git worktree add .worktrees/feature-name -b feature-name main -``` - -## When to use - -1. **Code review (`/workflows:review`)** — if not on target branch, offer worktree for isolated review -2. **Feature work (`/workflows:work`)** — always ask: new branch or parallel worktree -3. **Parallel development** — multiple features simultaneously -4. **Cleanup** — after completing work - -## Quick Reference - -```bash -# Create (copies .env files) -worktree-manager.sh create feature-login - -# List -worktree-manager.sh list - -# Switch -worktree-manager.sh switch feature-login - -# Copy env to existing -worktree-manager.sh copy-env feature-login - -# Cleanup (interactive) -worktree-manager.sh cleanup -``` - -Prefix all with `bash ${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/`. - -Full command reference, troubleshooting, and technical details → [references/commands.md](./references/commands.md). - -Script: [scripts/worktree-manager.sh](./scripts/worktree-manager.sh) - -## Workflow integration - -### `/workflows:review` -1. Check current branch -2. If already on target → stay, no worktree -3. If different → offer worktree: `"Use worktree for isolated review? (y/n)"` - -### `/workflows:work` -Always ask: -``` -1. New branch on current worktree (live work) -2. Worktree (parallel work) -``` - -## Design Principles - -**KISS** — one manager script, sensible defaults, interactive prompts, clear naming. - -**Opinionated defaults** — always from `main` unless specified; stored in `.worktrees/`; branch name = worktree name; `.gitignore` auto-managed. - -**Safety first** — confirms before creating and before cleanup; won't remove current worktree; clear error messages. diff --git a/skills/git-worktree/references/commands.md b/skills/git-worktree/references/commands.md deleted file mode 100644 index 30ebe38..0000000 --- a/skills/git-worktree/references/commands.md +++ /dev/null @@ -1,90 +0,0 @@ -# Commands Reference - -Entry point: `bash ${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh <command>` - -## `create <branch-name> [from-branch]` - -Creates new worktree. `from-branch` defaults to `main`. - -```bash -worktree-manager.sh create feature-login -``` - -What it does: -1. Checks if worktree already exists -2. Updates base branch from remote -3. Creates new worktree + branch -4. Copies all `.env*` files from main repo -5. Shows path for `cd` - -## `list` / `ls` - -Lists all worktrees with branches and status. Current worktree marked with ✓. - -## `switch <name>` / `go <name>` - -Switches to an existing worktree and `cd`s into it. If name omitted, lists available and prompts. - -## `copy-env <name>` - -Copies `.env*` files to an existing worktree (e.g., if created manually). - -## `cleanup` / `clean` - -Interactively cleans up inactive worktrees with confirmation. Cleans empty directories. - -# Workflow Examples - -## Code review with worktree - -```bash -# Create isolated worktree for review (copies .env automatically) -worktree-manager.sh create pr-123-feature-name -cd .worktrees/pr-123-feature-name -# Review... -cd ../.. -worktree-manager.sh cleanup -``` - -## Parallel feature development - -```bash -worktree-manager.sh create feature-login -worktree-manager.sh create feature-notifications -worktree-manager.sh list -worktree-manager.sh switch feature-login -# Later -worktree-manager.sh cleanup -``` - -# Troubleshooting - -| Symptom | Fix | -|---------|-----| -| "Worktree already exists" | Script asks to switch to it instead | -| "Cannot remove worktree: it is the current worktree" | `cd $(git rev-parse --show-toplevel)` then `cleanup` | -| Lost in a worktree | `worktree-manager.sh list` | -| `.env` files missing | `worktree-manager.sh copy-env feature-name` | - -# Technical Details - -## Directory layout - -``` -.worktrees/ -├── feature-login/ # branch: feature-login -├── feature-notifications/ # branch: feature-notifications -└── ... -.gitignore # includes .worktrees -``` - -## How it works - -- Uses `git worktree add` under the hood -- Each worktree = its own branch, shared git history -- Changes isolated per worktree -- Push from any worktree - -## Performance - -Worktrees are lightweight (file system links, no repo duplication). Shared git objects. Much faster than cloning or stash/switch. diff --git a/skills/git-worktree/scripts/worktree-manager.sh b/skills/git-worktree/scripts/worktree-manager.sh deleted file mode 100755 index 181d6d1..0000000 --- a/skills/git-worktree/scripts/worktree-manager.sh +++ /dev/null @@ -1,337 +0,0 @@ -#!/bin/bash - -# Git Worktree Manager -# Handles creating, listing, switching, and cleaning up Git worktrees -# KISS principle: Simple, interactive, opinionated - -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# Get repo root -GIT_ROOT=$(git rev-parse --show-toplevel) -WORKTREE_DIR="$GIT_ROOT/.worktrees" - -# Ensure .worktrees is in .gitignore -ensure_gitignore() { - if ! grep -q "^\.worktrees$" "$GIT_ROOT/.gitignore" 2>/dev/null; then - echo ".worktrees" >> "$GIT_ROOT/.gitignore" - fi -} - -# Copy .env files from main repo to worktree -copy_env_files() { - local worktree_path="$1" - - echo -e "${BLUE}Copying environment files...${NC}" - - # Find all .env* files in root (excluding .env.example which should be in git) - local env_files=() - for f in "$GIT_ROOT"/.env*; do - if [[ -f "$f" ]]; then - local basename=$(basename "$f") - # Skip .env.example (that's typically committed to git) - if [[ "$basename" != ".env.example" ]]; then - env_files+=("$basename") - fi - fi - done - - if [[ ${#env_files[@]} -eq 0 ]]; then - echo -e " ${YELLOW}ℹ️ No .env files found in main repository${NC}" - return - fi - - local copied=0 - for env_file in "${env_files[@]}"; do - local source="$GIT_ROOT/$env_file" - local dest="$worktree_path/$env_file" - - if [[ -f "$dest" ]]; then - echo -e " ${YELLOW}⚠️ $env_file already exists, backing up to ${env_file}.backup${NC}" - cp "$dest" "${dest}.backup" - fi - - cp "$source" "$dest" - echo -e " ${GREEN}✓ Copied $env_file${NC}" - copied=$((copied + 1)) - done - - echo -e " ${GREEN}✓ Copied $copied environment file(s)${NC}" -} - -# Create a new worktree -create_worktree() { - local branch_name="$1" - local from_branch="${2:-main}" - - if [[ -z "$branch_name" ]]; then - echo -e "${RED}Error: Branch name required${NC}" - exit 1 - fi - - local worktree_path="$WORKTREE_DIR/$branch_name" - - # Check if worktree already exists - if [[ -d "$worktree_path" ]]; then - echo -e "${YELLOW}Worktree already exists at: $worktree_path${NC}" - echo -e "Switch to it instead? (y/n)" - read -r response - if [[ "$response" == "y" ]]; then - switch_worktree "$branch_name" - fi - return - fi - - echo -e "${BLUE}Creating worktree: $branch_name${NC}" - echo " From: $from_branch" - echo " Path: $worktree_path" - - # Update main branch - echo -e "${BLUE}Updating $from_branch...${NC}" - git checkout "$from_branch" - git pull origin "$from_branch" || true - - # Create worktree - mkdir -p "$WORKTREE_DIR" - ensure_gitignore - - echo -e "${BLUE}Creating worktree...${NC}" - git worktree add -b "$branch_name" "$worktree_path" "$from_branch" - - # Copy environment files - copy_env_files "$worktree_path" - - echo -e "${GREEN}✓ Worktree created successfully!${NC}" - echo "" - echo "To switch to this worktree:" - echo -e "${BLUE}cd $worktree_path${NC}" - echo "" -} - -# List all worktrees -list_worktrees() { - echo -e "${BLUE}Available worktrees:${NC}" - echo "" - - if [[ ! -d "$WORKTREE_DIR" ]]; then - echo -e "${YELLOW}No worktrees found${NC}" - return - fi - - local count=0 - for worktree_path in "$WORKTREE_DIR"/*; do - if [[ -d "$worktree_path" && -e "$worktree_path/.git" ]]; then - count=$((count + 1)) - local worktree_name=$(basename "$worktree_path") - local branch=$(git -C "$worktree_path" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown") - - if [[ "$PWD" == "$worktree_path" ]]; then - echo -e "${GREEN}✓ $worktree_name${NC} (current) → branch: $branch" - else - echo -e " $worktree_name → branch: $branch" - fi - fi - done - - if [[ $count -eq 0 ]]; then - echo -e "${YELLOW}No worktrees found${NC}" - else - echo "" - echo -e "${BLUE}Total: $count worktree(s)${NC}" - fi - - echo "" - echo -e "${BLUE}Main repository:${NC}" - local main_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown") - echo " Branch: $main_branch" - echo " Path: $GIT_ROOT" -} - -# Switch to a worktree -switch_worktree() { - local worktree_name="$1" - - if [[ -z "$worktree_name" ]]; then - list_worktrees - echo -e "${BLUE}Switch to which worktree? (enter name)${NC}" - read -r worktree_name - fi - - local worktree_path="$WORKTREE_DIR/$worktree_name" - - if [[ ! -d "$worktree_path" ]]; then - echo -e "${RED}Error: Worktree not found: $worktree_name${NC}" - echo "" - list_worktrees - exit 1 - fi - - echo -e "${GREEN}Switching to worktree: $worktree_name${NC}" - cd "$worktree_path" - echo -e "${BLUE}Now in: $(pwd)${NC}" -} - -# Copy env files to an existing worktree (or current directory if in a worktree) -copy_env_to_worktree() { - local worktree_name="$1" - local worktree_path - - if [[ -z "$worktree_name" ]]; then - # Check if we're currently in a worktree - local current_dir=$(pwd) - if [[ "$current_dir" == "$WORKTREE_DIR"/* ]]; then - worktree_path="$current_dir" - worktree_name=$(basename "$worktree_path") - echo -e "${BLUE}Detected current worktree: $worktree_name${NC}" - else - echo -e "${YELLOW}Usage: worktree-manager.sh copy-env [worktree-name]${NC}" - echo "Or run from within a worktree to copy to current directory" - list_worktrees - return 1 - fi - else - worktree_path="$WORKTREE_DIR/$worktree_name" - - if [[ ! -d "$worktree_path" ]]; then - echo -e "${RED}Error: Worktree not found: $worktree_name${NC}" - list_worktrees - return 1 - fi - fi - - copy_env_files "$worktree_path" - echo "" -} - -# Clean up completed worktrees -cleanup_worktrees() { - if [[ ! -d "$WORKTREE_DIR" ]]; then - echo -e "${YELLOW}No worktrees to clean up${NC}" - return - fi - - echo -e "${BLUE}Checking for completed worktrees...${NC}" - echo "" - - local found=0 - local to_remove=() - - for worktree_path in "$WORKTREE_DIR"/*; do - if [[ -d "$worktree_path" && -e "$worktree_path/.git" ]]; then - local worktree_name=$(basename "$worktree_path") - - # Skip if current worktree - if [[ "$PWD" == "$worktree_path" ]]; then - echo -e "${YELLOW}(skip) $worktree_name - currently active${NC}" - continue - fi - - found=$((found + 1)) - to_remove+=("$worktree_path") - echo -e "${YELLOW}• $worktree_name${NC}" - fi - done - - if [[ $found -eq 0 ]]; then - echo -e "${GREEN}No inactive worktrees to clean up${NC}" - return - fi - - echo "" - echo -e "Remove $found worktree(s)? (y/n)" - read -r response - - if [[ "$response" != "y" ]]; then - echo -e "${YELLOW}Cleanup cancelled${NC}" - return - fi - - echo -e "${BLUE}Cleaning up worktrees...${NC}" - for worktree_path in "${to_remove[@]}"; do - local worktree_name=$(basename "$worktree_path") - git worktree remove "$worktree_path" --force 2>/dev/null || true - echo -e "${GREEN}✓ Removed: $worktree_name${NC}" - done - - # Clean up empty directory if nothing left - if [[ -z "$(ls -A "$WORKTREE_DIR" 2>/dev/null)" ]]; then - rmdir "$WORKTREE_DIR" 2>/dev/null || true - fi - - echo -e "${GREEN}Cleanup complete!${NC}" -} - -# Main command handler -main() { - local command="${1:-list}" - - case "$command" in - create) - create_worktree "$2" "$3" - ;; - list|ls) - list_worktrees - ;; - switch|go) - switch_worktree "$2" - ;; - copy-env|env) - copy_env_to_worktree "$2" - ;; - cleanup|clean) - cleanup_worktrees - ;; - help) - show_help - ;; - *) - echo -e "${RED}Unknown command: $command${NC}" - echo "" - show_help - exit 1 - ;; - esac -} - -show_help() { - cat << EOF -Git Worktree Manager - -Usage: worktree-manager.sh <command> [options] - -Commands: - create <branch-name> [from-branch] Create new worktree (copies .env files automatically) - (from-branch defaults to main) - list | ls List all worktrees - switch | go [name] Switch to worktree - copy-env | env [name] Copy .env files from main repo to worktree - (if name omitted, uses current worktree) - cleanup | clean Clean up inactive worktrees - help Show this help message - -Environment Files: - - Automatically copies .env, .env.local, .env.test, etc. on create - - Skips .env.example (should be in git) - - Creates .backup files if destination already exists - - Use 'copy-env' to refresh env files after main repo changes - -Examples: - worktree-manager.sh create feature-login - worktree-manager.sh create feature-auth develop - worktree-manager.sh switch feature-login - worktree-manager.sh copy-env feature-login - worktree-manager.sh copy-env # copies to current worktree - worktree-manager.sh cleanup - worktree-manager.sh list - -EOF -} - -# Run -main "$@" diff --git a/skills/microservice-focus/SKILL.md b/skills/microservice-focus/SKILL.md new file mode 100644 index 0000000..ba23c13 --- /dev/null +++ b/skills/microservice-focus/SKILL.md @@ -0,0 +1,47 @@ +--- +name: microservice-focus +description: Use when a workflow command needs to detect multi-service monorepos, prompt for service scope, and propagate `<focus_context>` to sub-agents. Triggers when `--services` is passed, when focus context already exists in the conversation, or when multiple `pyproject.toml` files exist at the repo root. +--- + +# Microservice Focus + +Consolidates the service-discovery and focus-context-propagation logic used by every Python workflow command in this plugin. Invoked once per command; returns the focused service list plus a `<focus_context>` block ready to inject into sub-agent prompts. + +## When to invoke this skill + +A workflow command should invoke this skill exactly once, near the top of its execution, before delegating to a `superpowers:*` skill. + +## Inputs + +The skill expects to find one of the following, in priority order: + +1. A `--services service-a,service-b` argument parsed from the command's `$ARGUMENTS`. +2. An existing `<focus_context>` block in the conversation (set by a prior invocation). +3. Multiple `pyproject.toml` files at the repo root (multi-service repo). +4. None of the above → return single-service mode. + +## What the skill does + +1. **Parse `--services` if present.** Skip the interactive prompt and use those services as the focused set. +2. **Discover services on disk** when no explicit list was given. See [service-discovery.md](./references/service-discovery.md) for the exact glob and parsing rules. +3. **If multi-service and no explicit list:** use `AskUserQuestion` to prompt the user with the discovered services as multi-select options. See [focus-gate.md](./references/focus-gate.md) for the prompt format. +4. **Load each focused service's context:** `prompt.md` (preferred) or `README.md` (first 50 lines), `pyproject.toml`, and `src/` structure. Cross-reference internal dependencies to build the dependency map. +5. **Build the `<focus_context>` block.** See [focus-context-block.md](./references/focus-context-block.md) for the canonical template. +6. **Return** the service list + the `<focus_context>` block to the caller. The caller is responsible for injecting it into the prompts of any sub-agents or sub-skills it invokes. + +## Output contract + +The skill returns two pieces of information to the caller: + +- `services`: a list like `["service-a", "service-b"]`, or an empty list in single-service mode. +- `focus_context`: a `<focus_context>...</focus_context>` block ready to splice into sub-agent prompts. Empty string in single-service mode. + +## Single-service mode + +If only one (or zero) `pyproject.toml` is found and no `--services` argument was passed, the skill returns immediately with an empty service list and an empty focus context. The caller proceeds without per-service path overrides. + +## References + +- [focus-gate.md](./references/focus-gate.md) — Discovery + interactive prompting protocol +- [focus-context-block.md](./references/focus-context-block.md) — `<focus_context>` template & propagation rules +- [service-discovery.md](./references/service-discovery.md) — Glob mechanics, dependency cross-reference algorithm diff --git a/skills/microservice-focus/references/focus-context-block.md b/skills/microservice-focus/references/focus-context-block.md new file mode 100644 index 0000000..1e8b9e1 --- /dev/null +++ b/skills/microservice-focus/references/focus-context-block.md @@ -0,0 +1,54 @@ +# `<focus_context>` Block — Template and Propagation Rules + +## Canonical template + +``` +<focus_context> + services: <name-1> (./<name-1>), <name-2> (./<name-2>) + + <name-1>: + description: [from prompt.md/README — what this service does] + stack: [e.g., Django 5.0, Celery, PostgreSQL — derived from pyproject.toml] + structure: [e.g., src/orders/, src/pricing/, src/shared/] + + <name-2>: + description: [from prompt.md/README — what this service does] + stack: [e.g., FastAPI, SQLAlchemy 2.0, Redis] + structure: [e.g., src/payments/, src/webhooks/] + + dependencies: + - <name-2> depends on <name-1> (event schema) + - both depend on lib-common (shared DTOs) +</focus_context> +``` + +## Construction rules + +1. **`services:` line** lists all focused services with their paths in the format `<name> (./<name>)`. +2. **Per-service block** for each focused service includes `description`, `stack`, and `structure`. Pull these from the per-service context loaded in [focus-gate.md](./focus-gate.md). +3. **`dependencies:` section** lists internal dependencies cross-referenced from `pyproject.toml` files. Format each as a single line stating "X depends on Y (reason)". See [service-discovery.md](./service-discovery.md) for cross-reference logic. +4. **Omit any section** for which there is no data. An empty repo description, empty stack, or no detected dependencies = omit the line. + +## Propagation rules + +The caller (a workflow command) **must inject the full `<focus_context>` block into the prompt of every sub-agent or sub-skill it invokes**. This includes: + +- `superpowers:brainstorming` (via the wrapper's delegate step) +- `superpowers:writing-plans` +- `superpowers:executing-plans` +- `superpowers:requesting-code-review` +- Any Python review agent spawned by `/workflows:review` +- Any sub-task spawned by `Agent` or `Task` calls inside the command body + +The block is inserted near the top of the sub-agent prompt, before any task description, so the sub-agent reads the constraint up front. + +## Stack-aware behavior expectation + +Sub-agents that read this block should: + +- Apply Django patterns only in services whose stack lists Django. +- Apply FastAPI patterns only in services whose stack lists FastAPI. +- Respect each service's test/lint command (often visible in its `pyproject.toml` scripts or `CLAUDE.md`). +- Use the dependency map to choose execution order in multi-step operations. + +The wrapper command is not responsible for enforcing these — sub-agents act on the block. diff --git a/skills/microservice-focus/references/focus-gate.md b/skills/microservice-focus/references/focus-gate.md new file mode 100644 index 0000000..566bda8 --- /dev/null +++ b/skills/microservice-focus/references/focus-gate.md @@ -0,0 +1,53 @@ +# Focus Gate Protocol + +This file documents the interactive prompting protocol when multiple services exist but the user has not specified `--services`. + +## Step 0: Detect existing `<focus_context>` + +Check the conversation history for an existing `<focus_context>...</focus_context>` block set by a prior invocation of this skill. + +If `--services` was also provided in the current invocation, that takes precedence — skip this step and use Step 1 instead. + +If a `<focus_context>` block is found (and no `--services` override is present): + +1. Parse the `services:` line to extract the focused service names. +2. Treat those names as the focused set; skip Steps 1-3 (no rediscovery, no interactive prompt). +3. Proceed to Step 4 only if any per-service context (description, stack, or structure) appears stale or missing from the prior block; otherwise reuse the prior `<focus_context>` contents and return immediately. + +## Step 1: Discovery + +Run `Glob("*/pyproject.toml")` from the repo root. Each match represents a candidate service. Strip the trailing `/pyproject.toml` to get the service name (e.g., `service-a/pyproject.toml` → `service-a`). + +If the glob returns 0 or 1 results, the repo is single-service. Return without prompting. + +## Step 2: Prompt + +If 2 or more services are discovered, use `AskUserQuestion` with `multiSelect: true`. Phrase the question to match the command context: + +- `/workflows:brainstorm` → "Which services are relevant to this brainstorm?" +- `/workflows:plan` → "Which services are involved in this plan?" +- `/workflows:work` → "Which services does this work touch?" +- `/workflows:review` → "Which services should be reviewed?" + +List discovered services as options. Each option's `label` is the service name; the `description` is a one-line summary read from `{service}/.claude/prompt.md` (first line) or `{service}/README.md` (first heading), or "Python service" as a fallback. + +## Step 3: Validate the user's selection + +If the user selects nothing or hits cancel, halt with: "No services selected. Re-invoke the command with `--services <list>` or pick services when prompted." + +If the user selects a subset, treat those as the focused services and proceed. + +## Step 4: Load per-service context + +For each focused service, in parallel where possible: + +1. Read `{service}/.claude/prompt.md` (preferred) — first 30 lines. +2. If not present, read `{service}/README.md` — first 50 lines. +3. Read `{service}/pyproject.toml` — extract `name`, Python version requirement, and the `dependencies`/`tool.poetry.dependencies` list. +4. Run `Glob("{service}/src/*/")` to enumerate top-level packages (apps, modules). + +Cache these loads — the same focused service may be referenced multiple times in the focus-context block. + +## Pipeline mode + +If the command was invoked from an automated workflow (e.g., orchestrating script passes a flag, or a `disable-model-invocation` context is detected), **skip the interactive prompt entirely**. Default behavior in pipeline mode without `--services`: treat the repo as single-service. diff --git a/skills/microservice-focus/references/service-discovery.md b/skills/microservice-focus/references/service-discovery.md new file mode 100644 index 0000000..62255f6 --- /dev/null +++ b/skills/microservice-focus/references/service-discovery.md @@ -0,0 +1,56 @@ +# Service Discovery & Dependency Cross-Reference + +## Discovering services + +Single-line discovery: + +``` +Glob("*/pyproject.toml") +``` + +Each match represents one candidate service. Strip the suffix: + +``` +service-a/pyproject.toml → service-a +service-b/pyproject.toml → service-b +lib-common/pyproject.toml → lib-common +``` + +If the glob returns 0 results: treat as single-service mode (the repo may not be a Python project, or may not use per-service pyproject.toml — either way, no multi-service focus is needed). +If 1 result: single-service repo — return single-service mode. +If 2+ results: multi-service repo — proceed with focus gate. + +## Reading service metadata + +For each discovered service: + +1. **Name and stack** — parse `{service}/pyproject.toml`. Extract: + - Package name (from `[tool.poetry].name` or `[project].name`) + - Python requirement (from `python` field) + - Dependency list (from `[tool.poetry.dependencies]` or `[project].dependencies`) + + The stack summary in `<focus_context>` is derived from notable dependencies: `django`, `fastapi`, `celery`, `sqlalchemy`, `psycopg2`/`psycopg`, `redis`, `pydantic`, etc. Pick the 2-4 most architecturally significant ones. + +2. **Description** — first usable text from `{service}/.claude/prompt.md` (first paragraph, max 200 chars) or `{service}/README.md` (first non-empty paragraph after the title, max 200 chars). + +3. **Structure** — enumerate `{service}/src/*/` top-level dirs and list as comma-separated. Limit to ~5 entries; if more exist, suffix with `, ...`. + +## Cross-referencing internal dependencies + +To detect that service-b depends on service-a: + +1. Build a list of all package names from the focused services (read from each `pyproject.toml`'s `name` field). +2. For each focused service, scan its `dependencies` list for entries that match another focused service's package name. +3. Record the dependency: "service-b depends on service-a". +4. Optionally infer the reason by reading the depending service's import statements or recent commits — leave blank if unknown. + +## Detecting `lib-*` shared libraries + +Any service whose name starts with `lib-` is treated as a library candidate. If multiple focused services depend on `lib-common` (or similar), surface that as a "both depend on lib-common" line in `dependencies:`. + +## Edge cases + +- **Service has no `src/`** — list the top-level Python packages instead, or omit `structure:`. +- **Service has no `pyproject.toml`** — skip; it should not have been discovered in the first place. +- **Circular dependency between focused services** — record both directions, do NOT halt; let the consumer skill decide how to handle it. +- **Service named identically to a top-level project module** — disambiguate by path, not by name. diff --git a/skills/orchestrating-swarms/SKILL.md b/skills/orchestrating-swarms/SKILL.md deleted file mode 100644 index ea6b82a..0000000 --- a/skills/orchestrating-swarms/SKILL.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -name: orchestrating-swarms -description: This skill should be used when orchestrating multi-agent swarms using Claude Code's TeammateTool and Task system. It applies when coordinating multiple agents, running parallel code reviews, creating pipeline workflows with dependencies, building self-organizing task queues, or any task benefiting from divide-and-conquer patterns. -model: opus -disable-model-invocation: true ---- - -# Claude Code Swarm Orchestration - -Master multi-agent orchestration using Claude Code's `TeammateTool` and `Task` system. - -## Primitives - -| Primitive | What It Is | File Location | -|-----------|-----------|---------------| -| **Agent** | A Claude instance that can use tools. You are an agent. | N/A (process) | -| **Team** | Named group of agents. One leader, multiple teammates. | `~/.claude/teams/{name}/config.json` | -| **Teammate** | Agent that joined a team. Has a name, color, inbox. | Listed in team config | -| **Leader** | Agent that created the team. Approves plans/shutdowns. | First member | -| **Task** | Work item with subject, status, owner, dependencies. | `~/.claude/tasks/{team}/N.json` | -| **Inbox** | JSON file where an agent receives messages. | `~/.claude/teams/{name}/inboxes/{agent}.json` | -| **Message** | JSON object sent between agents — text or structured (shutdown, idle, join, plan approval). | Inside inboxes | -| **Backend** | How teammates run. Auto-detected: `in-process`, `tmux`, `iterm2`. | Per-member in config | - -## Lifecycle - -``` -1. Create Team → 2. Create Tasks → 3. Spawn Teammates → 4. Work → 5. Coordinate → 6. Shutdown → 7. Cleanup -``` - -Messages flow Leader ↔ Teammates via inbox files. Tasks auto-unblock when dependencies complete. - -## When to use which pattern - -| Need | Pattern | File | -|------|---------|------| -| Multiple specialists review same artifact | Parallel Specialists | [references/patterns.md](./references/patterns.md) | -| Sequential stages with dependencies | Pipeline | [references/patterns.md](./references/patterns.md) | -| Many independent tasks, self-balancing | Swarm | [references/patterns.md](./references/patterns.md) | -| Research result drives implementation | Research + Implementation | [references/patterns.md](./references/patterns.md) | -| Require approval before implementation | Plan Approval | [references/patterns.md](./references/patterns.md) | -| Coordinated multi-file refactor | Coordinated Refactoring | [references/patterns.md](./references/patterns.md) | - -## Reference files - -- [references/architecture.md](./references/architecture.md) — File layout, config schema, env vars -- [references/spawning.md](./references/spawning.md) — Task vs Teammate spawning, built-in & plugin agent types -- [references/teammate-operations.md](./references/teammate-operations.md) — All 13 `Teammate()` operations -- [references/task-system.md](./references/task-system.md) — `TaskCreate`, `TaskUpdate`, dependencies, pipelines -- [references/message-formats.md](./references/message-formats.md) — Structured message JSON (shutdown, idle, plan, join, permission) -- [references/patterns.md](./references/patterns.md) — Six orchestration patterns with code -- [references/workflows.md](./references/workflows.md) — Three complete end-to-end workflows -- [references/backends.md](./references/backends.md) — in-process vs tmux vs iterm2, auto-detection, forcing, troubleshooting -- [references/error-handling.md](./references/error-handling.md) — Common errors, graceful shutdown, crash recovery, debugging - -## Best Practices - -1. **Always cleanup.** Don't leave orphaned teams. Call `cleanup` when done. -2. **Meaningful names.** `security-reviewer` over `worker-1`. -3. **Clear prompts.** Spell out steps: read X, do Y, send findings via `Teammate write`. -4. **Use dependencies.** `addBlockedBy` beats manual polling. -5. **Check inboxes.** `cat ~/.claude/teams/{team}/inboxes/team-lead.json | jq`. -6. **Handle failures.** 5-min heartbeat timeout; build retry logic in worker prompts. -7. **Prefer `write` over `broadcast`.** Broadcast sends N messages for N teammates. -8. **Match agent type to task.** `Explore` for search, `Plan` for design, `general-purpose` for implementation, specialized reviewers for review. - -## Quick Reference - -```javascript -// Subagent (no team) -Task({ subagent_type: "Explore", description: "Find files", prompt: "..." }) - -// Team + teammate -Teammate({ operation: "spawnTeam", team_name: "my-team" }) -Task({ team_name: "my-team", name: "worker", subagent_type: "general-purpose", prompt: "...", run_in_background: true }) - -// Message -Teammate({ operation: "write", target_agent_id: "worker-1", value: "..." }) - -// Task pipeline -TaskCreate({ subject: "Step 1", description: "..." }) -TaskCreate({ subject: "Step 2", description: "..." }) -TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) - -// Shutdown -Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" }) -// Wait for approval... -Teammate({ operation: "cleanup" }) -``` - -*Based on Claude Code v2.1.19.* diff --git a/skills/orchestrating-swarms/references/architecture.md b/skills/orchestrating-swarms/references/architecture.md deleted file mode 100644 index 12ed45e..0000000 --- a/skills/orchestrating-swarms/references/architecture.md +++ /dev/null @@ -1,75 +0,0 @@ -# Core Architecture - -## How Swarms Work - -A swarm consists of: -- **Leader** (you) - Creates team, spawns workers, coordinates work -- **Teammates** (spawned agents) - Execute tasks, report back -- **Task List** - Shared work queue with dependencies -- **Inboxes** - JSON files for inter-agent messaging - -## File Structure - -``` -~/.claude/teams/{team-name}/ -├── config.json # Team metadata and member list -└── inboxes/ - ├── team-lead.json # Leader's inbox - ├── worker-1.json # Worker 1's inbox - └── worker-2.json # Worker 2's inbox - -~/.claude/tasks/{team-name}/ -├── 1.json # Task #1 -├── 2.json # Task #2 -└── 3.json # Task #3 -``` - -## Team Config Structure - -```json -{ - "name": "my-project", - "description": "Working on feature X", - "leadAgentId": "team-lead@my-project", - "createdAt": 1706000000000, - "members": [ - { - "agentId": "team-lead@my-project", - "name": "team-lead", - "agentType": "team-lead", - "color": "#4A90D9", - "joinedAt": 1706000000000, - "backendType": "in-process" - }, - { - "agentId": "worker-1@my-project", - "name": "worker-1", - "agentType": "Explore", - "model": "haiku", - "prompt": "Analyze the codebase structure...", - "color": "#D94A4A", - "planModeRequired": false, - "joinedAt": 1706000001000, - "tmuxPaneId": "in-process", - "cwd": "/Users/me/project", - "backendType": "in-process" - } - ] -} -``` - -## Environment Variables - -Spawned teammates automatically receive: - -```bash -CLAUDE_CODE_TEAM_NAME="my-project" -CLAUDE_CODE_AGENT_ID="worker-1@my-project" -CLAUDE_CODE_AGENT_NAME="worker-1" -CLAUDE_CODE_AGENT_TYPE="Explore" -CLAUDE_CODE_AGENT_COLOR="#4A90D9" -CLAUDE_CODE_PLAN_MODE_REQUIRED="false" -CLAUDE_CODE_PARENT_SESSION_ID="session-xyz" -``` - -Use in prompts with `$CLAUDE_CODE_AGENT_NAME` etc. diff --git a/skills/orchestrating-swarms/references/backends.md b/skills/orchestrating-swarms/references/backends.md deleted file mode 100644 index 8101d4f..0000000 --- a/skills/orchestrating-swarms/references/backends.md +++ /dev/null @@ -1,99 +0,0 @@ -# Spawn Backends - -A **backend** determines how teammate Claude instances run. Auto-detected. - -| Backend | How | Visibility | Persistence | Speed | -|---------|-----|------------|-------------|-------| -| **in-process** | Same Node.js process as leader | Hidden | Dies with leader | Fastest | -| **tmux** | Separate tmux pane | Visible in tmux | Survives leader exit | Medium | -| **iterm2** | Split panes in iTerm2 | Visible side-by-side | Dies with window | Medium | - -## Auto-detection - -1. `$TMUX` set → `tmux` (native) -2. `$TERM_PROGRAM === "iTerm.app"` + `which it2` → `iterm2` -3. `which tmux` → `tmux` (external session `claude-swarm`) -4. Fallback → `in-process` - -## Forcing a backend - -```bash -export CLAUDE_CODE_SPAWN_BACKEND=in-process # Fastest, no visibility -export CLAUDE_CODE_SPAWN_BACKEND=tmux # Visible, persistent -unset CLAUDE_CODE_SPAWN_BACKEND # Auto-detect (default) -``` - -## in-process - -Pros: fastest startup, lowest overhead, works everywhere. -Cons: can't see teammate output live, all die if leader dies, harder to debug. - -``` -┌─────────────────────────────────────────┐ -│ Node.js Process │ -│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ -│ │ Leader │ │Worker 1 │ │Worker 2 │ │ -│ └─────────┘ └─────────┘ └─────────┘ │ -└─────────────────────────────────────────┘ -``` - -## tmux - -Inside tmux → splits current window. Outside → creates `claude-swarm` session. - -Pros: real-time visibility, survives leader exit, CI-friendly. -Cons: slower startup, requires tmux. - -Useful commands: -```bash -tmux list-panes -tmux select-pane -t 1 -tmux kill-pane -t %5 -tmux attach -t claude-swarm -tmux select-layout tiled -``` - -## iterm2 (macOS only) - -Uses `it2` CLI via iTerm2 Python API. - -Setup: -```bash -uv tool install it2 # or pipx install it2 -# Enable: iTerm2 → Settings → General → Magic → Enable Python API -# Restart iTerm2 -it2 --version -``` - -On first spawn if setup is incomplete, Claude Code prompts to install, fallback to tmux, or cancel. - -## Troubleshooting - -| Issue | Cause | Solution | -|-------|-------|----------| -| "No pane backend available" | No tmux or iTerm2 | `brew install tmux` | -| "it2 CLI not installed" | In iTerm2 but no it2 | `uv tool install it2` | -| "Python API not enabled" | it2 can't reach iTerm2 | iTerm2 Settings → enable Python API | -| Workers not visible | Using in-process | Start inside tmux or iTerm2 | -| Workers dying unexpectedly | Outside tmux, leader exited | Use tmux for persistence | - -## Checking current backend - -```bash -cat ~/.claude/teams/{team}/config.json | jq '.members[].backendType' -echo $TMUX -echo $TERM_PROGRAM -which tmux -which it2 -``` - -## Backend in config.json - -```json -{ - "members": [ - { "name": "worker-1", "backendType": "in-process", "tmuxPaneId": "in-process" }, - { "name": "worker-2", "backendType": "tmux", "tmuxPaneId": "%5" } - ] -} -``` diff --git a/skills/orchestrating-swarms/references/error-handling.md b/skills/orchestrating-swarms/references/error-handling.md deleted file mode 100644 index 9491dc5..0000000 --- a/skills/orchestrating-swarms/references/error-handling.md +++ /dev/null @@ -1,54 +0,0 @@ -# Error Handling - -## Common errors - -| Error | Cause | Solution | -|-------|-------|----------| -| "Cannot cleanup with active members" | Teammates still running | `requestShutdown` all first, wait for approval | -| "Already leading a team" | Team already exists | `cleanup` first, or use different name | -| "Agent not found" | Wrong teammate name | Check `config.json` for actual names | -| "Team does not exist" | No team created | Call `spawnTeam` first | -| "team_name is required" | Missing team context | Provide `team_name` parameter | -| "Agent type not found" | Invalid subagent_type | Check available agents with proper prefix | - -## Graceful shutdown sequence - -```javascript -// 1. Request shutdown -Teammate({ operation: "requestShutdown", target_agent_id: "worker-1" }) -Teammate({ operation: "requestShutdown", target_agent_id: "worker-2" }) - -// 2. Wait for {"type": "shutdown_approved", ...} in inbox - -// 3. Verify no active members (check config.json) - -// 4. Cleanup -Teammate({ operation: "cleanup" }) -``` - -## Crashed teammates - -Teammates have a 5-minute heartbeat timeout. If one crashes: -1. Auto-marked inactive after timeout -2. Their tasks remain in the task list -3. Another teammate can claim their tasks -4. Cleanup works after timeout expires - -## Debugging - -```bash -# Team config -cat ~/.claude/teams/{team}/config.json | jq '.members[] | {name, agentType, backendType}' - -# Inbox -cat ~/.claude/teams/{team}/inboxes/{agent}.json | jq '.' - -# All teams -ls ~/.claude/teams/ - -# Task states -cat ~/.claude/tasks/{team}/*.json | jq '{id, subject, status, owner, blockedBy}' - -# Tail new messages -tail -f ~/.claude/teams/{team}/inboxes/team-lead.json -``` diff --git a/skills/orchestrating-swarms/references/message-formats.md b/skills/orchestrating-swarms/references/message-formats.md deleted file mode 100644 index 61d48cf..0000000 --- a/skills/orchestrating-swarms/references/message-formats.md +++ /dev/null @@ -1,99 +0,0 @@ -# Message Formats - -## Regular message - -```json -{ - "from": "team-lead", - "text": "Please prioritize the auth module", - "timestamp": "2026-01-25T23:38:32.588Z", - "read": false -} -``` - -## Structured messages (JSON in text field) - -### shutdown_request -```json -{ - "type": "shutdown_request", - "requestId": "shutdown-abc123@worker-1", - "from": "team-lead", - "reason": "All tasks complete", - "timestamp": "2026-01-25T23:38:32.588Z" -} -``` - -### shutdown_approved -```json -{ - "type": "shutdown_approved", - "requestId": "shutdown-abc123@worker-1", - "from": "worker-1", - "paneId": "%5", - "backendType": "in-process", - "timestamp": "2026-01-25T23:39:00.000Z" -} -``` - -### idle_notification -Auto-sent when teammate stops. -```json -{ - "type": "idle_notification", - "from": "worker-1", - "timestamp": "2026-01-25T23:40:00.000Z", - "completedTaskId": "2", - "completedStatus": "completed" -} -``` - -### task_completed -```json -{ - "type": "task_completed", - "from": "worker-1", - "taskId": "2", - "taskSubject": "Review authentication module", - "timestamp": "2026-01-25T23:40:00.000Z" -} -``` - -### plan_approval_request -```json -{ - "type": "plan_approval_request", - "from": "architect", - "requestId": "plan-xyz789", - "planContent": "# Implementation Plan\n\n1. ...", - "timestamp": "2026-01-25T23:41:00.000Z" -} -``` - -### join_request -```json -{ - "type": "join_request", - "proposedName": "helper", - "requestId": "join-abc123", - "capabilities": "Code review and testing", - "timestamp": "2026-01-25T23:42:00.000Z" -} -``` - -### permission_request -```json -{ - "type": "permission_request", - "requestId": "perm-123", - "workerId": "worker-1@my-project", - "workerName": "worker-1", - "workerColor": "#4A90D9", - "toolName": "Bash", - "toolUseId": "toolu_abc123", - "description": "Run npm install", - "input": {"command": "npm install"}, - "permissionSuggestions": ["Bash(npm *)"], - "createdAt": 1706000000000 -} -``` diff --git a/skills/orchestrating-swarms/references/patterns.md b/skills/orchestrating-swarms/references/patterns.md deleted file mode 100644 index ef4a588..0000000 --- a/skills/orchestrating-swarms/references/patterns.md +++ /dev/null @@ -1,147 +0,0 @@ -# Orchestration Patterns - -## Pattern 1: Parallel Specialists (Leader Pattern) - -Multiple specialists review code simultaneously. - -```javascript -Teammate({ operation: "spawnTeam", team_name: "code-review" }) - -// Spawn in parallel — single message, multiple Task calls -Task({ - team_name: "code-review", - name: "security", - subagent_type: "compound-engineering:review:security-sentinel", - prompt: "Review PR for SQL injection, XSS, auth bypass. Send findings to team-lead.", - run_in_background: true -}) -Task({ - team_name: "code-review", - name: "performance", - subagent_type: "compound-engineering:review:performance-oracle", - prompt: "Review PR for N+1 queries, memory leaks, slow algorithms. Send findings.", - run_in_background: true -}) -Task({ - team_name: "code-review", - name: "simplicity", - subagent_type: "compound-engineering:review:code-simplicity-reviewer", - prompt: "Review PR for over-engineering, YAGNI violations. Send findings.", - run_in_background: true -}) - -// Wait, synthesize, then shutdown each + cleanup -``` - -## Pattern 2: Pipeline (Sequential Dependencies) - -Each stage depends on the previous. - -```javascript -Teammate({ operation: "spawnTeam", team_name: "feature-pipeline" }) - -TaskCreate({ subject: "Research", ... }) // #1 -TaskCreate({ subject: "Plan", ... }) // #2 -TaskCreate({ subject: "Implement", ... }) // #3 -TaskCreate({ subject: "Test", ... }) // #4 -TaskCreate({ subject: "Review", ... }) // #5 - -TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) -TaskUpdate({ taskId: "3", addBlockedBy: ["2"] }) -TaskUpdate({ taskId: "4", addBlockedBy: ["3"] }) -TaskUpdate({ taskId: "5", addBlockedBy: ["4"] }) - -Task({ - team_name: "feature-pipeline", - name: "researcher", - subagent_type: "compound-engineering:research:best-practices-researcher", - prompt: "Claim #1, research, complete, send findings. Then check for more work.", - run_in_background: true -}) -// Tasks auto-unblock as dependencies complete -``` - -## Pattern 3: Swarm (Self-Organizing) - -Workers grab available tasks from a pool. - -```javascript -Teammate({ operation: "spawnTeam", team_name: "file-review-swarm" }) - -for (const file of ["auth.py", "users/models.py", "api/views.py"]) { - TaskCreate({ subject: `Review ${file}`, description: `Review ${file} for issues`, activeForm: `Reviewing ${file}...` }) -} - -const swarmPrompt = ` - You are a swarm worker: - 1. Call TaskList - 2. Find a pending, unowned, unblocked task - 3. Claim it (TaskUpdate owner=your-name) - 4. Do the work - 5. Mark completed - 6. Send findings to team-lead via Teammate write - 7. Repeat until no tasks remain -` - -Task({ team_name: "file-review-swarm", name: "worker-1", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true }) -Task({ team_name: "file-review-swarm", name: "worker-2", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true }) -Task({ team_name: "file-review-swarm", name: "worker-3", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true }) -``` - -Workers race to claim tasks, naturally load-balance. - -## Pattern 4: Research + Implementation - -Research synchronously, then use results in implementation. - -```javascript -const research = await Task({ - subagent_type: "compound-engineering:research:best-practices-researcher", - description: "Research caching patterns", - prompt: "Research caching for Django/FastAPI: invalidation, Redis vs Memcached, key design." -}) - -Task({ - subagent_type: "general-purpose", - description: "Implement caching", - prompt: `Implement API caching based on this research:\n\n${research.content}\n\nFocus on users/views.py.` -}) -``` - -## Pattern 5: Plan Approval Workflow - -Require plan approval before implementation. - -```javascript -Teammate({ operation: "spawnTeam", team_name: "careful-work" }) - -Task({ - team_name: "careful-work", - name: "architect", - subagent_type: "Plan", - prompt: "Design implementation plan for OAuth2", - mode: "plan", // Requires plan approval - run_in_background: true -}) - -// On {"type": "plan_approval_request", "from": "architect", "requestId": "plan-xxx", ...}: -Teammate({ operation: "approvePlan", target_agent_id: "architect", request_id: "plan-xxx" }) -// OR -Teammate({ operation: "rejectPlan", target_agent_id: "architect", request_id: "plan-xxx", feedback: "Add rate limiting" }) -``` - -## Pattern 6: Coordinated Multi-File Refactoring - -```javascript -Teammate({ operation: "spawnTeam", team_name: "refactor-auth" }) - -TaskCreate({ subject: "Refactor User model", ... }) // #1 -TaskCreate({ subject: "Refactor Session controller", ... }) // #2 -TaskCreate({ subject: "Update specs", ... }) // #3 - -TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] }) // specs wait for both - -Task({ team_name: "refactor-auth", name: "model-worker", subagent_type: "general-purpose", prompt: "Claim #1, refactor User model", run_in_background: true }) -Task({ team_name: "refactor-auth", name: "controller-worker", subagent_type: "general-purpose", prompt: "Claim #2, refactor Session controller", run_in_background: true }) -Task({ team_name: "refactor-auth", name: "spec-worker", subagent_type: "general-purpose", prompt: "Wait for #3 to unblock, then update specs", run_in_background: true }) -``` diff --git a/skills/orchestrating-swarms/references/spawning.md b/skills/orchestrating-swarms/references/spawning.md deleted file mode 100644 index 80fe83e..0000000 --- a/skills/orchestrating-swarms/references/spawning.md +++ /dev/null @@ -1,82 +0,0 @@ -# Spawning Agents - -## Two Ways to Spawn - -### Method 1: Task Tool (Subagents) - -For **short-lived, focused work** that returns a result: - -```javascript -Task({ - subagent_type: "Explore", - description: "Find auth files", - prompt: "Find all authentication-related files in this codebase", - model: "haiku" -}) -``` - -Runs synchronously (or async with `run_in_background: true`), returns result directly, no team membership. - -### Method 2: Task Tool + team_name + name (Teammates) - -For **persistent teammates** in a team: - -```javascript -Teammate({ operation: "spawnTeam", team_name: "my-project" }) - -Task({ - team_name: "my-project", - name: "security-reviewer", - subagent_type: "security-sentinel", - prompt: "Review all authentication code. Send findings to team-lead via Teammate write.", - run_in_background: true -}) -``` - -Joins team, communicates via inbox, can claim tasks, persists until shutdown. - -### Comparison - -| Aspect | Task (subagent) | Task + team_name + name (teammate) | -|--------|-----------------|-----------------------------------| -| Lifespan | Until task complete | Until shutdown requested | -| Communication | Return value | Inbox messages | -| Task access | None | Shared task list | -| Team membership | No | Yes | -| Coordination | One-off | Ongoing | - -## Built-in Agent Types - -| Type | Tools | Model | Best For | -|------|-------|-------|----------| -| `Bash` | Bash only | Inherit | Git operations, shell tasks | -| `Explore` | Read-only (no Edit/Write/Task) | Haiku | Codebase exploration, searches. Thoroughness: "quick", "medium", "very thorough" | -| `Plan` | Read-only | Inherit | Architecture planning | -| `general-purpose` | All (*) | Inherit | Multi-step tasks | -| `claude-code-guide` | Read-only + WebFetch/WebSearch | Inherit | Claude Code / API questions | -| `statusline-setup` | Read, Edit | Sonnet | Status line config | - -Example: -```javascript -Task({ subagent_type: "Explore", description: "Find API endpoints", prompt: "...", model: "haiku" }) -``` - -## Plugin Agent Types (compound-engineering) - -### Review agents -`agent-native-reviewer`, `architecture-strategist`, `code-simplicity-reviewer`, `data-integrity-guardian`, `data-migration-expert`, `deployment-verification-agent`, `python-style-reviewer`, `python-typing-reviewer`, `pattern-recognition-specialist`, `performance-oracle`, `security-sentinel` - -### Research agents -`best-practices-researcher`, `framework-docs-researcher`, `git-history-analyzer`, `learnings-researcher`, `repo-research-analyst` - -### Design / Workflow -`figma-design-sync`, `bug-reproduction-validator` - -Invoke with full namespaced prefix: -```javascript -Task({ - subagent_type: "compound-engineering:review:security-sentinel", - description: "Security audit", - prompt: "Audit this PR for security vulnerabilities" -}) -``` diff --git a/skills/orchestrating-swarms/references/task-system.md b/skills/orchestrating-swarms/references/task-system.md deleted file mode 100644 index eaad967..0000000 --- a/skills/orchestrating-swarms/references/task-system.md +++ /dev/null @@ -1,65 +0,0 @@ -# Task System Integration - -## Core operations - -```javascript -// Create -TaskCreate({ - subject: "Review authentication module", - description: "Review all files in app/services/auth/ for security vulnerabilities", - activeForm: "Reviewing auth module..." -}) - -// List -TaskList() -// → #1 [completed] ... -// → #2 [in_progress] ... (owner: security-reviewer) -// → #3 [pending] ... [blocked by #2] - -// Get details -TaskGet({ taskId: "2" }) - -// Claim -TaskUpdate({ taskId: "2", owner: "security-reviewer" }) - -// Start / complete -TaskUpdate({ taskId: "2", status: "in_progress" }) -TaskUpdate({ taskId: "2", status: "completed" }) - -// Dependencies -TaskUpdate({ taskId: "3", addBlockedBy: ["1", "2"] }) -``` - -## Pipeline example - -```javascript -TaskCreate({ subject: "Step 1: Research" }) // #1 -TaskCreate({ subject: "Step 2: Implement" }) // #2 -TaskCreate({ subject: "Step 3: Test" }) // #3 -TaskCreate({ subject: "Step 4: Deploy" }) // #4 - -TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) -TaskUpdate({ taskId: "3", addBlockedBy: ["2"] }) -TaskUpdate({ taskId: "4", addBlockedBy: ["3"] }) -``` - -Blocked tasks auto-unblock when dependencies complete. - -## Task file structure - -`~/.claude/tasks/{team-name}/1.json`: - -```json -{ - "id": "1", - "subject": "Review authentication module", - "description": "...", - "status": "in_progress", - "owner": "security-reviewer", - "activeForm": "Reviewing auth module...", - "blockedBy": [], - "blocks": ["3"], - "createdAt": 1706000000000, - "updatedAt": 1706000001000 -} -``` diff --git a/skills/orchestrating-swarms/references/teammate-operations.md b/skills/orchestrating-swarms/references/teammate-operations.md deleted file mode 100644 index 52d7de1..0000000 --- a/skills/orchestrating-swarms/references/teammate-operations.md +++ /dev/null @@ -1,143 +0,0 @@ -# TeammateTool Operations - -## 1. spawnTeam - -```javascript -Teammate({ - operation: "spawnTeam", - team_name: "feature-auth", - description: "Implementing OAuth2 authentication" -}) -``` - -Creates `~/.claude/teams/feature-auth/config.json` and task dir. You become leader. - -## 2. discoverTeams - -```javascript -Teammate({ operation: "discoverTeams" }) -``` - -Lists teams you can join. - -## 3. requestJoin - -```javascript -Teammate({ - operation: "requestJoin", - team_name: "feature-auth", - proposed_name: "helper", - capabilities: "Code review and testing" -}) -``` - -## 4. approveJoin (Leader) - -```javascript -Teammate({ - operation: "approveJoin", - target_agent_id: "helper", - request_id: "join-123" -}) -``` - -## 5. rejectJoin (Leader) - -```javascript -Teammate({ - operation: "rejectJoin", - target_agent_id: "helper", - request_id: "join-123", - reason: "Team is at capacity" -}) -``` - -## 6. write — Message one teammate - -```javascript -Teammate({ - operation: "write", - target_agent_id: "security-reviewer", - value: "Please prioritize the auth module." -}) -``` - -**Teammates:** Your text output is NOT visible to the team. Use `write` to communicate. - -## 7. broadcast — Message ALL teammates - -```javascript -Teammate({ - operation: "broadcast", - name: "team-lead", - value: "Status check: report your progress" -}) -``` - -**WARNING:** Sends N messages for N teammates. Prefer `write`. - -Use only for critical issues or major announcements affecting everyone. - -## 8. requestShutdown (Leader) - -```javascript -Teammate({ - operation: "requestShutdown", - target_agent_id: "security-reviewer", - reason: "All tasks complete" -}) -``` - -## 9. approveShutdown (Teammate) - -On receiving `{"type": "shutdown_request", "requestId": "shutdown-123", ...}`, MUST call: - -```javascript -Teammate({ - operation: "approveShutdown", - request_id: "shutdown-123" -}) -``` - -Sends confirmation and terminates the process. - -## 10. rejectShutdown (Teammate) - -```javascript -Teammate({ - operation: "rejectShutdown", - request_id: "shutdown-123", - reason: "Still working on task #3, need 5 more minutes" -}) -``` - -## 11. approvePlan (Leader) - -On receiving `{"type": "plan_approval_request", "from": "architect", "requestId": "plan-456", ...}`: - -```javascript -Teammate({ - operation: "approvePlan", - target_agent_id: "architect", - request_id: "plan-456" -}) -``` - -## 12. rejectPlan (Leader) - -```javascript -Teammate({ - operation: "rejectPlan", - target_agent_id: "architect", - request_id: "plan-456", - feedback: "Please add error handling and rate limiting" -}) -``` - -## 13. cleanup - -```javascript -Teammate({ operation: "cleanup" }) -``` - -Removes team and task directories. Fails if teammates are still active — `requestShutdown` first. diff --git a/skills/orchestrating-swarms/references/workflows.md b/skills/orchestrating-swarms/references/workflows.md deleted file mode 100644 index e4434d7..0000000 --- a/skills/orchestrating-swarms/references/workflows.md +++ /dev/null @@ -1,112 +0,0 @@ -# Complete Workflows - -## Workflow 1: Full Code Review with Parallel Specialists - -```javascript -// Setup -Teammate({ operation: "spawnTeam", team_name: "pr-review-123", description: "Reviewing PR #123" }) - -// Spawn reviewers in parallel — single message, multiple Task calls -Task({ - team_name: "pr-review-123", - name: "security", - subagent_type: "compound-engineering:review:security-sentinel", - prompt: `Review PR #123 for security. Focus on: SQL injection, XSS, auth bypass, sensitive data exposure. - Send findings via: Teammate({ operation: "write", target_agent_id: "team-lead", value: "..." })`, - run_in_background: true -}) - -Task({ - team_name: "pr-review-123", - name: "perf", - subagent_type: "compound-engineering:review:performance-oracle", - prompt: `Review PR #123 for performance. Focus on: N+1 queries, missing indexes, memory leaks, inefficient algorithms. Send findings.`, - run_in_background: true -}) - -Task({ - team_name: "pr-review-123", - name: "arch", - subagent_type: "compound-engineering:review:architecture-strategist", - prompt: `Review PR #123 for architecture. Focus on: design patterns, SOLID, separation of concerns, testability. Send findings.`, - run_in_background: true -}) - -// Monitor inbox, synthesize, shutdown all, cleanup -``` - -## Workflow 2: Research → Plan → Implement → Test Pipeline - -```javascript -Teammate({ operation: "spawnTeam", team_name: "feature-oauth" }) - -// Pipeline tasks -TaskCreate({ subject: "Research OAuth providers", description: "OAuth2 best practices, compare Google/GitHub/Auth0", activeForm: "Researching..." }) -TaskCreate({ subject: "Create implementation plan", activeForm: "Planning..." }) -TaskCreate({ subject: "Implement OAuth", activeForm: "Implementing..." }) -TaskCreate({ subject: "Write tests", activeForm: "Writing tests..." }) -TaskCreate({ subject: "Final review", activeForm: "Final review..." }) - -TaskUpdate({ taskId: "2", addBlockedBy: ["1"] }) -TaskUpdate({ taskId: "3", addBlockedBy: ["2"] }) -TaskUpdate({ taskId: "4", addBlockedBy: ["3"] }) -TaskUpdate({ taskId: "5", addBlockedBy: ["4"] }) - -// Specialized workers per stage -Task({ team_name: "feature-oauth", name: "researcher", subagent_type: "compound-engineering:research:best-practices-researcher", - prompt: "Claim #1, research, complete, send summary.", run_in_background: true }) -Task({ team_name: "feature-oauth", name: "planner", subagent_type: "Plan", - prompt: "Wait for #2. Read #1's findings. Create plan. Send to team-lead.", run_in_background: true }) -Task({ team_name: "feature-oauth", name: "implementer", subagent_type: "general-purpose", - prompt: "Wait for #3. Read plan. Implement. Mark complete.", run_in_background: true }) -Task({ team_name: "feature-oauth", name: "tester", subagent_type: "general-purpose", - prompt: "Wait for #4. Write/run tests. Mark complete with results.", run_in_background: true }) -Task({ team_name: "feature-oauth", name: "reviewer", subagent_type: "compound-engineering:review:security-sentinel", - prompt: "Wait for #5. Final security review. Send assessment.", run_in_background: true }) -``` - -## Workflow 3: Self-Organizing Code Review Swarm - -```javascript -Teammate({ operation: "spawnTeam", team_name: "codebase-review" }) - -const files = [ - "src/users/models.py", "src/payments/models.py", - "src/users/views.py", "src/payments/views.py", - "src/payments/services.py", "src/notifications/services.py", - "src/core/encryption.py" -] - -for (const file of files) { - TaskCreate({ - subject: `Review ${file}`, - description: `Review ${file} for security, code quality, performance`, - activeForm: `Reviewing ${file}...` - }) -} - -const swarmPrompt = ` -You are a swarm worker. - -LOOP: -1. TaskList() → find task with status=pending, no owner, not blocked -2. If found: - - TaskUpdate({ taskId, owner: $CLAUDE_CODE_AGENT_NAME }) - - TaskUpdate({ taskId, status: "in_progress" }) - - Do the review - - TaskUpdate({ taskId, status: "completed" }) - - Send findings to team-lead via Teammate write - - Go back to 1 -3. If none available: - - Send idle notification - - Wait 30s, retry up to 3× - - Exit -` - -// Spawn 3 workers in parallel -Task({ team_name: "codebase-review", name: "worker-1", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true }) -Task({ team_name: "codebase-review", name: "worker-2", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true }) -Task({ team_name: "codebase-review", name: "worker-3", subagent_type: "general-purpose", prompt: swarmPrompt, run_in_background: true }) - -// Workers self-organize, load-balance naturally -``` diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.md index 00fa23c..44edb2a 100644 --- a/skills/setup/SKILL.md +++ b/skills/setup/SKILL.md @@ -67,11 +67,11 @@ Security / Performance / Architecture / Code simplicity — maps to focus-area a ``` - Auto-configure (Recommended) — load detected stack skills into all workflows -- Customize per workflow — multiSelect for each of 5 workflows +- Customize per workflow — multiSelect for each of 4 workflows - Skip — omit workflow_skills entirely ``` -If **Customize per workflow**, for each of `brainstorm`, `plan`, `work`, `review`, `compound`, present multiSelect of available skills (`django-patterns`, `django-drf`, `django-async`, `fastapi-patterns`, `fastapi-sqlalchemy`, `pytest-patterns`, `postgresql-patterns`, `postgis-patterns`) plus any local `.claude/skills/`. +If **Customize per workflow**, for each of `brainstorm`, `plan`, `work`, `review`, present multiSelect of available skills (`django-patterns`, `django-drf`, `django-async`, `fastapi-patterns`, `fastapi-sqlalchemy`, `pytest-patterns`, `postgresql-patterns`, `postgis-patterns`) plus any local `.claude/skills/`. ## Step 4: Build Agent List and Write File @@ -95,7 +95,6 @@ Workflow skills: {count} skills across {count} workflows plan: {skill list or "none"} work: {skill list or "none"} review: {skill list or "none"} - compound: {skill list or "none"} Tip: Edit the "Review Context" section for project-specific instructions. Edit workflow_skills in the YAML frontmatter to customize per-workflow. diff --git a/skills/setup/references/stack-detection.md b/skills/setup/references/stack-detection.md index bc074ac..1892ffb 100644 --- a/skills/setup/references/stack-detection.md +++ b/skills/setup/references/stack-detection.md @@ -76,7 +76,7 @@ Base Python reviewers + `code-simplicity-reviewer`. | PostgreSQL | `postgresql-patterns` | | PostGIS | `postgis-patterns` | -Apply to all 5 workflows uniformly. Always add `pytest-patterns` to `work` and `review`. +Apply to all 4 workflows uniformly. Always add `pytest-patterns` to `work` and `review`. ## Output template @@ -93,7 +93,6 @@ workflow_skills: plan: [{skill list}] work: [{skill list}] review: [{skill list}] - compound: [{skill list}] --- # Review Context diff --git a/skills/skill-creator/SKILL.md b/skills/skill-creator/SKILL.md deleted file mode 100644 index f3b012b..0000000 --- a/skills/skill-creator/SKILL.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -name: skill-creator -description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations. -model: opus -license: Complete terms in LICENSE.txt -disable-model-invocation: true ---- - -# Skill Creator - -This skill provides guidance for creating effective skills. - -## About Skills - -Skills are modular, self-contained packages that extend Claude's capabilities by providing -specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific -domains or tasks—they transform Claude from a general-purpose agent into a specialized agent -equipped with procedural knowledge that no model can fully possess. - -### What Skills Provide - -1. Specialized workflows - Multi-step procedures for specific domains -2. Tool integrations - Instructions for working with specific file formats or APIs -3. Domain expertise - Company-specific knowledge, schemas, business logic -4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks - -### Anatomy of a Skill - -Every skill consists of a required SKILL.md file and optional bundled resources: - -``` -skill-name/ -├── SKILL.md (required) -│ ├── YAML frontmatter metadata (required) -│ │ ├── name: (required) -│ │ └── description: (required) -│ └── Markdown instructions (required) -└── Bundled Resources (optional) - ├── scripts/ - Executable code (Python/Bash/etc.) - ├── references/ - Documentation intended to be loaded into context as needed - └── assets/ - Files used in output (templates, icons, fonts, etc.) -``` - -#### SKILL.md (required) - -**Metadata Quality:** The `name` and `description` in YAML frontmatter determine when Claude will use the skill. Be specific about what the skill does and when to use it. Use the third-person (e.g. "This skill should be used when..." instead of "Use this skill when..."). - -#### Bundled Resources (optional) - -##### Scripts (`scripts/`) - -Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten. - -- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed -- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks -- **Benefits**: Token efficient, deterministic, may be executed without loading into context -- **Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments - -##### References (`references/`) - -Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking. - -- **When to include**: For documentation that Claude should reference while working -- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications -- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides -- **Benefits**: Keeps SKILL.md lean, loaded only when Claude determines it's needed -- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md -- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files. - -##### Assets (`assets/`) - -Files not intended to be loaded into context, but rather used within the output Claude produces. - -- **When to include**: When the skill needs files that will be used in the final output -- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography -- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified -- **Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context - -### Progressive Disclosure Design Principle - -Skills use a three-level loading system to manage context efficiently: - -1. **Metadata (name + description)** - Always in context (~100 words) -2. **SKILL.md body** - When skill triggers (<5k words) -3. **Bundled resources** - As needed by Claude (Unlimited*) - -*Unlimited because scripts can be executed without reading into context window. - -## Skill Creation Process - -To create a skill, follow the "Skill Creation Process" in order, skipping steps only if there is a clear reason why they are not applicable. - -### Step 1: Understanding the Skill with Concrete Examples - -Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill. - -To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback. - -For example, when building an image-editor skill, relevant questions include: - -- "What functionality should the image-editor skill support? Editing, rotating, anything else?" -- "Can you give some examples of how this skill would be used?" -- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?" -- "What would a user say that should trigger this skill?" - -To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness. - -Conclude this step when there is a clear sense of the functionality the skill should support. - -### Step 2: Planning the Reusable Skill Contents - -To turn concrete examples into an effective skill, analyze each example by: - -1. Considering how to execute on the example from scratch -2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly - -Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows: - -1. Rotating a PDF requires re-writing the same code each time -2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill - -Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows: - -1. Writing a frontend webapp requires the same boilerplate HTML/React each time -2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill - -Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows: - -1. Querying BigQuery requires re-discovering the table schemas and relationships each time -2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill - -To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets. - -### Step 3: Initializing the Skill - -At this point, it is time to actually create the skill. - -Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step. - -When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable. - -Usage: - -```bash -scripts/init_skill.py <skill-name> --path <output-directory> -``` - -The script: - -- Creates the skill directory at the specified path -- Generates a SKILL.md template with proper frontmatter and TODO placeholders -- Creates example resource directories: `scripts/`, `references/`, and `assets/` -- Adds example files in each directory that can be customized or deleted - -After initialization, customize or remove the generated SKILL.md and example files as needed. - -### Step 4: Edit the Skill - -When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Focus on including information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively. - -#### Start with Reusable Skill Contents - -To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`. - -Also, delete any example files and directories not needed for the skill. The initialization script creates example files in `scripts/`, `references/`, and `assets/` to demonstrate structure, but most skills won't need all of them. - -#### Update SKILL.md - -**Writing Style:** Write the entire skill using **imperative/infinitive form** (verb-first instructions), not second person. Use objective, instructional language (e.g., "To accomplish X, do Y" rather than "You should do X" or "If you need to do X"). This maintains consistency and clarity for AI consumption. - -To complete SKILL.md, answer the following questions: - -1. What is the purpose of the skill, in a few sentences? -2. When should the skill be used? -3. In practice, how should Claude use the skill? All reusable skill contents developed above should be referenced so that Claude knows how to use them. - -### Step 5: Packaging a Skill - -Once the skill is ready, it should be packaged into a distributable zip file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements: - -```bash -scripts/package_skill.py <path/to/skill-folder> -``` - -Optional output directory specification: - -```bash -scripts/package_skill.py <path/to/skill-folder> ./dist -``` - -The packaging script will: - -1. **Validate** the skill automatically, checking: - - YAML frontmatter format and required fields - - Skill naming conventions and directory structure - - Description completeness and quality - - File organization and resource references - -2. **Package** the skill if validation passes, creating a zip file named after the skill (e.g., `my-skill.zip`) that includes all files and maintains the proper directory structure for distribution. - -If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again. - -### Step 6: Iterate - -After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed. - -**Iteration workflow:** -1. Use the skill on real tasks -2. Notice struggles or inefficiencies -3. Identify how SKILL.md or bundled resources should be updated -4. Implement changes and test again diff --git a/skills/skill-creator/scripts/init_skill.py b/skills/skill-creator/scripts/init_skill.py deleted file mode 100755 index 329ad4e..0000000 --- a/skills/skill-creator/scripts/init_skill.py +++ /dev/null @@ -1,303 +0,0 @@ -#!/usr/bin/env python3 -""" -Skill Initializer - Creates a new skill from template - -Usage: - init_skill.py <skill-name> --path <path> - -Examples: - init_skill.py my-new-skill --path skills/public - init_skill.py my-api-helper --path skills/private - init_skill.py custom-skill --path /custom/location -""" - -import sys -from pathlib import Path - - -SKILL_TEMPLATE = """--- -name: {skill_name} -description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.] ---- - -# {skill_title} - -## Overview - -[TODO: 1-2 sentences explaining what this skill enables] - -## Structuring This Skill - -[TODO: Choose the structure that best fits this skill's purpose. Common patterns: - -**1. Workflow-Based** (best for sequential processes) -- Works well when there are clear step-by-step procedures -- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing" -- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2... - -**2. Task-Based** (best for tool collections) -- Works well when the skill offers different operations/capabilities -- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text" -- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2... - -**3. Reference/Guidelines** (best for standards or specifications) -- Works well for brand guidelines, coding standards, or requirements -- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features" -- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage... - -**4. Capabilities-Based** (best for integrated systems) -- Works well when the skill provides multiple interrelated features -- Example: Product Management with "Core Capabilities" → numbered capability list -- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature... - -Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations). - -Delete this entire "Structuring This Skill" section when done - it's just guidance.] - -## [TODO: Replace with the first main section based on chosen structure] - -[TODO: Add content here. See examples in existing skills: -- Code samples for technical skills -- Decision trees for complex workflows -- Concrete examples with realistic user requests -- References to scripts/templates/references as needed] - -## Resources - -This skill includes example resource directories that demonstrate how to organize different types of bundled resources: - -### scripts/ -Executable code (Python/Bash/etc.) that can be run directly to perform specific operations. - -**Examples from other skills:** -- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation -- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing - -**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations. - -**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments. - -### references/ -Documentation and reference material intended to be loaded into context to inform Claude's process and thinking. - -**Examples from other skills:** -- Product management: `communication.md`, `context_building.md` - detailed workflow guides -- BigQuery: API reference documentation and query examples -- Finance: Schema documentation, company policies - -**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working. - -### assets/ -Files not intended to be loaded into context, but rather used within the output Claude produces. - -**Examples from other skills:** -- Brand styling: PowerPoint template files (.pptx), logo files -- Frontend builder: HTML/React boilerplate project directories -- Typography: Font files (.ttf, .woff2) - -**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output. - ---- - -**Any unneeded directories can be deleted.** Not every skill requires all three types of resources. -""" - -EXAMPLE_SCRIPT = '''#!/usr/bin/env python3 -""" -Example helper script for {skill_name} - -This is a placeholder script that can be executed directly. -Replace with actual implementation or delete if not needed. - -Example real scripts from other skills: -- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields -- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images -""" - -def main(): - print("This is an example script for {skill_name}") - # TODO: Add actual script logic here - # This could be data processing, file conversion, API calls, etc. - -if __name__ == "__main__": - main() -''' - -EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title} - -This is a placeholder for detailed reference documentation. -Replace with actual reference content or delete if not needed. - -Example real reference docs from other skills: -- product-management/references/communication.md - Comprehensive guide for status updates -- product-management/references/context_building.md - Deep-dive on gathering context -- bigquery/references/ - API references and query examples - -## When Reference Docs Are Useful - -Reference docs are ideal for: -- Comprehensive API documentation -- Detailed workflow guides -- Complex multi-step processes -- Information too lengthy for main SKILL.md -- Content that's only needed for specific use cases - -## Structure Suggestions - -### API Reference Example -- Overview -- Authentication -- Endpoints with examples -- Error codes -- Rate limits - -### Workflow Guide Example -- Prerequisites -- Step-by-step instructions -- Common patterns -- Troubleshooting -- Best practices -""" - -EXAMPLE_ASSET = """# Example Asset File - -This placeholder represents where asset files would be stored. -Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed. - -Asset files are NOT intended to be loaded into context, but rather used within -the output Claude produces. - -Example asset files from other skills: -- Brand guidelines: logo.png, slides_template.pptx -- Frontend builder: hello-world/ directory with HTML/React boilerplate -- Typography: custom-font.ttf, font-family.woff2 -- Data: sample_data.csv, test_dataset.json - -## Common Asset Types - -- Templates: .pptx, .docx, boilerplate directories -- Images: .png, .jpg, .svg, .gif -- Fonts: .ttf, .otf, .woff, .woff2 -- Boilerplate code: Project directories, starter files -- Icons: .ico, .svg -- Data files: .csv, .json, .xml, .yaml - -Note: This is a text placeholder. Actual assets can be any file type. -""" - - -def title_case_skill_name(skill_name): - """Convert hyphenated skill name to Title Case for display.""" - return ' '.join(word.capitalize() for word in skill_name.split('-')) - - -def init_skill(skill_name, path): - """ - Initialize a new skill directory with template SKILL.md. - - Args: - skill_name: Name of the skill - path: Path where the skill directory should be created - - Returns: - Path to created skill directory, or None if error - """ - # Determine skill directory path - skill_dir = Path(path).resolve() / skill_name - - # Check if directory already exists - if skill_dir.exists(): - print(f"❌ Error: Skill directory already exists: {skill_dir}") - return None - - # Create skill directory - try: - skill_dir.mkdir(parents=True, exist_ok=False) - print(f"✅ Created skill directory: {skill_dir}") - except Exception as e: - print(f"❌ Error creating directory: {e}") - return None - - # Create SKILL.md from template - skill_title = title_case_skill_name(skill_name) - skill_content = SKILL_TEMPLATE.format( - skill_name=skill_name, - skill_title=skill_title - ) - - skill_md_path = skill_dir / 'SKILL.md' - try: - skill_md_path.write_text(skill_content) - print("✅ Created SKILL.md") - except Exception as e: - print(f"❌ Error creating SKILL.md: {e}") - return None - - # Create resource directories with example files - try: - # Create scripts/ directory with example script - scripts_dir = skill_dir / 'scripts' - scripts_dir.mkdir(exist_ok=True) - example_script = scripts_dir / 'example.py' - example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name)) - example_script.chmod(0o755) - print("✅ Created scripts/example.py") - - # Create references/ directory with example reference doc - references_dir = skill_dir / 'references' - references_dir.mkdir(exist_ok=True) - example_reference = references_dir / 'api_reference.md' - example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title)) - print("✅ Created references/api_reference.md") - - # Create assets/ directory with example asset placeholder - assets_dir = skill_dir / 'assets' - assets_dir.mkdir(exist_ok=True) - example_asset = assets_dir / 'example_asset.txt' - example_asset.write_text(EXAMPLE_ASSET) - print("✅ Created assets/example_asset.txt") - except Exception as e: - print(f"❌ Error creating resource directories: {e}") - return None - - # Print next steps - print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}") - print("\nNext steps:") - print("1. Edit SKILL.md to complete the TODO items and update the description") - print("2. Customize or delete the example files in scripts/, references/, and assets/") - print("3. Run the validator when ready to check the skill structure") - - return skill_dir - - -def main(): - if len(sys.argv) < 4 or sys.argv[2] != '--path': - print("Usage: init_skill.py <skill-name> --path <path>") - print("\nSkill name requirements:") - print(" - Hyphen-case identifier (e.g., 'data-analyzer')") - print(" - Lowercase letters, digits, and hyphens only") - print(" - Max 40 characters") - print(" - Must match directory name exactly") - print("\nExamples:") - print(" init_skill.py my-new-skill --path skills/public") - print(" init_skill.py my-api-helper --path skills/private") - print(" init_skill.py custom-skill --path /custom/location") - sys.exit(1) - - skill_name = sys.argv[1] - path = sys.argv[3] - - print(f"🚀 Initializing skill: {skill_name}") - print(f" Location: {path}") - print() - - result = init_skill(skill_name, path) - - if result: - sys.exit(0) - else: - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/skills/skill-creator/scripts/package_skill.py b/skills/skill-creator/scripts/package_skill.py deleted file mode 100755 index 3ee8e8e..0000000 --- a/skills/skill-creator/scripts/package_skill.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python3 -""" -Skill Packager - Creates a distributable zip file of a skill folder - -Usage: - python utils/package_skill.py <path/to/skill-folder> [output-directory] - -Example: - python utils/package_skill.py skills/public/my-skill - python utils/package_skill.py skills/public/my-skill ./dist -""" - -import sys -import zipfile -from pathlib import Path -from quick_validate import validate_skill - - -def package_skill(skill_path, output_dir=None): - """ - Package a skill folder into a zip file. - - Args: - skill_path: Path to the skill folder - output_dir: Optional output directory for the zip file (defaults to current directory) - - Returns: - Path to the created zip file, or None if error - """ - skill_path = Path(skill_path).resolve() - - # Validate skill folder exists - if not skill_path.exists(): - print(f"❌ Error: Skill folder not found: {skill_path}") - return None - - if not skill_path.is_dir(): - print(f"❌ Error: Path is not a directory: {skill_path}") - return None - - # Validate SKILL.md exists - skill_md = skill_path / "SKILL.md" - if not skill_md.exists(): - print(f"❌ Error: SKILL.md not found in {skill_path}") - return None - - # Run validation before packaging - print("🔍 Validating skill...") - valid, message = validate_skill(skill_path) - if not valid: - print(f"❌ Validation failed: {message}") - print(" Please fix the validation errors before packaging.") - return None - print(f"✅ {message}\n") - - # Determine output location - skill_name = skill_path.name - if output_dir: - output_path = Path(output_dir).resolve() - output_path.mkdir(parents=True, exist_ok=True) - else: - output_path = Path.cwd() - - zip_filename = output_path / f"{skill_name}.zip" - - # Create the zip file - try: - with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf: - # Walk through the skill directory - for file_path in skill_path.rglob('*'): - if file_path.is_file(): - # Calculate the relative path within the zip - arcname = file_path.relative_to(skill_path.parent) - zipf.write(file_path, arcname) - print(f" Added: {arcname}") - - print(f"\n✅ Successfully packaged skill to: {zip_filename}") - return zip_filename - - except Exception as e: - print(f"❌ Error creating zip file: {e}") - return None - - -def main(): - if len(sys.argv) < 2: - print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]") - print("\nExample:") - print(" python utils/package_skill.py skills/public/my-skill") - print(" python utils/package_skill.py skills/public/my-skill ./dist") - sys.exit(1) - - skill_path = sys.argv[1] - output_dir = sys.argv[2] if len(sys.argv) > 2 else None - - print(f"📦 Packaging skill: {skill_path}") - if output_dir: - print(f" Output directory: {output_dir}") - print() - - result = package_skill(skill_path, output_dir) - - if result: - sys.exit(0) - else: - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/skills/skill-creator/scripts/quick_validate.py b/skills/skill-creator/scripts/quick_validate.py deleted file mode 100755 index 6fa6c63..0000000 --- a/skills/skill-creator/scripts/quick_validate.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 -""" -Quick validation script for skills - minimal version -""" - -import sys -import os -import re -from pathlib import Path - -def validate_skill(skill_path): - """Basic validation of a skill""" - skill_path = Path(skill_path) - - # Check SKILL.md exists - skill_md = skill_path / 'SKILL.md' - if not skill_md.exists(): - return False, "SKILL.md not found" - - # Read and validate frontmatter - content = skill_md.read_text() - if not content.startswith('---'): - return False, "No YAML frontmatter found" - - # Extract frontmatter - match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL) - if not match: - return False, "Invalid frontmatter format" - - frontmatter = match.group(1) - - # Check required fields - if 'name:' not in frontmatter: - return False, "Missing 'name' in frontmatter" - if 'description:' not in frontmatter: - return False, "Missing 'description' in frontmatter" - - # Extract name for validation - name_match = re.search(r'name:\s*(.+)', frontmatter) - if name_match: - name = name_match.group(1).strip() - # Check naming convention (hyphen-case: lowercase with hyphens) - if not re.match(r'^[a-z0-9-]+$', name): - return False, f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)" - if name.startswith('-') or name.endswith('-') or '--' in name: - return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens" - - # Extract and validate description - desc_match = re.search(r'description:\s*(.+)', frontmatter) - if desc_match: - description = desc_match.group(1).strip() - # Check for angle brackets - if '<' in description or '>' in description: - return False, "Description cannot contain angle brackets (< or >)" - - return True, "Skill is valid!" - -if __name__ == "__main__": - if len(sys.argv) != 2: - print("Usage: python quick_validate.py <skill_directory>") - sys.exit(1) - - valid, message = validate_skill(sys.argv[1]) - print(message) - sys.exit(0 if valid else 1) \ No newline at end of file