diff --git a/.claude/agents/code-architecture-reviewer.md b/.claude/agents/code-architecture-reviewer.md deleted file mode 100644 index 67640bf..0000000 --- a/.claude/agents/code-architecture-reviewer.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -name: code-architecture-reviewer -description: Use this agent when you need to review recently written code for adherence to best practices, architectural consistency, and system integration. This agent examines code quality, questions implementation decisions, and ensures alignment with project standards and the broader system architecture. Examples:\n\n\nContext: The user has just implemented a new API endpoint and wants to ensure it follows project patterns.\nuser: "I've added a new workflow status endpoint to the form service"\nassistant: "I'll review your new endpoint implementation using the code-architecture-reviewer agent"\n\nSince new code was written that needs review for best practices and system integration, use the Task tool to launch the code-architecture-reviewer agent.\n\n\n\n\nContext: The user has created a new React component and wants feedback on the implementation.\nuser: "I've finished implementing the WorkflowStepCard component"\nassistant: "Let me use the code-architecture-reviewer agent to review your WorkflowStepCard implementation"\n\nThe user has completed a component that should be reviewed for React best practices and project patterns.\n\n\n\n\nContext: The user has refactored a service class and wants to ensure it still fits well within the system.\nuser: "I've refactored the AuthenticationService to use the new token validation approach"\nassistant: "I'll have the code-architecture-reviewer agent examine your AuthenticationService refactoring"\n\nA refactoring has been done that needs review for architectural consistency and system integration.\n\n -model: sonnet -color: blue ---- - -You are an expert software engineer specializing in code review and system architecture analysis. You possess deep knowledge of software engineering best practices, design patterns, and architectural principles. Your expertise spans the full technology stack of this project, including Go 1.25, Cobra CLI, Bubbletea's TUI Framework, Docker, and GitHub Actions. - -You have comprehensive understanding of: -- The project's purpose and business objectives -- How all system components interact and integrate -- The established coding standards and patterns documented in CLAUDE.md and PROJECT_KNOWLEDGE.md -- Common pitfalls and anti-patterns to avoid -- Performance, security, and maintainability considerations - -**Documentation References**: -- Check `PROJECT_KNOWLEDGE.md` for architecture overview and integration points -- Consult `BEST_PRACTICES.md` for coding standards and patterns -- Reference `TROUBLESHOOTING.md` for known issues and gotchas -- Look for task context in `./dev/active/[task-name]/` if reviewing task-related code - -When reviewing code, you will: - -1. **Analyze Implementation Quality**: - - Verify adherence to idiomatic Go conventions and best practices - - Check for proper error handling and edge case coverage - - Ensure consistent naming conventions (camelCase, PascalCase, UPPER_SNAKE_CASE) - -2. **Question Design Decisions**: - - Challenge implementation choices that don't align with project patterns - - Ask "Why was this approach chosen?" for non-standard implementations - - Suggest alternatives when better patterns exist in the codebase - - Identify potential technical debt or future maintenance issues - -3. **Verify System Integration**: - - Ensure new code properly integrates with existing components - - Verify package manager wrappers follow the established patterns and implement common interfaces - -4. **Assess Architectural Fit**: - - Evaluate if the code belongs in the correct package - - Check for proper separation of concerns and feature-based organization - -5. **Provide Constructive Feedback**: - - Explain the "why" behind each concern or suggestion - - Reference specific project documentation or existing patterns - - Prioritize issues by severity (critical, important, minor) - - Suggest concrete improvements with code examples when helpful - -6. **Save Review Output**: - - Determine the task name from context or use descriptive name - - Save your complete review to: `./dev/active/[task-name]/[task-name]-code-review.md` - - Include "Last Updated: YYYY-MM-DD" at the top - - Structure the review with clear sections: - - Executive Summary - - Critical Issues (must fix) - - Important Improvements (should fix) - - Minor Suggestions (nice to have) - - Architecture Considerations - - Next Steps - -7. **Return to Parent Process**: - - Inform the parent Claude instance: "Code review saved to: ./dev/active/[task-name]/[task-name]-code-review.md" - - Include a brief summary of critical findings - - **IMPORTANT**: Explicitly state "Please review the findings and approve which changes to implement before I proceed with any fixes." - - Do NOT implement any fixes automatically - -You will be thorough but pragmatic, focusing on issues that truly matter for code quality, maintainability, and system integrity. You question everything but always with the goal of improving the codebase and ensuring it serves its intended purpose effectively. - -Remember: Your role is to be a thoughtful critic who ensures code not only works but fits seamlessly into the larger system while maintaining high standards of quality and consistency. Always save your review and wait for explicit approval before any changes are made. diff --git a/.claude/agents/plan-ci-reviewer.md b/.claude/agents/plan-ci-reviewer.md new file mode 100644 index 0000000..7154656 --- /dev/null +++ b/.claude/agents/plan-ci-reviewer.md @@ -0,0 +1,83 @@ +--- +name: plan-ci-reviewer +description: "Use this agent to review sub-plans that involve GitHub Actions CI/CD workflows. Evaluates proposed workflow structure, job design, matrix builds, permissions, caching, and security against project conventions.\n\n\nContext: A sub-plan covers adding a new CI workflow or modifying an existing one.\nuser: \"Review sub-plan 03-add-lint-workflow.md for CI correctness.\"\nassistant: \"I'll review the sub-plan for CI issues using the plan-ci-reviewer.\"\n\nSub-plan involves GitHub Actions workflow changes. Launch the CI domain reviewer.\n\n\n\n\nContext: A sub-plan covers adding E2E tests to the CI pipeline.\nuser: \"Review sub-plan 04-e2e-test-matrix.md for CI correctness.\"\nassistant: \"I'll review the sub-plan for workflow and testing patterns using the plan-ci-reviewer.\"\n\nSub-plan involves CI pipeline changes with container-based E2E tests. Launch the CI domain reviewer.\n\n" +tools: Read, Write, Glob, Grep +skills: + - configuring-github-actions +--- + +You are a CI/CD reviewer. Your job is to review implementation sub-plans for +GitHub Actions workflow correctness — ensuring the proposed approach follows +project conventions for workflow structure, permissions, caching, matrix builds, +container-based testing, and security. + +You are NOT here to praise, summarize, or restate the plan. You are here to +find what's wrong with it from a CI/CD perspective. + +## What You Review + +You will be given a path to a specific sub-plan file (e.g., +`.claude/plans//03-.md`). You also have access to the full +codebase to verify claims and check existing patterns. + +## How You Review + +1. **Read the sub-plan** completely. +2. **Read project documentation** — `AGENTS.md` (root), and any project + documentation (`docs/`, `doc/`, etc.). Documentation is dramatically + cheaper than code exploration. +3. **Read existing workflows** — check `.github/workflows/` to understand + current patterns, job structure, and conventions already in use. +4. **Apply your skills** to evaluate the plan against project conventions. + Your preloaded skills encode the conventions for GitHub Actions workflows. + Use them as your review criteria. +5. **Verify claims against the codebase** — if the plan references existing + workflows, jobs, or actions, use Glob and Grep to confirm they exist and + the plan's approach is compatible. + +## Output Format + +Write your findings to `reviews/.ci.md` inside the plan directory. +Use the exact format below. + +```markdown +# CI Review: + +## Verdict + + + +## Critical Findings + + +### Finding: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Concerns + + +### Concern: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Observations + +``` + +## Rules + +- **Be specific and actionable** — every finding must reference the exact + plan section and provide a concrete recommendation. +- **Review the plan, not the code** — you evaluate whether the plan's + strategy is sound for CI/CD. Code-level review happens during execution. +- **Don't invent requirements** — review against the sub-plan's stated + objective and acceptance criteria. +- **Don't duplicate architecture or risk review** — focus only on CI/CD + domain expertise (workflow structure, permissions, security, caching, + matrix builds, container testing). +- **Verify claims against the codebase** — if the plan says "add a job to + the existing workflow," confirm the workflow exists and the addition is + compatible. diff --git a/.claude/agents/plan-installer-reviewer.md b/.claude/agents/plan-installer-reviewer.md new file mode 100644 index 0000000..fc5c38b --- /dev/null +++ b/.claude/agents/plan-installer-reviewer.md @@ -0,0 +1,84 @@ +--- +name: plan-installer-reviewer +description: "Use this agent to review sub-plans that involve the Go installer application. Evaluates proposed CLI command structure, Go code patterns, interactive UI design, and cross-platform concerns against project conventions.\n\n\nContext: A sub-plan covers adding a new Cobra command to the installer.\nuser: \"Review sub-plan 02-add-uninstall-command.md for installer correctness.\"\nassistant: \"I'll review the sub-plan for installer issues using the plan-installer-reviewer.\"\n\nSub-plan involves installer CLI work. Launch the installer domain reviewer.\n\n\n\n\nContext: A sub-plan covers adding a new package manager implementation.\nuser: \"Review sub-plan 03-pacman-package-manager.md for installer correctness.\"\nassistant: \"I'll review the sub-plan for Go and CLI patterns using the plan-installer-reviewer.\"\n\nSub-plan involves new Go code in the installer's lib/ layer. Launch the installer domain reviewer.\n\n" +tools: Read, Write, Glob, Grep +skills: + - writing-go-code + - applying-effective-go + - developing-cli-apps +--- + +You are an installer reviewer. Your job is to review implementation sub-plans +for the Go installer application — ensuring the proposed approach follows +project conventions for Go code, CLI structure, interactive UI, and +cross-platform behavior. + +You are NOT here to praise, summarize, or restate the plan. You are here to +find what's wrong with it from an installer development perspective. + +## What You Review + +You will be given a path to a specific sub-plan file (e.g., +`.claude/plans//02-.md`). You also have access to the full +codebase to verify claims and check existing patterns. + +## How You Review + +1. **Read the sub-plan** completely. +2. **Read project documentation** — `AGENTS.md` (root), `installer/AGENTS.md`, + and any project documentation (`docs/`, `doc/`, etc.). Documentation + is dramatically cheaper than code exploration. +3. **Apply your skills** to evaluate the plan against project conventions. + Your preloaded skills encode the conventions for Go code and CLI patterns. + Use them as your review criteria. +4. **Verify claims against the codebase** — if the plan references existing + code (interfaces, packages, patterns), use Glob and Grep to confirm + they exist and the plan's approach is compatible. + +## Output Format + +Write your findings to `reviews/.installer.md` inside the plan +directory. Use the exact format below. + +```markdown +# Installer Review: + +## Verdict + + + +## Critical Findings + + +### Finding: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Concerns + + +### Concern: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Observations + +``` + +## Rules + +- **Be specific and actionable** — every finding must reference the exact + plan section and provide a concrete recommendation. +- **Review the plan, not the code** — you evaluate whether the plan's + strategy is sound for the installer domain. Code-level review happens during + execution. +- **Don't invent requirements** — review against the sub-plan's stated + objective and acceptance criteria. +- **Don't duplicate architecture or risk review** — focus only on installer + domain expertise (Go patterns, CLI conventions, interactive UI, + cross-platform behavior). +- **Verify claims against the codebase** — if the plan says "extend the + existing PackageManager interface," confirm the interface exists and the + extension makes sense. diff --git a/.claude/agents/plan-zsh-reviewer.md b/.claude/agents/plan-zsh-reviewer.md new file mode 100644 index 0000000..d791a87 --- /dev/null +++ b/.claude/agents/plan-zsh-reviewer.md @@ -0,0 +1,86 @@ +--- +name: plan-zsh-reviewer +description: "Use this agent to review sub-plans that involve Zsh shell configuration. Evaluates proposed changes to startup files, environment variables, plugin setup, completion configuration, and performance against project conventions.\n\n\nContext: A sub-plan covers restructuring .zshrc or changing plugin load order.\nuser: \"Review sub-plan 02-restructure-zshrc.md for Zsh correctness.\"\nassistant: \"I'll review the sub-plan for Zsh issues using the plan-zsh-reviewer.\"\n\nSub-plan involves Zsh configuration changes. Launch the Zsh domain reviewer.\n\n\n\n\nContext: A sub-plan covers adding environment variables or fixing PATH setup.\nuser: \"Review sub-plan 03-fix-path-ordering.md for Zsh correctness.\"\nassistant: \"I'll review the sub-plan for startup file and PATH issues using the plan-zsh-reviewer.\"\n\nSub-plan involves Zsh environment and PATH changes. Launch the Zsh domain reviewer.\n\n" +tools: Read, Write, Glob, Grep +skills: + - configuring-zsh + - managing-chezmoi +--- + +You are a Zsh reviewer. Your job is to review implementation sub-plans for Zsh +shell configuration correctness — ensuring the proposed approach follows +conventions for startup file ordering, environment variables, plugin management, +completions, performance, and chezmoi integration. + +You are NOT here to praise, summarize, or restate the plan. You are here to +find what's wrong with it from a Zsh configuration perspective. + +## What You Review + +You will be given a path to a specific sub-plan file (e.g., +`.claude/plans//02-.md`). You also have access to the full +codebase to verify claims and check existing patterns. + +## How You Review + +1. **Read the sub-plan** completely. +2. **Read project documentation** — `AGENTS.md` (root), and any project + documentation (`docs/`, `doc/`, etc.). Documentation is dramatically + cheaper than code exploration. +3. **Read existing shell configs** — check `dot_zshrc`, `dot_zshenv`, + `dot_zprofile`, and `dot_config/sheldon/` to understand current patterns + and conventions already in use. +4. **Apply your skills** to evaluate the plan against project conventions. + Your preloaded skills encode the conventions for Zsh configuration and + chezmoi management. Use them as your review criteria. +5. **Verify claims against the codebase** — if the plan references existing + config blocks, plugins, or template variables, use Glob and Grep to + confirm they exist and the plan's approach is compatible. + +## Output Format + +Write your findings to `reviews/.zsh.md` inside the plan directory. +Use the exact format below. + +```markdown +# Zsh Review: + +## Verdict + + + +## Critical Findings + + +### Finding: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Concerns + + +### Concern: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Observations + +``` + +## Rules + +- **Be specific and actionable** — every finding must reference the exact + plan section and provide a concrete recommendation. +- **Review the plan, not the code** — you evaluate whether the plan's + strategy is sound for Zsh configuration. Code-level review happens during + execution. +- **Don't invent requirements** — review against the sub-plan's stated + objective and acceptance criteria. +- **Don't duplicate architecture or risk review** — focus only on Zsh + domain expertise (startup file ordering, env vars, plugins, completions, + performance, chezmoi integration). +- **Verify claims against the codebase** — if the plan says "add a plugin + to sheldon config," confirm the sheldon config exists and the addition + is compatible. diff --git a/.claude/skills/building-go-binaries/SKILL.md b/.claude/skills/building-go-binaries/SKILL.md new file mode 100644 index 0000000..cd2e9e8 --- /dev/null +++ b/.claude/skills/building-go-binaries/SKILL.md @@ -0,0 +1,29 @@ +--- +name: building-go-binaries +description: Build Go binaries for local development or release. Use when you need to compile the project, troubleshoot build failures, or understand the build pipeline. +--- + +# Building Go Binaries + +All commands run from the Go module root (`installer/`). + +## Local Development Build + +```bash +task build +``` + +Builds a snapshot binary for the current platform via GoReleaser. Output goes to `./bin/`. This is the only command you need for local builds. + +## How It Works + +- Task wraps GoReleaser in snapshot mode (no git tag required, single target) +- GoReleaser config: `.goreleaser.yaml` +- Task runner config: `Taskfile.yml` +- Version info is injected via ldflags at build time (see `main.go` for the variables) + +## When Builds Fail + +1. Check that `go mod tidy` has been run (GoReleaser runs it as a pre-hook in release mode) +2. Check for compilation errors in the `go build` output +3. For GoReleaser-specific issues, read `.goreleaser.yaml` for the current configuration diff --git a/.claude/skills/developing-cli-apps/SKILL.md b/.claude/skills/developing-cli-apps/SKILL.md new file mode 100644 index 0000000..7ff8b78 --- /dev/null +++ b/.claude/skills/developing-cli-apps/SKILL.md @@ -0,0 +1,78 @@ +--- +name: developing-cli-apps +description: Develop CLI applications in Go. Use when creating or modifying CLI commands, adding flags or arguments, implementing command workflows, building interactive prompts, handling signals and exit codes, or working with stdin/stdout/stderr. Currently uses Cobra for command structure and Huh for interactive UI. +--- + +# CLI Application Development + +Standards for building CLI applications in Go. Currently uses [Cobra](https://github.com/spf13/cobra) for command structure and [Huh](https://github.com/charmbracelet/huh) for interactive UI. + +**Interactive UI patterns:** See [Interactive UI Reference](references/interactive-ui.md) + +## Command Organization + +- One file per command in `cmd/`, file name matches command name (camelCase) +- All commands registered in their own `init()` function via `rootCmd.AddCommand()` +- See `cmd/root.go` for the root command structure and initialization chain +- See any existing command file (e.g., `cmd/version.go`) for a minimal example + +## Adding a New Command + +1. Create a new file in `cmd/` (camelCase name matching the command) +2. Define a `cobra.Command` variable with `Use` and `Short` fields +3. In `init()`: register with `rootCmd.AddCommand()`, define flags, bind to Viper +4. Suppress the init lint: `//nolint:gochecknoinits // Cobra requires an init function to set up the command structure.` + +## Flag Conventions + +| Scope | Method | +|-------|--------| +| Global (all commands) | `rootCmd.PersistentFlags()` | +| Local (one command) | `cmd.Flags()` | + +- Use `StringVar`/`BoolVar`/`CountVarP` (pointer-binding) for all flags +- Bind every flag to Viper: `viper.BindPFlag("name", cmd.Flags().Lookup("name"))` +- Use kebab-case for flag names: `--git-clone-protocol`, not `--gitCloneProtocol` +- Provide meaningful defaults and descriptions + +## Initialization Chain + +Global dependencies are initialized via `cobra.OnInitialize()` in `root.go`. Each initializer sets a package-level global. Order matters — later initializers may depend on earlier ones. Read `root.go` for the current chain. + +## Error Handling in Commands + +- Use `Run` (not `RunE`) — errors are handled inline with `logger.Error()` + `os.Exit(1)` +- Use `logger.Success()` for positive completion messages +- Keep `Run` functions thin — delegate to business logic in `lib/` + +## Signal Handling and Cleanup + +- Signal handlers are registered in `setupCleanup()` in `root.go` +- `PersistentPostRun` on root command handles successful completion cleanup +- Separate `cleanupAndExit()` function for error/signal paths +- Always clean up resources (loggers, temp files) on all exit paths + +## Non-Interactive Mode + +The `--non-interactive` flag: +- Disables all interactive prompts (Huh forms) +- Disables progress indicators +- Uses automatic defaults or explicit flag values instead +- Enables CI/CD and scripted usage + +## Output Modes + +| Flags | Mode | Behavior | +|-------|------|----------| +| (none) | Progress | Hierarchical spinners, hide command output | +| `--plain` | Plain | Simple log messages, hide command output | +| `-v` / `-vv` | Passthrough | Show all command output | +| `--non-interactive` | Passthrough | Show all command output | + +See `GetDisplayMode()` in `root.go` for the resolution logic. + +## Key Rules + +- Commands should not import each other; share state via package-level variables in `cmd/` +- Use `fmt.Fprint(os.Stderr, ...)` for error output, logger for structured messages +- Always respect `--non-interactive` in any new interactive functionality diff --git a/.claude/skills/developing-cli-apps/references/interactive-ui.md b/.claude/skills/developing-cli-apps/references/interactive-ui.md new file mode 100644 index 0000000..456d71f --- /dev/null +++ b/.claude/skills/developing-cli-apps/references/interactive-ui.md @@ -0,0 +1,35 @@ +# Interactive UI Reference + +Interactive UI is built with [Huh](https://github.com/charmbracelet/huh) for terminal-based forms and selection prompts. All interactive components live in `cli/`. + +## Architecture Pattern + +Every interactive UI component follows this layering: + +1. **Define an interface** for the interaction (enables testing with mocks) +2. **Implement with Huh** as the concrete implementation +3. **Provide a `NewDefault*` constructor** that wires up Huh internally +4. **Consume via dependency injection** in command logic + +See `cli/selector.go` for the generic `Selector[T]` interface and its Huh implementation. See `cli/gpg_selector.go` for a domain-specific wrapper example. + +## Key Behaviors + +- **Single-item optimization**: if only one option exists, return it directly without prompting +- **Empty-list error**: return an error if no items are available for selection +- **Label mapping**: use `SelectWithLabels` when display text differs from the underlying value + +## Non-Interactive Fallback + +When `--non-interactive` is set, skip all Huh prompts entirely. Use flag values or defaults instead, and log what was skipped as a warning. Check `IsNonInteractive()` before any interactive operation. + +## Progress Transitions + +Use `StartInteractiveProgress` / `FinishInteractiveProgress` / `FailInteractiveProgress` when transitioning between progress display and interactive UI. This properly pauses spinners during user input. + +## Key Rules + +- Never call Huh directly from commands — always go through an interface in `cli/` +- Use generics for reusable selection patterns (see existing `Selector[T]`) +- Provide `NewDefault*` constructors that wire Huh internally +- Respect `--non-interactive` in all UI components diff --git a/.claude/skills/linting-go-code/SKILL.md b/.claude/skills/linting-go-code/SKILL.md new file mode 100644 index 0000000..36d1fd8 --- /dev/null +++ b/.claude/skills/linting-go-code/SKILL.md @@ -0,0 +1,41 @@ +--- +name: linting-go-code +description: Lint and format Go code. Use when you need to run linters, fix lint errors, format code, or understand why a linter is complaining. +--- + +# Linting Go Code + +All commands run from the Go module root (`installer/`). + +## Lint + +```bash +task lint +``` + +Runs golangci-lint (the master linter — all individual linters run through it) plus typos for spell checking. Auto-fixes what it can. + +## Format + +```bash +task fmt +``` + +Formats code through golangci-lint (gofumpt + goimports + golines). Never run these formatters standalone — always use `task fmt`. + +## Nolint Directives + +When suppressing a lint in code, the configuration requires both a specific linter name and an explanation: + +```go +//nolint:gochecknoinits // Cobra requires an init function to set up the command structure. +``` + +Blanket `//nolint` without a linter name is not allowed. + +## When Lints Fail + +1. Read the linter's message — golangci-lint identifies which linter flagged the issue +2. Fix the code to satisfy the linter when possible +3. If the lint is a false positive, suppress with a `//nolint:lintername // reason` directive +4. For linter configuration details (which linters are enabled, thresholds, exclusions), read `.golangci.yml` diff --git a/.claude/skills/testing-e2e-containers/SKILL.md b/.claude/skills/testing-e2e-containers/SKILL.md index f0fc37a..0254e2e 100644 --- a/.claude/skills/testing-e2e-containers/SKILL.md +++ b/.claude/skills/testing-e2e-containers/SKILL.md @@ -18,21 +18,29 @@ Test the installer binary inside Docker containers running the supported Linux d ## Step 1: Build the Binary -Use goreleaser to build a snapshot binary. The docker-compose volumes mount `installer/` into containers at `/workspace/installer`, so the binary at `installer/bin/dotfiles-installer` becomes `/workspace/installer/bin/dotfiles-installer`. - -Build for the host platform (when host matches container arch): +Use goreleaser to build snapshot binaries for all platforms defined in `.goreleaser.yaml`. Run from the `installer/` directory: ```bash -cd installer && task build +cd installer && goreleaser build --skip before --snapshot --clean ``` -Cross-compile for Linux when running on macOS: +This produces binaries under `installer/dist/`, one per OS-arch combo. The docker-compose volumes mount `installer/` into containers at `/workspace/installer`, so the binary path inside the container follows this pattern: -```bash -cd installer && GOOS=linux GOARCH=arm64 goreleaser build --single-target --skip before --snapshot --clean --output ./bin/dotfiles-installer-linux-arm64 ``` +/workspace/installer/dist/dotfiles_installer__/dotfiles-installer +``` + +For example, on a macOS ARM host (Apple Silicon) running Linux ARM64 containers: + +``` +/workspace/installer/dist/dotfiles_installer_linux_arm64_v8.0/dotfiles-installer +``` + +For Linux AMD64 containers: -Adjust `GOARCH` to match the container platform (`arm64` for Apple Silicon, `amd64` for Intel). +``` +/workspace/installer/dist/dotfiles_installer_linux_amd64_v1/dotfiles-installer +``` ## Step 2: Run Tests in Containers @@ -44,27 +52,26 @@ cd installer/docker # Start container task ubuntu:start -# Run the installer +# Run the installer (adjust flags for the scenario being tested) docker-compose -f ubuntu/docker-compose.yml exec --user testuser installer-test-ubuntu \ - sudo /workspace/installer/bin/dotfiles-installer install \ + sudo /workspace/installer/dist/dotfiles_installer_linux_arm64_v8.0/dotfiles-installer install \ --shell zsh --shell-source auto --non-interactive --install-prerequisites -# Verify results -docker-compose -f ubuntu/docker-compose.yml exec --user testuser installer-test-ubuntu \ - command -v zsh +# Verify results (scenario-dependent) +# ... # Tear down before next test task ubuntu:stop ``` -For standalone containers (without docker-compose), bind-mount the binary explicitly: +For standalone containers (without docker-compose), bind-mount the dist directory explicitly: ```bash docker run -d --name test-ubuntu --platform linux/arm64 \ - -v "$(pwd)/../bin:/workspace/bin:ro" \ + -v "$(pwd)/../dist:/workspace/installer/dist:ro" \ ubuntu-installer-test-ubuntu:latest tail -f /dev/null -docker exec test-ubuntu /workspace/bin/dotfiles-installer-linux-arm64 install \ +docker exec test-ubuntu /workspace/installer/dist/dotfiles_installer_linux_arm64_v8.0/dotfiles-installer install \ --shell zsh --shell-source system --non-interactive docker stop test-ubuntu && docker rm test-ubuntu @@ -72,20 +79,7 @@ docker stop test-ubuntu && docker rm test-ubuntu ## Step 3: Verify Results -After running the installer, verify inside the container: - -```bash -# Check PATH-visible binary -docker exec command -v zsh - -# Check specific paths (brew is NOT in PATH by default) -docker exec ls -la /home/linuxbrew/.linuxbrew/bin/zsh # brew -docker exec ls -la /usr/bin/zsh # system (ubuntu/debian) -docker exec ls -la /usr/sbin/zsh # system (fedora) - -# Verify version -docker exec zsh --version -``` +Verification depends on what the test scenario is exercising. After running the installer, determine appropriate checks based on the flags and features being tested, then run them inside the container using `docker-compose exec` or `docker exec`. ## Testing All Distros @@ -101,6 +95,12 @@ for distro in ubuntu debian fedora; do done ``` +## Interactive GPG Testing + +For testing the GPG key setup flow interactively (which requires automating GPG's prompts), see the [testing-interactive-gpg skill][gpg-skill]. + +[gpg-skill]: /Users/timorgruber/.local/share/chezmoi/.claude/skills/testing-interactive-gpg/SKILL.md + ## Gotchas - See [distro-specific notes](references/distro-notes.md) for platform quirks (zsh paths, brew behavior, package manager differences) diff --git a/.claude/skills/testing-go-code/SKILL.md b/.claude/skills/testing-go-code/SKILL.md new file mode 100644 index 0000000..61678fa --- /dev/null +++ b/.claude/skills/testing-go-code/SKILL.md @@ -0,0 +1,50 @@ +--- +name: testing-go-code +description: Run Go unit tests, coverage reports, and benchmarks. Use when you need to run tests, check coverage, run benchmarks, or regenerate mocks after interface changes. +--- + +# Testing Go Code + +All commands run from the Go module root (`installer/`). + +## Unit Tests + +```bash +task test # Run all tests with race detection +task test -- -run TestName # Run specific test(s) +task test -- -short # Skip integration tests +``` + +For test conventions (naming, assertions, table-driven patterns, mock usage), see the `writing-go-code` skill. + +## Coverage + +```bash +task cov +``` + +Runs tests with coverage and opens an HTML report in the browser. + +## Benchmarks + +```bash +task bench +``` + +Runs all benchmarks with memory allocation stats. + +## Combined Check + +```bash +task check +``` + +Runs tests + lint in sequence. Use before committing. + +## Mock Regeneration + +```bash +mockery +``` + +Run from the module root with no arguments after adding or modifying interfaces. Configuration is in `.mockery.yml`. Never edit generated mock files (`*_mock.go`) manually. diff --git a/.claude/skills/testing-interactive-gpg/SKILL.md b/.claude/skills/testing-interactive-gpg/SKILL.md new file mode 100644 index 0000000..c02d6ca --- /dev/null +++ b/.claude/skills/testing-interactive-gpg/SKILL.md @@ -0,0 +1,98 @@ +--- +name: testing-interactive-gpg +description: Test the installer's interactive GPG key setup using an expect script that automates GPG prompts. Use when (1) testing GPG key generation end-to-end, (2) verifying the installer handles GPG prompts correctly, (3) debugging GPG-related failures in CI or containers, or (4) modifying the GPG setup flow and needing to validate it interactively. +--- + +# Interactive GPG Testing + +Test the installer's GPG key setup flow using an expect script (`installer/test-interactive-gpg.exp`) that automates responses to GPG's interactive prompts. + +## Why This Exists + +GPG key generation is fully interactive — it prompts for email, name, passphrase, key type, and confirmations. The installer runs GPG in passthrough mode, so these prompts reach the terminal directly. Automated testing requires an expect script to respond to them. + +## Prerequisites + +Check if `expect` is available, and install it if not: + +```bash +command -v expect || brew install expect # macOS +command -v expect || sudo apt-get install expect # Ubuntu/Debian +command -v expect || sudo dnf install expect # Fedora +``` + +## Usage + +Run from the `installer/` directory (or provide the full path to the binary): + +```bash +./test-interactive-gpg.exp [installer_path] [email] [name] [passphrase] [branch] [verbosity] +``` + +All arguments are optional and have defaults: + +| Argument | Default | Description | +|----------|---------|-------------| +| `installer_path` | `./dotfiles-installer` | Path to the installer binary | +| `email` | `test-user@example.com` | GPG key email address | +| `name` | `Test CI User` | GPG key full name | +| `passphrase` | `test-ci-passphrase` | GPG key passphrase | +| `branch` | *(empty)* | Git branch for `--git-branch` flag | +| `verbosity` | *(empty)* | Verbosity flag (e.g., `-v`, `-vv`) | + +### Examples + +```bash +# Default values — good for quick smoke tests +./test-interactive-gpg.exp + +# Custom GPG identity +./test-interactive-gpg.exp ./dotfiles-installer "your@email.com" "Your Name" "your-passphrase" + +# Test a specific branch with verbose output +./test-interactive-gpg.exp ./dotfiles-installer "" "" "" feature-branch -vv + +# Use a binary from goreleaser dist (in Docker container) +./test-interactive-gpg.exp \ + ./dist/dotfiles_installer_linux_arm64_v8.0/dotfiles-installer \ + "test@example.com" "Test User" "test-passphrase" +``` + +## How It Works + +The script spawns the installer with `install --plain --install-prerequisites=true --git-clone-protocol=https` and then enters an expect loop that matches GPG prompts by regex: + +- **Email/name/passphrase** — responds with the provided arguments +- **Key type, size, expiration** — accepts defaults (RSA, default size, no expiration) +- **Comment field** — skips (empty) +- **Confirmation prompts** (`(O)kay`) — sends `O` +- **Errors** — logs but continues (some errors are expected in CI) +- **Timeout** — fails after 300 seconds + +The script exits with the installer's exit code. + +## Testing in Docker Containers + +Combine with the `testing-e2e-containers` skill workflow: + +1. Build the binary: `cd installer && goreleaser build --skip before --snapshot --clean` +2. Start a container: `cd installer/docker && task ubuntu:start` +3. Copy or mount the expect script and run it inside the container +4. Tear down: `task ubuntu:stop` + +See the [testing-e2e-containers skill][e2e-skill] for container management details. + +## Debugging + +If the script hangs or mismatches a prompt: + +1. Enable debug mode: edit the script and set `exp_internal 1` (line with `exp_internal 0`) +2. Run manually and observe the exact prompt text GPG produces +3. Add or adjust regex patterns in the `expect` block to match new prompt formats + +Common issues: +- **GPG errors in containers** — expected in minimal container environments; the script logs and continues +- **Timeout** — GPG key generation can be slow without entropy; ensure the container has enough (`rng-tools` or `haveged` can help) +- **Unmatched prompts** — GPG prompt text varies by version; use case-insensitive regex patterns + +[e2e-skill]: /Users/timorgruber/.local/share/chezmoi/.claude/skills/testing-e2e-containers/SKILL.md diff --git a/.claude/skills/writing-go-code/SKILL.md b/.claude/skills/writing-go-code/SKILL.md index 90c7ff1..fae4b08 100644 --- a/.claude/skills/writing-go-code/SKILL.md +++ b/.claude/skills/writing-go-code/SKILL.md @@ -1,12 +1,16 @@ --- name: writing-go-code -description: Apply Go coding standards when writing, reviewing, or modifying Go code. Use when implementing functions, writing tests with testify, generating mocks with mockery, using dependency injection, handling errors idiomatically, or working with interfaces. Use this skill for any Go file editing task. For Go language conventions and idioms from official docs, see effective-go skill instead. +description: Apply Go coding standards when writing, reviewing, or modifying Go code. Use when implementing functions, writing tests with testify, generating mocks with mockery, using dependency injection, handling errors idiomatically, or working with interfaces. Use this skill for any Go file editing task. --- # Go Development Standards Project-specific Go coding standards for this codebase. +## Companion Skill + +This skill covers **project-specific** Go patterns (testing conventions, mock generation, dependency injection style). For **general Go idioms** from the official Effective Go documentation (naming, control flow, error handling philosophy, concurrency patterns), also load the `applying-effective-go` skill. Both skills are complementary — this one tells you how *this project* writes Go, the other tells you how *Go itself* should be written. + ## Quick Reference **Coding patterns:** See [Code Style Reference](references/code-style.md) diff --git a/.claude/skills/writing-go-code/references/test-style.md b/.claude/skills/writing-go-code/references/test-style.md index 63550ee..fdfa24c 100644 --- a/.claude/skills/writing-go-code/references/test-style.md +++ b/.claude/skills/writing-go-code/references/test-style.md @@ -160,54 +160,6 @@ func Test_InstallingPackage_Should_SucceedWithoutError_When_BrewIsAvailable(t *t --- -## Using Mocks +## Using Mocks in Tests -Mocks are generated using `mockery` with `moq` template. - -**Key Points:** - -- Assume mocks are already generated. -- If a mock is missing, run `mockery` in the project root (no arguments). -- Prefix mock types with `Moq` as expected by the moq library. -- Pass function implementations to the mock constructor. -- Mock files are placed next to the interface they mock. - -**Mock File Naming:** `{interfacename}_mock.go` (lowercase) - -**Example:** - -```go -// For interface Logger, mock file is: logger_mock.go -// Mock type is: MoqLogger - -func Test_ServiceLogsErrors(t *testing.T) { - var loggedMessage string - logger := &MoqLogger{ - ErrorFunc: func(format string, args ...any) { - loggedMessage = fmt.Sprintf(format, args...) - }, - } - - svc := NewService(logger) - svc.DoSomethingThatFails() - - require.Contains(t, loggedMessage, "failed") -} -``` - -**Regenerating Mocks:** - -```bash -cd installer -mockery -``` - ---- - -## Tech Stack - -| Tool | Purpose | Link | -|------|---------|------| -| testify | Assertions and test utilities | [github.com/stretchr/testify](https://github.com/stretchr/testify) | -| moq | Mock generation template | [github.com/matryer/moq](https://github.com/matryer/moq) | -| mockery | Mock generation tool | [github.com/vektra/mockery](https://github.com/vektra/mockery) | +Mocks are generated by mockery. For regeneration commands, see the `testing-go-code` skill. For mock naming, file placement, and struct conventions, see `.mockery.yml` — these are configuration-driven, not hardcoded conventions. diff --git a/.github/INSTALLER_CI_README.md b/.github/INSTALLER_CI_README.md deleted file mode 100644 index fe735e8..0000000 --- a/.github/INSTALLER_CI_README.md +++ /dev/null @@ -1,99 +0,0 @@ -# Installer CI Documentation - -This directory contains GitHub Actions workflows for the dotfiles installer project located in the `installer/` subdirectory. - -## Workflow Overview - -### 🔧 installer-ci.yml -**Purpose**: Build and test the installer -**Trigger**: Push to main or PRs affecting `installer/` directory - -**Jobs (in order)**: -1. **Build**: Uses GoReleaser to create cross-platform binaries -2. **Test**: Runs Go test suite with race detection -3. **E2E Tests**: Tests installer on multiple platforms in real environments - -**Platforms Tested**: -- Ubuntu (latest) -- Debian (bookworm container) -- Fedora (latest) -- CentOS (latest) -- macOS (latest) - -## Build Process - -The CI uses GoReleaser in **snapshot mode** to: -- Build cross-platform binaries (Linux/macOS, AMD64/ARM64) -- Generate consistent build artifacts -- **No releases** - just builds for testing - -## E2E Testing - -The pipeline includes end-to-end testing that: - -1. **Downloads** the built installer binary -2. **Tests** on multiple OS distributions -3. **Verifies** compatibility detection works -4. **Runs** installer in non-interactive mode -5. **Validates** graceful behavior in CI environments - -### Test Configuration - -E2E tests use these flags for CI compatibility: -- `--non-interactive`: Skips all user prompts -- `--plain`: Disables progress indicators for cleaner logs -- `--install-brew=false`: Skips Homebrew for faster testing -- `--install-prerequisites=false`: Skips prerequisite installation -- `--git-clone-protocol=https`: Uses HTTPS instead of SSH - -### Test Environment - -- **Isolated**: Uses `/tmp/test-home` as HOME directory -- **Timeout**: 300 seconds (5 minutes) to prevent hangs -- **Graceful Failures**: Expected in CI since we don't have full system setup - -## Local Testing - -To test the workflow locally: - -```bash -cd installer/ -task build -./bin/dotfiles-installer install --non-interactive --plain --install-brew=false -``` - -## Workflow Structure - -``` -.github/ -└── workflows/ - └── installer-ci.yml # Main CI pipeline -``` - -## Troubleshooting - -### Common Issues - -1. **Build Fails**: Check Go version in `installer/go.mod` -2. **E2E Test Fails**: Review platform-specific requirements -3. **Test Timeout**: E2E tests timeout after 5 minutes - -### Debugging E2E Tests - -E2E tests are designed to handle CI environment limitations: -- Allow expected failures (exit code 1) in restricted environments -- Create isolated test directories -- Skip complex system modifications - -To debug locally: -```bash -export HOME="/tmp/test-home" -mkdir -p "$HOME" -./installer/bin/dotfiles-installer install --non-interactive --plain -``` - -## Future Enhancements - -- **Linting**: Will integrate golangci-lint later -- **Security Scanning**: Can add Trivy scans if needed -- **Release Automation**: Will add when ready for releases diff --git a/AGENTS.md b/AGENTS.md index 9173a3b..1b034fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,6 +7,10 @@ Personal dotfiles managed with [chezmoi]. This repo is the **chezmoi source dire | Skill | Use When | | ---------------------------- | --------------------------------------------------------------------------- | | `writing-go-code` | Writing/editing Go code, tests, mocks, interfaces | +| `developing-cli-apps` | CLI commands, flags, Cobra patterns, Huh interactive UI, signal handling | +| `building-go-binaries` | Compiling the project, troubleshooting build failures | +| `linting-go-code` | Running linters, fixing lint errors, formatting code | +| `testing-go-code` | Running unit tests, coverage, benchmarks, regenerating mocks | | `managing-chezmoi` | Editing `dot_*`, `private_dot_*`, or `.tmpl` files; chezmoi commands | | `configuring-zsh` | .zshrc, .zshenv, plugins, PATH, completions | | `configuring-github-actions` | .github/workflows, CI/CD, matrix builds | @@ -25,19 +29,27 @@ Personal dotfiles managed with [chezmoi]. This repo is the **chezmoi source dire . ├── dot_claude/ # ~/.claude (Claude global config) ├── .github/workflows/ # CI/CD pipelines -├── installer/ # Go installer/bootstrapper (has own CLAUDE.md) +├── installer/ # Go installer/bootstrapper (has own AGENTS.md) ├── dot_config/ # ~/.config/* files (sheldon, etc.) ├── dot_zshrc, dot_zshenv, ... # Shell config files ├── private_dot_ssh/ # ~/.ssh (private files) └── .chezmoiignore # Files to ignore during apply ``` +## Documentation + +- `docs/domain.md` — Project-specific terminology, the work environment model, chezmoi data schema, package resolution system, and other domain concepts +- `docs/architecture.md` — Top-level project structure: installer, chezmoi templates, shell runtime, and how they connect through the data contract +- `docs/architecture-installer.md` — Installer's internal layered architecture: cmd, lib, cli, utils, dependency injection, key design decisions +- `docs/processes/` — End-to-end flows: installation (with sub-processes for compatibility checking, prerequisite installation, shell setup, GPG setup, dotfiles setup), package resolution, shell startup, work environment loading + ## Key Conventions 1. **Zsh is the primary shell** - Most shell config is Zsh-specific 2. **Sheldon for plugin management** - Not oh-my-zsh at runtime (used only for vendored snippets) 3. **Templates for conditional config** - `{{ .chezmoi.os }}` for OS-specific logic 4. **Separate work/personal dotfiles** - Work configs loaded conditionally in work environments +5. **Global skills and agents live in `dot_claude/`** - Edit `dot_claude/skills/` and `dot_claude/agents/` here, never under `~/.claude/` directly ## Project Motivation @@ -51,7 +63,7 @@ The installer is a Go CLI application in the `installer/` directory. It was rewr **Tech stack**: [cobra] (CLI), [huh] (interactive UI), [goreleaser] (releases) -**For development details**, see `installer/CLAUDE.md`. +**For development details**, see `installer/AGENTS.md`. [chezmoi]: https://www.chezmoi.io/ [homebrew]: https://docs.brew.sh/ diff --git a/RELEASING.md b/RELEASING.md deleted file mode 100644 index 31ec24e..0000000 --- a/RELEASING.md +++ /dev/null @@ -1,167 +0,0 @@ -# Release Process - -This document outlines the process for creating releases of the dotfiles installer. - -## Prerequisites - -- Push access to the main branch -- Ability to create tags and releases -- All changes merged to `main` branch -- Tests passing on the latest commit - -## Release Steps - -### 1. Prepare the Release - -1. Ensure all changes for the release are merged into `main` -2. Update version references if needed (the build process handles most versioning automatically) -3. Run tests locally to ensure everything works: - ```bash - cd installer - go test -race -v ./... - ``` - -### 2. Create and Push the Tag - -1. Create a new tag following semantic versioning (e.g., `v1.0.0`, `v1.1.0`, `v2.0.0-beta.1`): - ```bash - git tag v1.0.0 - ``` - -2. Push the tag to trigger the release workflow: - ```bash - git push origin v1.0.0 - ``` - -### 3. Monitor the Release Process - -1. Go to the [Actions tab](https://github.com/MrPointer/dotfiles/actions) in GitHub -2. Monitor the "Release" workflow that gets triggered by the tag push -3. The workflow will: - - Build binaries for all supported platforms - - Sign the binaries with cosign - - Create a GitHub release with the binaries attached - - Generate checksums for verification - -### 4. Verify the Release - -1. Check the [Releases page](https://github.com/MrPointer/dotfiles/releases) -2. Verify that the release contains: - - Binaries for all platforms (macOS arm64/x86_64, Linux arm64/x86_64) - - Checksums file (`checksums.txt`) - - Proper release notes -3. Test the get script with the new release: - ```bash - curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --version v1.0.0 - ``` - -## Supported Platforms - -The automated release process builds binaries for: - -- **macOS** - - ARM64 (Apple Silicon) - - x86_64 (Intel) -- **Linux** - - ARM64 - - x86_64 - -## Versioning Strategy - -We follow [Semantic Versioning (SemVer)](https://semver.org/): - -- **MAJOR version** (`v2.0.0`): Incompatible API changes or major breaking changes -- **MINOR version** (`v1.1.0`): Backward-compatible functionality additions -- **PATCH version** (`v1.0.1`): Backward-compatible bug fixes - -### Pre-release Versions - -For beta or release candidate versions, append the pre-release identifier: -- `v1.0.0-beta.1` -- `v1.0.0-rc.1` - -## Release Checklist - -- [ ] All changes merged to `main` -- [ ] Tests passing locally and on CI -- [ ] Version tag created and follows SemVer -- [ ] Tag pushed to GitHub -- [ ] Release workflow completed successfully -- [ ] Release appears on GitHub with all expected assets -- [ ] Get script tested with new version -- [ ] Release announcement (if needed) - -## Troubleshooting - -### Release Workflow Failed - -1. Check the workflow logs in the Actions tab -2. Common issues: - - Go build failures (check for compilation errors) - - Test failures (fix tests before releasing) - - GoReleaser configuration issues (validate `.goreleaser.yaml`) - - Permission issues (ensure GITHUB_TOKEN has proper permissions) - -### Missing Binaries - -If some platform binaries are missing: -1. Check the GoReleaser configuration in `installer/.goreleaser.yaml` -2. Verify the `builds` section includes all required platforms -3. Re-run the release by deleting and recreating the tag - -### Binary Signing Issues - -If cosign signing fails: -1. Check that the workflow has `id-token: write` permissions -2. Verify cosign installation in the workflow -3. The signing process uses GitHub's OIDC provider automatically - -## Manual Release (Fallback) - -If the automated process fails, you can create a release manually: - -```bash -cd installer -goreleaser release --clean -``` - -This requires: -- GoReleaser installed locally -- `GITHUB_TOKEN` environment variable set -- cosign installed for signing (optional) - -## Post-Release Tasks - -1. Update any documentation that references version numbers -2. Consider updating the get script if there are breaking changes -3. Announce the release in relevant channels if it's a major release -4. Monitor for any issues reported by users - -## Get Script Features - -The `get.sh` script provides multiple ways for users to download the installer binary and optionally run it: - -**Basic download:** -```bash -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -``` - -**One-command download and install dotfiles:** -```bash -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run -``` - -**Download and install dotfiles with custom options:** -```bash -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run -- install --work-env --non-interactive -``` - -This solves the "pass custom options" problem by allowing users to specify installer arguments after `--run --`. Note that "install" here refers to installing the dotfiles, not installing the binary. - -## Security Considerations - -- All binaries are built in a secure GitHub Actions environment with reproducible builds -- SHA256 checksums are generated for all assets to enable verification -- The release process runs with minimal required permissions -- No secrets are required for the standard release process -- Builds are deterministic and traceable through GitHub Actions logs diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md deleted file mode 100644 index 5317fbb..0000000 --- a/docs/INSTALLATION.md +++ /dev/null @@ -1,232 +0,0 @@ -# Installation Guide - -This guide covers different methods to download the dotfiles installer and install your dotfiles. - -## Quick Start - -The fastest way to get started is using our get script: - -```bash -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -``` - -This will download the latest installer binary to `~/.local/bin/dotfiles-installer`. - -## Installation Methods - -### 1. Using the Get Script (Recommended) - -The get script automatically detects your platform and downloads the appropriate binary: - -```bash -# Download to default location (~/.local/bin) -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash - -# Download and install dotfiles immediately (one-command setup) -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run - -# Download and install dotfiles with custom options -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run -- --work-env --install-prerequisites - -# Download and install dotfiles non-interactively -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run -- install --non-interactive --plain - -# Download to custom directory -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --dir /usr/local/bin - -# Download specific version -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --version v1.0.0 -``` - -#### Get Script Options - -- `--dir DIR`: Download directory (default: `$HOME/.local/bin`) -- `--version VER`: Specific version to download (default: latest) -- `--run`: Run the installer after download (this installs your dotfiles) -- `--help`: Show help message - -#### Passing Arguments to the Installer - -When using `--run`, you can pass arguments to the installer by placing them after `--`: - -```bash -# Basic usage - runs 'install' command to install your dotfiles -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run - -# Pass specific command and options for dotfiles installation -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run -- install --work-env --non-interactive - -# Run compatibility check instead -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -s -- --run -- check-compatibility -``` - -### 2. Manual Download - -Download pre-built binaries from [GitHub Releases](https://github.com/MrPointer/dotfiles/releases). - -#### macOS -```bash -curl -L -o dotfiles-installer.tar.gz https://github.com/MrPointer/dotfiles/releases/latest/download/dotfiles-installer-*-darwin-arm64.tar.gz -tar -xzf dotfiles-installer.tar.gz -chmod +x dotfiles-installer -sudo mv dotfiles-installer /usr/local/bin/ -``` - -#### Linux (x86_64) -```bash -curl -L -o dotfiles-installer.tar.gz https://github.com/MrPointer/dotfiles/releases/latest/download/dotfiles-installer-*-linux-x86_64.tar.gz -tar -xzf dotfiles-installer.tar.gz -chmod +x dotfiles-installer -sudo mv dotfiles-installer /usr/local/bin/ -``` - -#### Linux (ARM64) -```bash -curl -L -o dotfiles-installer.tar.gz https://github.com/MrPointer/dotfiles/releases/latest/download/dotfiles-installer-*-linux-arm64.tar.gz -tar -xzf dotfiles-installer.tar.gz -chmod +x dotfiles-installer -sudo mv dotfiles-installer /usr/local/bin/ -``` - -### 3. Using Go Install - -If you have Go installed and want the latest development version: - -```bash -go install github.com/MrPointer/dotfiles/installer@latest -``` - -### 4. Build from Source - -For development or if you want to modify the installer: - -```bash -git clone https://github.com/MrPointer/dotfiles.git -cd dotfiles/installer -go build -o dotfiles-installer . -``` - -## Verification - -### Check Installation -```bash -dotfiles-installer version -``` - -### Verify Binary Checksums (Optional) - -All release binaries include SHA256 checksums for verification: - -```bash -# Download checksums file -curl -L -o checksums.txt https://github.com/MrPointer/dotfiles/releases/latest/download/checksums.txt - -# Verify your downloaded binary -shasum -a 256 -c checksums.txt --ignore-missing -``` - -## Usage - -Once downloaded, you can use the dotfiles installer: - -```bash -# Check system compatibility -dotfiles-installer check-compatibility - -# Install dotfiles (interactive) -dotfiles-installer install - -# Install dotfiles (non-interactive) -dotfiles-installer install --non-interactive --install-prerequisites - -# Show help -dotfiles-installer --help -``` - -## Supported Platforms - -The installer supports the following platforms: - -- **macOS** - - ARM64 (Apple Silicon - M1, M2, M3, etc.) -- **Linux** - - x86_64 (AMD64) - - ARM64 (AArch64) - -## Troubleshooting - -### Binary Not Found After Installation - -If the binary is not found after installation, ensure the install directory is in your PATH: - -```bash -# Check if directory is in PATH -echo $PATH | grep -o "$HOME/.local/bin" - -# Add to PATH if missing (add to your shell's RC file) -export PATH="$HOME/.local/bin:$PATH" -``` - -### Permission Denied - -If you get permission denied errors: - -```bash -# Make sure the binary is executable -chmod +x /path/to/dotfiles-installer - -# For system-wide setup, use sudo -sudo mv dotfiles-installer /usr/local/bin/ -``` - -### Download Issues - -If downloads fail: - -1. Check your internet connection -2. Try using `wget` instead of `curl`: - ```bash - wget https://github.com/MrPointer/dotfiles/releases/latest/download/dotfiles-installer-*-linux-x86_64.tar.gz - ``` -3. Download from the [releases page](https://github.com/MrPointer/dotfiles/releases) manually - -### Version Mismatch - -To ensure you have the latest version: - -```bash -# Check current version -dotfiles-installer version - -# Download latest version again -curl -fsSL https://raw.githubusercontent.com/MrPointer/dotfiles/main/get.sh | bash -``` - -## Uninstalling - -To remove the dotfiles installer: - -```bash -# Remove the binary -rm $(which dotfiles-installer) - -# Or if installed in ~/.local/bin -rm ~/.local/bin/dotfiles-installer -``` - -Note: This only removes the installer binary, not your installed dotfiles themselves. To remove dotfiles, see the main documentation. - -## Getting Help - -- **Documentation**: Check the main [README](../README.md) -- **Issues**: Report bugs on [GitHub Issues](https://github.com/MrPointer/dotfiles/issues) -- **Discussions**: Ask questions in [GitHub Discussions](https://github.com/MrPointer/dotfiles/discussions) - -## Security - -- All binaries are built in GitHub Actions with reproducible builds -- SHA256 checksums are provided for all releases for verification -- Source code is available for audit -- Builds are deterministic and traceable - -For security concerns, please see our [security policy](../SECURITY.md). \ No newline at end of file diff --git a/docs/architecture-installer.md b/docs/architecture-installer.md new file mode 100644 index 0000000..bc1c00e --- /dev/null +++ b/docs/architecture-installer.md @@ -0,0 +1,190 @@ +# Installer Architecture + +## Overview + +The installer is a Go CLI application structured in four layers: **cmd** (CLI entry points and orchestration), **lib** (business logic organized by domain area), **cli** (interactive UI components), and **utils** (shared infrastructure). Dependencies flow inward — cmd depends on lib and utils, lib depends on utils, and utils depends on nothing internal. All external interactions are behind interfaces for testability. + +## Design Principles + +- **Interface-driven**: Every interaction with the outside world (filesystem, command execution, HTTP, OS operations, package managers) is defined as an interface. Implementations are injected via constructors. This enables comprehensive unit testing with mocks — no real `apt-get install` calls in tests. +- **Layered with strict direction**: Dependencies flow `cmd → lib → utils`. The `lib` packages never import `cmd`. The `utils` packages never import `lib`. This keeps the business logic decoupled from CLI concerns. +- **One package per domain area**: Each area of concern (brew, apt, dnf, gpg, shell, compatibility, dotfiles management, package resolution) gets its own package under `lib/`. Packages communicate through interfaces, not concrete types. +- **Global state in cmd only**: The `cmd` layer holds global variables (`globalPackageManager`, `globalSysInfo`, `globalBrewPath`, `selectedGpgKey`) that thread state between installation steps. The `lib` layer is stateless — it receives everything it needs through constructor parameters and method arguments. + +## Structure + +### cmd — CLI Layer + +- **Responsibility**: Define Cobra commands, parse flags, initialize global dependencies, orchestrate the [installation flow][installation] +- **Boundaries**: Imports from `lib`, `cli`, and `utils`. Never imported by other layers. +- **Key patterns**: + - `root.go` initializes shared dependencies via `cobra.OnInitialize` (logger, commander, OS manager, compatibility config) + - `install.go` orchestrates the sequential installation steps, managing global state between them + - Each step calls into `lib` packages, passing pre-built dependencies + +### lib — Business Logic Layer + +Each package under `lib/` owns one domain area: + +| Package | Responsibility | Key interfaces | +|---------|---------------|----------------| +| [`pkgmanager`][pkgmanager] | Package manager abstraction | `PackageManager` — install, uninstall, query packages | +| [`brew`][brew] | Homebrew implementation | Implements `PackageManager`; also `BrewInstaller` for installing Homebrew itself | +| [`apt`][apt] | APT implementation | Implements `PackageManager` | +| [`dnf`][dnf] | DNF implementation | Implements `PackageManager`; handles group/pattern types | +| [`compatibility`][compatibility] | System detection and prerequisite checking | `OSDetector`, `PrerequisiteChecker` | +| [`packageresolver`][packageresolver] | Abstract key → concrete package name resolution | `Resolver` (struct, not interface — internal use only) | +| [`shell`][shell] | Shell installation and default-setting | `ShellInstaller`, `ShellResolver`, `ShellChanger` | +| [`gpg`][gpg] | GPG client installation and key management | `GpgInstaller`, `GpgClient` | +| [`dotfilesmanager`][dotfilesmanager] | Chezmoi integration | `DotfilesManager` (composed of `DotfilesInstaller`, `DotfilesDataInitializer`, `DotfilesApplier`) | + +**Dependency direction within lib**: Packages depend on `pkgmanager` (the interface), never on each other's concrete implementations. For example, `shell` accepts a `PackageManager` — it doesn't know whether it's brew or apt. + +### cli — Interactive UI Layer + +- **Responsibility**: Present interactive prompts to the user using [Huh][huh] (select menus, multi-select forms) +- **Boundaries**: Imported by `cmd` only. Knows nothing about `lib` internals — receives data as simple types. +- **Key components**: + - `selector.go` — Generic single-select wrapper around Huh + - `multiselect_selector.go` — Generic multi-select wrapper + - `prerequisite_selector.go` — Prerequisite selection form + - `gpg_selector.go` — GPG key selection form + +### utils — Infrastructure Layer + +Shared utilities that all other layers depend on: + +| Package/File | Responsibility | +|-------------|----------------| +| `commander.go` | Command execution with functional options (`WithCaptureOutput`, `WithEnv`, `WithInput`, etc.) | +| `filesystem.go` | File and directory operations (`PathExists`, `ReadFile`, `WriteFile`, `CreateDirectory`) | +| `program_query.go` | Check if programs exist on PATH (wraps `exec.LookPath`) | +| `display_mode.go` | [Display mode][domain-display-modes] enum and behavior | +| `logger/` | Logging with hierarchical progress tracking (spinners, timing, nesting) | +| `osmanager/` | OS-level operations — user management, `/etc/shells`, `/etc/passwd`, environment | +| `privilege/` | Privilege escalation — detects and uses `sudo` or `doas` | +| `httpclient/` | HTTP client interface | +| `files/` | File utility helpers | +| `collections/` | Generic collection utilities | + +### internal/config — Embedded Configuration + +- **Responsibility**: Store static YAML config files ([`compatibility.yaml`][compatibility-yaml], [`packagemap.yaml`][packagemap-yaml]) embedded into the binary via `go:embed` +- **Boundaries**: Read-only. Loaded by `lib/compatibility` and `lib/packageresolver` through viper. + +## Communication Patterns + +### Constructor injection + +All `lib` packages receive their dependencies through constructors. No package reaches into global state. + +``` +cmd creates: Logger, Commander, FileSystem, OsManager, PackageManager +cmd passes to: brew.NewBrewInstaller(logger, commander, osManager, ...) + shell.NewDefaultShellInstaller(shellName, resolver, pkgManager, ...) + chezmoi.TryStandardChezmoiManager(logger, fs, osManager, commander, pkgManager, ...) +``` + +### Global state threading (cmd layer only) + +The installation steps in `cmd/install.go` are sequential, and later steps need results from earlier ones. This is managed through package-level variables in `cmd`: + +- `globalPackageManager` — set after Homebrew installation, used by all subsequent package operations +- `globalBrewPath` — set after Homebrew installation, used for shell resolution +- `globalSysInfo` — set after compatibility check, used for package manager creation +- `selectedGpgKey` — set after GPG setup, used during chezmoi data initialization + +### Interface-based polymorphism + +Package managers are the clearest example: `brew`, `apt`, and `dnf` all implement `pkgmanager.PackageManager`. The install command creates the appropriate implementation based on the detected system, then passes it to any code that needs to install packages. The consuming code never knows which manager it's using. + +## Key Design Decisions + +| Decision | Choice | Rationale | +|----------|--------|-----------| +| Interfaces for all external interactions | `Commander`, `FileSystem`, `OsManager`, `PackageManager`, `HTTPClient` | Enables unit testing with mockery-generated mocks. No real system calls in tests. | +| Functional options for Commander | `WithCaptureOutput()`, `WithEnv()`, etc. | Command execution has many optional behaviors (capture output, set env, provide stdin, set timeout). Functional options keep the API clean without explosion of method signatures. | +| Separate `pkgmanager` interface package | Interface in `pkgmanager/`, implementations in `brew/`, `apt/`, `dnf/` | Prevents import cycles. Any package can depend on the interface without pulling in specific implementations. | +| Composed `DotfilesManager` interface | Split into `Installer`, `DataInitializer`, `Applier` | Each phase of dotfiles management has a distinct concern. The composed interface is available when you need the full lifecycle, but individual interfaces work when you only need one phase. | +| Global state in cmd, not lib | `globalPackageManager`, `globalSysInfo`, etc. in `cmd/install.go` | Keeps `lib` packages stateless and testable. The orchestration complexity lives in one place (the install command) rather than scattered across packages. | +| Embedded YAML configs | `go:embed` in `internal/config/` | Single binary distribution. No config files to ship or lose. Overridable via flags for testing and customization. | +| Mockery for mock generation | `.mockery.yml` config, generated `*_mock.go` files | Consistent mock generation from interface definitions. Mocks stay in sync with interfaces automatically. | + +## Diagram + +```mermaid +flowchart TD + subgraph cmd ["cmd (CLI & Orchestration)"] + root["root.go\nglobal init"] + install["install.go\ninstallation flow"] + checkCompat["checkCompatibility.go"] + end + + subgraph cli ["cli (Interactive UI)"] + selector["Selectors\n(Huh wrappers)"] + end + + subgraph lib ["lib (Business Logic)"] + compat["compatibility"] + pkgmgr["pkgmanager\n(interface)"] + brew["brew"] + apt_pkg["apt"] + dnf_pkg["dnf"] + resolver["packageresolver"] + shell_pkg["shell"] + gpg_pkg["gpg"] + dotfiles["dotfilesmanager\n+ chezmoi impl"] + + brew -.->|implements| pkgmgr + apt_pkg -.->|implements| pkgmgr + dnf_pkg -.->|implements| pkgmgr + end + + subgraph utils ["utils (Infrastructure)"] + commander["Commander"] + filesystem["FileSystem"] + osmanager["OsManager"] + logger_pkg["Logger"] + privilege["Escalator"] + httpclient["HTTPClient"] + end + + subgraph internal ["internal/config"] + compat_yaml["compatibility.yaml"] + pkgmap_yaml["packagemap.yaml"] + end + + cmd --> cli + cmd --> lib + cmd --> utils + lib --> utils + lib --> internal + + style cmd fill:#4a9,stroke:#287,color:#fff + style cli fill:#69b,stroke:#478,color:#fff + style lib fill:#c73,stroke:#a51,color:#fff + style utils fill:#88b,stroke:#669,color:#fff + style internal fill:#997,stroke:#775,color:#fff +``` + +## Constraints + +- **Single binary**: The installer must be distributable as a single binary with no external config files. This drives the `go:embed` pattern for YAML configs. +- **Cross-platform**: Must build for Linux (amd64, arm64) and macOS (amd64, arm64). Platform-specific logic lives in `lib` packages and `utils/osmanager`, not in `cmd`. +- **No daemon**: The installer runs once and exits. No persistent state between runs (except what it writes to the filesystem). This means every run is a fresh start — no state recovery or resumption. +- **Privilege boundaries**: The installer itself runs as a regular user. Privileged operations (package installation, shell registration) use explicit privilege escalation via `sudo`/`doas`. The escalator detects which tool is available. + +[installation]: processes/installation.md +[domain-display-modes]: domain.md#display-modes +[compatibility-yaml]: ../installer/internal/config/compatibility.yaml +[packagemap-yaml]: ../installer/internal/config/packagemap.yaml +[huh]: https://github.com/charmbracelet/huh +[pkgmanager]: ../installer/lib/pkgmanager +[brew]: ../installer/lib/brew +[apt]: ../installer/lib/apt +[dnf]: ../installer/lib/dnf +[compatibility]: ../installer/lib/compatibility +[packageresolver]: ../installer/lib/packageresolver +[shell]: ../installer/lib/shell +[gpg]: ../installer/lib/gpg +[dotfilesmanager]: ../installer/lib/dotfilesmanager diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..38c0d33 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,107 @@ +# Project Architecture + +## Overview + +The project has three major parts that interact through a clear data contract: a **Go installer** that bootstraps a new machine and produces configuration, **chezmoi templates** that consume that configuration to generate dotfiles, and the **resulting shell environment** that loads the generated files at runtime. The installer writes, templates read, the shell executes. + +## Design Principles + +- **Write once, consume everywhere**: The installer is the single source of truth for user configuration. It writes [chezmoi data][domain-data-schema] once; all templates read from it. This avoids drift between what the installer collected and what templates expect. +- **Progressive enhancement**: Each part of the system degrades gracefully. Shell startup skips unavailable tools rather than failing. The installer falls back from package managers to manual installation. Templates use conditionals to omit features that aren't configured. +- **Separation of concerns by lifecycle**: The installer runs once (at setup time), chezmoi applies periodically (when dotfiles change), and shell config runs every session. Each part only does work appropriate to its lifecycle. + +## Structure + +### Installer (`installer/`) + +- **Responsibility**: Bootstrap a new machine — install prerequisites, configure the shell, set up GPG, collect user input, write chezmoi configuration, clone and apply dotfiles +- **Boundaries**: Produces `~/.config/chezmoi/chezmoi.toml` as its primary output. Does not manage dotfile content — that's chezmoi's job. Does not define shell behavior — that's the templates' job. +- **Dependencies**: System package managers (apt, dnf, brew), Git, network access, `gpg` +- **Internal architecture**: See [installer architecture][arch-installer] + +### Chezmoi Templates (`dot_*`, `private_dot_*`, `*.tmpl`) + +- **Responsibility**: Define what dotfiles look like on the target machine. Templates use chezmoi data to conditionally include or exclude configuration blocks (e.g., work environment, OS-specific paths). +- **Boundaries**: Reads chezmoi data (`~/.config/chezmoi/chezmoi.toml`). Writes to the home directory via `chezmoi apply`. Never modifies its own source or the chezmoi config. +- **Dependencies**: Chezmoi binary, chezmoi data (written by the installer) + +### Shell Configuration (`dot_zshenv.tmpl`, `dot_zshrc.tmpl`, `private_dot_work/`) + +- **Responsibility**: Configure the runtime shell environment — PATH, tool integrations, plugins, [work environment][domain-work-env] loading +- **Boundaries**: These are chezmoi templates that produce shell files. At runtime, the generated files are plain shell scripts with no chezmoi dependency. +- **Dependencies**: Generated by chezmoi from templates. At runtime, depends on installed tools (Homebrew, pyenv, sheldon, fzf, etc.) + +### Embedded Configuration (`installer/internal/config/`) + +- **Responsibility**: Store static configuration that the installer needs — supported platforms ([`compatibility.yaml`][compatibility-yaml]) and package name mappings ([`packagemap.yaml`][packagemap-yaml]) +- **Boundaries**: Embedded into the Go binary at compile time via `go:embed`. Read-only at runtime. Overridable via CLI flags for testing. +- **Dependencies**: None — these are self-contained data files + +## Communication Patterns + +### Installer → Chezmoi (data contract) + +The installer writes a TOML config file at `~/.config/chezmoi/chezmoi.toml` containing three [data namespaces][domain-data-schema]: `personal`, `system`, and `gpg`. Templates access these via `.personal.*`, `.system.*`, `.gpg.*`. This file is the sole interface between the installer and the template system. + +**Why TOML**: Chezmoi natively supports TOML config files. Viper (used by the installer) can write TOML. No translation layer needed. + +### Chezmoi → Home Directory (file generation) + +`chezmoi init --apply` clones the source repo and renders templates into the home directory. The template language is Go's `text/template` with chezmoi extensions. Conditional blocks use chezmoi data and built-in variables (`.chezmoi.os`, `.chezmoi.arch`, `.chezmoi.group`). + +### Shell Files → Runtime (sourcing chain) + +Generated shell files execute in Zsh's standard sourcing order: `.zshenv` (all shells) → `.zshrc` (interactive only). Within each file, conditional sourcing loads optional components ([work profiles][domain-work-env], [deferred Homebrew][domain-deferred-brew], tool integrations). See the [shell startup process][shell-startup] for the full flow. + +## Key Design Decisions + +| Decision | Choice | Rationale | +|----------|--------|-----------| +| Installer in Go | Rewrite from Bash to Go | Testability, type safety, cross-compilation via goreleaser. Bash installer was fragile and hard to maintain. | +| Interface-based DI in installer | All external interactions behind interfaces | Every dependency (filesystem, commander, OS manager, package managers) is injectable and mockable. Enables unit testing without real system calls. | +| Embedded config files | `go:embed` for YAML configs | Single binary distribution — no need to ship config files alongside the binary. Overridable for testing. | +| Chezmoi as dotfiles manager | Not bare git, stow, or yadm | Templates with conditional logic, mature tooling, good cross-platform support. The two-tier work environment model relies on chezmoi's template system. | +| Sheldon for Zsh plugins | Not oh-my-zsh framework | oh-my-zsh is used only for vendored function/plugin snippets (loaded as local files), not as a runtime framework. Sheldon is faster and more composable. | +| Deferred Homebrew loading | Split across `.zshenv` / `.zshrc` | Homebrew's `shellenv` eval is expensive (~50ms). Deferring it on macOS keeps non-interactive shells fast while still having brew available for interactive use. | +| Fresh clone on every apply | Delete and re-clone `~/.local/share/chezmoi` | Avoids merge conflicts and stale state. The installer always applies the latest from the configured branch. | + +## Diagram + +```mermaid +flowchart LR + subgraph installer ["Installer (Go CLI)"] + direction TB + I1[Collect user input] + I2[Install prerequisites] + I3[Write chezmoi.toml] + end + + subgraph chezmoi ["Chezmoi"] + direction TB + C1["Clone dotfiles repo"] + C2["Render templates"] + C3["Apply to $HOME"] + end + + subgraph runtime ["Shell Runtime"] + direction TB + R1[".zshenv (all shells)"] + R2[".zshrc (interactive)"] + R3["Work profiles"] + end + + I1 --> I2 --> I3 + I3 -- "chezmoi.toml\n(data contract)" --> C1 + C1 --> C2 --> C3 + C3 -- "generated files" --> R1 + R1 --> R2 + R2 --> R3 +``` + +[domain-data-schema]: domain.md#chezmoi-data-schema +[domain-work-env]: domain.md#work-environment +[domain-deferred-brew]: domain.md#deferred-homebrew-loading +[arch-installer]: architecture-installer.md +[compatibility-yaml]: ../installer/internal/config/compatibility.yaml +[packagemap-yaml]: ../installer/internal/config/packagemap.yaml +[shell-startup]: processes/shell-startup.md diff --git a/docs/domain.md b/docs/domain.md new file mode 100644 index 0000000..ca20765 --- /dev/null +++ b/docs/domain.md @@ -0,0 +1,157 @@ +# Domain + +## Overview + +This project automates personal machine setup: an installer bootstraps prerequisites and applies dotfiles via chezmoi. The dotfiles support both personal and work environments, with conditional configuration driven by data the installer collects at install time. + +## Key Concepts + +### Work Environment + +The project implements a two-tier model for separating personal and work configuration. + +- **Activation**: Controlled by the `personal.work_env` boolean in chezmoi data. When `false`, all work-related configuration is skipped. +- **Work Name**: A short identifier for the employer (e.g., `sedg`). Used to locate employer-specific files and derive environment variable prefixes. + +**Two-tier profile system:** + +| Layer | Path | Purpose | +|-------|------|---------| +| Generic work profile | `~/.work/profile` | Cross-employer shared config — sets `WORK_DIR`, `WORK_EXECUTABLES_DIR`, and shell extension paths (`WORK_ZSH_ENV_EXTENSION`, `WORK_ZSH_RC_EXTENSION`) | +| Specific work profile | `~/.work/{work_name}/profile` | Employer-specific config — sourced by the generic profile | + +The generic profile delegates to the specific profile. Both layers produce shell extension files (`.zshenv` and `.zshrc` fragments) that are sourced during shell startup. See the [work environment loading process][work-env-loading] for the full loading flow. + +**File structure in chezmoi source:** + +``` +private_dot_work/ +├── profile.tmpl # Generic work profile (sets vars, sources specific profile) +├── zsh/ +│ ├── dot_zshenv.tmpl # Generic work zshenv extension +│ └── dot_zshrc.tmpl # Generic work zshrc extension +└── private_{work_name}/ + ├── profile # Employer-specific profile + └── zsh/ + ├── dot_zshenv.tmpl # Employer-specific zshenv extension + └── dot_zshrc.tmpl # Employer-specific zshrc extension +``` + +### Chezmoi Data Schema + +The installer collects user input and writes it to chezmoi's config file. Templates then consume these values. The data is organized into three namespaces: + +| Namespace | Set By | Purpose | +|-----------|--------|---------| +| `personal` | Installer | User identity — `email`, `full_name`, `work_env`, `work_name`, `work_email` | +| `system` | Installer | Runtime paths — `shell`, `work_generic_dotfiles_profile`, `work_specific_dotfiles_profile` | +| `gpg` | Installer | Security — `signing_key` | + +**Installer-side types** (in `dotfilesmanager.DotfilesData`): + +- `WorkEnv` is `Option[DotfilesWorkEnvData]` — when present, work mode is enabled +- `SystemData` is `Option[DotfilesSystemData]` — contains shell name and optional work profile paths +- `GpgSigningKey` is `Option[string]` — set when the user selects or creates a GPG key + +**Contract**: The installer writes `data.personal.*`, `data.system.*`, and `data.gpg.*` keys into chezmoi's YAML config. Templates read them via `.personal.*`, `.system.*`, and `.gpg.*`. Adding a new data key requires updating both `DotfilesData` (Go struct) and the `Initialize` method that maps struct fields to viper keys. See the [installation process][installation] for how these are populated. + +### Package Resolution + +The installer resolves abstract package names to concrete, installable names for the target system. This decouples prerequisite definitions from platform-specific package naming. + +- **Abstract package key**: A platform-independent name (e.g., `build-essential`, `gpg`). Used in compatibility checks and prerequisite lists. +- **Package mapping**: A YAML entry in [`packagemap.yaml`][packagemap-yaml] that maps an abstract key to manager-specific configurations. +- **Manager-specific mapping**: The concrete package name for a given package manager (`apt`, `dnf`, `brew`), optionally with a type and distro-specific name overrides. + +**Package types:** + +| Type | Meaning | Example | +|------|---------|---------| +| *(empty)* | Regular package | `apt install git` | +| `group` | Package group (DNF concept) | `dnf groupinstall "Development Tools"` | +| `pattern` | Installation pattern | Used by zypper-style managers | + +**Example mapping:** + +```yaml +build-essential: + apt: + name: build-essential + dnf: + type: group + name: + fedora: development-tools + centos: "Development Tools" +``` + +See the [package resolution process][pkg-resolution] for the resolution flow from abstract key to installable package. + +### Shell Source Strategy + +When installing the user's shell, the installer supports three strategies for locating and installing it: + +| Strategy | Flag value | Behavior | +|----------|-----------|----------| +| Auto | `auto` (default) | Try Homebrew first if available, fall back to native package manager | +| Brew | `brew` | Use Homebrew exclusively — fails if brew is not installed | +| System | `system` | Use native package manager exclusively (apt, dnf) | + +The strategy determines both the installation source and which binary path is registered as the user's default shell (brew-installed shells live under the brew prefix, system shells live in `/bin` or `/usr/bin`). + +### Display Modes + +The installer supports three output modes for controlling how external command output is presented: + +| Mode | Behavior | +|------|----------| +| Progress | Interactive spinners, command output hidden (default) | +| Plain | Simple text messages, command output hidden (non-interactive/CI) | +| Passthrough | All command output shown directly (debugging) | + +Progress and Plain discard command output; Passthrough does not. + +### Deferred Homebrew Loading + +A shell startup optimization pattern where Homebrew's expensive `shellenv` evaluation is postponed from `.zshenv` to `.zshrc` on macOS. This avoids the cost in non-interactive shells while keeping the environment available for interactive use. + +**Key state:** + +- `DEFER_BREW_LOAD` — flag set in `.zshenv` to signal that loading should happen later +- `BREW_LOADED` — guard that prevents double-evaluation across sourced files + +**Platform behavior:** + +| Platform | Behavior | Reason | +|----------|----------|--------| +| macOS | Deferred to `.zshrc` | Optimize non-interactive shell startup | +| Linux | Loaded immediately in `.zshenv` | Homebrew is less common; consistent PATH needed | +| Devbox | Simple PATH addition | `eval` is unnecessary in devbox environments | + +See the [shell startup process][shell-startup] for the full shell startup flow including deferred loading. + +## Domain Rules + +- **Package resolution is exact-match**: Distro-specific name resolution has no fallback — if the exact distro name isn't in the mapping, resolution fails. This is intentional to prevent silent mismatches. +- **Work environment is all-or-nothing at the profile level**: If `work_env` is true, the entire generic profile is sourced. Individual work features cannot be toggled independently. +- **Installer populates, templates consume**: The installer is the sole writer of chezmoi data. Templates are read-only consumers. Manual edits to chezmoi's config file will be overwritten on next install. + +## Glossary + +| Term | Definition | +|------|-----------| +| Abstract package key | Platform-independent package name used in config files, resolved to a concrete name at install time | +| Chezmoi data | Key-value pairs written to chezmoi's config file by the installer, consumed by templates via `.personal.*`, `.system.*`, `.gpg.*` | +| Deferred brew loading | Pattern where Homebrew's shell environment setup is postponed from `.zshenv` to `.zshrc` on macOS | +| Display mode | Installer output verbosity level: progress (spinners), plain (text), or passthrough (raw output) | +| Generic work profile | Shared work configuration at `~/.work/profile`, loaded for any employer | +| Package mapping | YAML entry mapping an abstract package key to manager-specific names and types | +| Package type | Classification of a package: regular (default), group (DNF group install), or pattern | +| Shell source strategy | How the installer finds/installs the shell: auto, brew, or system | +| Specific work profile | Employer-specific configuration at `~/.work/{work_name}/profile` | +| Work name | Short employer identifier (e.g., `sedg`) used in paths and environment variable prefixes | + +[installation]: processes/installation.md +[pkg-resolution]: processes/package-resolution.md +[shell-startup]: processes/shell-startup.md +[work-env-loading]: processes/work-environment-loading.md +[packagemap-yaml]: ../installer/internal/config/packagemap.yaml diff --git a/docs/processes/compatibility-checking.md b/docs/processes/compatibility-checking.md new file mode 100644 index 0000000..838325d --- /dev/null +++ b/docs/processes/compatibility-checking.md @@ -0,0 +1,105 @@ +# Compatibility Checking + +## Overview + +Verifies that the current system can run the dotfiles setup: detects the OS and distribution, checks that required tools are installed, and validates that the platform is supported. This is the first gate in the [installation process][installation]. + +## Trigger + +Either: +- The user runs `dotfiles-installer install` (automatically as step 1) +- The user runs `dotfiles-installer check-compatibility` (standalone check) + +## Actors + +- **OS detector**: Identifies the operating system, distribution, and architecture +- **Prerequisite checker**: Tests whether each required tool is present on the system PATH +- **[Compatibility config][compatibility-yaml]**: Declares supported platforms and their prerequisites + +## Diagram + +```mermaid +flowchart TD + A[Load compatibility config] --> B[Detect OS, distro, arch] + B --> C[Gather prerequisite list] + C --> D{OS-level
prerequisites?} + D -- Yes --> E[Add OS prerequisites] + D -- No --> F + E --> F{Distro-specific
prerequisites?} + F -- Yes --> G[Add distro prerequisites] + F -- No --> H + G --> H[Check each prerequisite] + H --> I{All found
on PATH?} + I -- Yes --> J{OS supported?} + I -- No --> K[Return missing list + error] + J -- Yes --> L{Distro supported?
Linux only} + J -- No --> M([Error: unsupported OS]) + L -- Yes --> N([System compatible]) + L -- No --> O([Error: unsupported distro]) + + style M fill:#d33,stroke:#911,color:#fff + style O fill:#d33,stroke:#911,color:#fff + style K fill:#e90,stroke:#b60,color:#fff + style N fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Happy Path + +1. **Load config** — Read [`compatibility.yaml`][compatibility-yaml] (embedded in the binary or overridden via `--compat-config` flag). Contains supported OS/distro declarations and prerequisite lists. +2. **Detect system** — Identify OS (`runtime.GOOS`), architecture (`runtime.GOARCH`), and distribution: + - **Linux**: Fallback chain — `/etc/os-release` → `/etc/lsb-release` → known distro files → `uname -s` → "unknown" + - **macOS**: Distro hardcoded to `"mac"` +3. **Gather prerequisites** — Merge OS-level prerequisites with distro-specific prerequisites into a single list +4. **Check each prerequisite** — For each entry, test whether its command exists on the system PATH via `exec.LookPath`. Classify into Available and Missing lists. +5. **Validate platform support** — Confirm the OS is listed as `supported: true` in the config. For Linux, also confirm the distro is supported. + +Result: A `SystemInfo` struct containing OS name, distro name, architecture, and prerequisite status (available, missing, details). + +**Prerequisites checked per platform:** + +| Platform | Prerequisites | +|----------|--------------| +| macOS | `xcode-select`, `bash`, `git` | +| Ubuntu / Debian | `gcc` (build-essential), `ps` (procps), `curl`, `file`, `git` | +| Fedora / CentOS / RHEL | `gcc` (build-essential), `ps` (procps), `curl`, `file`, `git` | + +### Failure Scenarios + +#### Missing prerequisites + +- **Trigger**: One or more required commands not found on PATH +- **At step**: 4 +- **Handling**: Returns the `SystemInfo` with a populated Missing list alongside an error. The caller (install command) decides whether to attempt [prerequisite installation][prereq-install]. +- **User impact**: In standalone mode, the user sees the missing items with install hints. In install mode, the installer may offer to install them. + +#### Unsupported OS or distro + +- **Trigger**: The detected OS or Linux distribution isn't declared as `supported: true` in the config +- **At step**: 5 +- **Handling**: Returns an error naming the unsupported platform +- **User impact**: The installer exits. The user must either add support to the config or set up the system manually. + +#### System detection fails + +- **Trigger**: `runtime.GOOS` returns an unexpected value, or Linux distro detection exhausts all fallback methods +- **At step**: 2 +- **Handling**: Returns an error immediately +- **User impact**: The installer cannot proceed. This typically means the OS is not Linux or macOS. + +## State Changes + +- No state changes — this is a read-only detection process. +- `globalSysInfo` is populated in the install command's scope for use by subsequent steps. + +## Dependencies + +- Embedded [`compatibility.yaml`][compatibility-yaml] +- `/etc/os-release`, `/etc/lsb-release` (Linux distro detection) +- `exec.LookPath` for each prerequisite command +- `runtime.GOOS` and `runtime.GOARCH` + +[compatibility-yaml]: ../../installer/internal/config/compatibility.yaml +[installation]: installation.md +[prereq-install]: prerequisite-installation.md diff --git a/docs/processes/dotfiles-setup.md b/docs/processes/dotfiles-setup.md new file mode 100644 index 0000000..7a7f4ac --- /dev/null +++ b/docs/processes/dotfiles-setup.md @@ -0,0 +1,147 @@ +# Dotfiles Setup + +## Overview + +Installs chezmoi, prepares the [chezmoi data][domain-data-schema] configuration from all collected input, clones the dotfiles repository, and applies the dotfiles to the home directory. This is the final step of the [installation process][installation] — everything before this was preparation for this moment. + +## Trigger + +Called during the [installation process][installation] after shell and GPG setup are complete. + +## Actors + +- **Chezmoi manager**: Orchestrates installation, data initialization, and application +- **Package manager**: Installs chezmoi (primary method) +- **HTTP client**: Downloads the chezmoi install script (fallback method) +- **Chezmoi binary**: Clones the repo and applies dotfiles +- **Git**: Used by chezmoi under the hood for repository cloning + +## Diagram + +```mermaid +flowchart TD + subgraph install ["Install Chezmoi"] + A{Already
installed?} + A -- Yes --> B([Skip]) + A -- No --> C[Install via package manager] + C --> D{Succeeded?} + D -- Yes --> B + D -- No --> E[Download get.chezmoi.io script] + E --> F["Run: sh script -b ~/.local/bin"] + F --> B + end + + subgraph init ["Initialize Data"] + G[Build DotfilesData struct] --> H[Create ~/.config/chezmoi/] + H --> I[Write chezmoi.toml] + end + + subgraph apply ["Apply Dotfiles"] + J["Remove existing clone dir"] --> K["chezmoi init --apply MrPointer"] + K --> L([Dotfiles applied]) + end + + B --> G + I --> J + + style B fill:#36a,stroke:#248,color:#fff + style L fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Step 1: Install Chezmoi + +1. **Check if installed** — Ask the package manager if chezmoi is already present +2. **Try package manager** — Install `chezmoi` with version constraint `>= 2.60.0` +3. **Fallback to manual install** — If the package manager fails, download the install script from `get.chezmoi.io` and run `sh script -b ~/.local/bin` + +### Step 2: Initialize Data + +4. **Build data struct** — Assemble `DotfilesData` from all collected input: + + | Field | Source | + |-------|--------| + | `Email`, `FirstName`, `LastName` | Hardcoded (personal info) | + | `Shell` | `--shell` flag (default: `zsh`) | + | `GpgSigningKey` | Selected/created during [GPG setup][gpg-setup] | + | `WorkEnv`, `WorkName`, `WorkEmail` | `--work-env`, `--work-name`, `--work-email` flags | + | `GenericWorkProfile` | Computed: `~/.work/profile` (if work env) | + | `SpecificWorkProfile` | Computed: `~/.work/{work_name}/profile` (if work env) | + +5. **Create config directory** — Ensure `~/.config/chezmoi/` exists +6. **Write config file** — Map the data struct to chezmoi's [data schema][domain-data-schema] and write `~/.config/chezmoi/chezmoi.toml`: + - `data.personal.email`, `data.personal.full_name` + - `data.personal.work_env`, `data.personal.work_name`, `data.personal.work_email` (if work env) + - `data.gpg.signing_key` (if GPG key selected) + - `data.system.shell` + - `data.system.work_generic_dotfiles_profile`, `data.system.work_specific_dotfiles_profile` (if work env) + +### Step 3: Apply Dotfiles + +7. **Remove existing clone** — Delete `~/.local/share/chezmoi` unconditionally (ensures a fresh clone) +8. **Run chezmoi** — Execute `chezmoi init --apply MrPointer` with flags: + - `--source ~/.local/share/chezmoi` + - `--config ~/.config/chezmoi/chezmoi.toml` + - `--ssh` (if `--git-clone-protocol=ssh`) + - `--branch {branch}` (if `--git-branch` specified) + + Chezmoi clones the dotfiles repo from GitHub, reads the config file for template data, renders all templates, and copies managed files to `$HOME`. + +Result: All dotfiles are applied — shell configs, git config, work profiles, SSH config, and everything else managed by chezmoi. + +### Failure Scenarios + +#### Both installation methods fail + +- **Trigger**: Package manager can't install chezmoi AND the `get.chezmoi.io` download/execution fails +- **At step**: 1-3 +- **Handling**: Error propagated, installer exits +- **User impact**: Must install chezmoi manually + +#### Config directory creation fails + +- **Trigger**: Filesystem permission issue +- **At step**: 5 +- **Handling**: Error propagated, installer exits +- **User impact**: Must create `~/.config/chezmoi/` manually and re-run + +#### Config file write fails + +- **Trigger**: Filesystem error or viper serialization issue +- **At step**: 6 +- **Handling**: Error propagated, installer exits +- **User impact**: Must create the chezmoi config manually + +#### Clone directory removal fails + +- **Trigger**: Filesystem permission issue or locked files +- **At step**: 7 +- **Handling**: Error propagated, installer exits +- **User impact**: Must remove `~/.local/share/chezmoi` manually and re-run + +#### `chezmoi init --apply` fails + +- **Trigger**: Git clone fails (network, auth), template rendering error (missing data key), or file permission issue during apply +- **At step**: 8 +- **Handling**: Installer logs chezmoi's stderr and exits +- **User impact**: Must fix the issue (network, template, permissions) and run `chezmoi init --apply` manually + +## State Changes + +- **Chezmoi binary**: Installed (via package manager or `~/.local/bin/chezmoi`) +- **`~/.config/chezmoi/chezmoi.toml`**: Created with all template data +- **`~/.local/share/chezmoi/`**: Deleted and re-cloned from GitHub +- **Home directory**: All managed dotfiles applied (shell configs, git config, work profiles, SSH config, etc.) + +## Dependencies + +- Package manager (brew, apt, or dnf) for chezmoi installation +- `get.chezmoi.io` (fallback installer, requires HTTP access) +- Git (used by chezmoi for repository cloning) +- GitHub access (to clone `MrPointer/dotfiles`) +- Network access for both package installation and repo cloning + +[installation]: installation.md +[gpg-setup]: gpg-setup.md +[domain-data-schema]: ../domain.md#chezmoi-data-schema diff --git a/docs/processes/gpg-setup.md b/docs/processes/gpg-setup.md new file mode 100644 index 0000000..7b2e772 --- /dev/null +++ b/docs/processes/gpg-setup.md @@ -0,0 +1,116 @@ +# GPG Setup + +## Overview + +Ensures a GPG client is installed and sets up a signing key for the user. Either creates a new key pair interactively or lets the user select from existing keys. The selected key is stored for use in [chezmoi data initialization][dotfiles-setup]. Skipped entirely in non-interactive mode. + +## Trigger + +Called during the [installation process][installation] after the shell is set up. + +## Actors + +- **GPG installer**: Checks for and installs the GPG client +- **GPG client**: Interfaces with the `gpg` binary for key listing and creation +- **User**: Selects an existing key or provides input for key creation (interactive only) +- **Package manager**: Installs the GPG package if needed + +## Diagram + +```mermaid +flowchart TD + subgraph phase1 ["Phase 1: GPG Client"] + A{gpg binary exists &
version >= 2.2.0 &
gpg-agent exists?} + A -- Yes --> B([Client ready]) + A -- No --> C[Install GPG via package manager] + C --> B + end + + subgraph phase2 ["Phase 2: Key Management"] + D{Non-interactive
mode?} + D -- Yes --> D1([Skip — warn user]) + D -- No --> E[List existing secret keys] + E --> F{Keys found?} + F -- No --> G[Create new key pair interactively] + F -- Yes --> H{How many?} + H -- One --> I[Use it automatically] + H -- Multiple --> J[Show selection UI] + G --> K([Key selected]) + I --> K + J --> K + end + + B --> D + + style B fill:#36a,stroke:#248,color:#fff + style D1 fill:#e90,stroke:#b60,color:#fff + style K fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Phase 1: GPG Client Installation + +1. **Check availability** — Three conditions must all pass: + - `gpg` binary exists on PATH + - `gpg --version` reports version >= 2.2.0 + - `gpg-agent` binary exists on PATH +2. **Install if needed** — If any check fails, install the `gpg` package via the active package manager + +### Phase 2: Key Management + +3. **Non-interactive guard** — If running in non-interactive mode, log a warning and skip key setup entirely. The user must set up keys manually afterward. +4. **List existing keys** — Run `gpg --list-secret-keys --keyid-format LONG` and parse output for key IDs (extract the ID after `/` on `sec` lines) +5. **Create or select**: + - **No keys exist**: Run `gpg --gen-key --pinentry-mode loopback --default-new-key-algo nistp256` interactively. The user sees GPG's prompts directly. Extract the new key ID from the output using multiple fallback patterns. + - **One key exists**: Use it automatically without prompting + - **Multiple keys exist**: Show a Huh selection form listing all key IDs + +Result: A GPG signing key ID is stored in `selectedGpgKey` for use by the [dotfiles setup process][dotfiles-setup]. + +### Failure Scenarios + +#### GPG client installation fails + +- **Trigger**: Package manager error +- **At step**: 2 +- **Handling**: Error propagated, installer exits +- **User impact**: Must install GPG manually (`gnupg2` on apt/dnf, `gnupg` on brew) + +#### TTY detection fails during key creation + +- **Trigger**: No usable TTY found (no `GPG_TTY`, `tty` command fails, `/dev/tty` doesn't exist) +- **At step**: 5 (create path) +- **Handling**: Error propagated, installer exits +- **User impact**: Must create a GPG key manually. This typically only happens in non-standard environments. + +#### Key ID extraction fails + +- **Trigger**: GPG output format changed or none of the extraction patterns match +- **At step**: 5 (create path) +- **Handling**: Error reported — "could not find key ID in GPG output" +- **User impact**: Key was likely created but the installer couldn't identify it. Run `gpg --list-secret-keys` to find the key ID and configure chezmoi data manually. + +#### User cancels key selection + +- **Trigger**: User aborts the Huh selection form +- **At step**: 5 (select path) +- **Handling**: Error propagated, installer exits +- **User impact**: Must re-run the installer or configure the GPG key in chezmoi data manually + +## State Changes + +- **GPG package**: Installed if not already present +- **GPG keyring** (`~/.gnupg/`): New key pair created (if no keys existed) +- **`selectedGpgKey`**: Global variable set with the chosen key ID (consumed by [dotfiles setup][dotfiles-setup]) + +## Dependencies + +- Package manager (brew, apt, or dnf) for GPG client installation +- `gpg` and `gpg-agent` binaries +- `pinentry` (implicit GPG dependency for passphrase entry during key creation) +- Terminal/TTY for interactive key creation and selection + +[installation]: installation.md +[dotfiles-setup]: dotfiles-setup.md +[domain-data-schema]: ../domain.md#chezmoi-data-schema diff --git a/docs/processes/installation.md b/docs/processes/installation.md new file mode 100644 index 0000000..d591aab --- /dev/null +++ b/docs/processes/installation.md @@ -0,0 +1,112 @@ +# Installation + +## Overview + +The installer bootstraps a new machine from scratch: it ensures system prerequisites are met, sets up the user's shell, configures GPG keys, and applies dotfiles through chezmoi. The process is designed to work on both macOS and Linux with minimal manual intervention. + +## Trigger + +User runs the `install` command (directly or via a release artifact). + +## Actors + +- **User**: Provides input (work environment, GPG key selection) in interactive mode +- **Installer CLI**: Orchestrates the entire flow +- **Package manager**: Installs prerequisites and tools (apt, dnf, or brew) +- **Chezmoi**: Applies dotfiles from the source repository to the home directory + +## Diagram + +```mermaid +flowchart TD + A[Detect system info] --> B{macOS &
--install-brew?} + B -- Yes --> C[Install Homebrew early] + B -- No --> D + C --> D[Check system compatibility] + D --> E{Prerequisites
missing?} + E -- No --> H + E -- Yes --> F{Interactive?} + F -- Yes --> F1[User selects prerequisites] + F -- No --> F2[Install all automatically] + F1 --> G[Resolve & install prerequisites] + F2 --> G + G --> G1[Re-check compatibility] + G1 --> H{--install-brew &
brew not yet installed?} + H -- Yes --> I[Install Homebrew] + H -- No --> J + I --> J[Install & set default shell] + J --> K{Interactive?} + K -- Yes --> L[Set up GPG keys] + K -- No --> M[Skip GPG setup] + L --> N + M --> N[Install chezmoi] + N --> O[Initialize chezmoi data] + O --> P[Apply dotfiles] + P --> Q([Installation complete]) + + style Q fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Happy Path + +1. **Detect basic system info** — OS name, architecture, distro (via OS detector) +2. **Install Homebrew early on macOS** — If `--install-brew` is set and the OS is macOS, install Homebrew *before* prerequisite checks. This solves the chicken-and-egg problem: Homebrew provides tools needed for prerequisite checks on macOS. +3. **[Check system compatibility][compat-check]** — Verify the system meets minimum requirements and identify missing prerequisites against [`compatibility.yaml`][compatibility-yaml] +4. **[Install missing prerequisites][prereq-install]** — Resolve [abstract package keys][domain-pkg-resolution] to concrete names, then install via the active package manager. In interactive mode, the user selects which prerequisites to install; in non-interactive mode, all are installed automatically. +5. **Re-check compatibility** — After installing prerequisites, verify the system passes all checks +6. **Install Homebrew on non-macOS** — If `--install-brew` is set and Homebrew wasn't installed in step 2 +7. **[Install and configure shell][shell-setup]** — Install the target shell (default: zsh) using the [shell source strategy][domain-shell-source], then set it as the user's default shell +8. **[Set up GPG keys][gpg-setup]** — Check for existing GPG keys. If none exist, create a new key pair interactively. If keys exist, let the user select one. Skipped in non-interactive mode. +9. **[Set up dotfiles manager][dotfiles-setup]** — Install chezmoi if needed, initialize [chezmoi data][domain-data-schema] from collected input, then apply dotfiles + +Result: Machine is fully configured with the user's dotfiles, shell, and GPG setup. + +### Failure Scenarios + +Each sub-process has its own detailed failure scenarios. At the orchestration level: + +- Any step failure causes the installer to exit non-zero — there is no rollback mechanism +- On macOS, Homebrew failure at step 2 blocks the entire flow (prerequisites depend on it) +- Steps are sequential: each depends on state set by previous steps (e.g., `selectedGpgKey` from step 8 feeds into step 9) + +See the individual process docs for detailed failure scenarios and handling. + +## State Changes + +- **System packages**: Missing prerequisites installed (see [prerequisite installation][prereq-install]) +- **Homebrew**: Installed and on PATH (if opted in) +- **Default shell**: Changed to the target shell (see [shell setup][shell-setup]) +- **GPG keyring**: New key pair created or existing key selected (see [GPG setup][gpg-setup]) +- **Chezmoi config**: `~/.config/chezmoi/chezmoi.toml` written with all data namespaces (see [dotfiles setup][dotfiles-setup]) +- **Home directory**: Dotfiles applied — shell configs, git config, work profiles, etc. + +## Sub-Processes + +| Process | Description | +|---------|-------------| +| [Compatibility Checking][compat-check] | Detect OS/distro, verify prerequisites, validate platform support | +| [Prerequisite Installation][prereq-install] | Resolve and install missing prerequisites | +| [Package Resolution][pkg-resolution] | Translate abstract package keys to platform-specific names | +| [Shell Setup][shell-setup] | Install shell and set as default | +| [GPG Setup][gpg-setup] | Install GPG client, create or select signing key | +| [Dotfiles Setup][dotfiles-setup] | Install chezmoi, write config, clone repo, apply dotfiles | + +## Dependencies + +- Internet access (for Homebrew installation, chezmoi installation, dotfiles repo clone) +- Sufficient privileges for package installation and shell changing (sudo) +- Git (listed as a prerequisite, installed automatically if missing) + +[compatibility-yaml]: ../../installer/internal/config/compatibility.yaml +[packagemap-yaml]: ../../installer/internal/config/packagemap.yaml +[compat-check]: compatibility-checking.md +[prereq-install]: prerequisite-installation.md +[pkg-resolution]: package-resolution.md +[shell-setup]: shell-setup.md +[gpg-setup]: gpg-setup.md +[dotfiles-setup]: dotfiles-setup.md +[domain-shell-source]: ../domain.md#shell-source-strategy +[domain-data-schema]: ../domain.md#chezmoi-data-schema +[domain-pkg-resolution]: ../domain.md#package-resolution diff --git a/docs/processes/package-resolution.md b/docs/processes/package-resolution.md new file mode 100644 index 0000000..5b86d7d --- /dev/null +++ b/docs/processes/package-resolution.md @@ -0,0 +1,93 @@ +# Package Resolution + +## Overview + +Translates a platform-independent package name into a concrete, installable package for the current system. This allows prerequisite lists and compatibility checks to use abstract names while the installer handles platform-specific differences at install time. + +## Trigger + +The installer needs to install a package identified by an [abstract key][domain-pkg-resolution] (e.g., during prerequisite installation in the [installation process][installation]). + +## Actors + +- **Package resolver**: Looks up mappings and resolves names +- **Package manager**: Provides the manager type (apt, dnf, brew) used to select the right mapping +- **System info**: Provides the distro name used for distro-specific overrides + +## Diagram + +```mermaid +flowchart TD + A[Receive abstract package key] --> B{Key exists in
packagemap.yaml?} + B -- No --> B1([Error: unknown package]) + B -- Yes --> C{Mapping exists for
active pkg manager?} + C -- No --> C1([Error: no mapping for manager]) + C -- Yes --> D{Name type?} + D -- String --> E[Use name directly] + D -- Map --> F{Exact distro
match?} + F -- No --> F1([Error: no mapping for distro]) + F -- Yes --> G[Use distro-specific name] + E --> H{Type specified?} + G --> H + H -- Yes --> I[Include type: group / pattern] + H -- No --> J[Type: regular] + I --> K([Return resolved package]) + J --> K + + style B1 fill:#d33,stroke:#911,color:#fff + style C1 fill:#d33,stroke:#911,color:#fff + style F1 fill:#d33,stroke:#911,color:#fff + style K fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Happy Path + +1. **Look up abstract key** — Find the entry in [`packagemap.yaml`][packagemap-yaml] for the requested package name (e.g., `build-essential`) +2. **Select manager mapping** — From that entry, find the sub-entry for the active package manager (e.g., `dnf`) +3. **Resolve package name** — Two cases: + - Name is a string → use it directly (e.g., `apt: build-essential`) + - Name is a map → look up the exact distro name (e.g., `fedora: development-tools`) +4. **Determine package type** — If the mapping specifies a `type` (e.g., `group`), include it in the resolved result. Otherwise, it's a regular package. See [package types][domain-pkg-types] for the full list. +5. **Return resolved package** — Name + type + any version constraints, ready for the package manager to install + +Result: A concrete package name and type that the package manager can install directly. + +### Failure Scenarios + +#### No mapping for abstract key + +- **Trigger**: The abstract key doesn't exist in [`packagemap.yaml`][packagemap-yaml] +- **At step**: 1 +- **Handling**: Resolver returns an error indicating the package is unknown +- **User impact**: The package must be added to [`packagemap.yaml`][packagemap-yaml] or installed manually + +#### No mapping for active package manager + +- **Trigger**: The abstract key exists but has no entry for the current package manager (e.g., key has `apt` and `dnf` but not `brew`) +- **At step**: 2 +- **Handling**: Resolver returns an error — no fallback to another manager +- **User impact**: A mapping for this manager must be added, or the package installed manually + +#### Distro-specific name not found + +- **Trigger**: The name is a distro map but the current distro isn't listed (e.g., map has `fedora` and `centos` but system is `rhel`) +- **At step**: 3 +- **Handling**: Resolver returns an error. There is no fallback behavior — this is intentional to prevent installing the wrong package. +- **User impact**: A mapping for this distro must be added to [`packagemap.yaml`][packagemap-yaml] + +## State Changes + +- No state changes — resolution is a pure lookup. The actual installation happens in the calling process. + +## Dependencies + +- [`packagemap.yaml`][packagemap-yaml] must be loaded and accessible +- System info (distro name) must be detected before resolution +- A package manager must be active (determines which mapping branch to follow) + +[packagemap-yaml]: ../../installer/internal/config/packagemap.yaml +[installation]: installation.md +[domain-pkg-resolution]: ../domain.md#package-resolution +[domain-pkg-types]: ../domain.md#package-resolution diff --git a/docs/processes/prerequisite-installation.md b/docs/processes/prerequisite-installation.md new file mode 100644 index 0000000..5d6f39e --- /dev/null +++ b/docs/processes/prerequisite-installation.md @@ -0,0 +1,122 @@ +# Prerequisite Installation + +## Overview + +Installs missing system prerequisites identified by [compatibility checking][compat-check]. Resolves [abstract package keys][domain-pkg-resolution] to platform-specific names and installs them via the active package manager. In interactive mode, the user selects which prerequisites to install. + +## Trigger + +The [compatibility check][compat-check] returns one or more missing prerequisites during the [installation process][installation]. + +## Actors + +- **User**: Selects which prerequisites to install (interactive mode only) +- **Package resolver**: Translates abstract keys to concrete package names (see [package resolution][pkg-resolution]) +- **Package manager**: Installs the resolved packages (apt, dnf, or brew) +- **Privilege escalator**: Provides sudo/doas for package installation on Linux + +## Diagram + +```mermaid +flowchart TD + A{Any prerequisites
missing?} -- No --> Z([Skip]) + A -- Yes --> B[Create package manager] + B --> C{Manager
available?} + C -- No --> C1([Warning: cannot auto-install]) + C -- Yes --> D{Interactive?} + D -- No --> E[Install all missing automatically] + D -- Yes --> F[Show multi-select UI] + F --> G{User selected
any?} + G -- No --> G1([Skip: nothing selected]) + G -- Yes --> H[Create package resolver] + E --> H + H --> I[For each prerequisite] + I --> J[Resolve abstract key] + J --> K{Resolved?} + K -- No --> K1([Error: resolution failed]) + K -- Yes --> L[Install via package manager] + L --> M{Install
succeeded?} + M -- No --> M1([Error: install failed]) + M -- Yes --> N{More to
install?} + N -- Yes --> I + N -- No --> O([Re-check compatibility]) + + style Z fill:#36a,stroke:#248,color:#fff + style C1 fill:#e90,stroke:#b60,color:#fff + style G1 fill:#36a,stroke:#248,color:#fff + style K1 fill:#d33,stroke:#911,color:#fff + style M1 fill:#d33,stroke:#911,color:#fff + style O fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Happy Path + +1. **Guard** — If no prerequisites are missing, skip entirely +2. **Create package manager** — Use the global package manager if already set (e.g., Homebrew installed early on macOS), otherwise create a native one based on OS/distro (apt for Ubuntu/Debian, dnf for Fedora/CentOS/RHEL) +3. **Decide what to install**: + - **Non-interactive** (`--non-interactive` or `--install-prerequisites`): install all missing prerequisites + - **Interactive**: present a multi-select form (via Huh) showing each prerequisite with its description and install hint. User selects with space, confirms with enter. +4. **Create package resolver** — Load [`packagemap.yaml`][packagemap-yaml] mappings and create a resolver for the active package manager and system info +5. **Resolve and install each prerequisite** — For each selected prerequisite: + - Resolve the abstract key to a concrete package name and type via the [package resolution process][pkg-resolution] + - Install via the package manager (handles regular packages, groups, and patterns) +6. **Trigger re-check** — Return success to the caller, which re-runs compatibility checking to verify all prerequisites are now present + +Result: Missing prerequisites installed. The caller re-checks compatibility to confirm. + +### Failure Scenarios + +#### No package manager available + +- **Trigger**: System has no supported native package manager and Homebrew isn't installed +- **At step**: 2 +- **Handling**: Logs a warning and returns without installing. Falls through to the compatibility error handler. +- **User impact**: Must install prerequisites manually using the install hints shown + +#### User selects nothing (interactive) + +- **Trigger**: User deselects all items in the multi-select form +- **At step**: 3 +- **Handling**: Returns gracefully without installing anything +- **User impact**: Compatibility check will fail again, and the installer exits with hints + +#### Package resolution fails + +- **Trigger**: A prerequisite's abstract key has no mapping for the active manager or distro +- **At step**: 5 +- **Handling**: Logs the failure and returns +- **User impact**: Must add the mapping to [`packagemap.yaml`][packagemap-yaml] or install the package manually + +#### Package installation fails + +- **Trigger**: Package manager returns an error (network issue, permission denied, package not found) +- **At step**: 5 +- **Handling**: Logs the failure and returns +- **User impact**: Must resolve the package manager issue and retry + +#### Re-check still fails + +- **Trigger**: Some prerequisites couldn't be installed or the installed version doesn't satisfy the check +- **At step**: 6 (in the caller) +- **Handling**: The installer prints remaining missing items with install hints and exits +- **User impact**: Must resolve the remaining issues manually + +## State Changes + +- System packages installed via apt/dnf/brew +- No installer-specific state files written + +## Dependencies + +- A supported package manager (apt, dnf, or brew) +- [`packagemap.yaml`][packagemap-yaml] for name resolution +- Privilege escalation (sudo/doas) for apt/dnf installations +- Terminal/TTY for interactive prerequisite selection + +[compat-check]: compatibility-checking.md +[installation]: installation.md +[pkg-resolution]: package-resolution.md +[packagemap-yaml]: ../../installer/internal/config/packagemap.yaml +[domain-pkg-resolution]: ../domain.md#package-resolution diff --git a/docs/processes/shell-setup.md b/docs/processes/shell-setup.md new file mode 100644 index 0000000..9ae6ab2 --- /dev/null +++ b/docs/processes/shell-setup.md @@ -0,0 +1,119 @@ +# Shell Setup + +## Overview + +Installs the target shell (default: zsh) if not already present and sets it as the user's default login shell. The [shell source strategy][domain-shell-source] determines where the shell binary comes from and which path is registered as the default. + +## Trigger + +Called during the [installation process][installation] after prerequisites are satisfied and Homebrew is set up. + +## Actors + +- **Shell resolver**: Determines the expected shell binary path based on the source strategy +- **Package manager**: Installs the shell if missing (brew, apt, or dnf) +- **Shell changer**: Registers the shell in `/etc/shells` and changes the user's default via `chsh`/`dscl` +- **Privilege escalator**: Provides sudo/doas for system modifications + +## Diagram + +```mermaid +flowchart TD + A[Resolve install strategy] --> B[Determine shell path] + B --> C{Shell binary
exists?} + C -- Yes --> D + C -- No --> C1[Install via package manager] + C1 --> D[Resolve target shell path] + D --> E{Already default
shell?} + E -- Yes --> Z([Done — no changes needed]) + E -- No --> F{Running
as root?} + F -- Yes --> F1[Log root warning] + F -- No --> G + F1 --> G{Shell in
/etc/shells?} + G -- Yes --> H + G -- No --> G1["Append to /etc/shells (sudo)"] + G1 --> H["Set default shell (sudo)"] + H --> Z2([Shell setup complete]) + + style Z fill:#36a,stroke:#248,color:#fff + style Z2 fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### Happy Path + +1. **Resolve install strategy** — Based on the `--shell-source` flag, select the package manager and create a shell resolver: + - `auto`: try brew first (if available), fall back to native package manager + - `brew`: use Homebrew exclusively + - `system`: use native package manager exclusively +2. **Check availability** — The resolver determines the expected binary path based on the strategy: + | Source | Path resolution | + |--------|----------------| + | `brew` | `{brew_prefix}/bin/{shell}` | + | `system` | First match in `/bin`, `/usr/bin`, `/usr/local/bin` | + | `auto` | Brew path if it exists, otherwise system dirs | +3. **Install shell** — If the binary doesn't exist at the expected path, install it via the selected package manager +4. **Check if already default** — Read the current user's default shell: + - **macOS**: `dscl . -read /Users/{username} UserShell` + - **Linux**: Parse field 7 of the user's `/etc/passwd` entry + - If already set to the target path, skip the remaining steps +5. **Ensure shell in `/etc/shells`** — Read `/etc/shells` and check if the target path is listed. If not, append it using `sudo tee -a /etc/shells`. +6. **Set as default** — Change the user's login shell: + - **macOS**: `sudo dscl . -create /Users/{username} UserShell {path}` + - **Linux**: `sudo usermod -s {path} {username}` + +Result: The target shell is installed and set as the user's default login shell. + +### Failure Scenarios + +#### Invalid shell source + +- **Trigger**: `--shell-source` is not `auto`, `brew`, or `system` +- **At step**: 1 +- **Handling**: Returns an error immediately +- **User impact**: Must use a valid shell source value + +#### Shell source requires unavailable manager + +- **Trigger**: `--shell-source=brew` but Homebrew isn't installed, or `--shell-source=system` but no native manager exists +- **At step**: 1 +- **Handling**: Returns a descriptive error +- **User impact**: Must install the required package manager or use a different source strategy + +#### Package installation fails + +- **Trigger**: Package manager error (network, permissions, package not found) +- **At step**: 3 +- **Handling**: Error propagated, installer exits +- **User impact**: Must install the shell manually + +#### Cannot modify `/etc/shells` + +- **Trigger**: Privilege escalation fails (no sudo access, user cancels sudo prompt) +- **At step**: 5 +- **Handling**: Error propagated, installer exits +- **User impact**: Must manually add the shell path to `/etc/shells` + +#### Cannot change default shell + +- **Trigger**: `dscl` or `usermod` command fails +- **At step**: 6 +- **Handling**: Error propagated, installer exits +- **User impact**: Must run `chsh` or equivalent manually + +## State Changes + +- **Shell binary**: Installed if not already present +- **`/etc/shells`**: New entry appended if the shell path wasn't listed +- **Default shell**: Changed for the current user (Directory Services on macOS, `/etc/passwd` on Linux) + +## Dependencies + +- Package manager (brew, apt, or dnf) for shell installation +- `sudo`/`doas` for modifying `/etc/shells` and changing the default shell +- `dscl` (macOS) or `usermod` (Linux) for setting the default shell +- `/etc/passwd` (Linux) for reading the current default shell + +[installation]: installation.md +[domain-shell-source]: ../domain.md#shell-source-strategy diff --git a/docs/processes/shell-startup.md b/docs/processes/shell-startup.md new file mode 100644 index 0000000..ce30f7b --- /dev/null +++ b/docs/processes/shell-startup.md @@ -0,0 +1,150 @@ +# Shell Startup + +## Overview + +Describes how the Zsh shell environment initializes, including Homebrew loading, PATH setup, work environment activation, and plugin loading. The startup is split across `.zshenv` (all shells) and `.zshrc` (interactive shells) with an emphasis on keeping non-interactive shell startup fast. + +## Trigger + +A new Zsh shell session starts — either interactive (terminal) or non-interactive (script execution, IDE subprocess). + +## Actors + +- **Zsh**: Executes `.zshenv` for all sessions, then `.zshrc` for interactive sessions +- **Chezmoi templates**: Generate the actual shell files from [`dot_zshenv.tmpl`][zshenv-tmpl] and [`dot_zshrc.tmpl`][zshrc-tmpl] using [chezmoi data][domain-data-schema] +- **Homebrew**: Provides the `shellenv` command that sets up PATH and environment +- **Sheldon**: Plugin manager that loads Zsh plugins in interactive sessions + +## Diagram + +```mermaid +flowchart TD + subgraph zshenv [".zshenv — All Shells"] + direction TB + A[Set base PATH] --> B[Determine Homebrew location] + B --> C{BREW_LOADED?} + C -- Yes --> D4 + C -- No --> D{Platform?} + D -- macOS --> D1["Set DEFER_BREW_LOAD=true"] + D -- Linux --> D2["load_brew_env immediately"] + D -- Devbox --> D3["Add brew dirs to PATH"] + D1 --> D4["BREW_LOADED=true"] + D2 --> D4 + D3 --> D4 + D4 --> E{~/.pyenv exists?} + E -- Yes --> E1[Add pyenv shims to PATH] + E -- No --> F + E1 --> F{Linux + mold?} + F -- Yes --> F1[Set RUSTFLAGS for mold] + F -- No --> G + F1 --> G{work_env?} + G -- Yes --> G1[Load work environment] + G -- No --> H([.zshenv done]) + G1 --> H + end + + subgraph zshrc [".zshrc — Interactive Shells"] + direction TB + I[p10k instant prompt] --> J[Editor, locale, history] + J --> K[compinit -C] + K --> L{DEFER_BREW_LOAD?} + L -- Yes --> L1[load_brew_env now] + L -- No --> M + L1 --> M[Aliases & tool PATHs] + M --> N[Lazy pyenv init] + N --> O[Cache completions] + O --> P{work_env?} + P -- Yes --> P1[Source work RC extension] + P -- No --> Q + P1 --> Q[oh-my-zsh plugins] + Q --> R[sheldon plugins] + R --> S[p10k theme] + S --> T[fzf + fzf-tab] + T --> U{VS Code?} + U -- Yes --> U1[Load VS Code integration] + U -- No --> V([Shell ready]) + U1 --> V + end + + H --> I + + style H fill:#36a,stroke:#248,color:#fff + style V fill:#2d6,stroke:#183,color:#fff +``` + +## Flow + +### `.zshenv` Phase (All Shells) + +1. **Set base PATH** — Add `~/.local/bin`, `~/bin`, `/usr/local/bin` +2. **Determine Homebrew location** — Based on OS and architecture: + - Linux: `/home/linuxbrew/.linuxbrew` + - macOS arm64: `/opt/homebrew` + - macOS x86: `/usr/local` +3. **Handle Homebrew loading** — Platform-dependent behavior (only if `BREW_LOADED` is not already set). See [deferred Homebrew loading][domain-deferred-brew] for the concept. + - **macOS (non-devbox)**: Set `DEFER_BREW_LOAD=true` — postpone the expensive `shellenv` eval to `.zshrc` + - **Linux**: Call `load_brew_env` immediately — PATH consistency is more important than startup speed + - **Devbox**: Add brew directories to PATH directly — no `eval` needed + - Set `BREW_LOADED=true` to prevent double-loading +4. **Set up pyenv** — If `~/.pyenv` exists, add shims and bin directories to PATH (fast, no eval) +5. **Set up Rust linker** — On Linux with mold available, configure `RUSTFLAGS` to use mold +6. **Load work environment** — If `personal.work_env` is true, see the [work environment loading process][work-env-loading] + +### `.zshrc` Phase (Interactive Shells Only) + +1. **Powerlevel10k instant prompt** — Load cached prompt for immediate visual feedback +2. **Set editor and locale** — `VISUAL`, `EDITOR`, `LANG`, `LC_ALL` +3. **Configure history** — History file, size, append mode +4. **Set up completions** — Configure fpath, load Homebrew completions, run `compinit -C` (cached) +5. **Complete deferred brew loading** — If `DEFER_BREW_LOAD` is `true`, call `load_brew_env` now +6. **Set up aliases** — Git, neovim, GPG unlock +7. **Configure pyenv** — Lazy initialization: full pyenv shell integration is loaded only when a Python-related command is detected or `.python-version`/`.envrc` is found in the directory tree +8. **Add tool PATHs** — Cargo, Go, Ruby gems, clang-format, bun (conditional on tool availability) +9. **Cache completions** — Generate completion files for cargo, poetry, pip, pipx only if missing or older than 7 days +10. **Source work RC extension** — If `personal.work_env` is true, source `WORK_ZSH_RC_EXTENSION` (see [work environment loading][work-env-loading]) +11. **Load oh-my-zsh functions and plugins** — Vendored git functions, key-bindings, git, dotenv plugins +12. **Load sheldon plugins** — `eval "$(sheldon source)"` loads the plugin set defined in [`plugins.toml`][sheldon-plugins] +13. **Load Powerlevel10k theme** — Source `~/.p10k.zsh` +14. **Configure fzf and fzf-tab** — Fuzzy finder integration with completion system +15. **VS Code shell integration** — If running inside VS Code terminal, load VS Code's shell integration script + +### Failure Scenarios + +#### Homebrew binary not found + +- **Trigger**: `BREW_BINARY` path doesn't exist (Homebrew not installed) +- **At step**: `.zshenv` step 3 +- **Handling**: The `if [[ -f "$BREW_BINARY" ]]` guard skips all Homebrew setup silently +- **User impact**: No Homebrew-provided tools on PATH. Everything else works normally. + +#### Work profile not readable + +- **Trigger**: `work_env` is true but the profile file doesn't exist or isn't readable +- **At step**: `.zshenv` step 6 +- **Handling**: The `[[ -r ... ]]` guard skips sourcing. Shell starts without work config. +- **User impact**: Work-specific environment variables and paths won't be set. Run the installer with `--work-env` to regenerate. + +#### pyenv not installed + +- **Trigger**: `~/.pyenv` directory doesn't exist +- **At step**: `.zshenv` step 4, `.zshrc` step 7 +- **Handling**: Conditional checks skip all pyenv setup +- **User impact**: None — pyenv features simply aren't available + +## State Changes + +- **Environment variables**: PATH, BREW_HOME, BREW_LOADED, DEFER_BREW_LOAD, WORK_ENV_LOADED, and tool-specific vars +- **Shell functions**: `load_brew_env`, `brew` wrapper (invalidates completion cache on install/uninstall), pyenv lazy loaders +- **Completion system**: `compinit` initialized with cache, fpath populated + +## Dependencies + +- Chezmoi must have applied the dotfiles (`.zshenv` and `.zshrc` are generated from templates) +- [Chezmoi data][domain-data-schema] must be populated (templates reference `.personal.*`, `.system.*`, `.chezmoi.*`) + +[zshenv-tmpl]: ../../dot_zshenv.tmpl +[zshrc-tmpl]: ../../dot_zshrc.tmpl +[sheldon-plugins]: ../../dot_config/sheldon/plugins.toml +[domain-data-schema]: ../domain.md#chezmoi-data-schema +[domain-deferred-brew]: ../domain.md#deferred-homebrew-loading +[work-env-loading]: work-environment-loading.md diff --git a/docs/processes/work-environment-loading.md b/docs/processes/work-environment-loading.md new file mode 100644 index 0000000..77b33b5 --- /dev/null +++ b/docs/processes/work-environment-loading.md @@ -0,0 +1,125 @@ +# Work Environment Loading + +## Overview + +Activates work-specific shell configuration during shell startup when the machine is configured as a work environment. Loads a two-tier profile system (generic work config, then employer-specific config) and injects shell extensions into both `.zshenv` and `.zshrc`. + +## Trigger + +A Zsh shell session starts on a machine where [chezmoi data][domain-data-schema] has `personal.work_env` set to `true`. This process is a sub-flow of [shell startup][shell-startup]. + +## Actors + +- **Zsh**: Sources the profiles and extensions during startup +- **[Generic work profile][domain-work-env]** (`~/.work/profile`): Sets shared work variables and sources the specific profile +- **[Specific work profile][domain-work-env]** (`~/.work/{work_name}/profile`): Sets employer-specific variables +- **Shell extensions**: `.zshenv` and `.zshrc` fragments produced by both profile tiers + +## Diagram + +```mermaid +sequenceDiagram + participant zshenv as .zshenv + participant gp as Generic Profile
~/.work/profile + participant sp as Specific Profile
~/.work/{work_name}/profile + participant ext as Shell Extensions + + Note over zshenv: Template checks personal.work_env + + alt work_env = false + Note over zshenv: Skip entire work block + else work_env = true + zshenv ->> zshenv: Check WORK_ENV_LOADED guard + alt already loaded + Note over zshenv: Skip (prevent double-load) + else not loaded + zshenv ->> gp: source ~/.work/profile + activate gp + Note over gp: Set WORK_DIR, WORK_EXECUTABLES_DIR,
WORK_ZSH_DIR, extension paths + gp ->> sp: source ~/.work/{work_name}/profile + activate sp + Note over sp: Set employer-specific variables + sp -->> gp: return + deactivate sp + gp -->> zshenv: return + deactivate gp + zshenv ->> ext: source WORK_ZSH_ENV_EXTENSION + activate ext + Note over ext: Employer-specific env vars + ext -->> zshenv: return + deactivate ext + zshenv ->> zshenv: WORK_ENV_LOADED=true + end + end + + Note over zshenv: ... rest of .zshenv ... + + Note over zshenv: .zshrc phase (interactive only) + zshenv ->> ext: source WORK_ZSH_RC_EXTENSION + activate ext + Note over ext: Employer-specific aliases,
functions, interactive config + ext -->> zshenv: return + deactivate ext +``` + +## Flow + +### Happy Path + +**During `.zshenv`** (all shells): + +1. **Check activation** — Template checks `personal.work_env`. If false, the entire work block is skipped at template rendering time (not at runtime). +2. **Check guard** — If `WORK_ENV_LOADED` is set, skip to prevent double-loading (relevant when `.zshenv` is sourced multiple times) +3. **Source generic work profile** — [`~/.work/profile`][generic-profile-tmpl] runs, setting: + - `WORK_DIR` (`~/.work`) + - `WORK_EXECUTABLES_DIR` (`~/.work/bin`) + - `WORK_ZSH_DIR`, `WORK_ZSH_RC_EXTENSION`, `WORK_ZSH_ENV_EXTENSION` (paths to shell extension files) + - Then sources the specific work profile (`~/.work/{work_name}/profile`) +4. **Source work zshenv extension** — If `WORK_ZSH_ENV_EXTENSION` is set and the file is readable, source it. This adds employer-specific environment variables. +5. **Set guard** — `WORK_ENV_LOADED=true` + +**During `.zshrc`** (interactive shells only): + +6. **Source work zshrc extension** — If `WORK_ZSH_RC_EXTENSION` is set and the file is readable, source it. This adds employer-specific aliases, functions, or interactive config. + +Result: Work-specific environment variables, paths, aliases, and functions are available in the shell session. + +### Failure Scenarios + +#### Work profiles not generated by chezmoi + +- **Trigger**: Installer was not run with `--work-env`, or chezmoi hasn't been applied yet +- **At step**: 3 +- **Handling**: The `[[ -r ... ]]` guard prevents sourcing a missing file. Shell starts without work config. +- **User impact**: No work environment active. Re-run the installer with `--work-env` and `chezmoi apply`. + +#### Specific work profile missing + +- **Trigger**: The generic profile tries to source `~/.work/{work_name}/profile` but the employer directory doesn't exist +- **At step**: 3 (inside generic profile) +- **Handling**: The `source` command fails. Depending on shell error handling, this may produce a warning. +- **User impact**: Generic work variables are set, but employer-specific config is missing. Ensure the employer directory exists in chezmoi source as `private_dot_work/private_{work_name}/`. + +#### Shell extension files missing + +- **Trigger**: The work zsh directory or extension files don't exist +- **At step**: 4 or 6 +- **Handling**: The `[[ -n ... && -r ... ]]` guards skip sourcing silently +- **User impact**: No error, but work-specific shell extensions won't take effect + +## State Changes + +- **Environment variables**: `WORK_DIR`, `WORK_EXECUTABLES_DIR`, `WORK_ZSH_DIR`, `WORK_ZSH_RC_EXTENSION`, `WORK_ZSH_ENV_EXTENSION`, `WORK_ENV_LOADED`, plus any employer-specific variables +- **PATH**: May be extended with `WORK_EXECUTABLES_DIR` and employer-specific paths +- **Shell functions/aliases**: Employer-specific additions from zshrc extension + +## Dependencies + +- [Chezmoi data][domain-data-schema]: `personal.work_env`, `system.work_generic_dotfiles_profile`, `system.work_specific_dotfiles_profile` must be set +- Work profile files must exist at the expected paths (generated by chezmoi from [`private_dot_work/`][work-source-dir] templates) + +[domain-data-schema]: ../domain.md#chezmoi-data-schema +[domain-work-env]: ../domain.md#work-environment +[shell-startup]: shell-startup.md +[generic-profile-tmpl]: ../../private_dot_work/profile.tmpl +[work-source-dir]: ../../private_dot_work diff --git a/dot_claude/agents/plan-architect-reviewer.md b/dot_claude/agents/plan-architect-reviewer.md new file mode 100644 index 0000000..bbf534e --- /dev/null +++ b/dot_claude/agents/plan-architect-reviewer.md @@ -0,0 +1,99 @@ +--- +name: plan-architect-reviewer +description: "Use this agent to review master plans and their sub-plan decompositions for architectural soundness. Evaluates whether the decomposition boundaries are in the right places, dependencies between sub-plans are minimal and correctly captured, the pieces will fit together when assembled, and the overall approach is feasible.\n\n\nContext: A master plan has been created for adding a new authentication system with 5 sub-plans.\nuser: \"Review the master plan and sub-plans in .claude/plans/auth-system/ for architectural soundness.\"\nassistant: \"I'll review the plan decomposition for boundary correctness, dependency completeness, and integration feasibility.\"\n\nInvoke plan-architect-reviewer after initial plan creation (Phase 5, Step 1 of project-feature-planning) to catch decomposition issues before sub-plans are reviewed individually.\n\n\n\n\nContext: A sub-plan review found that two sub-plans have a hidden circular dependency. The master plan was updated and needs re-review.\nuser: \"The master plan was updated after sub-plan review feedback. Re-review the affected parts.\"\nassistant: \"I'll re-evaluate the changed boundaries and dependency graph to confirm the circular dependency is resolved.\"\n\nInvoke plan-architect-reviewer during the convergence loop when master plan changes need re-validation.\n\n" +tools: Read, Write, Glob, Grep +--- + +You are an architecture reviewer. Your job is to review feature plans — specifically, a master plan and its sub-plan decomposition — and find problems before an executing agent attempts implementation. + +You are NOT here to praise, summarize, or restate the plan. You are here to find what's wrong with it. + +## What You Review + +You will be given a path to a plan directory (e.g., `.claude/plans//`) containing: +- `00-master.md` — orchestration: requirements, scope, sub-plan table, execution order, risks +- `01-*.md`, `02-*.md`, ... — self-contained sub-plans with implementation details + +You also have access to the full codebase to verify claims made in the plan. + +## How You Review + +### 1. Read All Plan Files + +Read the master plan and every sub-plan. Understand the full picture before making any judgments. + +### 2. Evaluate Decomposition Boundaries + +- Are the sub-plans split at natural seams (layers, domains, modules)? +- Is any sub-plan doing too much? Could it be split further? +- Is any sub-plan too granular, creating unnecessary coordination overhead? +- Are there responsibilities that fall between sub-plans (gaps)? +- Are there responsibilities claimed by multiple sub-plans (overlaps)? + +### 3. Evaluate the Dependency Graph + +- Are all dependencies between sub-plans captured in the master plan's table? +- Are there hidden dependencies the planner missed? (e.g., sub-plan 03 assumes a type defined in sub-plan 01, but doesn't list it as a dependency) +- Are there circular dependencies? +- Could dependencies be reduced by shifting responsibilities between sub-plans? +- Are the prerequisites in each sub-plan specific enough? (They should include actual signatures/shapes, not just "the user service must exist") + +### 4. Evaluate Integration Feasibility + +- When all sub-plans are executed independently, will the results actually fit together? +- Are interface contracts between sub-plans consistent? (e.g., if sub-plan 01 defines an interface and sub-plan 02 consumes it, do they agree on the shape?) +- Are there implicit assumptions about execution order beyond what the master plan declares? + +### 5. Evaluate Against the Codebase + +- Do the proposed changes conflict with existing architecture or patterns? +- Are there existing abstractions the plan should use but doesn't? +- Does the plan introduce unnecessary complexity where simpler approaches exist in the codebase? +- Are the files listed in sub-plans correct? Do they exist where the plan says they do? + +### 6. Evaluate Risks + +- Are the risks in the master plan realistic and complete? +- Are there risks the planner didn't identify? +- Are the mitigations concrete or just hand-waving? + +## Output Format + +Write your findings to the `reviews/` subdirectory within the plan directory you were given. Use the naming pattern `.architect.md` (e.g., `reviews/00-master.architect.md`). + +Be direct and specific — every finding must reference the exact plan file and section it relates to. + +```markdown +# Architecture Review: + +## Verdict + + + +## Critical Findings + + +### Finding: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Concerns + + +### Concern: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Observations + +``` + +## Rules + +- **Be skeptical, not hostile.** Your job is to find real problems, not to nitpick. +- **Verify claims against the codebase.** If the plan says "we'll extend the existing UserService," confirm that UserService exists, where it is, and that extending it makes sense. +- **Every finding must be actionable.** Don't just say "this could be a problem" — say what the problem is and what to do about it. +- **Don't review implementation details within sub-plans.** That's the codebase alignment reviewer's job. You focus on the decomposition, boundaries, dependencies, and integration. +- **Don't invent requirements.** Review the plan against its own stated requirements, not against what you think the requirements should be. diff --git a/dot_claude/agents/plan-reviewer.md b/dot_claude/agents/plan-reviewer.md deleted file mode 100644 index adfd950..0000000 --- a/dot_claude/agents/plan-reviewer.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -name: plan-reviewer -description: Use this agent when you have a development plan that needs thorough review before implementation to identify potential issues, missing considerations, or better alternatives. ---- - -You are a Senior Technical Plan Reviewer, a meticulous architect with deep expertise in system integration, database design, and software engineering best practices. Your specialty is identifying critical flaws, missing considerations, and potential failure points in development plans before they become costly implementation problems. - -**Your Core Responsibilities:** -1. **Deep System Analysis**: Research and understand all systems, technologies, and components mentioned in the plan. Verify compatibility, limitations, and integration requirements. -2. **Database Impact Assessment**: Analyze how the plan affects database schema, performance, migrations, and data integrity. Identify missing indexes, constraint issues, or scaling concerns. -3. **Dependency Mapping**: Identify all dependencies, both explicit and implicit, that the plan relies on. Check for version conflicts, deprecated features, or unsupported combinations. -4. **Alternative Solution Evaluation**: Consider if there are better approaches, simpler solutions, or more maintainable alternatives that weren't explored. -5. **Risk Assessment**: Identify potential failure points, edge cases, and scenarios where the plan might break down. - -**Your Review Process:** -1. **Context Deep Dive**: Thoroughly understand the existing system architecture, current implementations, and constraints from the provided context. -2. **Plan Deconstruction**: Break down the plan into individual components and analyze each step for feasibility and completeness. -3. **Research Phase**: Investigate any technologies, APIs, or systems mentioned. Verify current documentation, known issues, and compatibility requirements. -4. **Gap Analysis**: Identify what's missing from the plan - error handling, rollback strategies, testing approaches, monitoring, etc. -5. **Impact Analysis**: Consider how changes affect existing functionality, performance, security, and user experience. - -**Critical Areas to Examine:** -- **Authentication/Authorization**: Verify compatibility with existing auth systems, token handling, session management -- **Database Operations**: Check for proper migrations, indexing strategies, transaction handling, and data validation -- **API Integrations**: Validate endpoint availability, rate limits, authentication requirements, and error handling -- **Type Safety**: Ensure proper TypeScript types are defined for new data structures and API responses -- **Error Handling**: Verify comprehensive error scenarios are addressed -- **Performance**: Consider scalability, caching strategies, and potential bottlenecks -- **Security**: Identify potential vulnerabilities or security gaps -- **Testing Strategy**: Ensure the plan includes adequate testing approaches -- **Rollback Plans**: Verify there are safe ways to undo changes if issues arise - -**Your Output Requirements:** -1. **Executive Summary**: Brief overview of plan viability and major concerns -2. **Critical Issues**: Show-stopping problems that must be addressed before implementation -3. **Missing Considerations**: Important aspects not covered in the original plan -4. **Alternative Approaches**: Better or simpler solutions if they exist -5. **Implementation Recommendations**: Specific improvements to make the plan more robust -6. **Risk Mitigation**: Strategies to handle identified risks -7. **Research Findings**: Key discoveries from your investigation of mentioned technologies/systems - -**Quality Standards:** -- Only flag genuine issues - don't create problems where none exist -- Provide specific, actionable feedback with concrete examples -- Reference actual documentation, known limitations, or compatibility issues when possible -- Suggest practical alternatives, not theoretical ideals -- Focus on preventing real-world implementation failures -- Consider the project's specific context and constraints - -Create your review as a comprehensive markdown report that saves the development team from costly implementation mistakes. Your goal is to catch the "gotchas" before they become roadblocks, just like identifying that HTTPie wouldn't work with the existing Keycloak authentication system before spending time on a doomed implementation. diff --git a/dot_claude/agents/plan-risk-reviewer.md b/dot_claude/agents/plan-risk-reviewer.md new file mode 100644 index 0000000..6ea3e92 --- /dev/null +++ b/dot_claude/agents/plan-risk-reviewer.md @@ -0,0 +1,104 @@ +--- +name: plan-risk-reviewer +description: "Use this agent to review master plans and their sub-plan decompositions for technical risks and feasibility issues. Identifies migration pitfalls, backward-compatibility landmines, missing rollback strategies, and sub-plans that may be significantly harder or more complex than they appear.\n\n\nContext: A master plan has been created for migrating a database schema with 4 sub-plans.\nuser: \"Review the plan in .claude/plans/db-migration/ for risks and feasibility.\"\nassistant: \"I'll review the plan for technical risks, hidden complexity, and feasibility issues.\"\n\nInvoke plan-risk-reviewer after initial plan creation (Phase 5, Step 1 of project-feature-planning) alongside plan-architect-reviewer to catch risks before sub-plans are reviewed individually.\n\n\n\n\nContext: The architecture reviewer flagged a decomposition change. The master plan was updated and needs risk re-assessment.\nuser: \"The master plan was restructured after architecture review. Re-assess risks for the affected parts.\"\nassistant: \"I'll re-evaluate the changed plan for new risks introduced by the restructuring.\"\n\nInvoke plan-risk-reviewer during the convergence loop when master plan changes may have introduced new risks.\n\n" +tools: Read, Write, Glob, Grep +--- + +You are a risk and feasibility reviewer. Your job is to review feature plans — specifically, a master plan and its sub-plan decomposition — and find risks, hidden complexity, and feasibility problems before an executing agent attempts implementation. + +You are NOT here to praise, summarize, or restate the plan. You are here to find what could go wrong. + +## What You Review + +You will be given a path to a plan directory (e.g., `.claude/plans//`) containing: +- `00-master.md` — orchestration: requirements, scope, sub-plan table, execution order, risks +- `01-*.md`, `02-*.md`, ... — self-contained sub-plans with implementation details + +You also have access to the full codebase to verify claims and assess feasibility. + +## How You Review + +### 1. Read All Plan Files + +Read the master plan and every sub-plan. Understand the full picture before making any judgments. + +### 2. Evaluate Feasibility + +- Is each sub-plan actually achievable as described? Are the implementation steps realistic? +- Are there steps that sound simple but are actually hard? (e.g., "migrate the data" with no rollback strategy, "update all callers" when there are hundreds) +- Does the plan assume capabilities that don't exist in the current codebase or tech stack? +- Are time/effort estimates (implicit or explicit) realistic? + +### 3. Identify Hidden Complexity + +- Are there steps that gloss over significant effort? (e.g., "migrate the data" without addressing volume, downtime, or rollback) +- Does the plan involve data migrations? If so, is there a rollback strategy? +- Are there ordering constraints the plan doesn't acknowledge? (e.g., database schema must change before code deployment) +- Will any sub-plan require coordination with external systems, teams, or processes not mentioned in the plan? +- Does a sub-plan underestimate its scope? (e.g., "update all callers" when the codebase has hundreds of call sites) + +### 4. Assess Backward Compatibility + +- Will the changes break existing functionality, APIs, or contracts? +- Are there consumers of the affected code that the plan doesn't account for? +- Does the plan handle the transition period? (e.g., old and new code running simultaneously during deployment) +- Are there database changes that are incompatible with the current running code? + +### 5. Evaluate the Plan's Own Risk Section + +- Are the risks listed in the master plan realistic and complete? +- Are the mitigations concrete and actionable, or just hand-waving? (e.g., "we'll handle errors" is hand-waving; "we'll wrap the migration in a transaction with a rollback trigger" is concrete) +- Are there obvious risks missing from the list? + +### 6. Check for Single Points of Failure + +- Is there a sub-plan that, if it fails, makes all other sub-plans useless? +- Are there irreversible steps without adequate safeguards? +- Does the plan have a recovery path if something goes wrong mid-execution? + +## Output Format + +Write your findings to the `reviews/` subdirectory within the plan directory you were given. Use the naming pattern `.risk.md` (e.g., `reviews/00-master.risk.md`). + +Be direct and specific — every finding must reference the exact plan file and section it relates to. + +```markdown +# Risk Review: + +## Verdict + + + +## Critical Findings + + +### Finding: +- **Affects**: +- **Risk**: +- **Likelihood**: +- **Impact**: +- **Recommendation**: + +## Concerns + + +### Concern: +- **Affects**: +- **Risk**: +- **Likelihood**: +- **Impact**: +- **Recommendation**: + +## Observations + +``` + +## Rules + +- **Be skeptical, not hostile.** Your job is to find real risks, not to imagine unlikely disaster scenarios. +- **Verify claims against the codebase.** If the plan says "this is a simple change," check whether it actually is. +- **Every finding must be actionable.** Don't just say "this is risky" — say what the risk is, how likely it is, what the impact would be, and what to do about it. +- **Focus on risks and feasibility, not architecture.** Don't evaluate decomposition boundaries or dependency structure — that's the architecture reviewer's job. You focus on what could go wrong and what's harder than it looks. +- **Stay at the plan level, not the code level.** You assess whether the plan's *strategy* is sound — rollback paths, migration approaches, scope estimates. You don't analyze code-level edge cases like empty lists or race conditions — that's the codebase reviewer's job. +- **Don't invent requirements.** Assess risks against the plan's stated requirements, not against what you think the requirements should be. +- **Distinguish between real risks and theoretical risks.** A data migration without rollback is a real risk. "What if the server catches fire" is not useful. diff --git a/dot_claude/agents/refactor-planner.md b/dot_claude/agents/refactor-planner.md index c13041c..daf7751 100644 --- a/dot_claude/agents/refactor-planner.md +++ b/dot_claude/agents/refactor-planner.md @@ -41,7 +41,7 @@ When creating your refactoring plan, you will: - **Start with a comprehensive analysis** of the current state, using code examples and specific file references - **Categorize issues** by severity (critical, major, minor) and type (structural, behavioral, naming) -- **Propose solutions** that align with the project's existing patterns and conventions (check CLAUDE.md) +- **Propose solutions** that align with the project's existing patterns and conventions (check AGENTS.md) - **Structure the plan** in markdown format with clear sections: - Executive Summary - Current State Analysis @@ -58,4 +58,4 @@ When creating your refactoring plan, you will: Your analysis should be thorough but pragmatic, focusing on changes that provide the most value with acceptable risk. Always consider the team's capacity and the project's timeline when proposing refactoring phases. Be specific about file paths, function names, and code patterns to make your plan actionable. -Remember to check for any project-specific guidelines in CLAUDE.md files and ensure your refactoring plan aligns with established coding standards and architectural decisions. +Remember to check for any project-specific guidelines in AGENTS.md files and ensure your refactoring plan aligns with established coding standards and architectural decisions. diff --git a/dot_claude/skills/Command Development/README.md b/dot_claude/skills/Command Development/README.md deleted file mode 100644 index a5d303f..0000000 --- a/dot_claude/skills/Command Development/README.md +++ /dev/null @@ -1,272 +0,0 @@ -# Command Development Skill - -Comprehensive guidance on creating Claude Code slash commands, including file format, frontmatter options, dynamic arguments, and best practices. - -## Overview - -This skill provides knowledge about: -- Slash command file format and structure -- YAML frontmatter configuration fields -- Dynamic arguments ($ARGUMENTS, $1, $2, etc.) -- File references with @ syntax -- Bash execution with !` syntax -- Command organization and namespacing -- Best practices for command development -- Plugin-specific features (${CLAUDE_PLUGIN_ROOT}, plugin patterns) -- Integration with plugin components (agents, skills, hooks) -- Validation patterns and error handling - -## Skill Structure - -### SKILL.md (~2,470 words) - -Core skill content covering: - -**Fundamentals:** -- Command basics and locations -- File format (Markdown with optional frontmatter) -- YAML frontmatter fields overview -- Dynamic arguments ($ARGUMENTS and positional) -- File references (@ syntax) -- Bash execution (!` syntax) -- Command organization patterns -- Best practices and common patterns -- Troubleshooting - -**Plugin-Specific:** -- ${CLAUDE_PLUGIN_ROOT} environment variable -- Plugin command discovery and organization -- Plugin command patterns (configuration, template, multi-script) -- Integration with plugin components (agents, skills, hooks) -- Validation patterns (argument, file, resource, error handling) - -### References - -Detailed documentation: - -- **frontmatter-reference.md**: Complete YAML frontmatter field specifications - - All field descriptions with types and defaults - - When to use each field - - Examples and best practices - - Validation and common errors - -- **plugin-features-reference.md**: Plugin-specific command features - - Plugin command discovery and organization - - ${CLAUDE_PLUGIN_ROOT} environment variable usage - - Plugin command patterns (configuration, template, multi-script) - - Integration with plugin agents, skills, and hooks - - Validation patterns and error handling - -### Examples - -Practical command examples: - -- **simple-commands.md**: 10 complete command examples - - Code review commands - - Testing commands - - Deployment commands - - Documentation generators - - Git integration commands - - Analysis and research commands - -- **plugin-commands.md**: 10 plugin-specific command examples - - Simple plugin commands with scripts - - Multi-script workflows - - Template-based generation - - Configuration-driven deployment - - Agent and skill integration - - Multi-component workflows - - Validated input commands - - Environment-aware commands - -## When This Skill Triggers - -Claude Code activates this skill when users: -- Ask to "create a slash command" or "add a command" -- Need to "write a custom command" -- Want to "define command arguments" -- Ask about "command frontmatter" or YAML configuration -- Need to "organize commands" or use namespacing -- Want to create commands with file references -- Ask about "bash execution in commands" -- Need command development best practices - -## Progressive Disclosure - -The skill uses progressive disclosure: - -1. **SKILL.md** (~2,470 words): Core concepts, common patterns, and plugin features overview -2. **References** (~13,500 words total): Detailed specifications - - frontmatter-reference.md (~1,200 words) - - plugin-features-reference.md (~1,800 words) - - interactive-commands.md (~2,500 words) - - advanced-workflows.md (~1,700 words) - - testing-strategies.md (~2,200 words) - - documentation-patterns.md (~2,000 words) - - marketplace-considerations.md (~2,200 words) -3. **Examples** (~6,000 words total): Complete working command examples - - simple-commands.md - - plugin-commands.md - -Claude loads references and examples as needed based on task. - -## Command Basics Quick Reference - -### File Format - -```markdown ---- -description: Brief description -argument-hint: [arg1] [arg2] -allowed-tools: Read, Bash(git:*) ---- - -Command prompt content with: -- Arguments: $1, $2, or $ARGUMENTS -- Files: @path/to/file -- Bash: !`command here` -``` - -### Locations - -- **Project**: `.claude/commands/` (shared with team) -- **Personal**: `~/.claude/commands/` (your commands) -- **Plugin**: `plugin-name/commands/` (plugin-specific) - -### Key Features - -**Dynamic arguments:** -- `$ARGUMENTS` - All arguments as single string -- `$1`, `$2`, `$3` - Positional arguments - -**File references:** -- `@path/to/file` - Include file contents - -**Bash execution:** -- `!`command`` - Execute and include output - -## Frontmatter Fields Quick Reference - -| Field | Purpose | Example | -|-------|---------|---------| -| `description` | Brief description for /help | `"Review code for issues"` | -| `allowed-tools` | Restrict tool access | `Read, Bash(git:*)` | -| `model` | Specify model | `sonnet`, `opus`, `haiku` | -| `argument-hint` | Document arguments | `[pr-number] [priority]` | -| `disable-model-invocation` | Manual-only command | `true` | - -## Common Patterns - -### Simple Review Command - -```markdown ---- -description: Review code for issues ---- - -Review this code for quality and potential bugs. -``` - -### Command with Arguments - -```markdown ---- -description: Deploy to environment -argument-hint: [environment] [version] ---- - -Deploy to $1 environment using version $2 -``` - -### Command with File Reference - -```markdown ---- -description: Document file -argument-hint: [file-path] ---- - -Generate documentation for @$1 -``` - -### Command with Bash Execution - -```markdown ---- -description: Show Git status -allowed-tools: Bash(git:*) ---- - -Current status: !`git status` -Recent commits: !`git log --oneline -5` -``` - -## Development Workflow - -1. **Design command:** - - Define purpose and scope - - Determine required arguments - - Identify needed tools - -2. **Create file:** - - Choose appropriate location - - Create `.md` file with command name - - Write basic prompt - -3. **Add frontmatter:** - - Start minimal (just description) - - Add fields as needed (allowed-tools, etc.) - - Document arguments with argument-hint - -4. **Test command:** - - Invoke with `/command-name` - - Verify arguments work - - Check bash execution - - Test file references - -5. **Refine:** - - Improve prompt clarity - - Handle edge cases - - Add examples in comments - - Document requirements - -## Best Practices Summary - -1. **Single responsibility**: One command, one clear purpose -2. **Clear descriptions**: Make discoverable in `/help` -3. **Document arguments**: Always use argument-hint -4. **Minimal tools**: Use most restrictive allowed-tools -5. **Test thoroughly**: Verify all features work -6. **Add comments**: Explain complex logic -7. **Handle errors**: Consider missing arguments/files - -## Status - -**Completed enhancements:** -- ✓ Plugin command patterns (${CLAUDE_PLUGIN_ROOT}, discovery, organization) -- ✓ Integration patterns (agents, skills, hooks coordination) -- ✓ Validation patterns (input, file, resource validation, error handling) - -**Remaining enhancements (in progress):** -- Advanced workflows (multi-step command sequences) -- Testing strategies (how to test commands effectively) -- Documentation patterns (command documentation best practices) -- Marketplace considerations (publishing and distribution) - -## Maintenance - -To update this skill: -1. Keep SKILL.md focused on core fundamentals -2. Move detailed specifications to references/ -3. Add new examples/ for different use cases -4. Update frontmatter when new fields added -5. Ensure imperative/infinitive form throughout -6. Test examples work with current Claude Code - -## Version History - -**v0.1.0** (2025-01-15): -- Initial release with basic command fundamentals -- Frontmatter field reference -- 10 simple command examples -- Ready for plugin-specific pattern additions diff --git a/dot_claude/skills/Command Development/SKILL.md b/dot_claude/skills/Command Development/SKILL.md deleted file mode 100644 index e39435e..0000000 --- a/dot_claude/skills/Command Development/SKILL.md +++ /dev/null @@ -1,834 +0,0 @@ ---- -name: Command Development -description: This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code. -version: 0.2.0 ---- - -# Command Development for Claude Code - -## Overview - -Slash commands are frequently-used prompts defined as Markdown files that Claude executes during interactive sessions. Understanding command structure, frontmatter options, and dynamic features enables creating powerful, reusable workflows. - -**Key concepts:** -- Markdown file format for commands -- YAML frontmatter for configuration -- Dynamic arguments and file references -- Bash execution for context -- Command organization and namespacing - -## Command Basics - -### What is a Slash Command? - -A slash command is a Markdown file containing a prompt that Claude executes when invoked. Commands provide: -- **Reusability**: Define once, use repeatedly -- **Consistency**: Standardize common workflows -- **Sharing**: Distribute across team or projects -- **Efficiency**: Quick access to complex prompts - -### Critical: Commands are Instructions FOR Claude - -**Commands are written for agent consumption, not human consumption.** - -When a user invokes `/command-name`, the command content becomes Claude's instructions. Write commands as directives TO Claude about what to do, not as messages TO the user. - -**Correct approach (instructions for Claude):** -```markdown -Review this code for security vulnerabilities including: -- SQL injection -- XSS attacks -- Authentication issues - -Provide specific line numbers and severity ratings. -``` - -**Incorrect approach (messages to user):** -```markdown -This command will review your code for security issues. -You'll receive a report with vulnerability details. -``` - -The first example tells Claude what to do. The second tells the user what will happen but doesn't instruct Claude. Always use the first approach. - -### Command Locations - -**Project commands** (shared with team): -- Location: `.claude/commands/` -- Scope: Available in specific project -- Label: Shown as "(project)" in `/help` -- Use for: Team workflows, project-specific tasks - -**Personal commands** (available everywhere): -- Location: `~/.claude/commands/` -- Scope: Available in all projects -- Label: Shown as "(user)" in `/help` -- Use for: Personal workflows, cross-project utilities - -**Plugin commands** (bundled with plugins): -- Location: `plugin-name/commands/` -- Scope: Available when plugin installed -- Label: Shown as "(plugin-name)" in `/help` -- Use for: Plugin-specific functionality - -## File Format - -### Basic Structure - -Commands are Markdown files with `.md` extension: - -``` -.claude/commands/ -├── review.md # /review command -├── test.md # /test command -└── deploy.md # /deploy command -``` - -**Simple command:** -```markdown -Review this code for security vulnerabilities including: -- SQL injection -- XSS attacks -- Authentication bypass -- Insecure data handling -``` - -No frontmatter needed for basic commands. - -### With YAML Frontmatter - -Add configuration using YAML frontmatter: - -```markdown ---- -description: Review code for security issues -allowed-tools: Read, Grep, Bash(git:*) -model: sonnet ---- - -Review this code for security vulnerabilities... -``` - -## YAML Frontmatter Fields - -### description - -**Purpose:** Brief description shown in `/help` -**Type:** String -**Default:** First line of command prompt - -```yaml ---- -description: Review pull request for code quality ---- -``` - -**Best practice:** Clear, actionable description (under 60 characters) - -### allowed-tools - -**Purpose:** Specify which tools command can use -**Type:** String or Array -**Default:** Inherits from conversation - -```yaml ---- -allowed-tools: Read, Write, Edit, Bash(git:*) ---- -``` - -**Patterns:** -- `Read, Write, Edit` - Specific tools -- `Bash(git:*)` - Bash with git commands only -- `*` - All tools (rarely needed) - -**Use when:** Command requires specific tool access - -### model - -**Purpose:** Specify model for command execution -**Type:** String (sonnet, opus, haiku) -**Default:** Inherits from conversation - -```yaml ---- -model: haiku ---- -``` - -**Use cases:** -- `haiku` - Fast, simple commands -- `sonnet` - Standard workflows -- `opus` - Complex analysis - -### argument-hint - -**Purpose:** Document expected arguments for autocomplete -**Type:** String -**Default:** None - -```yaml ---- -argument-hint: [pr-number] [priority] [assignee] ---- -``` - -**Benefits:** -- Helps users understand command arguments -- Improves command discovery -- Documents command interface - -### disable-model-invocation - -**Purpose:** Prevent SlashCommand tool from programmatically calling command -**Type:** Boolean -**Default:** false - -```yaml ---- -disable-model-invocation: true ---- -``` - -**Use when:** Command should only be manually invoked - -## Dynamic Arguments - -### Using $ARGUMENTS - -Capture all arguments as single string: - -```markdown ---- -description: Fix issue by number -argument-hint: [issue-number] ---- - -Fix issue #$ARGUMENTS following our coding standards and best practices. -``` - -**Usage:** -``` -> /fix-issue 123 -> /fix-issue 456 -``` - -**Expands to:** -``` -Fix issue #123 following our coding standards... -Fix issue #456 following our coding standards... -``` - -### Using Positional Arguments - -Capture individual arguments with `$1`, `$2`, `$3`, etc.: - -```markdown ---- -description: Review PR with priority and assignee -argument-hint: [pr-number] [priority] [assignee] ---- - -Review pull request #$1 with priority level $2. -After review, assign to $3 for follow-up. -``` - -**Usage:** -``` -> /review-pr 123 high alice -``` - -**Expands to:** -``` -Review pull request #123 with priority level high. -After review, assign to alice for follow-up. -``` - -### Combining Arguments - -Mix positional and remaining arguments: - -```markdown -Deploy $1 to $2 environment with options: $3 -``` - -**Usage:** -``` -> /deploy api staging --force --skip-tests -``` - -**Expands to:** -``` -Deploy api to staging environment with options: --force --skip-tests -``` - -## File References - -### Using @ Syntax - -Include file contents in command: - -```markdown ---- -description: Review specific file -argument-hint: [file-path] ---- - -Review @$1 for: -- Code quality -- Best practices -- Potential bugs -``` - -**Usage:** -``` -> /review-file src/api/users.ts -``` - -**Effect:** Claude reads `src/api/users.ts` before processing command - -### Multiple File References - -Reference multiple files: - -```markdown -Compare @src/old-version.js with @src/new-version.js - -Identify: -- Breaking changes -- New features -- Bug fixes -``` - -### Static File References - -Reference known files without arguments: - -```markdown -Review @package.json and @tsconfig.json for consistency - -Ensure: -- TypeScript version matches -- Dependencies are aligned -- Build configuration is correct -``` - -## Bash Execution in Commands - -Commands can execute bash commands inline to dynamically gather context before Claude processes the command. This is useful for including repository state, environment information, or project-specific context. - -**When to use:** -- Include dynamic context (git status, environment vars, etc.) -- Gather project/repository state -- Build context-aware workflows - -**Implementation details:** -For complete syntax, examples, and best practices, see `references/plugin-features-reference.md` section on bash execution. The reference includes the exact syntax and multiple working examples to avoid execution issues - -## Command Organization - -### Flat Structure - -Simple organization for small command sets: - -``` -.claude/commands/ -├── build.md -├── test.md -├── deploy.md -├── review.md -└── docs.md -``` - -**Use when:** 5-15 commands, no clear categories - -### Namespaced Structure - -Organize commands in subdirectories: - -``` -.claude/commands/ -├── ci/ -│ ├── build.md # /build (project:ci) -│ ├── test.md # /test (project:ci) -│ └── lint.md # /lint (project:ci) -├── git/ -│ ├── commit.md # /commit (project:git) -│ └── pr.md # /pr (project:git) -└── docs/ - ├── generate.md # /generate (project:docs) - └── publish.md # /publish (project:docs) -``` - -**Benefits:** -- Logical grouping by category -- Namespace shown in `/help` -- Easier to find related commands - -**Use when:** 15+ commands, clear categories - -## Best Practices - -### Command Design - -1. **Single responsibility:** One command, one task -2. **Clear descriptions:** Self-explanatory in `/help` -3. **Explicit dependencies:** Use `allowed-tools` when needed -4. **Document arguments:** Always provide `argument-hint` -5. **Consistent naming:** Use verb-noun pattern (review-pr, fix-issue) - -### Argument Handling - -1. **Validate arguments:** Check for required arguments in prompt -2. **Provide defaults:** Suggest defaults when arguments missing -3. **Document format:** Explain expected argument format -4. **Handle edge cases:** Consider missing or invalid arguments - -```markdown ---- -argument-hint: [pr-number] ---- - -$IF($1, - Review PR #$1, - Please provide a PR number. Usage: /review-pr [number] -) -``` - -### File References - -1. **Explicit paths:** Use clear file paths -2. **Check existence:** Handle missing files gracefully -3. **Relative paths:** Use project-relative paths -4. **Glob support:** Consider using Glob tool for patterns - -### Bash Commands - -1. **Limit scope:** Use `Bash(git:*)` not `Bash(*)` -2. **Safe commands:** Avoid destructive operations -3. **Handle errors:** Consider command failures -4. **Keep fast:** Long-running commands slow invocation - -### Documentation - -1. **Add comments:** Explain complex logic -2. **Provide examples:** Show usage in comments -3. **List requirements:** Document dependencies -4. **Version commands:** Note breaking changes - -```markdown ---- -description: Deploy application to environment -argument-hint: [environment] [version] ---- - - - -Deploy application to $1 environment using version $2... -``` - -## Common Patterns - -### Review Pattern - -```markdown ---- -description: Review code changes -allowed-tools: Read, Bash(git:*) ---- - -Files changed: !`git diff --name-only` - -Review each file for: -1. Code quality and style -2. Potential bugs or issues -3. Test coverage -4. Documentation needs - -Provide specific feedback for each file. -``` - -### Testing Pattern - -```markdown ---- -description: Run tests for specific file -argument-hint: [test-file] -allowed-tools: Bash(npm:*) ---- - -Run tests: !`npm test $1` - -Analyze results and suggest fixes for failures. -``` - -### Documentation Pattern - -```markdown ---- -description: Generate documentation for file -argument-hint: [source-file] ---- - -Generate comprehensive documentation for @$1 including: -- Function/class descriptions -- Parameter documentation -- Return value descriptions -- Usage examples -- Edge cases and errors -``` - -### Workflow Pattern - -```markdown ---- -description: Complete PR workflow -argument-hint: [pr-number] -allowed-tools: Bash(gh:*), Read ---- - -PR #$1 Workflow: - -1. Fetch PR: !`gh pr view $1` -2. Review changes -3. Run checks -4. Approve or request changes -``` - -## Troubleshooting - -**Command not appearing:** -- Check file is in correct directory -- Verify `.md` extension present -- Ensure valid Markdown format -- Restart Claude Code - -**Arguments not working:** -- Verify `$1`, `$2` syntax correct -- Check `argument-hint` matches usage -- Ensure no extra spaces - -**Bash execution failing:** -- Check `allowed-tools` includes Bash -- Verify command syntax in backticks -- Test command in terminal first -- Check for required permissions - -**File references not working:** -- Verify `@` syntax correct -- Check file path is valid -- Ensure Read tool allowed -- Use absolute or project-relative paths - -## Plugin-Specific Features - -### CLAUDE_PLUGIN_ROOT Variable - -Plugin commands have access to `${CLAUDE_PLUGIN_ROOT}`, an environment variable that resolves to the plugin's absolute path. - -**Purpose:** -- Reference plugin files portably -- Execute plugin scripts -- Load plugin configuration -- Access plugin templates - -**Basic usage:** - -```markdown ---- -description: Analyze using plugin script -allowed-tools: Bash(node:*) ---- - -Run analysis: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1` - -Review results and report findings. -``` - -**Common patterns:** - -```markdown -# Execute plugin script -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/script.sh` - -# Load plugin configuration -@${CLAUDE_PLUGIN_ROOT}/config/settings.json - -# Use plugin template -@${CLAUDE_PLUGIN_ROOT}/templates/report.md - -# Access plugin resources -@${CLAUDE_PLUGIN_ROOT}/docs/reference.md -``` - -**Why use it:** -- Works across all installations -- Portable between systems -- No hardcoded paths needed -- Essential for multi-file plugins - -### Plugin Command Organization - -Plugin commands discovered automatically from `commands/` directory: - -``` -plugin-name/ -├── commands/ -│ ├── foo.md # /foo (plugin:plugin-name) -│ ├── bar.md # /bar (plugin:plugin-name) -│ └── utils/ -│ └── helper.md # /helper (plugin:plugin-name:utils) -└── plugin.json -``` - -**Namespace benefits:** -- Logical command grouping -- Shown in `/help` output -- Avoid name conflicts -- Organize related commands - -**Naming conventions:** -- Use descriptive action names -- Avoid generic names (test, run) -- Consider plugin-specific prefix -- Use hyphens for multi-word names - -### Plugin Command Patterns - -**Configuration-based pattern:** - -```markdown ---- -description: Deploy using plugin configuration -argument-hint: [environment] -allowed-tools: Read, Bash(*) ---- - -Load configuration: @${CLAUDE_PLUGIN_ROOT}/config/$1-deploy.json - -Deploy to $1 using configuration settings. -Monitor deployment and report status. -``` - -**Template-based pattern:** - -```markdown ---- -description: Generate docs from template -argument-hint: [component] ---- - -Template: @${CLAUDE_PLUGIN_ROOT}/templates/docs.md - -Generate documentation for $1 following template structure. -``` - -**Multi-script pattern:** - -```markdown ---- -description: Complete build workflow -allowed-tools: Bash(*) ---- - -Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh` -Test: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test.sh` -Package: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/package.sh` - -Review outputs and report workflow status. -``` - -**See `references/plugin-features-reference.md` for detailed patterns.** - -## Integration with Plugin Components - -Commands can integrate with other plugin components for powerful workflows. - -### Agent Integration - -Launch plugin agents for complex tasks: - -```markdown ---- -description: Deep code review -argument-hint: [file-path] ---- - -Initiate comprehensive review of @$1 using the code-reviewer agent. - -The agent will analyze: -- Code structure -- Security issues -- Performance -- Best practices - -Agent uses plugin resources: -- ${CLAUDE_PLUGIN_ROOT}/config/rules.json -- ${CLAUDE_PLUGIN_ROOT}/checklists/review.md -``` - -**Key points:** -- Agent must exist in `plugin/agents/` directory -- Claude uses Task tool to launch agent -- Document agent capabilities -- Reference plugin resources agent uses - -### Skill Integration - -Leverage plugin skills for specialized knowledge: - -```markdown ---- -description: Document API with standards -argument-hint: [api-file] ---- - -Document API in @$1 following plugin standards. - -Use the api-docs-standards skill to ensure: -- Complete endpoint documentation -- Consistent formatting -- Example quality -- Error documentation - -Generate production-ready API docs. -``` - -**Key points:** -- Skill must exist in `plugin/skills/` directory -- Mention skill name to trigger invocation -- Document skill purpose -- Explain what skill provides - -### Hook Coordination - -Design commands that work with plugin hooks: -- Commands can prepare state for hooks to process -- Hooks execute automatically on tool events -- Commands should document expected hook behavior -- Guide Claude on interpreting hook output - -See `references/plugin-features-reference.md` for examples of commands that coordinate with hooks - -### Multi-Component Workflows - -Combine agents, skills, and scripts: - -```markdown ---- -description: Comprehensive review workflow -argument-hint: [file] -allowed-tools: Bash(node:*), Read ---- - -Target: @$1 - -Phase 1 - Static Analysis: -!`node ${CLAUDE_PLUGIN_ROOT}/scripts/lint.js $1` - -Phase 2 - Deep Review: -Launch code-reviewer agent for detailed analysis. - -Phase 3 - Standards Check: -Use coding-standards skill for validation. - -Phase 4 - Report: -Template: @${CLAUDE_PLUGIN_ROOT}/templates/review.md - -Compile findings into report following template. -``` - -**When to use:** -- Complex multi-step workflows -- Leverage multiple plugin capabilities -- Require specialized analysis -- Need structured outputs - -## Validation Patterns - -Commands should validate inputs and resources before processing. - -### Argument Validation - -```markdown ---- -description: Deploy with validation -argument-hint: [environment] ---- - -Validate environment: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"` - -If $1 is valid environment: - Deploy to $1 -Otherwise: - Explain valid environments: dev, staging, prod - Show usage: /deploy [environment] -``` - -### File Existence Checks - -```markdown ---- -description: Process configuration -argument-hint: [config-file] ---- - -Check file exists: !`test -f $1 && echo "EXISTS" || echo "MISSING"` - -If file exists: - Process configuration: @$1 -Otherwise: - Explain where to place config file - Show expected format - Provide example configuration -``` - -### Plugin Resource Validation - -```markdown ---- -description: Run plugin analyzer -allowed-tools: Bash(test:*) ---- - -Validate plugin setup: -- Script: !`test -x ${CLAUDE_PLUGIN_ROOT}/bin/analyze && echo "✓" || echo "✗"` -- Config: !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "✓" || echo "✗"` - -If all checks pass, run analysis. -Otherwise, report missing components. -``` - -### Error Handling - -```markdown ---- -description: Build with error handling -allowed-tools: Bash(*) ---- - -Execute build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh 2>&1 || echo "BUILD_FAILED"` - -If build succeeded: - Report success and output location -If build failed: - Analyze error output - Suggest likely causes - Provide troubleshooting steps -``` - -**Best practices:** -- Validate early in command -- Provide helpful error messages -- Suggest corrective actions -- Handle edge cases gracefully - ---- - -For detailed frontmatter field specifications, see `references/frontmatter-reference.md`. -For plugin-specific features and patterns, see `references/plugin-features-reference.md`. -For command pattern examples, see `examples/` directory. diff --git a/dot_claude/skills/Command Development/examples/plugin-commands.md b/dot_claude/skills/Command Development/examples/plugin-commands.md deleted file mode 100644 index e14ef4d..0000000 --- a/dot_claude/skills/Command Development/examples/plugin-commands.md +++ /dev/null @@ -1,557 +0,0 @@ -# Plugin Command Examples - -Practical examples of commands designed for Claude Code plugins, demonstrating plugin-specific patterns and features. - -## Table of Contents - -1. [Simple Plugin Command](#1-simple-plugin-command) -2. [Script-Based Analysis](#2-script-based-analysis) -3. [Template-Based Generation](#3-template-based-generation) -4. [Multi-Script Workflow](#4-multi-script-workflow) -5. [Configuration-Driven Deployment](#5-configuration-driven-deployment) -6. [Agent Integration](#6-agent-integration) -7. [Skill Integration](#7-skill-integration) -8. [Multi-Component Workflow](#8-multi-component-workflow) -9. [Validated Input Command](#9-validated-input-command) -10. [Environment-Aware Command](#10-environment-aware-command) - ---- - -## 1. Simple Plugin Command - -**Use case:** Basic command that uses plugin script - -**File:** `commands/analyze.md` - -```markdown ---- -description: Analyze code quality using plugin tools -argument-hint: [file-path] -allowed-tools: Bash(node:*), Read ---- - -Analyze @$1 using plugin's quality checker: - -!`node ${CLAUDE_PLUGIN_ROOT}/scripts/quality-check.js $1` - -Review the analysis output and provide: -1. Summary of findings -2. Priority issues to address -3. Suggested improvements -4. Code quality score interpretation -``` - -**Key features:** -- Uses `${CLAUDE_PLUGIN_ROOT}` for portable path -- Combines file reference with script execution -- Simple single-purpose command - ---- - -## 2. Script-Based Analysis - -**Use case:** Run comprehensive analysis using multiple plugin scripts - -**File:** `commands/full-audit.md` - -```markdown ---- -description: Complete code audit using plugin suite -argument-hint: [directory] -allowed-tools: Bash(*) -model: sonnet ---- - -Running complete audit on $1: - -**Security scan:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/security-scan.sh $1` - -**Performance analysis:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/perf-analyze.sh $1` - -**Best practices check:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/best-practices.sh $1` - -Analyze all results and create comprehensive report including: -- Critical issues requiring immediate attention -- Performance optimization opportunities -- Security vulnerabilities and fixes -- Overall health score and recommendations -``` - -**Key features:** -- Multiple script executions -- Organized output sections -- Comprehensive workflow -- Clear reporting structure - ---- - -## 3. Template-Based Generation - -**Use case:** Generate documentation following plugin template - -**File:** `commands/gen-api-docs.md` - -```markdown ---- -description: Generate API documentation from template -argument-hint: [api-file] ---- - -Template structure: @${CLAUDE_PLUGIN_ROOT}/templates/api-documentation.md - -API implementation: @$1 - -Generate complete API documentation following the template format above. - -Ensure documentation includes: -- Endpoint descriptions with HTTP methods -- Request/response schemas -- Authentication requirements -- Error codes and handling -- Usage examples with curl commands -- Rate limiting information - -Format output as markdown suitable for README or docs site. -``` - -**Key features:** -- Uses plugin template -- Combines template with source file -- Standardized output format -- Clear documentation structure - ---- - -## 4. Multi-Script Workflow - -**Use case:** Orchestrate build, test, and deploy workflow - -**File:** `commands/release.md` - -```markdown ---- -description: Execute complete release workflow -argument-hint: [version] -allowed-tools: Bash(*), Read ---- - -Executing release workflow for version $1: - -**Step 1 - Pre-release validation:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/pre-release-check.sh $1` - -**Step 2 - Build artifacts:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build-release.sh $1` - -**Step 3 - Run test suite:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/run-tests.sh` - -**Step 4 - Package release:** -!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/package.sh $1` - -Review all step outputs and report: -1. Any failures or warnings -2. Build artifacts location -3. Test results summary -4. Next steps for deployment -5. Rollback plan if needed -``` - -**Key features:** -- Multi-step workflow -- Sequential script execution -- Clear step numbering -- Comprehensive reporting - ---- - -## 5. Configuration-Driven Deployment - -**Use case:** Deploy using environment-specific plugin configuration - -**File:** `commands/deploy.md` - -```markdown ---- -description: Deploy application to environment -argument-hint: [environment] -allowed-tools: Read, Bash(*) ---- - -Deployment configuration for $1: @${CLAUDE_PLUGIN_ROOT}/config/$1-deploy.json - -Current git state: !`git rev-parse --short HEAD` - -Build info: !`cat package.json | grep -E '(name|version)'` - -Execute deployment to $1 environment using configuration above. - -Deployment checklist: -1. Validate configuration settings -2. Build application for $1 -3. Run pre-deployment tests -4. Deploy to target environment -5. Run smoke tests -6. Verify deployment success -7. Update deployment log - -Report deployment status and any issues encountered. -``` - -**Key features:** -- Environment-specific configuration -- Dynamic config file loading -- Pre-deployment validation -- Structured checklist - ---- - -## 6. Agent Integration - -**Use case:** Command that launches plugin agent for complex task - -**File:** `commands/deep-review.md` - -```markdown ---- -description: Deep code review using plugin agent -argument-hint: [file-or-directory] ---- - -Initiate comprehensive code review of @$1 using the code-reviewer agent. - -The agent will perform: -1. **Static analysis** - Check for code smells and anti-patterns -2. **Security audit** - Identify potential vulnerabilities -3. **Performance review** - Find optimization opportunities -4. **Best practices** - Ensure code follows standards -5. **Documentation check** - Verify adequate documentation - -The agent has access to: -- Plugin's linting rules: ${CLAUDE_PLUGIN_ROOT}/config/lint-rules.json -- Security checklist: ${CLAUDE_PLUGIN_ROOT}/checklists/security.md -- Performance guidelines: ${CLAUDE_PLUGIN_ROOT}/docs/performance.md - -Note: This uses the Task tool to launch the plugin's code-reviewer agent for thorough analysis. -``` - -**Key features:** -- Delegates to plugin agent -- Documents agent capabilities -- References plugin resources -- Clear scope definition - ---- - -## 7. Skill Integration - -**Use case:** Command that leverages plugin skill for specialized knowledge - -**File:** `commands/document-api.md` - -```markdown ---- -description: Document API following plugin standards -argument-hint: [api-file] ---- - -API source code: @$1 - -Generate API documentation following the plugin's API documentation standards. - -Use the api-documentation-standards skill to ensure: -- **OpenAPI compliance** - Follow OpenAPI 3.0 specification -- **Consistent formatting** - Use plugin's documentation style -- **Complete coverage** - Document all endpoints and schemas -- **Example quality** - Provide realistic usage examples -- **Error documentation** - Cover all error scenarios - -The skill provides: -- Standard documentation templates -- API documentation best practices -- Common patterns for this codebase -- Quality validation criteria - -Generate production-ready API documentation. -``` - -**Key features:** -- Invokes plugin skill by name -- Documents skill purpose -- Clear expectations -- Leverages skill knowledge - ---- - -## 8. Multi-Component Workflow - -**Use case:** Complex workflow using agents, skills, and scripts - -**File:** `commands/complete-review.md` - -```markdown ---- -description: Comprehensive review using all plugin components -argument-hint: [file-path] -allowed-tools: Bash(node:*), Read ---- - -Target file: @$1 - -Execute comprehensive review workflow: - -**Phase 1: Automated Analysis** -Run plugin analyzer: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1` - -**Phase 2: Deep Review (Agent)** -Launch the code-quality-reviewer agent for detailed analysis. -Agent will examine: -- Code structure and organization -- Error handling patterns -- Testing coverage -- Documentation quality - -**Phase 3: Standards Check (Skill)** -Use the coding-standards skill to validate: -- Naming conventions -- Code formatting -- Best practices adherence -- Framework-specific patterns - -**Phase 4: Report Generation** -Template: @${CLAUDE_PLUGIN_ROOT}/templates/review-report.md - -Compile all findings into comprehensive report following template. - -**Phase 5: Recommendations** -Generate prioritized action items: -1. Critical issues (must fix) -2. Important improvements (should fix) -3. Nice-to-have enhancements (could fix) - -Include specific file locations and suggested changes for each item. -``` - -**Key features:** -- Multi-phase workflow -- Combines scripts, agents, skills -- Template-based reporting -- Prioritized outputs - ---- - -## 9. Validated Input Command - -**Use case:** Command with input validation and error handling - -**File:** `commands/build-env.md` - -```markdown ---- -description: Build for specific environment with validation -argument-hint: [environment] -allowed-tools: Bash(*) ---- - -Validate environment argument: !`echo "$1" | grep -E "^(dev|staging|prod)$" && echo "VALID" || echo "INVALID"` - -Check build script exists: !`test -x ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh && echo "EXISTS" || echo "MISSING"` - -Verify configuration available: !`test -f ${CLAUDE_PLUGIN_ROOT}/config/$1.json && echo "FOUND" || echo "NOT_FOUND"` - -If all validations pass: - -**Configuration:** @${CLAUDE_PLUGIN_ROOT}/config/$1.json - -**Execute build:** !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh $1 2>&1` - -**Validation results:** !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate-build.sh $1 2>&1` - -Report build status and any issues. - -If validations fail: -- Explain which validation failed -- Provide expected values/locations -- Suggest corrective actions -- Document troubleshooting steps -``` - -**Key features:** -- Input validation -- Resource existence checks -- Error handling -- Helpful error messages -- Graceful failure handling - ---- - -## 10. Environment-Aware Command - -**Use case:** Command that adapts behavior based on environment - -**File:** `commands/run-checks.md` - -```markdown ---- -description: Run environment-appropriate checks -argument-hint: [environment] -allowed-tools: Bash(*), Read ---- - -Environment: $1 - -Load environment configuration: @${CLAUDE_PLUGIN_ROOT}/config/$1-checks.json - -Determine check level: !`echo "$1" | grep -E "^prod$" && echo "FULL" || echo "BASIC"` - -**For production environment:** -- Full test suite: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test-full.sh` -- Security scan: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/security-scan.sh` -- Performance audit: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/perf-check.sh` -- Compliance check: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/compliance.sh` - -**For non-production environments:** -- Basic tests: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test-basic.sh` -- Quick lint: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/lint.sh` - -Analyze results based on environment requirements: - -**Production:** All checks must pass with zero critical issues -**Staging:** No critical issues, warnings acceptable -**Development:** Focus on blocking issues only - -Report status and recommend proceed/block decision. -``` - -**Key features:** -- Environment-aware logic -- Conditional execution -- Different validation levels -- Appropriate reporting per environment - ---- - -## Common Patterns Summary - -### Pattern: Plugin Script Execution -```markdown -!`node ${CLAUDE_PLUGIN_ROOT}/scripts/script-name.js $1` -``` -Use for: Running plugin-provided Node.js scripts - -### Pattern: Plugin Configuration Loading -```markdown -@${CLAUDE_PLUGIN_ROOT}/config/config-name.json -``` -Use for: Loading plugin configuration files - -### Pattern: Plugin Template Usage -```markdown -@${CLAUDE_PLUGIN_ROOT}/templates/template-name.md -``` -Use for: Using plugin templates for generation - -### Pattern: Agent Invocation -```markdown -Launch the [agent-name] agent for [task description]. -``` -Use for: Delegating complex tasks to plugin agents - -### Pattern: Skill Reference -```markdown -Use the [skill-name] skill to ensure [requirements]. -``` -Use for: Leveraging plugin skills for specialized knowledge - -### Pattern: Input Validation -```markdown -Validate input: !`echo "$1" | grep -E "^pattern$" && echo "OK" || echo "ERROR"` -``` -Use for: Validating command arguments - -### Pattern: Resource Validation -```markdown -Check exists: !`test -f ${CLAUDE_PLUGIN_ROOT}/path/file && echo "YES" || echo "NO"` -``` -Use for: Verifying required plugin files exist - ---- - -## Development Tips - -### Testing Plugin Commands - -1. **Test with plugin installed:** - ```bash - cd /path/to/plugin - claude /command-name args - ``` - -2. **Verify ${CLAUDE_PLUGIN_ROOT} expansion:** - ```bash - # Add debug output to command - !`echo "Plugin root: ${CLAUDE_PLUGIN_ROOT}"` - ``` - -3. **Test across different working directories:** - ```bash - cd /tmp && claude /command-name - cd /other/project && claude /command-name - ``` - -4. **Validate resource availability:** - ```bash - # Check all plugin resources exist - !`ls -la ${CLAUDE_PLUGIN_ROOT}/scripts/` - !`ls -la ${CLAUDE_PLUGIN_ROOT}/config/` - ``` - -### Common Mistakes to Avoid - -1. **Using relative paths instead of ${CLAUDE_PLUGIN_ROOT}:** - ```markdown - # Wrong - !`node ./scripts/analyze.js` - - # Correct - !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js` - ``` - -2. **Forgetting to allow required tools:** - ```markdown - # Missing allowed-tools - !`bash script.sh` # Will fail without Bash permission - - # Correct - --- - allowed-tools: Bash(*) - --- - !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/script.sh` - ``` - -3. **Not validating inputs:** - ```markdown - # Risky - no validation - Deploy to $1 environment - - # Better - with validation - Validate: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"` - Deploy to $1 environment (if valid) - ``` - -4. **Hardcoding plugin paths:** - ```markdown - # Wrong - breaks on different installations - @/home/user/.claude/plugins/my-plugin/config.json - - # Correct - works everywhere - @${CLAUDE_PLUGIN_ROOT}/config.json - ``` - ---- - -For detailed plugin-specific features, see `references/plugin-features-reference.md`. -For general command development, see main `SKILL.md`. diff --git a/dot_claude/skills/Command Development/examples/simple-commands.md b/dot_claude/skills/Command Development/examples/simple-commands.md deleted file mode 100644 index 2348239..0000000 --- a/dot_claude/skills/Command Development/examples/simple-commands.md +++ /dev/null @@ -1,504 +0,0 @@ -# Simple Command Examples - -Basic slash command patterns for common use cases. - -**Important:** All examples below are written as instructions FOR Claude (agent consumption), not messages TO users. Commands tell Claude what to do, not tell users what will happen. - -## Example 1: Code Review Command - -**File:** `.claude/commands/review.md` - -```markdown ---- -description: Review code for quality and issues -allowed-tools: Read, Bash(git:*) ---- - -Review the code in this repository for: - -1. **Code Quality:** - - Readability and maintainability - - Consistent style and formatting - - Appropriate abstraction levels - -2. **Potential Issues:** - - Logic errors or bugs - - Edge cases not handled - - Performance concerns - -3. **Best Practices:** - - Design patterns used correctly - - Error handling present - - Documentation adequate - -Provide specific feedback with file and line references. -``` - -**Usage:** -``` -> /review -``` - ---- - -## Example 2: Security Review Command - -**File:** `.claude/commands/security-review.md` - -```markdown ---- -description: Review code for security vulnerabilities -allowed-tools: Read, Grep -model: sonnet ---- - -Perform comprehensive security review checking for: - -**Common Vulnerabilities:** -- SQL injection risks -- Cross-site scripting (XSS) -- Authentication/authorization issues -- Insecure data handling -- Hardcoded secrets or credentials - -**Security Best Practices:** -- Input validation present -- Output encoding correct -- Secure defaults used -- Error messages safe -- Logging appropriate (no sensitive data) - -For each issue found: -- File and line number -- Severity (Critical/High/Medium/Low) -- Description of vulnerability -- Recommended fix - -Prioritize issues by severity. -``` - -**Usage:** -``` -> /security-review -``` - ---- - -## Example 3: Test Command with File Argument - -**File:** `.claude/commands/test-file.md` - -```markdown ---- -description: Run tests for specific file -argument-hint: [test-file] -allowed-tools: Bash(npm:*), Bash(jest:*) ---- - -Run tests for $1: - -Test execution: !`npm test $1` - -Analyze results: -- Tests passed/failed -- Code coverage -- Performance issues -- Flaky tests - -If failures found, suggest fixes based on error messages. -``` - -**Usage:** -``` -> /test-file src/utils/helpers.test.ts -``` - ---- - -## Example 4: Documentation Generator - -**File:** `.claude/commands/document.md` - -```markdown ---- -description: Generate documentation for file -argument-hint: [source-file] ---- - -Generate comprehensive documentation for @$1 - -Include: - -**Overview:** -- Purpose and responsibility -- Main functionality -- Dependencies - -**API Documentation:** -- Function/method signatures -- Parameter descriptions with types -- Return values with types -- Exceptions/errors thrown - -**Usage Examples:** -- Basic usage -- Common patterns -- Edge cases - -**Implementation Notes:** -- Algorithm complexity -- Performance considerations -- Known limitations - -Format as Markdown suitable for project documentation. -``` - -**Usage:** -``` -> /document src/api/users.ts -``` - ---- - -## Example 5: Git Status Summary - -**File:** `.claude/commands/git-status.md` - -```markdown ---- -description: Summarize Git repository status -allowed-tools: Bash(git:*) ---- - -Repository Status Summary: - -**Current Branch:** !`git branch --show-current` - -**Status:** !`git status --short` - -**Recent Commits:** !`git log --oneline -5` - -**Remote Status:** !`git fetch && git status -sb` - -Provide: -- Summary of changes -- Suggested next actions -- Any warnings or issues -``` - -**Usage:** -``` -> /git-status -``` - ---- - -## Example 6: Deployment Command - -**File:** `.claude/commands/deploy.md` - -```markdown ---- -description: Deploy to specified environment -argument-hint: [environment] [version] -allowed-tools: Bash(kubectl:*), Read ---- - -Deploy to $1 environment using version $2 - -**Pre-deployment Checks:** -1. Verify $1 configuration exists -2. Check version $2 is valid -3. Verify cluster accessibility: !`kubectl cluster-info` - -**Deployment Steps:** -1. Update deployment manifest with version $2 -2. Apply configuration to $1 -3. Monitor rollout status -4. Verify pod health -5. Run smoke tests - -**Rollback Plan:** -Document current version for rollback if issues occur. - -Proceed with deployment? (yes/no) -``` - -**Usage:** -``` -> /deploy staging v1.2.3 -``` - ---- - -## Example 7: Comparison Command - -**File:** `.claude/commands/compare-files.md` - -```markdown ---- -description: Compare two files -argument-hint: [file1] [file2] ---- - -Compare @$1 with @$2 - -**Analysis:** - -1. **Differences:** - - Lines added - - Lines removed - - Lines modified - -2. **Functional Changes:** - - Breaking changes - - New features - - Bug fixes - - Refactoring - -3. **Impact:** - - Affected components - - Required updates elsewhere - - Migration requirements - -4. **Recommendations:** - - Code review focus areas - - Testing requirements - - Documentation updates needed - -Present as structured comparison report. -``` - -**Usage:** -``` -> /compare-files src/old-api.ts src/new-api.ts -``` - ---- - -## Example 8: Quick Fix Command - -**File:** `.claude/commands/quick-fix.md` - -```markdown ---- -description: Quick fix for common issues -argument-hint: [issue-description] -model: haiku ---- - -Quickly fix: $ARGUMENTS - -**Approach:** -1. Identify the issue -2. Find relevant code -3. Propose fix -4. Explain solution - -Focus on: -- Simple, direct solution -- Minimal changes -- Following existing patterns -- No breaking changes - -Provide code changes with file paths and line numbers. -``` - -**Usage:** -``` -> /quick-fix button not responding to clicks -> /quick-fix typo in error message -``` - ---- - -## Example 9: Research Command - -**File:** `.claude/commands/research.md` - -```markdown ---- -description: Research best practices for topic -argument-hint: [topic] -model: sonnet ---- - -Research best practices for: $ARGUMENTS - -**Coverage:** - -1. **Current State:** - - How we currently handle this - - Existing implementations - -2. **Industry Standards:** - - Common patterns - - Recommended approaches - - Tools and libraries - -3. **Comparison:** - - Our approach vs standards - - Gaps or improvements needed - - Migration considerations - -4. **Recommendations:** - - Concrete action items - - Priority and effort estimates - - Resources for implementation - -Provide actionable guidance based on research. -``` - -**Usage:** -``` -> /research error handling in async operations -> /research API authentication patterns -``` - ---- - -## Example 10: Explain Code Command - -**File:** `.claude/commands/explain.md` - -```markdown ---- -description: Explain how code works -argument-hint: [file-or-function] ---- - -Explain @$1 in detail - -**Explanation Structure:** - -1. **Overview:** - - What it does - - Why it exists - - How it fits in system - -2. **Step-by-Step:** - - Line-by-line walkthrough - - Key algorithms or logic - - Important details - -3. **Inputs and Outputs:** - - Parameters and types - - Return values - - Side effects - -4. **Edge Cases:** - - Error handling - - Special cases - - Limitations - -5. **Usage Examples:** - - How to call it - - Common patterns - - Integration points - -Explain at level appropriate for junior engineer. -``` - -**Usage:** -``` -> /explain src/utils/cache.ts -> /explain AuthService.login -``` - ---- - -## Key Patterns - -### Pattern 1: Read-Only Analysis - -```markdown ---- -allowed-tools: Read, Grep ---- - -Analyze but don't modify... -``` - -**Use for:** Code review, documentation, analysis - -### Pattern 2: Git Operations - -```markdown ---- -allowed-tools: Bash(git:*) ---- - -!`git status` -Analyze and suggest... -``` - -**Use for:** Repository status, commit analysis - -### Pattern 3: Single Argument - -```markdown ---- -argument-hint: [target] ---- - -Process $1... -``` - -**Use for:** File operations, targeted actions - -### Pattern 4: Multiple Arguments - -```markdown ---- -argument-hint: [source] [target] [options] ---- - -Process $1 to $2 with $3... -``` - -**Use for:** Workflows, deployments, comparisons - -### Pattern 5: Fast Execution - -```markdown ---- -model: haiku ---- - -Quick simple task... -``` - -**Use for:** Simple, repetitive commands - -### Pattern 6: File Comparison - -```markdown -Compare @$1 with @$2... -``` - -**Use for:** Diff analysis, migration planning - -### Pattern 7: Context Gathering - -```markdown ---- -allowed-tools: Bash(git:*), Read ---- - -Context: !`git status` -Files: @file1 @file2 - -Analyze... -``` - -**Use for:** Informed decision making - -## Tips for Writing Simple Commands - -1. **Start basic:** Single responsibility, clear purpose -2. **Add complexity gradually:** Start without frontmatter -3. **Test incrementally:** Verify each feature works -4. **Use descriptive names:** Command name should indicate purpose -5. **Document arguments:** Always use argument-hint -6. **Provide examples:** Show usage in comments -7. **Handle errors:** Consider missing arguments or files diff --git a/dot_claude/skills/Command Development/references/advanced-workflows.md b/dot_claude/skills/Command Development/references/advanced-workflows.md deleted file mode 100644 index 5e0d7b1..0000000 --- a/dot_claude/skills/Command Development/references/advanced-workflows.md +++ /dev/null @@ -1,722 +0,0 @@ -# Advanced Workflow Patterns - -Multi-step command sequences and composition patterns for complex workflows. - -## Overview - -Advanced workflows combine multiple commands, coordinate state across invocations, and create sophisticated automation sequences. These patterns enable building complex functionality from simple command building blocks. - -## Multi-Step Command Patterns - -### Sequential Workflow Command - -Commands that guide users through multi-step processes: - -```markdown ---- -description: Complete PR review workflow -argument-hint: [pr-number] -allowed-tools: Bash(gh:*), Read, Grep ---- - -# PR Review Workflow for #$1 - -## Step 1: Fetch PR Details -!`gh pr view $1 --json title,body,author,files` - -## Step 2: Review Files -Files changed: !`gh pr diff $1 --name-only` - -For each file: -- Check code quality -- Verify tests exist -- Review documentation - -## Step 3: Run Checks -Test status: !`gh pr checks $1` - -Verify: -- All tests passing -- No merge conflicts -- CI/CD successful - -## Step 4: Provide Feedback - -Summarize: -- Issues found (critical/minor) -- Suggestions for improvement -- Approval recommendation - -Would you like to: -1. Approve PR -2. Request changes -3. Leave comments only - -Reply with your choice and I'll help complete the action. -``` - -**Key features:** -- Numbered steps for clarity -- Bash execution for context -- Decision points for user input -- Next action suggestions - -### State-Carrying Workflow - -Commands that maintain state between invocations: - -```markdown ---- -description: Initialize deployment workflow -allowed-tools: Write, Bash(git:*) ---- - -# Initialize Deployment - -Creating deployment tracking file... - -Current branch: !`git branch --show-current` -Latest commit: !`git log -1 --format=%H` - -Deployment state saved to `.claude/deployment-state.local.md`: - -\`\`\`markdown ---- -initialized: true -branch: $(git branch --show-current) -commit: $(git log -1 --format=%H) -timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ) -status: initialized ---- - -# Deployment Tracking - -Branch: $(git branch --show-current) -Started: $(date) - -Next steps: -1. Run tests: /deploy-test -2. Build: /deploy-build -3. Deploy: /deploy-execute -\`\`\` - -State saved. Run `/deploy-test` to continue. -``` - -**Next command** (`/deploy-test`): -```markdown ---- -description: Run deployment tests -allowed-tools: Read, Bash(npm:*) ---- - -Reading deployment state from `.claude/deployment-state.local.md`... - -Running tests: !`npm test` - -Updating state to 'tested'... - -Tests complete. Run `/deploy-build` to continue. -``` - -**Pattern benefits:** -- Persistent state across commands -- Clear workflow progression -- Safety checkpoints -- Resume capability - -### Conditional Workflow Branching - -Commands that adapt based on conditions: - -```markdown ---- -description: Smart deployment workflow -argument-hint: [environment] -allowed-tools: Bash(git:*), Bash(npm:*), Read ---- - -# Deploy to $1 - -## Pre-flight Checks - -Branch: !`git branch --show-current` -Status: !`git status --short` - -**Checking conditions:** - -1. Branch status: - - If main/master: Require approval - - If feature branch: Warning about target - - If hotfix: Fast-track process - -2. Tests: - !`npm test` - - If tests fail: STOP - fix tests first - - If tests pass: Continue - -3. Environment: - - If $1 = 'production': Extra validation - - If $1 = 'staging': Standard process - - If $1 = 'dev': Minimal checks - -**Workflow decision:** -Based on above, proceeding with: [determined workflow] - -[Conditional steps based on environment and status] - -Ready to deploy? (yes/no) -``` - -## Command Composition Patterns - -### Command Chaining - -Commands designed to work together: - -```markdown ---- -description: Prepare for code review ---- - -# Prepare Code Review - -Running preparation sequence: - -1. Format code: /format-code -2. Run linter: /lint-code -3. Run tests: /test-all -4. Generate coverage: /coverage-report -5. Create review summary: /review-summary - -This is a meta-command. After completing each step above, -I'll compile results and prepare comprehensive review materials. - -Starting sequence... -``` - -**Individual commands** are simple: -- `/format-code` - Just formats -- `/lint-code` - Just lints -- `/test-all` - Just tests - -**Composition command** orchestrates them. - -### Pipeline Pattern - -Commands that process output from previous commands: - -```markdown ---- -description: Analyze test failures ---- - -# Analyze Test Failures - -## Step 1: Get test results -(Run /test-all first if not done) - -Reading test output... - -## Step 2: Categorize failures -- Flaky tests (random failures) -- Consistent failures -- New failures vs existing - -## Step 3: Prioritize -Rank by: -- Impact (critical path vs edge case) -- Frequency (always fails vs sometimes) -- Effort (quick fix vs major work) - -## Step 4: Generate fix plan -For each failure: -- Root cause hypothesis -- Suggested fix approach -- Estimated effort - -Would you like me to: -1. Fix highest priority failure -2. Generate detailed fix plans for all -3. Create GitHub issues for each -``` - -### Parallel Execution Pattern - -Commands that coordinate multiple simultaneous operations: - -```markdown ---- -description: Run comprehensive validation -allowed-tools: Bash(*), Read ---- - -# Comprehensive Validation - -Running validations in parallel... - -Starting: -- Code quality checks -- Security scanning -- Dependency audit -- Performance profiling - -This will take 2-3 minutes. I'll monitor all processes -and report when complete. - -[Poll each process and report progress] - -All validations complete. Summary: -- Quality: PASS (0 issues) -- Security: WARN (2 minor issues) -- Dependencies: PASS -- Performance: PASS (baseline met) - -Details: -[Collated results from all checks] -``` - -## Workflow State Management - -### Using .local.md Files - -Store workflow state in plugin-specific files: - -```markdown -.claude/plugin-name-workflow.local.md: - ---- -workflow: deployment -stage: testing -started: 2025-01-15T10:30:00Z -environment: staging -branch: feature/new-api -commit: abc123def -tests_passed: false -build_complete: false ---- - -# Deployment Workflow State - -Current stage: Testing -Started: 2025-01-15 10:30 UTC - -Completed steps: -- ✅ Validation -- ✅ Branch check -- ⏳ Testing (in progress) - -Pending steps: -- Build -- Deploy -- Smoke tests -``` - -**Reading state in commands:** - -```markdown ---- -description: Continue deployment workflow -allowed-tools: Read, Write ---- - -Reading workflow state from .claude/plugin-name-workflow.local.md... - -Current stage: @.claude/plugin-name-workflow.local.md - -[Parse YAML frontmatter to determine next step] - -Next action based on state: [determined action] -``` - -### Workflow Recovery - -Handle interrupted workflows: - -```markdown ---- -description: Resume deployment workflow -allowed-tools: Read ---- - -# Resume Deployment - -Checking for interrupted workflow... - -State file: @.claude/plugin-name-workflow.local.md - -**Workflow found:** -- Started: [timestamp] -- Environment: [env] -- Last completed: [step] - -**Recovery options:** -1. Resume from last step -2. Restart from beginning -3. Abort and clean up - -Which would you like? (1/2/3) -``` - -## Workflow Coordination Patterns - -### Cross-Command Communication - -Commands that signal each other: - -```markdown ---- -description: Mark feature complete -allowed-tools: Write ---- - -# Mark Feature Complete - -Writing completion marker... - -Creating: .claude/feature-complete.flag - -This signals other commands that feature is ready for: -- Integration testing (/integration-test will auto-detect) -- Documentation generation (/docs-generate will include) -- Release notes (/release-notes will add) - -Feature marked complete. -``` - -**Other commands check for flag:** - -```markdown ---- -description: Generate release notes -allowed-tools: Read, Bash(git:*) ---- - -Checking for completed features... - -if [ -f .claude/feature-complete.flag ]; then - Feature ready for release notes -fi - -[Include in release notes] -``` - -### Workflow Locking - -Prevent concurrent workflow execution: - -```markdown ---- -description: Start deployment -allowed-tools: Read, Write, Bash ---- - -# Start Deployment - -Checking for active deployments... - -if [ -f .claude/deployment.lock ]; then - ERROR: Deployment already in progress - Started: [timestamp from lock file] - - Cannot start concurrent deployment. - Wait for completion or run /deployment-abort - - Exit. -fi - -Creating deployment lock... - -Deployment started. Lock created. -[Proceed with deployment] -``` - -**Lock cleanup:** - -```markdown ---- -description: Complete deployment -allowed-tools: Write, Bash ---- - -Deployment complete. - -Removing deployment lock... -rm .claude/deployment.lock - -Ready for next deployment. -``` - -## Advanced Argument Handling - -### Optional Arguments with Defaults - -```markdown ---- -description: Deploy with optional version -argument-hint: [environment] [version] ---- - -Environment: ${1:-staging} -Version: ${2:-latest} - -Deploying ${2:-latest} to ${1:-staging}... - -Note: Using defaults for missing arguments: -- Environment defaults to 'staging' -- Version defaults to 'latest' -``` - -### Argument Validation - -```markdown ---- -description: Deploy to validated environment -argument-hint: [environment] ---- - -Environment: $1 - -Validating environment... - -valid_envs="dev staging production" -if ! echo "$valid_envs" | grep -w "$1" > /dev/null; then - ERROR: Invalid environment '$1' - Valid options: dev, staging, production - Exit. -fi - -Environment validated. Proceeding... -``` - -### Argument Transformation - -```markdown ---- -description: Deploy with shorthand -argument-hint: [env-shorthand] ---- - -Input: $1 - -Expanding shorthand: -- d/dev → development -- s/stg → staging -- p/prod → production - -case "$1" in - d|dev) ENV="development";; - s|stg) ENV="staging";; - p|prod) ENV="production";; - *) ENV="$1";; -esac - -Deploying to: $ENV -``` - -## Error Handling in Workflows - -### Graceful Failure - -```markdown ---- -description: Resilient deployment workflow ---- - -# Deployment Workflow - -Running steps with error handling... - -## Step 1: Tests -!`npm test` - -if [ $? -ne 0 ]; then - ERROR: Tests failed - - Options: - 1. Fix tests and retry - 2. Skip tests (NOT recommended) - 3. Abort deployment - - What would you like to do? - - [Wait for user input before continuing] -fi - -## Step 2: Build -[Continue only if Step 1 succeeded] -``` - -### Rollback on Failure - -```markdown ---- -description: Deployment with rollback ---- - -# Deploy with Rollback - -Saving current state for rollback... -Previous version: !`current-version.sh` - -Deploying new version... - -!`deploy.sh` - -if [ $? -ne 0 ]; then - DEPLOYMENT FAILED - - Initiating automatic rollback... - !`rollback.sh` - - Rolled back to previous version. - Check logs for failure details. -fi - -Deployment complete. -``` - -### Checkpoint Recovery - -```markdown ---- -description: Workflow with checkpoints ---- - -# Multi-Stage Deployment - -## Checkpoint 1: Validation -!`validate.sh` -echo "checkpoint:validation" >> .claude/deployment-checkpoints.log - -## Checkpoint 2: Build -!`build.sh` -echo "checkpoint:build" >> .claude/deployment-checkpoints.log - -## Checkpoint 3: Deploy -!`deploy.sh` -echo "checkpoint:deploy" >> .claude/deployment-checkpoints.log - -If any step fails, resume with: -/deployment-resume [last-successful-checkpoint] -``` - -## Best Practices - -### Workflow Design - -1. **Clear progression**: Number steps, show current position -2. **Explicit state**: Don't rely on implicit state -3. **User control**: Provide decision points -4. **Error recovery**: Handle failures gracefully -5. **Progress indication**: Show what's done, what's pending - -### Command Composition - -1. **Single responsibility**: Each command does one thing well -2. **Composable design**: Commands work together easily -3. **Standard interfaces**: Consistent input/output formats -4. **Loose coupling**: Commands don't depend on each other's internals - -### State Management - -1. **Persistent state**: Use .local.md files -2. **Atomic updates**: Write complete state files atomically -3. **State validation**: Check state file format/completeness -4. **Cleanup**: Remove stale state files -5. **Documentation**: Document state file formats - -### Error Handling - -1. **Fail fast**: Detect errors early -2. **Clear messages**: Explain what went wrong -3. **Recovery options**: Provide clear next steps -4. **State preservation**: Keep state for recovery -5. **Rollback capability**: Support undoing changes - -## Example: Complete Deployment Workflow - -### Initialize Command - -```markdown ---- -description: Initialize deployment -argument-hint: [environment] -allowed-tools: Write, Bash(git:*) ---- - -# Initialize Deployment to $1 - -Creating workflow state... - -\`\`\`yaml ---- -workflow: deployment -environment: $1 -branch: !`git branch --show-current` -commit: !`git rev-parse HEAD` -stage: initialized -timestamp: !`date -u +%Y-%m-%dT%H:%M:%SZ` ---- -\`\`\` - -Written to .claude/deployment-state.local.md - -Next: Run /deployment-validate -``` - -### Validation Command - -```markdown ---- -description: Validate deployment -allowed-tools: Read, Bash ---- - -Reading state: @.claude/deployment-state.local.md - -Running validation... -- Branch check: PASS -- Tests: PASS -- Build: PASS - -Updating state to 'validated'... - -Next: Run /deployment-execute -``` - -### Execution Command - -```markdown ---- -description: Execute deployment -allowed-tools: Read, Bash, Write ---- - -Reading state: @.claude/deployment-state.local.md - -Executing deployment to [environment]... - -!`deploy.sh [environment]` - -Deployment complete. -Updating state to 'completed'... - -Cleanup: /deployment-cleanup -``` - -### Cleanup Command - -```markdown ---- -description: Clean up deployment -allowed-tools: Bash ---- - -Removing deployment state... -rm .claude/deployment-state.local.md - -Deployment workflow complete. -``` - -This complete workflow demonstrates state management, sequential execution, error handling, and clean separation of concerns across multiple commands. diff --git a/dot_claude/skills/Command Development/references/documentation-patterns.md b/dot_claude/skills/Command Development/references/documentation-patterns.md deleted file mode 100644 index 3ea03ec..0000000 --- a/dot_claude/skills/Command Development/references/documentation-patterns.md +++ /dev/null @@ -1,739 +0,0 @@ -# Command Documentation Patterns - -Strategies for creating self-documenting, maintainable commands with excellent user experience. - -## Overview - -Well-documented commands are easier to use, maintain, and distribute. Documentation should be embedded in the command itself, making it immediately accessible to users and maintainers. - -## Self-Documenting Command Structure - -### Complete Command Template - -```markdown ---- -description: Clear, actionable description under 60 chars -argument-hint: [arg1] [arg2] [optional-arg] -allowed-tools: Read, Bash(git:*) -model: sonnet ---- - - - -# Command Implementation - -[Command prompt content here...] - -[Explain what will happen...] - -[Guide user through steps...] - -[Provide clear output...] -``` - -### Documentation Comment Sections - -**PURPOSE**: Why the command exists -- Problem it solves -- Use cases -- When to use vs when not to use - -**USAGE**: Basic syntax -- Command invocation pattern -- Required vs optional arguments -- Default values - -**ARGUMENTS**: Detailed argument documentation -- Each argument described -- Type information -- Valid values/ranges -- Defaults - -**EXAMPLES**: Concrete usage examples -- Common use cases -- Edge cases -- Expected outputs - -**REQUIREMENTS**: Prerequisites -- Dependencies -- Permissions -- Environmental setup - -**RELATED COMMANDS**: Connections -- Similar commands -- Complementary commands -- Alternative approaches - -**TROUBLESHOOTING**: Common issues -- Known problems -- Solutions -- Workarounds - -**CHANGELOG**: Version history -- What changed when -- Breaking changes highlighted -- Migration guidance - -## In-Line Documentation Patterns - -### Commented Sections - -```markdown ---- -description: Complex multi-step command ---- - - - - -Checking prerequisites... -- Git repository: !`git rev-parse --git-dir 2>/dev/null` -- Branch exists: [validation logic] - - - - -Analyzing differences between $1 and $2... -[Analysis logic...] - - - - -Based on analysis, recommend: -[Recommendations...] - - -``` - -### Inline Explanations - -```markdown ---- -description: Deployment command with inline docs ---- - -# Deploy to $1 - -## Pre-flight Checks - - -Current branch: !`git branch --show-current` - - -if [ "$1" = "production" ] && [ "$(git branch --show-current)" != "main" ]; then - ⚠️ WARNING: Not on main branch for production deploy - This is unusual. Confirm this is intentional. -fi - - -Running tests: !`npm test` - -✓ All checks passed - -## Deployment - - - -Deploying to $1 environment... -[Deployment steps...] - - -Verifying deployment health... -[Health checks...] - -Deployment complete! - -## Next Steps - - -1. Monitor logs: /logs $1 -2. Run smoke tests: /smoke-test $1 -3. Notify team: /notify-deployment $1 -``` - -### Decision Point Documentation - -```markdown ---- -description: Interactive deployment command ---- - -# Interactive Deployment - -## Configuration Review - -Target: $1 -Current version: !`cat version.txt` -New version: $2 - - - - - -Review the above configuration. - -**Continue with deployment?** -- Reply "yes" to proceed -- Reply "no" to cancel -- Reply "edit" to modify configuration - -[Await user input before continuing...] - - - - -Proceeding with deployment... -``` - -## Help Text Patterns - -### Built-in Help Command - -Create a help subcommand for complex commands: - -```markdown ---- -description: Main command with help -argument-hint: [subcommand] [args] ---- - -# Command Processor - -if [ "$1" = "help" ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then - **Command Help** - - USAGE: - /command [subcommand] [args] - - SUBCOMMANDS: - init [name] Initialize new configuration - deploy [env] Deploy to environment - status Show current status - rollback Rollback last deployment - help Show this help - - EXAMPLES: - /command init my-project - /command deploy staging - /command status - /command rollback - - For detailed help on a subcommand: - /command [subcommand] --help - - Exit. -fi - -[Regular command processing...] -``` - -### Contextual Help - -Provide help based on context: - -```markdown ---- -description: Context-aware command -argument-hint: [operation] [target] ---- - -# Context-Aware Operation - -if [ -z "$1" ]; then - **No operation specified** - - Available operations: - - analyze: Analyze target for issues - - fix: Apply automatic fixes - - report: Generate detailed report - - Usage: /command [operation] [target] - - Examples: - /command analyze src/ - /command fix src/app.js - /command report - - Run /command help for more details. - - Exit. -fi - -[Command continues if operation provided...] -``` - -## Error Message Documentation - -### Helpful Error Messages - -```markdown ---- -description: Command with good error messages ---- - -# Validation Command - -if [ -z "$1" ]; then - ❌ ERROR: Missing required argument - - The 'file-path' argument is required. - - USAGE: - /validate [file-path] - - EXAMPLE: - /validate src/app.js - - Try again with a file path. - - Exit. -fi - -if [ ! -f "$1" ]; then - ❌ ERROR: File not found: $1 - - The specified file does not exist or is not accessible. - - COMMON CAUSES: - 1. Typo in file path - 2. File was deleted or moved - 3. Insufficient permissions - - SUGGESTIONS: - - Check spelling: $1 - - Verify file exists: ls -la $(dirname "$1") - - Check permissions: ls -l "$1" - - Exit. -fi - -[Command continues if validation passes...] -``` - -### Error Recovery Guidance - -```markdown ---- -description: Command with recovery guidance ---- - -# Operation Command - -Running operation... - -!`risky-operation.sh` - -if [ $? -ne 0 ]; then - ❌ OPERATION FAILED - - The operation encountered an error and could not complete. - - WHAT HAPPENED: - The risky-operation.sh script returned a non-zero exit code. - - WHAT THIS MEANS: - - Changes may be partially applied - - System may be in inconsistent state - - Manual intervention may be needed - - RECOVERY STEPS: - 1. Check operation logs: cat /tmp/operation.log - 2. Verify system state: /check-state - 3. If needed, rollback: /rollback-operation - 4. Fix underlying issue - 5. Retry operation: /retry-operation - - NEED HELP? - - Check troubleshooting guide: /help troubleshooting - - Contact support with error code: ERR_OP_FAILED_001 - - Exit. -fi -``` - -## Usage Example Documentation - -### Embedded Examples - -```markdown ---- -description: Command with embedded examples ---- - -# Feature Command - -This command performs feature analysis with multiple options. - -## Basic Usage - -\`\`\` -/feature analyze src/ -\`\`\` - -Analyzes all files in src/ directory for feature usage. - -## Advanced Usage - -\`\`\` -/feature analyze src/ --detailed -\`\`\` - -Provides detailed analysis including: -- Feature breakdown by file -- Usage patterns -- Optimization suggestions - -## Use Cases - -**Use Case 1: Quick overview** -\`\`\` -/feature analyze . -\`\`\` -Get high-level feature summary of entire project. - -**Use Case 2: Specific directory** -\`\`\` -/feature analyze src/components -\`\`\` -Focus analysis on components directory only. - -**Use Case 3: Comparison** -\`\`\` -/feature analyze src/ --compare baseline.json -\`\`\` -Compare current features against baseline. - ---- - -Now processing your request... - -[Command implementation...] -``` - -### Example-Driven Documentation - -```markdown ---- -description: Example-heavy command ---- - -# Transformation Command - -## What This Does - -Transforms data from one format to another. - -## Examples First - -### Example 1: JSON to YAML -**Input:** `data.json` -\`\`\`json -{"name": "test", "value": 42} -\`\`\` - -**Command:** `/transform data.json yaml` - -**Output:** `data.yaml` -\`\`\`yaml -name: test -value: 42 -\`\`\` - -### Example 2: CSV to JSON -**Input:** `data.csv` -\`\`\`csv -name,value -test,42 -\`\`\` - -**Command:** `/transform data.csv json` - -**Output:** `data.json` -\`\`\`json -[{"name": "test", "value": "42"}] -\`\`\` - -### Example 3: With Options -**Command:** `/transform data.json yaml --pretty --sort-keys` - -**Result:** Formatted YAML with sorted keys - ---- - -## Your Transformation - -File: $1 -Format: $2 - -[Perform transformation...] -``` - -## Maintenance Documentation - -### Version and Changelog - -```markdown - -``` - -### Maintenance Notes - -```markdown - -``` - -## README Documentation - -Commands should have companion README files: - -```markdown -# Command Name - -Brief description of what the command does. - -## Installation - -This command is part of the [plugin-name] plugin. - -Install with: -\`\`\` -/plugin install plugin-name -\`\`\` - -## Usage - -Basic usage: -\`\`\` -/command-name [arg1] [arg2] -\`\`\` - -## Arguments - -- `arg1`: Description (required) -- `arg2`: Description (optional, defaults to X) - -## Examples - -### Example 1: Basic Usage -\`\`\` -/command-name value1 value2 -\`\`\` - -Description of what happens. - -### Example 2: Advanced Usage -\`\`\` -/command-name value1 --option -\`\`\` - -Description of advanced feature. - -## Configuration - -Optional configuration file: `.claude/command-name.local.md` - -\`\`\`markdown ---- -default_arg: value -enable_feature: true ---- -\`\`\` - -## Requirements - -- Git 2.x or later -- jq (for JSON processing) -- Node.js 14+ (optional, for advanced features) - -## Troubleshooting - -### Issue: Command not found - -**Solution:** Ensure plugin is installed and enabled. - -### Issue: Permission denied - -**Solution:** Check file permissions and allowed-tools setting. - -## Contributing - -Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md). - -## License - -MIT License - See [LICENSE](LICENSE). - -## Support - -- Issues: https://github.com/user/plugin/issues -- Docs: https://docs.example.com -- Email: support@example.com -``` - -## Best Practices - -### Documentation Principles - -1. **Write for your future self**: Assume you'll forget details -2. **Examples before explanations**: Show, then tell -3. **Progressive disclosure**: Basic info first, details available -4. **Keep it current**: Update docs when code changes -5. **Test your docs**: Verify examples actually work - -### Documentation Locations - -1. **In command file**: Core usage, examples, inline explanations -2. **README**: Installation, configuration, troubleshooting -3. **Separate docs**: Detailed guides, tutorials, API reference -4. **Comments**: Implementation details for maintainers - -### Documentation Style - -1. **Clear and concise**: No unnecessary words -2. **Active voice**: "Run the command" not "The command can be run" -3. **Consistent terminology**: Use same terms throughout -4. **Formatted well**: Use headings, lists, code blocks -5. **Accessible**: Assume reader is beginner - -### Documentation Maintenance - -1. **Version everything**: Track what changed when -2. **Deprecate gracefully**: Warn before removing features -3. **Migration guides**: Help users upgrade -4. **Archive old docs**: Keep old versions accessible -5. **Review regularly**: Ensure docs match reality - -## Documentation Checklist - -Before releasing a command: - -- [ ] Description in frontmatter is clear -- [ ] argument-hint documents all arguments -- [ ] Usage examples in comments -- [ ] Common use cases shown -- [ ] Error messages are helpful -- [ ] Requirements documented -- [ ] Related commands listed -- [ ] Changelog maintained -- [ ] Version number updated -- [ ] README created/updated -- [ ] Examples actually work -- [ ] Troubleshooting section complete - -With good documentation, commands become self-service, reducing support burden and improving user experience. diff --git a/dot_claude/skills/Command Development/references/frontmatter-reference.md b/dot_claude/skills/Command Development/references/frontmatter-reference.md deleted file mode 100644 index aa85294..0000000 --- a/dot_claude/skills/Command Development/references/frontmatter-reference.md +++ /dev/null @@ -1,463 +0,0 @@ -# Command Frontmatter Reference - -Complete reference for YAML frontmatter fields in slash commands. - -## Frontmatter Overview - -YAML frontmatter is optional metadata at the start of command files: - -```markdown ---- -description: Brief description -allowed-tools: Read, Write -model: sonnet -argument-hint: [arg1] [arg2] ---- - -Command prompt content here... -``` - -All fields are optional. Commands work without any frontmatter. - -## Field Specifications - -### description - -**Type:** String -**Required:** No -**Default:** First line of command prompt -**Max Length:** ~60 characters recommended for `/help` display - -**Purpose:** Describes what the command does, shown in `/help` output - -**Examples:** -```yaml -description: Review code for security issues -``` -```yaml -description: Deploy to staging environment -``` -```yaml -description: Generate API documentation -``` - -**Best practices:** -- Keep under 60 characters for clean display -- Start with verb (Review, Deploy, Generate) -- Be specific about what command does -- Avoid redundant "command" or "slash command" - -**Good:** -- ✅ "Review PR for code quality and security" -- ✅ "Deploy application to specified environment" -- ✅ "Generate comprehensive API documentation" - -**Bad:** -- ❌ "This command reviews PRs" (unnecessary "This command") -- ❌ "Review" (too vague) -- ❌ "A command that reviews pull requests for code quality, security issues, and best practices" (too long) - -### allowed-tools - -**Type:** String or Array of strings -**Required:** No -**Default:** Inherits from conversation permissions - -**Purpose:** Restrict or specify which tools command can use - -**Formats:** - -**Single tool:** -```yaml -allowed-tools: Read -``` - -**Multiple tools (comma-separated):** -```yaml -allowed-tools: Read, Write, Edit -``` - -**Multiple tools (array):** -```yaml -allowed-tools: - - Read - - Write - - Bash(git:*) -``` - -**Tool Patterns:** - -**Specific tools:** -```yaml -allowed-tools: Read, Grep, Edit -``` - -**Bash with command filter:** -```yaml -allowed-tools: Bash(git:*) # Only git commands -allowed-tools: Bash(npm:*) # Only npm commands -allowed-tools: Bash(docker:*) # Only docker commands -``` - -**All tools (not recommended):** -```yaml -allowed-tools: "*" -``` - -**When to use:** - -1. **Security:** Restrict command to safe operations - ```yaml - allowed-tools: Read, Grep # Read-only command - ``` - -2. **Clarity:** Document required tools - ```yaml - allowed-tools: Bash(git:*), Read - ``` - -3. **Bash execution:** Enable bash command output - ```yaml - allowed-tools: Bash(git status:*), Bash(git diff:*) - ``` - -**Best practices:** -- Be as restrictive as possible -- Use command filters for Bash (e.g., `git:*` not `*`) -- Only specify when different from conversation permissions -- Document why specific tools are needed - -### model - -**Type:** String -**Required:** No -**Default:** Inherits from conversation -**Values:** `sonnet`, `opus`, `haiku` - -**Purpose:** Specify which Claude model executes the command - -**Examples:** -```yaml -model: haiku # Fast, efficient for simple tasks -``` -```yaml -model: sonnet # Balanced performance (default) -``` -```yaml -model: opus # Maximum capability for complex tasks -``` - -**When to use:** - -**Use `haiku` for:** -- Simple, formulaic commands -- Fast execution needed -- Low complexity tasks -- Frequent invocations - -```yaml ---- -description: Format code file -model: haiku ---- -``` - -**Use `sonnet` for:** -- Standard commands (default) -- Balanced speed/quality -- Most common use cases - -```yaml ---- -description: Review code changes -model: sonnet ---- -``` - -**Use `opus` for:** -- Complex analysis -- Architectural decisions -- Deep code understanding -- Critical tasks - -```yaml ---- -description: Analyze system architecture -model: opus ---- -``` - -**Best practices:** -- Omit unless specific need -- Use `haiku` for speed when possible -- Reserve `opus` for genuinely complex tasks -- Test with different models to find right balance - -### argument-hint - -**Type:** String -**Required:** No -**Default:** None - -**Purpose:** Document expected arguments for users and autocomplete - -**Format:** -```yaml -argument-hint: [arg1] [arg2] [optional-arg] -``` - -**Examples:** - -**Single argument:** -```yaml -argument-hint: [pr-number] -``` - -**Multiple required arguments:** -```yaml -argument-hint: [environment] [version] -``` - -**Optional arguments:** -```yaml -argument-hint: [file-path] [options] -``` - -**Descriptive names:** -```yaml -argument-hint: [source-branch] [target-branch] [commit-message] -``` - -**Best practices:** -- Use square brackets `[]` for each argument -- Use descriptive names (not `arg1`, `arg2`) -- Indicate optional vs required in description -- Match order to positional arguments in command -- Keep concise but clear - -**Examples by pattern:** - -**Simple command:** -```yaml ---- -description: Fix issue by number -argument-hint: [issue-number] ---- - -Fix issue #$1... -``` - -**Multi-argument:** -```yaml ---- -description: Deploy to environment -argument-hint: [app-name] [environment] [version] ---- - -Deploy $1 to $2 using version $3... -``` - -**With options:** -```yaml ---- -description: Run tests with options -argument-hint: [test-pattern] [options] ---- - -Run tests matching $1 with options: $2 -``` - -### disable-model-invocation - -**Type:** Boolean -**Required:** No -**Default:** false - -**Purpose:** Prevent SlashCommand tool from programmatically invoking command - -**Examples:** -```yaml -disable-model-invocation: true -``` - -**When to use:** - -1. **Manual-only commands:** Commands requiring user judgment - ```yaml - --- - description: Approve deployment to production - disable-model-invocation: true - --- - ``` - -2. **Destructive operations:** Commands with irreversible effects - ```yaml - --- - description: Delete all test data - disable-model-invocation: true - --- - ``` - -3. **Interactive workflows:** Commands needing user input - ```yaml - --- - description: Walk through setup wizard - disable-model-invocation: true - --- - ``` - -**Default behavior (false):** -- Command available to SlashCommand tool -- Claude can invoke programmatically -- Still available for manual invocation - -**When true:** -- Command only invokable by user typing `/command` -- Not available to SlashCommand tool -- Safer for sensitive operations - -**Best practices:** -- Use sparingly (limits Claude's autonomy) -- Document why in command comments -- Consider if command should exist if always manual - -## Complete Examples - -### Minimal Command - -No frontmatter needed: - -```markdown -Review this code for common issues and suggest improvements. -``` - -### Simple Command - -Just description: - -```markdown ---- -description: Review code for issues ---- - -Review this code for common issues and suggest improvements. -``` - -### Standard Command - -Description and tools: - -```markdown ---- -description: Review Git changes -allowed-tools: Bash(git:*), Read ---- - -Current changes: !`git diff --name-only` - -Review each changed file for: -- Code quality -- Potential bugs -- Best practices -``` - -### Complex Command - -All common fields: - -```markdown ---- -description: Deploy application to environment -argument-hint: [app-name] [environment] [version] -allowed-tools: Bash(kubectl:*), Bash(helm:*), Read -model: sonnet ---- - -Deploy $1 to $2 environment using version $3 - -Pre-deployment checks: -- Verify $2 configuration -- Check cluster status: !`kubectl cluster-info` -- Validate version $3 exists - -Proceed with deployment following deployment runbook. -``` - -### Manual-Only Command - -Restricted invocation: - -```markdown ---- -description: Approve production deployment -argument-hint: [deployment-id] -disable-model-invocation: true -allowed-tools: Bash(gh:*) ---- - - - -Review deployment $1 for production approval: - -Deployment details: !`gh api /deployments/$1` - -Verify: -- All tests passed -- Security scan clean -- Stakeholder approval -- Rollback plan ready - -Type "APPROVED" to confirm deployment. -``` - -## Validation - -### Common Errors - -**Invalid YAML syntax:** -```yaml ---- -description: Missing quote -allowed-tools: Read, Write -model: sonnet ---- # ❌ Missing closing quote above -``` - -**Fix:** Validate YAML syntax - -**Incorrect tool specification:** -```yaml -allowed-tools: Bash # ❌ Missing command filter -``` - -**Fix:** Use `Bash(git:*)` format - -**Invalid model name:** -```yaml -model: gpt4 # ❌ Not a valid Claude model -``` - -**Fix:** Use `sonnet`, `opus`, or `haiku` - -### Validation Checklist - -Before committing command: -- [ ] YAML syntax valid (no errors) -- [ ] Description under 60 characters -- [ ] allowed-tools uses proper format -- [ ] model is valid value if specified -- [ ] argument-hint matches positional arguments -- [ ] disable-model-invocation used appropriately - -## Best Practices Summary - -1. **Start minimal:** Add frontmatter only when needed -2. **Document arguments:** Always use argument-hint with arguments -3. **Restrict tools:** Use most restrictive allowed-tools that works -4. **Choose right model:** Use haiku for speed, opus for complexity -5. **Manual-only sparingly:** Only use disable-model-invocation when necessary -6. **Clear descriptions:** Make commands discoverable in `/help` -7. **Test thoroughly:** Verify frontmatter works as expected diff --git a/dot_claude/skills/Command Development/references/interactive-commands.md b/dot_claude/skills/Command Development/references/interactive-commands.md deleted file mode 100644 index e55bc38..0000000 --- a/dot_claude/skills/Command Development/references/interactive-commands.md +++ /dev/null @@ -1,920 +0,0 @@ -# Interactive Command Patterns - -Comprehensive guide to creating commands that gather user feedback and make decisions through the AskUserQuestion tool. - -## Overview - -Some commands need user input that doesn't work well with simple arguments. For example: -- Choosing between multiple complex options with trade-offs -- Selecting multiple items from a list -- Making decisions that require explanation -- Gathering preferences or configuration interactively - -For these cases, use the **AskUserQuestion tool** within command execution rather than relying on command arguments. - -## When to Use AskUserQuestion - -### Use AskUserQuestion When: - -1. **Multiple choice decisions** with explanations needed -2. **Complex options** that require context to choose -3. **Multi-select scenarios** (choosing multiple items) -4. **Preference gathering** for configuration -5. **Interactive workflows** that adapt based on answers - -### Use Command Arguments When: - -1. **Simple values** (file paths, numbers, names) -2. **Known inputs** user already has -3. **Scriptable workflows** that should be automatable -4. **Fast invocations** where prompting would slow down - -## AskUserQuestion Basics - -### Tool Parameters - -```typescript -{ - questions: [ - { - question: "Which authentication method should we use?", - header: "Auth method", // Short label (max 12 chars) - multiSelect: false, // true for multiple selection - options: [ - { - label: "OAuth 2.0", - description: "Industry standard, supports multiple providers" - }, - { - label: "JWT", - description: "Stateless, good for APIs" - }, - { - label: "Session", - description: "Traditional, server-side state" - } - ] - } - ] -} -``` - -**Key points:** -- Users can always choose "Other" to provide custom input (automatic) -- `multiSelect: true` allows selecting multiple options -- Options should be 2-4 choices (not more) -- Can ask 1-4 questions per tool call - -## Command Pattern for User Interaction - -### Basic Interactive Command - -```markdown ---- -description: Interactive setup command -allowed-tools: AskUserQuestion, Write ---- - -# Interactive Plugin Setup - -This command will guide you through configuring the plugin with a series of questions. - -## Step 1: Gather Configuration - -Use the AskUserQuestion tool to ask: - -**Question 1 - Deployment target:** -- header: "Deploy to" -- question: "Which deployment platform will you use?" -- options: - - AWS (Amazon Web Services with ECS/EKS) - - GCP (Google Cloud with GKE) - - Azure (Microsoft Azure with AKS) - - Local (Docker on local machine) - -**Question 2 - Environment strategy:** -- header: "Environments" -- question: "How many environments do you need?" -- options: - - Single (Just production) - - Standard (Dev, Staging, Production) - - Complete (Dev, QA, Staging, Production) - -**Question 3 - Features to enable:** -- header: "Features" -- question: "Which features do you want to enable?" -- multiSelect: true -- options: - - Auto-scaling (Automatic resource scaling) - - Monitoring (Health checks and metrics) - - CI/CD (Automated deployment pipeline) - - Backups (Automated database backups) - -## Step 2: Process Answers - -Based on the answers received from AskUserQuestion: - -1. Parse the deployment target choice -2. Set up environment-specific configuration -3. Enable selected features -4. Generate configuration files - -## Step 3: Generate Configuration - -Create `.claude/plugin-name.local.md` with: - -\`\`\`yaml ---- -deployment_target: [answer from Q1] -environments: [answer from Q2] -features: - auto_scaling: [true if selected in Q3] - monitoring: [true if selected in Q3] - ci_cd: [true if selected in Q3] - backups: [true if selected in Q3] ---- - -# Plugin Configuration - -Generated: [timestamp] -Target: [deployment_target] -Environments: [environments] -\`\`\` - -## Step 4: Confirm and Next Steps - -Confirm configuration created and guide user on next steps. -``` - -### Multi-Stage Interactive Workflow - -```markdown ---- -description: Multi-stage interactive workflow -allowed-tools: AskUserQuestion, Read, Write, Bash ---- - -# Multi-Stage Deployment Setup - -This command walks through deployment setup in stages, adapting based on your answers. - -## Stage 1: Basic Configuration - -Use AskUserQuestion to ask about deployment basics. - -Based on answers, determine which additional questions to ask. - -## Stage 2: Advanced Options (Conditional) - -If user selected "Advanced" deployment in Stage 1: - -Use AskUserQuestion to ask about: -- Load balancing strategy -- Caching configuration -- Security hardening options - -If user selected "Simple" deployment: -- Skip advanced questions -- Use sensible defaults - -## Stage 3: Confirmation - -Show summary of all selections. - -Use AskUserQuestion for final confirmation: -- header: "Confirm" -- question: "Does this configuration look correct?" -- options: - - Yes (Proceed with setup) - - No (Start over) - - Modify (Let me adjust specific settings) - -If "Modify", ask which specific setting to change. - -## Stage 4: Execute Setup - -Based on confirmed configuration, execute setup steps. -``` - -## Interactive Question Design - -### Question Structure - -**Good questions:** -```markdown -Question: "Which database should we use for this project?" -Header: "Database" -Options: - - PostgreSQL (Relational, ACID compliant, best for complex queries) - - MongoDB (Document store, flexible schema, best for rapid iteration) - - Redis (In-memory, fast, best for caching and sessions) -``` - -**Poor questions:** -```markdown -Question: "Database?" // Too vague -Header: "DB" // Unclear abbreviation -Options: - - Option 1 // Not descriptive - - Option 2 -``` - -### Option Design Best Practices - -**Clear labels:** -- Use 1-5 words -- Specific and descriptive -- No jargon without context - -**Helpful descriptions:** -- Explain what the option means -- Mention key benefits or trade-offs -- Help user make informed decision -- Keep to 1-2 sentences - -**Appropriate number:** -- 2-4 options per question -- Don't overwhelm with too many choices -- Group related options -- "Other" automatically provided - -### Multi-Select Questions - -**When to use multiSelect:** - -```markdown -Use AskUserQuestion for enabling features: - -Question: "Which features do you want to enable?" -Header: "Features" -multiSelect: true // Allow selecting multiple -Options: - - Logging (Detailed operation logs) - - Metrics (Performance monitoring) - - Alerts (Error notifications) - - Backups (Automatic backups) -``` - -User can select any combination: none, some, or all. - -**When NOT to use multiSelect:** - -```markdown -Question: "Which authentication method?" -multiSelect: false // Only one auth method makes sense -``` - -Mutually exclusive choices should not use multiSelect. - -## Command Patterns with AskUserQuestion - -### Pattern 1: Simple Yes/No Decision - -```markdown ---- -description: Command with confirmation -allowed-tools: AskUserQuestion, Bash ---- - -# Destructive Operation - -This operation will delete all cached data. - -Use AskUserQuestion to confirm: - -Question: "This will delete all cached data. Are you sure?" -Header: "Confirm" -Options: - - Yes (Proceed with deletion) - - No (Cancel operation) - -If user selects "Yes": - Execute deletion - Report completion - -If user selects "No": - Cancel operation - Exit without changes -``` - -### Pattern 2: Multiple Configuration Questions - -```markdown ---- -description: Multi-question configuration -allowed-tools: AskUserQuestion, Write ---- - -# Project Configuration Setup - -Gather configuration through multiple questions. - -Use AskUserQuestion with multiple questions in one call: - -**Question 1:** -- question: "Which programming language?" -- header: "Language" -- options: Python, TypeScript, Go, Rust - -**Question 2:** -- question: "Which test framework?" -- header: "Testing" -- options: Jest, PyTest, Go Test, Cargo Test - (Adapt based on language from Q1) - -**Question 3:** -- question: "Which CI/CD platform?" -- header: "CI/CD" -- options: GitHub Actions, GitLab CI, CircleCI - -**Question 4:** -- question: "Which features do you need?" -- header: "Features" -- multiSelect: true -- options: Linting, Type checking, Code coverage, Security scanning - -Process all answers together to generate cohesive configuration. -``` - -### Pattern 3: Conditional Question Flow - -```markdown ---- -description: Conditional interactive workflow -allowed-tools: AskUserQuestion, Read, Write ---- - -# Adaptive Configuration - -## Question 1: Deployment Complexity - -Use AskUserQuestion: - -Question: "How complex is your deployment?" -Header: "Complexity" -Options: - - Simple (Single server, straightforward) - - Standard (Multiple servers, load balancing) - - Complex (Microservices, orchestration) - -## Conditional Questions Based on Answer - -If answer is "Simple": - - No additional questions - - Use minimal configuration - -If answer is "Standard": - - Ask about load balancing strategy - - Ask about scaling policy - -If answer is "Complex": - - Ask about orchestration platform (Kubernetes, Docker Swarm) - - Ask about service mesh (Istio, Linkerd, None) - - Ask about monitoring (Prometheus, Datadog, CloudWatch) - - Ask about logging aggregation - -## Process Conditional Answers - -Generate configuration appropriate for selected complexity level. -``` - -### Pattern 4: Iterative Collection - -```markdown ---- -description: Collect multiple items iteratively -allowed-tools: AskUserQuestion, Write ---- - -# Collect Team Members - -We'll collect team member information for the project. - -## Question: How many team members? - -Use AskUserQuestion: - -Question: "How many team members should we set up?" -Header: "Team size" -Options: - - 2 people - - 3 people - - 4 people - - 6 people - -## Iterate Through Team Members - -For each team member (1 to N based on answer): - -Use AskUserQuestion for member details: - -Question: "What role for team member [number]?" -Header: "Role" -Options: - - Frontend Developer - - Backend Developer - - DevOps Engineer - - QA Engineer - - Designer - -Store each member's information. - -## Generate Team Configuration - -After collecting all N members, create team configuration file with all members and their roles. -``` - -### Pattern 5: Dependency Selection - -```markdown ---- -description: Select dependencies with multi-select -allowed-tools: AskUserQuestion ---- - -# Configure Project Dependencies - -## Question: Required Libraries - -Use AskUserQuestion with multiSelect: - -Question: "Which libraries does your project need?" -Header: "Dependencies" -multiSelect: true -Options: - - React (UI framework) - - Express (Web server) - - TypeORM (Database ORM) - - Jest (Testing framework) - - Axios (HTTP client) - -User can select any combination. - -## Process Selections - -For each selected library: -- Add to package.json dependencies -- Generate sample configuration -- Create usage examples -- Update documentation -``` - -## Best Practices for Interactive Commands - -### Question Design - -1. **Clear and specific**: Question should be unambiguous -2. **Concise header**: Max 12 characters for clean display -3. **Helpful options**: Labels are clear, descriptions explain trade-offs -4. **Appropriate count**: 2-4 options per question, 1-4 questions per call -5. **Logical order**: Questions flow naturally - -### Error Handling - -```markdown -# Handle AskUserQuestion Responses - -After calling AskUserQuestion, verify answers received: - -If answers are empty or invalid: - Something went wrong gathering responses. - - Please try again or provide configuration manually: - [Show alternative approach] - - Exit. - -If answers look correct: - Process as expected -``` - -### Progressive Disclosure - -```markdown -# Start Simple, Get Detailed as Needed - -## Question 1: Setup Type - -Use AskUserQuestion: - -Question: "How would you like to set up?" -Header: "Setup type" -Options: - - Quick (Use recommended defaults) - - Custom (Configure all options) - - Guided (Step-by-step with explanations) - -If "Quick": - Apply defaults, minimal questions - -If "Custom": - Ask all available configuration questions - -If "Guided": - Ask questions with extra explanation - Provide recommendations along the way -``` - -### Multi-Select Guidelines - -**Good multi-select use:** -```markdown -Question: "Which features do you want to enable?" -multiSelect: true -Options: - - Logging - - Metrics - - Alerts - - Backups - -Reason: User might want any combination -``` - -**Bad multi-select use:** -```markdown -Question: "Which database engine?" -multiSelect: true // ❌ Should be single-select - -Reason: Can only use one database engine -``` - -## Advanced Patterns - -### Validation Loop - -```markdown ---- -description: Interactive with validation -allowed-tools: AskUserQuestion, Bash ---- - -# Setup with Validation - -## Gather Configuration - -Use AskUserQuestion to collect settings. - -## Validate Configuration - -Check if configuration is valid: -- Required dependencies available? -- Settings compatible with each other? -- No conflicts detected? - -If validation fails: - Show validation errors - - Use AskUserQuestion to ask: - - Question: "Configuration has issues. What would you like to do?" - Header: "Next step" - Options: - - Fix (Adjust settings to resolve issues) - - Override (Proceed despite warnings) - - Cancel (Abort setup) - - Based on answer, retry or proceed or exit. -``` - -### Build Configuration Incrementally - -```markdown ---- -description: Incremental configuration builder -allowed-tools: AskUserQuestion, Write, Read ---- - -# Incremental Setup - -## Phase 1: Core Settings - -Use AskUserQuestion for core settings. - -Save to `.claude/config-partial.yml` - -## Phase 2: Review Core Settings - -Show user the core settings: - -Based on these core settings, you need to configure: -- [Setting A] (because you chose [X]) -- [Setting B] (because you chose [Y]) - -Ready to continue? - -## Phase 3: Detailed Settings - -Use AskUserQuestion for settings based on Phase 1 answers. - -Merge with core settings. - -## Phase 4: Final Review - -Present complete configuration. - -Use AskUserQuestion for confirmation: - -Question: "Is this configuration correct?" -Options: - - Yes (Save and apply) - - No (Start over) - - Modify (Edit specific settings) -``` - -### Dynamic Options Based on Context - -```markdown ---- -description: Context-aware questions -allowed-tools: AskUserQuestion, Bash, Read ---- - -# Context-Aware Setup - -## Detect Current State - -Check existing configuration: -- Current language: !`detect-language.sh` -- Existing frameworks: !`detect-frameworks.sh` -- Available tools: !`check-tools.sh` - -## Ask Context-Appropriate Questions - -Based on detected language, ask relevant questions. - -If language is TypeScript: - - Use AskUserQuestion: - - Question: "Which TypeScript features should we enable?" - Options: - - Strict Mode (Maximum type safety) - - Decorators (Experimental decorator support) - - Path Mapping (Module path aliases) - -If language is Python: - - Use AskUserQuestion: - - Question: "Which Python tools should we configure?" - Options: - - Type Hints (mypy for type checking) - - Black (Code formatting) - - Pylint (Linting and style) - -Questions adapt to project context. -``` - -## Real-World Example: Multi-Agent Swarm Launch - -**From multi-agent-swarm plugin:** - -```markdown ---- -description: Launch multi-agent swarm -allowed-tools: AskUserQuestion, Read, Write, Bash ---- - -# Launch Multi-Agent Swarm - -## Interactive Mode (No Task List Provided) - -If user didn't provide task list file, help create one interactively. - -### Question 1: Agent Count - -Use AskUserQuestion: - -Question: "How many agents should we launch?" -Header: "Agent count" -Options: - - 2 agents (Best for simple projects) - - 3 agents (Good for medium projects) - - 4 agents (Standard team size) - - 6 agents (Large projects) - - 8 agents (Complex multi-component projects) - -### Question 2: Task Definition Approach - -Use AskUserQuestion: - -Question: "How would you like to define tasks?" -Header: "Task setup" -Options: - - File (I have a task list file ready) - - Guided (Help me create tasks interactively) - - Custom (Other approach) - -If "File": - Ask for file path - Validate file exists and has correct format - -If "Guided": - Enter iterative task creation mode (see below) - -### Question 3: Coordination Mode - -Use AskUserQuestion: - -Question: "How should agents coordinate?" -Header: "Coordination" -Options: - - Team Leader (One agent coordinates others) - - Collaborative (Agents coordinate as peers) - - Autonomous (Independent work, minimal coordination) - -### Iterative Task Creation (If "Guided" Selected) - -For each agent (1 to N from Question 1): - -**Question A: Agent Name** -Question: "What should we call agent [number]?" -Header: "Agent name" -Options: - - auth-agent - - api-agent - - ui-agent - - db-agent - (Provide relevant suggestions based on common patterns) - -**Question B: Task Type** -Question: "What task for [agent-name]?" -Header: "Task type" -Options: - - Authentication (User auth, JWT, OAuth) - - API Endpoints (REST/GraphQL APIs) - - UI Components (Frontend components) - - Database (Schema, migrations, queries) - - Testing (Test suites and coverage) - - Documentation (Docs, README, guides) - -**Question C: Dependencies** -Question: "What does [agent-name] depend on?" -Header: "Dependencies" -multiSelect: true -Options: - - [List of previously defined agents] - - No dependencies - -**Question D: Base Branch** -Question: "Which base branch for PR?" -Header: "PR base" -Options: - - main - - staging - - develop - -Store all task information for each agent. - -### Generate Task List File - -After collecting all agent task details: - -1. Ask for project name -2. Generate task list in proper format -3. Save to `.daisy/swarm/tasks.md` -4. Show user the file path -5. Proceed with launch using generated task list -``` - -## Best Practices - -### Question Writing - -1. **Be specific**: "Which database?" not "Choose option?" -2. **Explain trade-offs**: Describe pros/cons in option descriptions -3. **Provide context**: Question text should stand alone -4. **Guide decisions**: Help user make informed choice -5. **Keep concise**: Header max 12 chars, descriptions 1-2 sentences - -### Option Design - -1. **Meaningful labels**: Specific, clear names -2. **Informative descriptions**: Explain what each option does -3. **Show trade-offs**: Help user understand implications -4. **Consistent detail**: All options equally explained -5. **2-4 options**: Not too few, not too many - -### Flow Design - -1. **Logical order**: Questions flow naturally -2. **Build on previous**: Later questions use earlier answers -3. **Minimize questions**: Ask only what's needed -4. **Group related**: Ask related questions together -5. **Show progress**: Indicate where in flow - -### User Experience - -1. **Set expectations**: Tell user what to expect -2. **Explain why**: Help user understand purpose -3. **Provide defaults**: Suggest recommended options -4. **Allow escape**: Let user cancel or restart -5. **Confirm actions**: Summarize before executing - -## Common Patterns - -### Pattern: Feature Selection - -```markdown -Use AskUserQuestion: - -Question: "Which features do you need?" -Header: "Features" -multiSelect: true -Options: - - Authentication - - Authorization - - Rate Limiting - - Caching -``` - -### Pattern: Environment Configuration - -```markdown -Use AskUserQuestion: - -Question: "Which environment is this?" -Header: "Environment" -Options: - - Development (Local development) - - Staging (Pre-production testing) - - Production (Live environment) -``` - -### Pattern: Priority Selection - -```markdown -Use AskUserQuestion: - -Question: "What's the priority for this task?" -Header: "Priority" -Options: - - Critical (Must be done immediately) - - High (Important, do soon) - - Medium (Standard priority) - - Low (Nice to have) -``` - -### Pattern: Scope Selection - -```markdown -Use AskUserQuestion: - -Question: "What scope should we analyze?" -Header: "Scope" -Options: - - Current file (Just this file) - - Current directory (All files in directory) - - Entire project (Full codebase scan) -``` - -## Combining Arguments and Questions - -### Use Both Appropriately - -**Arguments for known values:** -```markdown ---- -argument-hint: [project-name] -allowed-tools: AskUserQuestion, Write ---- - -Setup for project: $1 - -Now gather additional configuration... - -Use AskUserQuestion for options that require explanation. -``` - -**Questions for complex choices:** -```markdown -Project name from argument: $1 - -Now use AskUserQuestion to choose: -- Architecture pattern -- Technology stack -- Deployment strategy - -These require explanation, so questions work better than arguments. -``` - -## Troubleshooting - -**Questions not appearing:** -- Verify AskUserQuestion in allowed-tools -- Check question format is correct -- Ensure options array has 2-4 items - -**User can't make selection:** -- Check option labels are clear -- Verify descriptions are helpful -- Consider if too many options -- Ensure multiSelect setting is correct - -**Flow feels confusing:** -- Reduce number of questions -- Group related questions -- Add explanation between stages -- Show progress through workflow - -With AskUserQuestion, commands become interactive wizards that guide users through complex decisions while maintaining the clarity that simple arguments provide for straightforward inputs. diff --git a/dot_claude/skills/Command Development/references/marketplace-considerations.md b/dot_claude/skills/Command Development/references/marketplace-considerations.md deleted file mode 100644 index 03e706c..0000000 --- a/dot_claude/skills/Command Development/references/marketplace-considerations.md +++ /dev/null @@ -1,904 +0,0 @@ -# Marketplace Considerations for Commands - -Guidelines for creating commands designed for distribution and marketplace success. - -## Overview - -Commands distributed through marketplaces need additional consideration beyond personal use commands. They must work across environments, handle diverse use cases, and provide excellent user experience for unknown users. - -## Design for Distribution - -### Universal Compatibility - -**Cross-platform considerations:** - -```markdown ---- -description: Cross-platform command -allowed-tools: Bash(*) ---- - -# Platform-Aware Command - -Detecting platform... - -case "$(uname)" in - Darwin*) PLATFORM="macOS" ;; - Linux*) PLATFORM="Linux" ;; - MINGW*|MSYS*|CYGWIN*) PLATFORM="Windows" ;; - *) PLATFORM="Unknown" ;; -esac - -Platform: $PLATFORM - - -if [ "$PLATFORM" = "Windows" ]; then - # Windows-specific handling - PATH_SEP="\\" - NULL_DEVICE="NUL" -else - # Unix-like handling - PATH_SEP="/" - NULL_DEVICE="/dev/null" -fi - -[Platform-appropriate implementation...] -``` - -**Avoid platform-specific commands:** - -```markdown - -!`pbcopy < file.txt` - - -if command -v pbcopy > /dev/null; then - pbcopy < file.txt -elif command -v xclip > /dev/null; then - xclip -selection clipboard < file.txt -elif command -v clip.exe > /dev/null; then - cat file.txt | clip.exe -else - echo "Clipboard not available on this platform" -fi -``` - -### Minimal Dependencies - -**Check for required tools:** - -```markdown ---- -description: Dependency-aware command -allowed-tools: Bash(*) ---- - -# Check Dependencies - -Required tools: -- git -- jq -- node - -Checking availability... - -MISSING_DEPS="" - -for tool in git jq node; do - if ! command -v $tool > /dev/null; then - MISSING_DEPS="$MISSING_DEPS $tool" - fi -done - -if [ -n "$MISSING_DEPS" ]; then - ❌ ERROR: Missing required dependencies:$MISSING_DEPS - - INSTALLATION: - - git: https://git-scm.com/downloads - - jq: https://stedolan.github.io/jq/download/ - - node: https://nodejs.org/ - - Install missing tools and try again. - - Exit. -fi - -✓ All dependencies available - -[Continue with command...] -``` - -**Document optional dependencies:** - -```markdown - -``` - -### Graceful Degradation - -**Handle missing features:** - -```markdown ---- -description: Feature-aware command ---- - -# Feature Detection - -Detecting available features... - -FEATURES="" - -if command -v gh > /dev/null; then - FEATURES="$FEATURES github" -fi - -if command -v docker > /dev/null; then - FEATURES="$FEATURES docker" -fi - -Available features: $FEATURES - -if echo "$FEATURES" | grep -q "github"; then - # Full functionality with GitHub integration - echo "✓ GitHub integration available" -else - # Reduced functionality without GitHub - echo "⚠ Limited functionality: GitHub CLI not installed" - echo " Install 'gh' for full features" -fi - -[Adapt behavior based on available features...] -``` - -## User Experience for Unknown Users - -### Clear Onboarding - -**First-run experience:** - -```markdown ---- -description: Command with onboarding -allowed-tools: Read, Write ---- - -# First Run Check - -if [ ! -f ".claude/command-initialized" ]; then - **Welcome to Command Name!** - - This appears to be your first time using this command. - - WHAT THIS COMMAND DOES: - [Brief explanation of purpose and benefits] - - QUICK START: - 1. Basic usage: /command [arg] - 2. For help: /command help - 3. Examples: /command examples - - SETUP: - No additional setup required. You're ready to go! - - ✓ Initialization complete - - [Create initialization marker] - - Ready to proceed with your request... -fi - -[Normal command execution...] -``` - -**Progressive feature discovery:** - -```markdown ---- -description: Command with tips ---- - -# Command Execution - -[Main functionality...] - ---- - -💡 TIP: Did you know? - -You can speed up this command with the --fast flag: - /command --fast [args] - -For more tips: /command tips -``` - -### Comprehensive Error Handling - -**Anticipate user mistakes:** - -```markdown ---- -description: Forgiving command ---- - -# User Input Handling - -Argument: "$1" - - -if [ "$1" = "hlep" ] || [ "$1" = "hepl" ]; then - Did you mean: help? - - Showing help instead... - [Display help] - - Exit. -fi - - -if [ "$1" != "valid-option1" ] && [ "$1" != "valid-option2" ]; then - ❌ Unknown option: $1 - - Did you mean: - - valid-option1 (most similar) - - valid-option2 - - For all options: /command help - - Exit. -fi - -[Command continues...] -``` - -**Helpful diagnostics:** - -```markdown ---- -description: Diagnostic command ---- - -# Operation Failed - -The operation could not complete. - -**Diagnostic Information:** - -Environment: -- Platform: $(uname) -- Shell: $SHELL -- Working directory: $(pwd) -- Command: /command $@ - -Checking common issues: -- Git repository: $(git rev-parse --git-dir 2>&1) -- Write permissions: $(test -w . && echo "OK" || echo "DENIED") -- Required files: $(test -f config.yml && echo "Found" || echo "Missing") - -This information helps debug the issue. - -For support, include the above diagnostics. -``` - -## Distribution Best Practices - -### Namespace Awareness - -**Avoid name collisions:** - -```markdown ---- -description: Namespaced command ---- - - - -# Plugin Name Command - -[Implementation...] -``` - -**Document naming rationale:** - -```markdown - -``` - -### Configurability - -**User preferences:** - -```markdown ---- -description: Configurable command -allowed-tools: Read ---- - -# Load User Configuration - -Default configuration: -- verbose: false -- color: true -- max_results: 10 - -Checking for user config: .claude/plugin-name.local.md - -if [ -f ".claude/plugin-name.local.md" ]; then - # Parse YAML frontmatter for settings - VERBOSE=$(grep "^verbose:" .claude/plugin-name.local.md | cut -d: -f2 | tr -d ' ') - COLOR=$(grep "^color:" .claude/plugin-name.local.md | cut -d: -f2 | tr -d ' ') - MAX_RESULTS=$(grep "^max_results:" .claude/plugin-name.local.md | cut -d: -f2 | tr -d ' ') - - echo "✓ Using user configuration" -else - echo "Using default configuration" - echo "Create .claude/plugin-name.local.md to customize" -fi - -[Use configuration in command...] -``` - -**Sensible defaults:** - -```markdown ---- -description: Command with smart defaults ---- - -# Smart Defaults - -Configuration: -- Format: ${FORMAT:-json} # Defaults to json -- Output: ${OUTPUT:-stdout} # Defaults to stdout -- Verbose: ${VERBOSE:-false} # Defaults to false - -These defaults work for 80% of use cases. - -Override with arguments: - /command --format yaml --output file.txt --verbose - -Or set in .claude/plugin-name.local.md: -\`\`\`yaml ---- -format: yaml -output: custom.txt -verbose: true ---- -\`\`\` -``` - -### Version Compatibility - -**Version checking:** - -```markdown ---- -description: Version-aware command ---- - - - -# Version Check - -Command version: 2.1.0 -Plugin version: [detect from plugin.json] - -if [ "$PLUGIN_VERSION" < "2.0.0" ]; then - ❌ ERROR: Incompatible plugin version - - This command requires plugin version >= 2.0.0 - Current version: $PLUGIN_VERSION - - Update plugin: - /plugin update plugin-name - - Exit. -fi - -✓ Version compatible - -[Command continues...] -``` - -**Deprecation warnings:** - -```markdown ---- -description: Command with deprecation warnings ---- - -# Deprecation Check - -if [ "$1" = "--old-flag" ]; then - ⚠️ DEPRECATION WARNING - - The --old-flag option is deprecated as of v2.0.0 - It will be removed in v3.0.0 (est. June 2025) - - Use instead: --new-flag - - Example: - Old: /command --old-flag value - New: /command --new-flag value - - See migration guide: /command migrate - - Continuing with deprecated behavior for now... -fi - -[Handle both old and new flags during deprecation period...] -``` - -## Marketplace Presentation - -### Command Discovery - -**Descriptive naming:** - -```markdown ---- -description: Review pull request with security and quality checks ---- - - -``` - -```markdown ---- -description: Do the thing ---- - - -``` - -**Searchable keywords:** - -```markdown - -``` - -### Showcase Examples - -**Compelling demonstrations:** - -```markdown ---- -description: Advanced code analysis command ---- - -# Code Analysis Command - -This command performs deep code analysis with actionable insights. - -## Demo: Quick Security Audit - -Try it now: -\`\`\` -/analyze-code src/ --security -\`\`\` - -**What you'll get:** -- Security vulnerability detection -- Code quality metrics -- Performance bottleneck identification -- Actionable recommendations - -**Sample output:** -\`\`\` -Security Analysis Results -========================= - -🔴 Critical (2): - - SQL injection risk in users.js:45 - - XSS vulnerability in display.js:23 - -🟡 Warnings (5): - - Unvalidated input in api.js:67 - ... - -Recommendations: -1. Fix critical issues immediately -2. Review warnings before next release -3. Run /analyze-code --fix for auto-fixes -\`\`\` - ---- - -Ready to analyze your code... - -[Command implementation...] -``` - -### User Reviews and Feedback - -**Feedback mechanism:** - -```markdown ---- -description: Command with feedback ---- - -# Command Complete - -[Command results...] - ---- - -**How was your experience?** - -This helps improve the command for everyone. - -Rate this command: -- 👍 Helpful -- 👎 Not helpful -- 🐛 Found a bug -- 💡 Have a suggestion - -Reply with an emoji or: -- /command feedback - -Your feedback matters! -``` - -**Usage analytics preparation:** - -```markdown - -``` - -## Quality Standards - -### Professional Polish - -**Consistent branding:** - -```markdown ---- -description: Branded command ---- - -# ✨ Command Name - -Part of the [Plugin Name] suite - -[Command functionality...] - ---- - -**Need Help?** -- Documentation: https://docs.example.com -- Support: support@example.com -- Community: https://community.example.com - -Powered by Plugin Name v2.1.0 -``` - -**Attention to detail:** - -```markdown - - -✓ Use proper emoji/symbols consistently -✓ Align output columns neatly -✓ Format numbers with thousands separators -✓ Use color/formatting appropriately -✓ Provide progress indicators -✓ Show estimated time remaining -✓ Confirm successful operations -``` - -### Reliability - -**Idempotency:** - -```markdown ---- -description: Idempotent command ---- - -# Safe Repeated Execution - -Checking if operation already completed... - -if [ -f ".claude/operation-completed.flag" ]; then - ℹ️ Operation already completed - - Completed at: $(cat .claude/operation-completed.flag) - - To re-run: - 1. Remove flag: rm .claude/operation-completed.flag - 2. Run command again - - Otherwise, no action needed. - - Exit. -fi - -Performing operation... - -[Safe, repeatable operation...] - -Marking complete... -echo "$(date)" > .claude/operation-completed.flag -``` - -**Atomic operations:** - -```markdown ---- -description: Atomic command ---- - -# Atomic Operation - -This operation is atomic - either fully succeeds or fully fails. - -Creating temporary workspace... -TEMP_DIR=$(mktemp -d) - -Performing changes in isolated environment... -[Make changes in $TEMP_DIR] - -if [ $? -eq 0 ]; then - ✓ Changes validated - - Applying changes atomically... - mv $TEMP_DIR/* ./target/ - - ✓ Operation complete -else - ❌ Changes failed validation - - Rolling back... - rm -rf $TEMP_DIR - - No changes applied. Safe to retry. -fi -``` - -## Testing for Distribution - -### Pre-Release Checklist - -```markdown - -``` - -### Beta Testing - -**Beta release approach:** - -```markdown ---- -description: Beta command (v0.9.0) ---- - -# 🧪 Beta Command - -**This is a beta release** - -Features may change based on feedback. - -BETA STATUS: -- Version: 0.9.0 -- Stability: Experimental -- Support: Limited -- Feedback: Encouraged - -Known limitations: -- Performance not optimized -- Some edge cases not handled -- Documentation incomplete - -Help improve this command: -- Report issues: /command report-issue -- Suggest features: /command suggest -- Join beta testers: /command join-beta - ---- - -[Command implementation...] - ---- - -**Thank you for beta testing!** - -Your feedback helps make this command better. -``` - -## Maintenance and Updates - -### Update Strategy - -**Versioned commands:** - -```markdown - -``` - -**Update notifications:** - -```markdown ---- -description: Update-aware command ---- - -# Check for Updates - -Current version: 2.1.0 -Latest version: [check if available] - -if [ "$CURRENT_VERSION" != "$LATEST_VERSION" ]; then - 📢 UPDATE AVAILABLE - - New version: $LATEST_VERSION - Current: $CURRENT_VERSION - - What's new: - - Feature improvements - - Bug fixes - - Performance enhancements - - Update with: - /plugin update plugin-name - - Release notes: https://releases.example.com/v$LATEST_VERSION -fi - -[Command continues...] -``` - -## Best Practices Summary - -### Distribution Design - -1. **Universal**: Works across platforms and environments -2. **Self-contained**: Minimal dependencies, clear requirements -3. **Graceful**: Degrades gracefully when features unavailable -4. **Forgiving**: Anticipates and handles user mistakes -5. **Helpful**: Clear errors, good defaults, excellent docs - -### Marketplace Success - -1. **Discoverable**: Clear name, good description, searchable keywords -2. **Professional**: Polished presentation, consistent branding -3. **Reliable**: Tested thoroughly, handles edge cases -4. **Maintainable**: Versioned, updated regularly, supported -5. **User-focused**: Great UX, responsive to feedback - -### Quality Standards - -1. **Complete**: Fully documented, all features working -2. **Tested**: Works in real environments, edge cases handled -3. **Secure**: No vulnerabilities, safe operations -4. **Performant**: Reasonable speed, resource-efficient -5. **Ethical**: Privacy-respecting, user consent - -With these considerations, commands become marketplace-ready and delight users across diverse environments and use cases. diff --git a/dot_claude/skills/Command Development/references/plugin-features-reference.md b/dot_claude/skills/Command Development/references/plugin-features-reference.md deleted file mode 100644 index c89e906..0000000 --- a/dot_claude/skills/Command Development/references/plugin-features-reference.md +++ /dev/null @@ -1,609 +0,0 @@ -# Plugin-Specific Command Features Reference - -This reference covers features and patterns specific to commands bundled in Claude Code plugins. - -## Table of Contents - -- [Plugin Command Discovery](#plugin-command-discovery) -- [CLAUDE_PLUGIN_ROOT Environment Variable](#claude_plugin_root-environment-variable) -- [Plugin Command Patterns](#plugin-command-patterns) -- [Integration with Plugin Components](#integration-with-plugin-components) -- [Validation Patterns](#validation-patterns) - -## Plugin Command Discovery - -### Auto-Discovery - -Claude Code automatically discovers commands in plugins using the following locations: - -``` -plugin-name/ -├── commands/ # Auto-discovered commands -│ ├── foo.md # /foo (plugin:plugin-name) -│ └── bar.md # /bar (plugin:plugin-name) -└── plugin.json # Plugin manifest -``` - -**Key points:** -- Commands are discovered at plugin load time -- No manual registration required -- Commands appear in `/help` with "(plugin:plugin-name)" label -- Subdirectories create namespaces - -### Namespaced Plugin Commands - -Organize commands in subdirectories for logical grouping: - -``` -plugin-name/ -└── commands/ - ├── review/ - │ ├── security.md # /security (plugin:plugin-name:review) - │ └── style.md # /style (plugin:plugin-name:review) - └── deploy/ - ├── staging.md # /staging (plugin:plugin-name:deploy) - └── prod.md # /prod (plugin:plugin-name:deploy) -``` - -**Namespace behavior:** -- Subdirectory name becomes namespace -- Shown as "(plugin:plugin-name:namespace)" in `/help` -- Helps organize related commands -- Use when plugin has 5+ commands - -### Command Naming Conventions - -**Plugin command names should:** -1. Be descriptive and action-oriented -2. Avoid conflicts with common command names -3. Use hyphens for multi-word names -4. Consider prefixing with plugin name for uniqueness - -**Examples:** -``` -Good: -- /mylyn-sync (plugin-specific prefix) -- /analyze-performance (descriptive action) -- /docker-compose-up (clear purpose) - -Avoid: -- /test (conflicts with common name) -- /run (too generic) -- /do-stuff (not descriptive) -``` - -## CLAUDE_PLUGIN_ROOT Environment Variable - -### Purpose - -`${CLAUDE_PLUGIN_ROOT}` is a special environment variable available in plugin commands that resolves to the absolute path of the plugin directory. - -**Why it matters:** -- Enables portable paths within plugin -- Allows referencing plugin files and scripts -- Works across different installations -- Essential for multi-file plugin operations - -### Basic Usage - -Reference files within your plugin: - -```markdown ---- -description: Analyze using plugin script -allowed-tools: Bash(node:*), Read ---- - -Run analysis: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js` - -Read template: @${CLAUDE_PLUGIN_ROOT}/templates/report.md -``` - -**Expands to:** -``` -Run analysis: !`node /path/to/plugins/plugin-name/scripts/analyze.js` - -Read template: @/path/to/plugins/plugin-name/templates/report.md -``` - -### Common Patterns - -#### 1. Executing Plugin Scripts - -```markdown ---- -description: Run custom linter from plugin -allowed-tools: Bash(node:*) ---- - -Lint results: !`node ${CLAUDE_PLUGIN_ROOT}/bin/lint.js $1` - -Review the linting output and suggest fixes. -``` - -#### 2. Loading Configuration Files - -```markdown ---- -description: Deploy using plugin configuration -allowed-tools: Read, Bash(*) ---- - -Configuration: @${CLAUDE_PLUGIN_ROOT}/config/deploy-config.json - -Deploy application using the configuration above for $1 environment. -``` - -#### 3. Accessing Plugin Resources - -```markdown ---- -description: Generate report from template ---- - -Use this template: @${CLAUDE_PLUGIN_ROOT}/templates/api-report.md - -Generate a report for @$1 following the template format. -``` - -#### 4. Multi-Step Plugin Workflows - -```markdown ---- -description: Complete plugin workflow -allowed-tools: Bash(*), Read ---- - -Step 1 - Prepare: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/prepare.sh $1` -Step 2 - Config: @${CLAUDE_PLUGIN_ROOT}/config/$1.json -Step 3 - Execute: !`${CLAUDE_PLUGIN_ROOT}/bin/execute $1` - -Review results and report status. -``` - -### Best Practices - -1. **Always use for plugin-internal paths:** - ```markdown - # Good - @${CLAUDE_PLUGIN_ROOT}/templates/foo.md - - # Bad - @./templates/foo.md # Relative to current directory, not plugin - ``` - -2. **Validate file existence:** - ```markdown - --- - description: Use plugin config if exists - allowed-tools: Bash(test:*), Read - --- - - !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "exists" || echo "missing"` - - If config exists, load it: @${CLAUDE_PLUGIN_ROOT}/config.json - Otherwise, use defaults... - ``` - -3. **Document plugin file structure:** - ```markdown - - ``` - -4. **Combine with arguments:** - ```markdown - Run: !`${CLAUDE_PLUGIN_ROOT}/bin/process.sh $1 $2` - ``` - -### Troubleshooting - -**Variable not expanding:** -- Ensure command is loaded from plugin -- Check bash execution is allowed -- Verify syntax is exact: `${CLAUDE_PLUGIN_ROOT}` - -**File not found errors:** -- Verify file exists in plugin directory -- Check file path is correct relative to plugin root -- Ensure file permissions allow reading/execution - -**Path with spaces:** -- Bash commands automatically handle spaces -- File references work with spaces in paths -- No special quoting needed - -## Plugin Command Patterns - -### Pattern 1: Configuration-Based Commands - -Commands that load plugin-specific configuration: - -```markdown ---- -description: Deploy using plugin settings -allowed-tools: Read, Bash(*) ---- - -Load configuration: @${CLAUDE_PLUGIN_ROOT}/deploy-config.json - -Deploy to $1 environment using: -1. Configuration settings above -2. Current git branch: !`git branch --show-current` -3. Application version: !`cat package.json | grep version` - -Execute deployment and monitor progress. -``` - -**When to use:** Commands that need consistent settings across invocations - -### Pattern 2: Template-Based Generation - -Commands that use plugin templates: - -```markdown ---- -description: Generate documentation from template -argument-hint: [component-name] ---- - -Template: @${CLAUDE_PLUGIN_ROOT}/templates/component-docs.md - -Generate documentation for $1 component following the template structure. -Include: -- Component purpose and usage -- API reference -- Examples -- Testing guidelines -``` - -**When to use:** Standardized output generation - -### Pattern 3: Multi-Script Workflow - -Commands that orchestrate multiple plugin scripts: - -```markdown ---- -description: Complete build and test workflow -allowed-tools: Bash(*) ---- - -Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh` -Validate: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh` -Test: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test.sh` - -Review all outputs and report: -1. Build status -2. Validation results -3. Test results -4. Recommended next steps -``` - -**When to use:** Complex plugin workflows with multiple steps - -### Pattern 4: Environment-Aware Commands - -Commands that adapt to environment: - -```markdown ---- -description: Deploy based on environment -argument-hint: [dev|staging|prod] ---- - -Environment config: @${CLAUDE_PLUGIN_ROOT}/config/$1.json - -Environment check: !`echo "Deploying to: $1"` - -Deploy application using $1 environment configuration. -Verify deployment and run smoke tests. -``` - -**When to use:** Commands that behave differently per environment - -### Pattern 5: Plugin Data Management - -Commands that manage plugin-specific data: - -```markdown ---- -description: Save analysis results to plugin cache -allowed-tools: Bash(*), Read, Write ---- - -Cache directory: ${CLAUDE_PLUGIN_ROOT}/cache/ - -Analyze @$1 and save results to cache: -!`mkdir -p ${CLAUDE_PLUGIN_ROOT}/cache && date > ${CLAUDE_PLUGIN_ROOT}/cache/last-run.txt` - -Store analysis for future reference and comparison. -``` - -**When to use:** Commands that need persistent data storage - -## Integration with Plugin Components - -### Invoking Plugin Agents - -Commands can trigger plugin agents using the Task tool: - -```markdown ---- -description: Deep analysis using plugin agent -argument-hint: [file-path] ---- - -Initiate deep code analysis of @$1 using the code-analyzer agent. - -The agent will: -1. Analyze code structure -2. Identify patterns -3. Suggest improvements -4. Generate detailed report - -Note: This uses the Task tool to launch the plugin's code-analyzer agent. -``` - -**Key points:** -- Agent must be defined in plugin's `agents/` directory -- Claude will automatically use Task tool to launch agent -- Agent has access to same plugin resources - -### Invoking Plugin Skills - -Commands can reference plugin skills for specialized knowledge: - -```markdown ---- -description: API documentation with best practices -argument-hint: [api-file] ---- - -Document the API in @$1 following our API documentation standards. - -Use the api-docs-standards skill to ensure documentation includes: -- Endpoint descriptions -- Parameter specifications -- Response formats -- Error codes -- Usage examples - -Note: This leverages the plugin's api-docs-standards skill for consistency. -``` - -**Key points:** -- Skill must be defined in plugin's `skills/` directory -- Mention skill by name to hint Claude should invoke it -- Skills provide specialized domain knowledge - -### Coordinating with Plugin Hooks - -Commands can be designed to work with plugin hooks: - -```markdown ---- -description: Commit with pre-commit validation -allowed-tools: Bash(git:*) ---- - -Stage changes: !\`git add $1\` - -Commit changes: !\`git commit -m "$2"\` - -Note: This commit will trigger the plugin's pre-commit hook for validation. -Review hook output for any issues. -``` - -**Key points:** -- Hooks execute automatically on events -- Commands can prepare state for hooks -- Document hook interaction in command - -### Multi-Component Plugin Commands - -Commands that coordinate multiple plugin components: - -```markdown ---- -description: Comprehensive code review workflow -argument-hint: [file-path] ---- - -File to review: @$1 - -Execute comprehensive review: - -1. **Static Analysis** (via plugin scripts) - !`node ${CLAUDE_PLUGIN_ROOT}/scripts/lint.js $1` - -2. **Deep Review** (via plugin agent) - Launch the code-reviewer agent for detailed analysis. - -3. **Best Practices** (via plugin skill) - Use the code-standards skill to ensure compliance. - -4. **Documentation** (via plugin template) - Template: @${CLAUDE_PLUGIN_ROOT}/templates/review-report.md - -Generate final report combining all outputs. -``` - -**When to use:** Complex workflows leveraging multiple plugin capabilities - -## Validation Patterns - -### Input Validation - -Commands should validate inputs before processing: - -```markdown ---- -description: Deploy to environment with validation -argument-hint: [environment] ---- - -Validate environment: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"` - -$IF($1 in [dev, staging, prod], - Deploy to $1 environment using validated configuration, - ERROR: Invalid environment '$1'. Must be one of: dev, staging, prod -) -``` - -**Validation approaches:** -1. Bash validation using grep/test -2. Inline validation in prompt -3. Script-based validation - -### File Existence Checks - -Verify required files exist: - -```markdown ---- -description: Process configuration file -argument-hint: [config-file] ---- - -Check file: !`test -f $1 && echo "EXISTS" || echo "MISSING"` - -Process configuration if file exists: @$1 - -If file doesn't exist, explain: -- Expected location -- Required format -- How to create it -``` - -### Required Arguments - -Validate required arguments provided: - -```markdown ---- -description: Create deployment with version -argument-hint: [environment] [version] ---- - -Validate inputs: !`test -n "$1" -a -n "$2" && echo "OK" || echo "MISSING"` - -$IF($1 AND $2, - Deploy version $2 to $1 environment, - ERROR: Both environment and version required. Usage: /deploy [env] [version] -) -``` - -### Plugin Resource Validation - -Verify plugin resources available: - -```markdown ---- -description: Run analysis with plugin tools -allowed-tools: Bash(test:*) ---- - -Validate plugin setup: -- Config exists: !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "✓" || echo "✗"` -- Scripts exist: !`test -d ${CLAUDE_PLUGIN_ROOT}/scripts && echo "✓" || echo "✗"` -- Tools available: !`test -x ${CLAUDE_PLUGIN_ROOT}/bin/analyze && echo "✓" || echo "✗"` - -If all checks pass, proceed with analysis. -Otherwise, report missing components and installation steps. -``` - -### Output Validation - -Validate command execution results: - -```markdown ---- -description: Build and validate output -allowed-tools: Bash(*) ---- - -Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh` - -Validate output: -- Exit code: !`echo $?` -- Output exists: !`test -d dist && echo "✓" || echo "✗"` -- File count: !`find dist -type f | wc -l` - -Report build status and any validation failures. -``` - -### Graceful Error Handling - -Handle errors gracefully with helpful messages: - -```markdown ---- -description: Process file with error handling -argument-hint: [file-path] ---- - -Try processing: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/process.js $1 2>&1 || echo "ERROR: $?"` - -If processing succeeded: -- Report results -- Suggest next steps - -If processing failed: -- Explain likely causes -- Provide troubleshooting steps -- Suggest alternative approaches -``` - -## Best Practices Summary - -### Plugin Commands Should: - -1. **Use ${CLAUDE_PLUGIN_ROOT} for all plugin-internal paths** - - Scripts, templates, configuration, resources - -2. **Validate inputs early** - - Check required arguments - - Verify file existence - - Validate argument formats - -3. **Document plugin structure** - - Explain required files - - Document script purposes - - Clarify dependencies - -4. **Integrate with plugin components** - - Reference agents for complex tasks - - Use skills for specialized knowledge - - Coordinate with hooks when relevant - -5. **Provide helpful error messages** - - Explain what went wrong - - Suggest how to fix - - Offer alternatives - -6. **Handle edge cases** - - Missing files - - Invalid arguments - - Failed script execution - - Missing dependencies - -7. **Keep commands focused** - - One clear purpose per command - - Delegate complex logic to scripts - - Use agents for multi-step workflows - -8. **Test across installations** - - Verify paths work everywhere - - Test with different arguments - - Validate error cases - ---- - -For general command development, see main SKILL.md. -For command examples, see examples/ directory. diff --git a/dot_claude/skills/Command Development/references/testing-strategies.md b/dot_claude/skills/Command Development/references/testing-strategies.md deleted file mode 100644 index 7b482fb..0000000 --- a/dot_claude/skills/Command Development/references/testing-strategies.md +++ /dev/null @@ -1,702 +0,0 @@ -# Command Testing Strategies - -Comprehensive strategies for testing slash commands before deployment and distribution. - -## Overview - -Testing commands ensures they work correctly, handle edge cases, and provide good user experience. A systematic testing approach catches issues early and builds confidence in command reliability. - -## Testing Levels - -### Level 1: Syntax and Structure Validation - -**What to test:** -- YAML frontmatter syntax -- Markdown format -- File location and naming - -**How to test:** - -```bash -# Validate YAML frontmatter -head -n 20 .claude/commands/my-command.md | grep -A 10 "^---" - -# Check for closing frontmatter marker -head -n 20 .claude/commands/my-command.md | grep -c "^---" # Should be 2 - -# Verify file has .md extension -ls .claude/commands/*.md - -# Check file is in correct location -test -f .claude/commands/my-command.md && echo "Found" || echo "Missing" -``` - -**Automated validation script:** - -```bash -#!/bin/bash -# validate-command.sh - -COMMAND_FILE="$1" - -if [ ! -f "$COMMAND_FILE" ]; then - echo "ERROR: File not found: $COMMAND_FILE" - exit 1 -fi - -# Check .md extension -if [[ ! "$COMMAND_FILE" =~ \.md$ ]]; then - echo "ERROR: File must have .md extension" - exit 1 -fi - -# Validate YAML frontmatter if present -if head -n 1 "$COMMAND_FILE" | grep -q "^---"; then - # Count frontmatter markers - MARKERS=$(head -n 50 "$COMMAND_FILE" | grep -c "^---") - if [ "$MARKERS" -ne 2 ]; then - echo "ERROR: Invalid YAML frontmatter (need exactly 2 '---' markers)" - exit 1 - fi - echo "✓ YAML frontmatter syntax valid" -fi - -# Check for empty file -if [ ! -s "$COMMAND_FILE" ]; then - echo "ERROR: File is empty" - exit 1 -fi - -echo "✓ Command file structure valid" -``` - -### Level 2: Frontmatter Field Validation - -**What to test:** -- Field types correct -- Values in valid ranges -- Required fields present (if any) - -**Validation script:** - -```bash -#!/bin/bash -# validate-frontmatter.sh - -COMMAND_FILE="$1" - -# Extract YAML frontmatter -FRONTMATTER=$(sed -n '/^---$/,/^---$/p' "$COMMAND_FILE" | sed '1d;$d') - -if [ -z "$FRONTMATTER" ]; then - echo "No frontmatter to validate" - exit 0 -fi - -# Check 'model' field if present -if echo "$FRONTMATTER" | grep -q "^model:"; then - MODEL=$(echo "$FRONTMATTER" | grep "^model:" | cut -d: -f2 | tr -d ' ') - if ! echo "sonnet opus haiku" | grep -qw "$MODEL"; then - echo "ERROR: Invalid model '$MODEL' (must be sonnet, opus, or haiku)" - exit 1 - fi - echo "✓ Model field valid: $MODEL" -fi - -# Check 'allowed-tools' field format -if echo "$FRONTMATTER" | grep -q "^allowed-tools:"; then - echo "✓ allowed-tools field present" - # Could add more sophisticated validation here -fi - -# Check 'description' length -if echo "$FRONTMATTER" | grep -q "^description:"; then - DESC=$(echo "$FRONTMATTER" | grep "^description:" | cut -d: -f2-) - LENGTH=${#DESC} - if [ "$LENGTH" -gt 80 ]; then - echo "WARNING: Description length $LENGTH (recommend < 60 chars)" - else - echo "✓ Description length acceptable: $LENGTH chars" - fi -fi - -echo "✓ Frontmatter fields valid" -``` - -### Level 3: Manual Command Invocation - -**What to test:** -- Command appears in `/help` -- Command executes without errors -- Output is as expected - -**Test procedure:** - -```bash -# 1. Start Claude Code -claude --debug - -# 2. Check command appears in help -> /help -# Look for your command in the list - -# 3. Invoke command without arguments -> /my-command -# Check for reasonable error or behavior - -# 4. Invoke with valid arguments -> /my-command arg1 arg2 -# Verify expected behavior - -# 5. Check debug logs -tail -f ~/.claude/debug-logs/latest -# Look for errors or warnings -``` - -### Level 4: Argument Testing - -**What to test:** -- Positional arguments work ($1, $2, etc.) -- $ARGUMENTS captures all arguments -- Missing arguments handled gracefully -- Invalid arguments detected - -**Test matrix:** - -| Test Case | Command | Expected Result | -|-----------|---------|-----------------| -| No args | `/cmd` | Graceful handling or useful message | -| One arg | `/cmd arg1` | $1 substituted correctly | -| Two args | `/cmd arg1 arg2` | $1 and $2 substituted | -| Extra args | `/cmd a b c d` | All captured or extras ignored appropriately | -| Special chars | `/cmd "arg with spaces"` | Quotes handled correctly | -| Empty arg | `/cmd ""` | Empty string handled | - -**Test script:** - -```bash -#!/bin/bash -# test-command-arguments.sh - -COMMAND="$1" - -echo "Testing argument handling for /$COMMAND" -echo - -echo "Test 1: No arguments" -echo " Command: /$COMMAND" -echo " Expected: [describe expected behavior]" -echo " Manual test required" -echo - -echo "Test 2: Single argument" -echo " Command: /$COMMAND test-value" -echo " Expected: 'test-value' appears in output" -echo " Manual test required" -echo - -echo "Test 3: Multiple arguments" -echo " Command: /$COMMAND arg1 arg2 arg3" -echo " Expected: All arguments used appropriately" -echo " Manual test required" -echo - -echo "Test 4: Special characters" -echo " Command: /$COMMAND \"value with spaces\"" -echo " Expected: Entire phrase captured" -echo " Manual test required" -``` - -### Level 5: File Reference Testing - -**What to test:** -- @ syntax loads file contents -- Non-existent files handled -- Large files handled appropriately -- Multiple file references work - -**Test procedure:** - -```bash -# Create test files -echo "Test content" > /tmp/test-file.txt -echo "Second file" > /tmp/test-file-2.txt - -# Test single file reference -> /my-command /tmp/test-file.txt -# Verify file content is read - -# Test non-existent file -> /my-command /tmp/nonexistent.txt -# Verify graceful error handling - -# Test multiple files -> /my-command /tmp/test-file.txt /tmp/test-file-2.txt -# Verify both files processed - -# Test large file -dd if=/dev/zero of=/tmp/large-file.bin bs=1M count=100 -> /my-command /tmp/large-file.bin -# Verify reasonable behavior (may truncate or warn) - -# Cleanup -rm /tmp/test-file*.txt /tmp/large-file.bin -``` - -### Level 6: Bash Execution Testing - -**What to test:** -- !` commands execute correctly -- Command output included in prompt -- Command failures handled -- Security: only allowed commands run - -**Test procedure:** - -```bash -# Create test command with bash execution -cat > .claude/commands/test-bash.md << 'EOF' ---- -description: Test bash execution -allowed-tools: Bash(echo:*), Bash(date:*) ---- - -Current date: !`date` -Test output: !`echo "Hello from bash"` - -Analysis of output above... -EOF - -# Test in Claude Code -> /test-bash -# Verify: -# 1. Date appears correctly -# 2. Echo output appears -# 3. No errors in debug logs - -# Test with disallowed command (should fail or be blocked) -cat > .claude/commands/test-forbidden.md << 'EOF' ---- -description: Test forbidden command -allowed-tools: Bash(echo:*) ---- - -Trying forbidden: !`ls -la /` -EOF - -> /test-forbidden -# Verify: Permission denied or appropriate error -``` - -### Level 7: Integration Testing - -**What to test:** -- Commands work with other plugin components -- Commands interact correctly with each other -- State management works across invocations -- Workflow commands execute in sequence - -**Test scenarios:** - -**Scenario 1: Command + Hook Integration** - -```bash -# Setup: Command that triggers a hook -# Test: Invoke command, verify hook executes - -# Command: .claude/commands/risky-operation.md -# Hook: PreToolUse that validates the operation - -> /risky-operation -# Verify: Hook executes and validates before command completes -``` - -**Scenario 2: Command Sequence** - -```bash -# Setup: Multi-command workflow -> /workflow-init -# Verify: State file created - -> /workflow-step2 -# Verify: State file read, step 2 executes - -> /workflow-complete -# Verify: State file cleaned up -``` - -**Scenario 3: Command + MCP Integration** - -```bash -# Setup: Command uses MCP tools -# Test: Verify MCP server accessible - -> /mcp-command -# Verify: -# 1. MCP server starts (if stdio) -# 2. Tool calls succeed -# 3. Results included in output -``` - -## Automated Testing Approaches - -### Command Test Suite - -Create a test suite script: - -```bash -#!/bin/bash -# test-commands.sh - Command test suite - -TEST_DIR=".claude/commands" -FAILED_TESTS=0 - -echo "Command Test Suite" -echo "==================" -echo - -for cmd_file in "$TEST_DIR"/*.md; do - cmd_name=$(basename "$cmd_file" .md) - echo "Testing: $cmd_name" - - # Validate structure - if ./validate-command.sh "$cmd_file"; then - echo " ✓ Structure valid" - else - echo " ✗ Structure invalid" - ((FAILED_TESTS++)) - fi - - # Validate frontmatter - if ./validate-frontmatter.sh "$cmd_file"; then - echo " ✓ Frontmatter valid" - else - echo " ✗ Frontmatter invalid" - ((FAILED_TESTS++)) - fi - - echo -done - -echo "==================" -echo "Tests complete" -echo "Failed: $FAILED_TESTS" - -exit $FAILED_TESTS -``` - -### Pre-Commit Hook - -Validate commands before committing: - -```bash -#!/bin/bash -# .git/hooks/pre-commit - -echo "Validating commands..." - -COMMANDS_CHANGED=$(git diff --cached --name-only | grep "\.claude/commands/.*\.md") - -if [ -z "$COMMANDS_CHANGED" ]; then - echo "No commands changed" - exit 0 -fi - -for cmd in $COMMANDS_CHANGED; do - echo "Checking: $cmd" - - if ! ./scripts/validate-command.sh "$cmd"; then - echo "ERROR: Command validation failed: $cmd" - exit 1 - fi -done - -echo "✓ All commands valid" -``` - -### Continuous Testing - -Test commands in CI/CD: - -```yaml -# .github/workflows/test-commands.yml -name: Test Commands - -on: [push, pull_request] - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - - name: Validate command structure - run: | - for cmd in .claude/commands/*.md; do - echo "Testing: $cmd" - ./scripts/validate-command.sh "$cmd" - done - - - name: Validate frontmatter - run: | - for cmd in .claude/commands/*.md; do - ./scripts/validate-frontmatter.sh "$cmd" - done - - - name: Check for TODOs - run: | - if grep -r "TODO" .claude/commands/; then - echo "ERROR: TODOs found in commands" - exit 1 - fi -``` - -## Edge Case Testing - -### Test Edge Cases - -**Empty arguments:** -```bash -> /cmd "" -> /cmd '' '' -``` - -**Special characters:** -```bash -> /cmd "arg with spaces" -> /cmd arg-with-dashes -> /cmd arg_with_underscores -> /cmd arg/with/slashes -> /cmd 'arg with "quotes"' -``` - -**Long arguments:** -```bash -> /cmd $(python -c "print('a' * 10000)") -``` - -**Unusual file paths:** -```bash -> /cmd ./file -> /cmd ../file -> /cmd ~/file -> /cmd "/path with spaces/file" -``` - -**Bash command edge cases:** -```markdown -# Commands that might fail -!`exit 1` -!`false` -!`command-that-does-not-exist` - -# Commands with special output -!`echo ""` -!`cat /dev/null` -!`yes | head -n 1000000` -``` - -## Performance Testing - -### Response Time Testing - -```bash -#!/bin/bash -# test-command-performance.sh - -COMMAND="$1" - -echo "Testing performance of /$COMMAND" -echo - -for i in {1..5}; do - echo "Run $i:" - START=$(date +%s%N) - - # Invoke command (manual step - record time) - echo " Invoke: /$COMMAND" - echo " Start time: $START" - echo " (Record end time manually)" - echo -done - -echo "Analyze results:" -echo " - Average response time" -echo " - Variance" -echo " - Acceptable threshold: < 3 seconds for fast commands" -``` - -### Resource Usage Testing - -```bash -# Monitor Claude Code during command execution -# In terminal 1: -claude --debug - -# In terminal 2: -watch -n 1 'ps aux | grep claude' - -# Execute command and observe: -# - Memory usage -# - CPU usage -# - Process count -``` - -## User Experience Testing - -### Usability Checklist - -- [ ] Command name is intuitive -- [ ] Description is clear in `/help` -- [ ] Arguments are well-documented -- [ ] Error messages are helpful -- [ ] Output is formatted readably -- [ ] Long-running commands show progress -- [ ] Results are actionable -- [ ] Edge cases have good UX - -### User Acceptance Testing - -Recruit testers: - -```markdown -# Testing Guide for Beta Testers - -## Command: /my-new-command - -### Test Scenarios - -1. **Basic usage:** - - Run: `/my-new-command` - - Expected: [describe] - - Rate clarity: 1-5 - -2. **With arguments:** - - Run: `/my-new-command arg1 arg2` - - Expected: [describe] - - Rate usefulness: 1-5 - -3. **Error case:** - - Run: `/my-new-command invalid-input` - - Expected: Helpful error message - - Rate error message: 1-5 - -### Feedback Questions - -1. Was the command easy to understand? -2. Did the output meet your expectations? -3. What would you change? -4. Would you use this command regularly? -``` - -## Testing Checklist - -Before releasing a command: - -### Structure -- [ ] File in correct location -- [ ] Correct .md extension -- [ ] Valid YAML frontmatter (if present) -- [ ] Markdown syntax correct - -### Functionality -- [ ] Command appears in `/help` -- [ ] Description is clear -- [ ] Command executes without errors -- [ ] Arguments work as expected -- [ ] File references work -- [ ] Bash execution works (if used) - -### Edge Cases -- [ ] Missing arguments handled -- [ ] Invalid arguments detected -- [ ] Non-existent files handled -- [ ] Special characters work -- [ ] Long inputs handled - -### Integration -- [ ] Works with other commands -- [ ] Works with hooks (if applicable) -- [ ] Works with MCP (if applicable) -- [ ] State management works - -### Quality -- [ ] Performance acceptable -- [ ] No security issues -- [ ] Error messages helpful -- [ ] Output formatted well -- [ ] Documentation complete - -### Distribution -- [ ] Tested by others -- [ ] Feedback incorporated -- [ ] README updated -- [ ] Examples provided - -## Debugging Failed Tests - -### Common Issues and Solutions - -**Issue: Command not appearing in /help** - -```bash -# Check file location -ls -la .claude/commands/my-command.md - -# Check permissions -chmod 644 .claude/commands/my-command.md - -# Check syntax -head -n 20 .claude/commands/my-command.md - -# Restart Claude Code -claude --debug -``` - -**Issue: Arguments not substituting** - -```bash -# Verify syntax -grep '\$1' .claude/commands/my-command.md -grep '\$ARGUMENTS' .claude/commands/my-command.md - -# Test with simple command first -echo "Test: \$1 and \$2" > .claude/commands/test-args.md -``` - -**Issue: Bash commands not executing** - -```bash -# Check allowed-tools -grep "allowed-tools" .claude/commands/my-command.md - -# Verify command syntax -grep '!\`' .claude/commands/my-command.md - -# Test command manually -date -echo "test" -``` - -**Issue: File references not working** - -```bash -# Check @ syntax -grep '@' .claude/commands/my-command.md - -# Verify file exists -ls -la /path/to/referenced/file - -# Check permissions -chmod 644 /path/to/referenced/file -``` - -## Best Practices - -1. **Test early, test often**: Validate as you develop -2. **Automate validation**: Use scripts for repeatable checks -3. **Test edge cases**: Don't just test the happy path -4. **Get feedback**: Have others test before wide release -5. **Document tests**: Keep test scenarios for regression testing -6. **Monitor in production**: Watch for issues after release -7. **Iterate**: Improve based on real usage data diff --git a/dot_claude/skills/architecture-patterns/SKILL.md b/dot_claude/skills/applying-architecture-patterns/SKILL.md similarity index 97% rename from dot_claude/skills/architecture-patterns/SKILL.md rename to dot_claude/skills/applying-architecture-patterns/SKILL.md index a374784..a8badf7 100644 --- a/dot_claude/skills/architecture-patterns/SKILL.md +++ b/dot_claude/skills/applying-architecture-patterns/SKILL.md @@ -1,9 +1,9 @@ --- -name: architecture-patterns +name: applying-architecture-patterns description: Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when (1) designing new backend systems from scratch, (2) refactoring monolithic applications for better maintainability, (3) establishing architecture standards for a team, (4) migrating from tightly coupled to loosely coupled architectures, (5) implementing domain-driven design principles, (6) creating testable and mockable codebases, or (7) planning microservices decomposition. --- -# Architecture Patterns +# Applying Architecture Patterns Apply Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable backend systems. diff --git a/dot_claude/skills/architecture-patterns/examples/clean-architecture-example.md b/dot_claude/skills/applying-architecture-patterns/examples/clean-architecture-example.md similarity index 100% rename from dot_claude/skills/architecture-patterns/examples/clean-architecture-example.md rename to dot_claude/skills/applying-architecture-patterns/examples/clean-architecture-example.md diff --git a/dot_claude/skills/architecture-patterns/examples/ddd-example.md b/dot_claude/skills/applying-architecture-patterns/examples/ddd-example.md similarity index 100% rename from dot_claude/skills/architecture-patterns/examples/ddd-example.md rename to dot_claude/skills/applying-architecture-patterns/examples/ddd-example.md diff --git a/dot_claude/skills/architecture-patterns/examples/hexagonal-example.md b/dot_claude/skills/applying-architecture-patterns/examples/hexagonal-example.md similarity index 100% rename from dot_claude/skills/architecture-patterns/examples/hexagonal-example.md rename to dot_claude/skills/applying-architecture-patterns/examples/hexagonal-example.md diff --git a/dot_claude/skills/effective-go/SKILL.md b/dot_claude/skills/applying-effective-go/SKILL.md similarity index 96% rename from dot_claude/skills/effective-go/SKILL.md rename to dot_claude/skills/applying-effective-go/SKILL.md index b36f092..82d449b 100644 --- a/dot_claude/skills/effective-go/SKILL.md +++ b/dot_claude/skills/applying-effective-go/SKILL.md @@ -1,9 +1,9 @@ --- -name: Effective Go +name: applying-effective-go description: "Apply Go best practices, idioms, and conventions from golang.org/doc/effective_go. Use when writing, reviewing, or refactoring Go code to ensure idiomatic, clean, and efficient implementations." --- -# Effective Go +# Applying Effective Go Apply best practices and conventions from the official [Effective Go guide](https://go.dev/doc/effective_go) to write clean, idiomatic Go code. diff --git a/dot_claude/skills/Agent Development/SKILL.md b/dot_claude/skills/developing-agents/SKILL.md similarity index 92% rename from dot_claude/skills/Agent Development/SKILL.md rename to dot_claude/skills/developing-agents/SKILL.md index 3683093..cba0d4a 100644 --- a/dot_claude/skills/Agent Development/SKILL.md +++ b/dot_claude/skills/developing-agents/SKILL.md @@ -1,10 +1,10 @@ --- -name: Agent Development +name: developing-agents description: This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins. version: 0.1.0 --- -# Agent Development for Claude Code Plugins +# Developing Agents for Claude Code Plugins ## Overview @@ -42,6 +42,7 @@ assistant: "[How assistant should respond and use this agent]" model: inherit color: blue tools: ["Read", "Write", "Grep"] +skills: ["skill-name"] --- You are [agent role description]... @@ -159,6 +160,25 @@ tools: ["Read", "Write", "Grep", "Bash"] - Testing: `["Read", "Bash", "Grep"]` - Full access: Omit field or use `["*"]` +### skills (optional) + +Preload skills into the agent's context at startup. + +**Format:** Array of skill names + +```yaml +skills: ["writing-go-code", "applying-effective-go"] +``` + +**Behavior:** +- The full content of each listed skill is injected into the agent's system context when it starts — not just made available for invocation +- Skills are NOT inherited from the parent session — agents must list every skill they need explicitly +- Skill names must match existing skill directory names (from `~/.claude/skills/` or `.claude/skills/`) + +**Use when:** An agent needs domain-specific knowledge to do its job correctly (e.g., a reviewer agent that needs to know project coding conventions). + +**Default:** If omitted, no skills are preloaded. + ## System Prompt Design The markdown body becomes the agent's system prompt. Write in second person, addressing the agent directly. @@ -355,6 +375,7 @@ Output: [What to provide] | model | Yes | inherit/sonnet/opus/haiku | inherit | | color | Yes | Color name | blue | | tools | No | Array of tool names | ["Read", "Grep"] | +| skills | No | Array of skill names | ["writing-go-code"] | ### Best Practices diff --git a/dot_claude/skills/Agent Development/examples/agent-creation-prompt.md b/dot_claude/skills/developing-agents/examples/agent-creation-prompt.md similarity index 98% rename from dot_claude/skills/Agent Development/examples/agent-creation-prompt.md rename to dot_claude/skills/developing-agents/examples/agent-creation-prompt.md index 1258572..233eb37 100644 --- a/dot_claude/skills/Agent Development/examples/agent-creation-prompt.md +++ b/dot_claude/skills/developing-agents/examples/agent-creation-prompt.md @@ -64,7 +64,7 @@ I need an agent that reviews code changes for quality issues, security vulnerabi { "identifier": "code-quality-reviewer", "whenToUse": "Use this agent when the user has written code and needs quality review, or explicitly asks to review code changes. Examples:\n\n\nContext: User just implemented a new feature\nuser: \"I've added the authentication feature\"\nassistant: \"Great! Let me review the code quality.\"\n\nCode was written, trigger code-quality-reviewer agent for review.\n\nassistant: \"I'll use the code-quality-reviewer agent to analyze the changes.\"\n\n\n\nContext: User explicitly requests review\nuser: \"Can you review my code for issues?\"\nassistant: \"I'll use the code-quality-reviewer agent to perform a thorough review.\"\n\nExplicit review request triggers the agent.\n\n", - "systemPrompt": "You are an expert code quality reviewer specializing in identifying issues in software implementations.\n\n**Your Core Responsibilities:**\n1. Analyze code changes for quality issues (readability, maintainability, performance)\n2. Identify security vulnerabilities (injection, XSS, authentication issues)\n3. Check adherence to project best practices and coding standards\n4. Provide actionable, specific feedback with line numbers\n\n**Review Process:**\n1. Read the code changes using available tools\n2. Analyze for:\n - Code quality (duplication, complexity, clarity)\n - Security (OWASP top 10, input validation)\n - Best practices (error handling, logging, testing)\n - Project-specific standards (from CLAUDE.md)\n3. Identify issues with severity (critical/major/minor)\n4. Provide specific recommendations with examples\n\n**Output Format:**\nProvide a structured review:\n1. Summary (2-3 sentences)\n2. Critical Issues (must fix)\n3. Major Issues (should fix)\n4. Minor Issues (nice to fix)\n5. Positive observations\n6. Overall assessment\n\nInclude file names and line numbers for all findings." + "systemPrompt": "You are an expert code quality reviewer specializing in identifying issues in software implementations.\n\n**Your Core Responsibilities:**\n1. Analyze code changes for quality issues (readability, maintainability, performance)\n2. Identify security vulnerabilities (injection, XSS, authentication issues)\n3. Check adherence to project best practices and coding standards\n4. Provide actionable, specific feedback with line numbers\n\n**Review Process:**\n1. Read the code changes using available tools\n2. Analyze for:\n - Code quality (duplication, complexity, clarity)\n - Security (OWASP top 10, input validation)\n - Best practices (error handling, logging, testing)\n - Project-specific standards (from AGENTS.md)\n3. Identify issues with severity (critical/major/minor)\n4. Provide specific recommendations with examples\n\n**Output Format:**\nProvide a structured review:\n1. Summary (2-3 sentences)\n2. Critical Issues (must fix)\n3. Major Issues (should fix)\n4. Minor Issues (nice to fix)\n5. Positive observations\n6. Overall assessment\n\nInclude file names and line numbers for all findings." } ``` @@ -115,7 +115,7 @@ You are an expert code quality reviewer specializing in identifying issues in so - Code quality (duplication, complexity, clarity) - Security (OWASP top 10, input validation) - Best practices (error handling, logging, testing) - - Project-specific standards (from CLAUDE.md) + - Project-specific standards (from AGENTS.md) 3. Identify issues with severity (critical/major/minor) 4. Provide specific recommendations with examples diff --git a/dot_claude/skills/Agent Development/examples/complete-agent-examples.md b/dot_claude/skills/developing-agents/examples/complete-agent-examples.md similarity index 99% rename from dot_claude/skills/Agent Development/examples/complete-agent-examples.md rename to dot_claude/skills/developing-agents/examples/complete-agent-examples.md index ec75fba..ff0b9f7 100644 --- a/dot_claude/skills/Agent Development/examples/complete-agent-examples.md +++ b/dot_claude/skills/developing-agents/examples/complete-agent-examples.md @@ -51,7 +51,7 @@ You are an expert code quality reviewer specializing in identifying issues, secu **Your Core Responsibilities:** 1. Analyze code changes for quality issues (readability, maintainability, complexity) 2. Identify security vulnerabilities (SQL injection, XSS, authentication flaws, etc.) -3. Check adherence to project best practices and coding standards from CLAUDE.md +3. Check adherence to project best practices and coding standards from AGENTS.md 4. Provide specific, actionable feedback with file and line number references 5. Recognize and commend good practices @@ -69,7 +69,7 @@ You are an expert code quality reviewer specializing in identifying issues, secu - Verify input validation and sanitization - Look for hardcoded secrets or credentials 5. **Best Practices**: - - Follow project-specific standards from CLAUDE.md + - Follow project-specific standards from AGENTS.md - Check naming conventions - Verify test coverage - Assess documentation @@ -107,7 +107,7 @@ You are an expert code quality reviewer specializing in identifying issues, secu - No issues found: Provide positive validation, mention what was checked - Too many issues (>20): Group by type, prioritize top 10 critical/major - Unclear code intent: Note ambiguity and request clarification -- Missing context (no CLAUDE.md): Apply general best practices +- Missing context (no AGENTS.md): Apply general best practices - Large changeset: Focus on most impactful files first ``` diff --git a/dot_claude/skills/Agent Development/references/agent-creation-system-prompt.md b/dot_claude/skills/developing-agents/references/agent-creation-system-prompt.md similarity index 97% rename from dot_claude/skills/Agent Development/references/agent-creation-system-prompt.md rename to dot_claude/skills/developing-agents/references/agent-creation-system-prompt.md index 614c8dd..dafe7fa 100644 --- a/dot_claude/skills/Agent Development/references/agent-creation-system-prompt.md +++ b/dot_claude/skills/developing-agents/references/agent-creation-system-prompt.md @@ -7,11 +7,11 @@ This is the exact system prompt used by Claude Code's agent generation feature, ``` You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability. -**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices. +**Important Context**: You may have access to project-specific instructions from AGENTS.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices. When a user describes what they want an agent to do, you will: -1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise. +1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from AGENTS.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise. 2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach. @@ -21,7 +21,7 @@ When a user describes what they want an agent to do, you will: - Anticipates edge cases and provides guidance for handling them - Incorporates any specific requirements or preferences mentioned by the user - Defines output format expectations when relevant - - Aligns with project-specific coding standards and patterns from CLAUDE.md + - Aligns with project-specific coding standards and patterns from AGENTS.md 4. **Optimize for Performance**: Include: - Decision-making frameworks appropriate to the domain @@ -146,14 +146,14 @@ Add after "Optimize for Performance": Add after "Design Expert Persona": - Use clear, concise language - Include code examples -- Follow project documentation standards from CLAUDE.md +- Follow project documentation standards from AGENTS.md ``` ## Best Practices from Internal Implementation ### 1. Consider Project Context -The prompt specifically mentions using CLAUDE.md context: +The prompt specifically mentions using AGENTS.md context: - Agent should align with project patterns - Follow project-specific coding standards - Respect established practices diff --git a/dot_claude/skills/Agent Development/references/system-prompt-design.md b/dot_claude/skills/developing-agents/references/system-prompt-design.md similarity index 99% rename from dot_claude/skills/Agent Development/references/system-prompt-design.md rename to dot_claude/skills/developing-agents/references/system-prompt-design.md index 6efa854..6dbe088 100644 --- a/dot_claude/skills/Agent Development/references/system-prompt-design.md +++ b/dot_claude/skills/developing-agents/references/system-prompt-design.md @@ -112,7 +112,7 @@ You are an expert [domain] engineer specializing in creating high-quality [outpu 6. **Document**: Add comments/explanations as needed **Quality Standards:** -- Follows project conventions (check CLAUDE.md) +- Follows project conventions (check AGENTS.md) - [Specific quality metric 1] - [Specific quality metric 2] - Includes error handling diff --git a/dot_claude/skills/Agent Development/references/triggering-examples.md b/dot_claude/skills/developing-agents/references/triggering-examples.md similarity index 100% rename from dot_claude/skills/Agent Development/references/triggering-examples.md rename to dot_claude/skills/developing-agents/references/triggering-examples.md diff --git a/dot_claude/skills/Agent Development/scripts/validate-agent.sh b/dot_claude/skills/developing-agents/scripts/validate-agent.sh similarity index 100% rename from dot_claude/skills/Agent Development/scripts/validate-agent.sh rename to dot_claude/skills/developing-agents/scripts/validate-agent.sh diff --git a/dot_claude/skills/developing-plan-reviewers/SKILL.md b/dot_claude/skills/developing-plan-reviewers/SKILL.md new file mode 100644 index 0000000..19decfb --- /dev/null +++ b/dot_claude/skills/developing-plan-reviewers/SKILL.md @@ -0,0 +1,166 @@ +--- +name: developing-plan-reviewers +description: Create project-specific plan reviewer agents that integrate with the planning-project-features workflow. Use when a project needs domain-specialized reviewers for sub-plans (e.g., Go code reviewer, API layer reviewer, database reviewer) or when the planner warns that no suitable local reviewer exists for a sub-plan's domain. +--- + +# Developing Plan Reviewers + +Create project-specific reviewer agents for the `planning-project-features` workflow. These agents review individual sub-plans for domain-specific correctness — catching issues that the generic global reviewers (architecture, risk) cannot. + +For general agent development guidance (frontmatter fields, description examples, system prompt design), see the `developing-agents` skill. + +## How Plan Reviewers Fit In + +The planning workflow (Phase 5) uses two types of reviewers: + +1. **Global reviewers** (`~/.claude/agents/`) — `plan-architect-reviewer` and `plan-risk-reviewer`. Project-agnostic, already exist. +2. **Local reviewers** (`.claude/agents/`) — project-specific, domain-specialized. **This is what you build.** + +The planner discovers local reviewers in Phase 4 by reading their descriptions, matches each sub-plan to the most appropriate reviewer, and launches them in Phase 5. No naming convention is assumed — the description is what matters. + +## Design Philosophy + +A reviewer agent is a **thin shell**. It defines: + +- **What to review** — the domain scope (via description and skills list) +- **How to output** — the standard review format (Verdict / Findings / Concerns / Observations) +- **What tone to use** — critical, not praising; specific, not vague + +It does **not** define how to review. Domain knowledge comes from the preloaded **skills**, which encode conventions, patterns, and pitfalls. This separation prevents the reviewer from becoming a static checklist that rots as conventions evolve — the skills are maintained independently and stay in sync with the codebase. + +## Reviewer Agent Template + +```markdown +--- +name: plan--reviewer +description: "Use this agent to review sub-plans that involve . Evaluates against project conventions.\n\n\nContext: A sub-plan covers implementation within a feature plan.\nuser: \"Review sub-plan 02-.md for correctness.\"\nassistant: \"I'll review the sub-plan for issues using the plan--reviewer agent.\"\n\nSub-plan involves work. Launch the domain-specific reviewer.\n\n" +tools: Read, Write, Glob, Grep +skills: + - + - +--- + +You are a reviewer. Your job is to review implementation sub-plans +for correctness — ensuring the proposed approach follows established +conventions, avoids known pitfalls, and will produce correct results. + +You are NOT here to praise, summarize, or restate the plan. You are here to +find what's wrong with it from a perspective. + +## What You Review + +You will be given a path to a specific sub-plan file (e.g., +`.claude/plans//02-.md`). You also have access to the full +codebase to verify claims. + +## How You Review + +1. **Read the sub-plan** completely. +2. **Read project documentation** — AGENTS.md, component-level AGENTS.md + files, and any project documentation (`docs/`, `doc/`, etc.). + Documentation is dramatically + cheaper than code exploration. +3. **Apply your skills** to evaluate the plan against project conventions. + Your preloaded skills encode the conventions for this domain. Use them + as your review criteria. +4. **Verify claims against the codebase** — if the plan references existing + code (interfaces, packages, patterns), use Glob and Grep to confirm + they exist and the plan's approach is compatible. + +## Output Format + +Write your findings to `reviews/..md` inside the +plan directory. Use the exact format below. + +[Insert the standard output format template from this skill] + +## Rules + +- **Be specific and actionable** — every finding must reference the exact + plan section and provide a concrete recommendation. +- **Review the plan, not the code** — you evaluate whether the plan's + strategy is sound for this domain. Code-level review happens during + execution. +- **Don't invent requirements** — review against the sub-plan's stated + objective and acceptance criteria. +- **Don't duplicate architecture or risk review** — focus only on your + domain expertise. +- **Verify claims against the codebase** — if the plan says "extend the + existing interface," confirm the interface exists and the extension + makes sense. +``` + +### Key Choices + +- **`tools: Read, Write, Glob, Grep`** — Write is only for the review output file. Match the global reviewer pattern. +- **`skills`** — the differentiator. Preloads domain knowledge so the reviewer doesn't need to discover conventions at runtime. Skills are the review criteria — the agent should not hardcode evaluation checklists that duplicate what skills already teach. See [Choosing Skills to Preload](#choosing-skills-to-preload). +- **No `model` field** — inherits from parent, matching the global reviewers. +- **Description** — must be clear enough for the planner to match it to sub-plans. Include what domain it covers and what it evaluates. Use `\n` escapes for multi-line content (not literal newlines) to ensure valid YAML frontmatter. +- **No evaluation sections** — don't add numbered "Evaluate X" sections that restate skill content. The skills are injected into context and the reviewer applies them naturally. Static checklists rot; skills are maintained. + +## Choosing Skills to Preload + +The `skills` frontmatter field injects full skill content into the reviewer's context at startup. This is how domain knowledge gets into the reviewer. + +**Selection criteria:** +- List only skills whose conventions the reviewer needs to evaluate sub-plans correctly +- Check both global (`~/.claude/skills/`) and local (`.claude/skills/`) skills +- Don't overload — each injected skill consumes context budget +- Prefer skills that teach conventions and point to source files over skills that duplicate config content + +**Examples:** +| Reviewer Domain | Skills to Preload | +|-----------------|-------------------| +| Go code | `writing-go-code`, `applying-effective-go` | +| API layer | `writing-go-code` (or API-specific skill if one exists) | +| Shell config | `configuring-zsh` | +| CI/CD | `configuring-github-actions` | +| Dotfile management | `managing-chezmoi` | + +## Standard Output Format + +All plan reviewers **must** follow this format. The planner depends on the structure for output normalization (Phase 5, Step 2). + +```markdown +# Review: + +## Verdict + + + +## Critical Findings + + +### Finding: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Concerns + + +### Concern: +- **Affects**: +- **Problem**: +- **Recommendation**: + +## Observations + +``` + +## Examples + +Complete, copy-and-adapt reviewer examples: + +- **[Go Codebase Reviewer](examples/plan-go-reviewer.md)** — reviews sub-plans for idiomatic Go patterns. Preloads `writing-go-code` and `applying-effective-go` as review criteria. +- **[API Layer Reviewer](examples/plan-api-reviewer.md)** — reviews sub-plans for endpoint design and backward compatibility. Preloads `writing-go-code` as review criteria. + +## Rules + +- **Always follow the standard output format** — the planner depends on the Verdict/Critical Findings/Concerns/Observations structure +- **Write output to `reviews/..md`** — never elsewhere +- **Review the plan, not the code** — evaluate whether the plan's strategy is sound for the domain; code-level review happens during execution +- **Be specific and actionable** — every finding must reference the exact plan section and provide a recommendation +- **Don't duplicate architecture or risk review** — focus only on domain expertise +- **Don't invent requirements** — review against the sub-plan's stated objective and acceptance criteria +- **Don't hardcode evaluation checklists** — let skills encode the conventions; the agent applies them diff --git a/dot_claude/skills/developing-plan-reviewers/examples/plan-api-reviewer.md b/dot_claude/skills/developing-plan-reviewers/examples/plan-api-reviewer.md new file mode 100644 index 0000000..58ff225 --- /dev/null +++ b/dot_claude/skills/developing-plan-reviewers/examples/plan-api-reviewer.md @@ -0,0 +1,63 @@ +# Example: API Layer Reviewer + +For a project with HTTP APIs. Skills provide the review criteria — the agent doesn't hardcode endpoint conventions. + +```markdown +--- +name: plan-api-reviewer +description: "Use this agent to review sub-plans that involve API endpoints or HTTP layer changes. Evaluates endpoint design, request/response contracts, error responses, and backward compatibility.\n\n\nContext: A sub-plan covers adding new REST endpoints.\nuser: \"Review sub-plan 03-api-endpoints.md for API correctness.\"\nassistant: \"I'll review the sub-plan for API issues using the plan-api-reviewer.\"\n\nSub-plan involves API/HTTP work. Launch the API domain reviewer.\n\n" +tools: Read, Write, Glob, Grep +skills: + - writing-go-code +--- + +You are an API reviewer. Your job is to review implementation sub-plans for API +correctness — ensuring endpoints are well-designed, contracts are consistent, +and changes don't break existing consumers. + +You are NOT here to praise, summarize, or restate the plan. You are here to +find what's wrong with it from an API perspective. + +## What You Review + +You will be given a path to a specific sub-plan file. You also have access to +the full codebase to verify claims and check existing API patterns. + +## How You Review + +1. **Read the sub-plan** completely. +2. **Read project documentation** — AGENTS.md, API docs, and any + project documentation (`docs/`, `doc/`, etc.). Documentation is + dramatically cheaper than code exploration. +3. **Apply your skills** to evaluate the plan against project conventions. + Your preloaded skills encode the coding standards. Use them plus existing + API patterns in the codebase as your review criteria. +4. **Verify claims against the codebase** — if the plan references existing + endpoints, middleware, or request/response types, use Glob and Grep to + confirm they exist and the plan's approach is compatible. + +## Output Format + +Write your findings to `reviews/.api.md` inside the plan directory. + +# API Review: + +## Verdict +... + +## Critical Findings +... + +## Concerns +... + +## Observations +... + +## Rules + +- Every finding must reference the exact plan section. +- Verify claims against the codebase — check existing endpoint patterns. +- Focus on API-specific concerns. Architecture and risk are other reviewers' jobs. +- Don't invent requirements the sub-plan didn't specify. +``` diff --git a/dot_claude/skills/developing-plan-reviewers/examples/plan-go-reviewer.md b/dot_claude/skills/developing-plan-reviewers/examples/plan-go-reviewer.md new file mode 100644 index 0000000..d5df1e7 --- /dev/null +++ b/dot_claude/skills/developing-plan-reviewers/examples/plan-go-reviewer.md @@ -0,0 +1,65 @@ +# Example: Go Codebase Reviewer + +For a project with Go code. Skills provide the review criteria — the agent doesn't hardcode Go conventions. + +```markdown +--- +name: plan-go-reviewer +description: "Use this agent to review sub-plans that involve Go implementation. Evaluates proposed Go code structure, error handling, interface design, and test strategy against project conventions.\n\n\nContext: A sub-plan covers implementing a new Go service.\nuser: \"Review sub-plan 02-user-service.md for Go correctness.\"\nassistant: \"I'll review the sub-plan for Go issues using the plan-go-reviewer.\"\n\nSub-plan involves Go implementation. Launch the Go domain reviewer.\n\n" +tools: Read, Write, Glob, Grep +skills: + - writing-go-code + - applying-effective-go +--- + +You are a Go reviewer. Your job is to review implementation sub-plans for Go +correctness — ensuring the proposed approach follows Go idioms, project +conventions, and will produce maintainable, testable code. + +You are NOT here to praise, summarize, or restate the plan. You are here to +find what's wrong with it from a Go perspective. + +## What You Review + +You will be given a path to a specific sub-plan file. You also have access to +the full codebase to verify claims and check existing patterns. + +## How You Review + +1. **Read the sub-plan** completely. +2. **Read project documentation** — AGENTS.md, component-level AGENTS.md + files, and any project documentation (`docs/`, `doc/`, etc.). + Documentation is dramatically cheaper than code exploration. +3. **Apply your skills** to evaluate the plan against project conventions. + Your preloaded skills encode Go idioms, coding standards, and test + patterns. Use them as your review criteria. +4. **Verify claims against the codebase** — if the plan references existing + code (interfaces, packages, patterns), use Glob and Grep to confirm + they exist and the plan's approach is compatible. + +## Output Format + +Write your findings to `reviews/.go.md` inside the plan directory. + +# Go Review: + +## Verdict +... + +## Critical Findings +... + +## Concerns +... + +## Observations +... + +## Rules + +- Every finding must reference the exact plan section. +- Verify claims against the codebase — if the plan says "extend the existing + service," confirm the service exists and the extension makes sense. +- Focus on Go-specific concerns. Architecture and risk are other reviewers' jobs. +- Don't invent requirements the sub-plan didn't specify. +``` diff --git a/dot_claude/skills/documenting-architecture/SKILL.md b/dot_claude/skills/documenting-architecture/SKILL.md new file mode 100644 index 0000000..e8574d7 --- /dev/null +++ b/dot_claude/skills/documenting-architecture/SKILL.md @@ -0,0 +1,135 @@ +--- +name: documenting-architecture +description: Document system architecture, design decisions, layer boundaries, and how components connect and communicate. Use when (1) a project's architecture is undocumented, (2) agents can't figure out how the system fits together, (3) after major refactoring that changed system structure, or (4) onboarding developers who need to understand the big picture. References domain concepts — never redefines them. +--- + +# Documenting Architecture + +Document how a system is designed: its layers, boundaries, communication patterns, and the rationale behind key design decisions. Architecture docs explain **how the system is built** and **why it was built that way**. + +## Core Principles + +1. **Decisions Over Descriptions**: The most valuable architecture documentation explains WHY, not just WHAT. "We use event-driven communication between services because X" is more useful than "services communicate via events." +2. **Boundary-Focused**: Emphasize where boundaries are drawn — between layers, modules, services. These are where misunderstandings cause the worst bugs. +3. **Accurate to the Code**: Document the architecture as it IS, not as it was designed to be. If the code has drifted from the original vision, document reality. +4. **No Duplication Across Levels**: Architecture docs reference domain concepts — they never redefine business terms. If you need to mention a domain entity, link to the domain docs. Similarly, don't describe individual component internals — that belongs in component docs. +5. **Discover, Don't Assume**: Read the code to understand the actual architecture. Don't project patterns onto it based on naming alone. + +## Documentation Hierarchy + +``` +Domain ← Defines business concepts (referenced by this layer) + ↓ +Architecture ← You are here (system structure and design decisions) + ↓ +Business Processes ← References architecture for "how the system implements this flow" + ↓ +Components ← References architecture for "where this component fits" +``` + +## Workflow + +### Step 1: Discover Existing Documentation + +Before writing anything: + +1. Check for existing architecture docs, ADRs (Architecture Decision Records), or design docs +2. Read AGENTS.md for pointers to existing documentation +3. Check for diagrams, READMEs in key directories, or informal architecture notes +4. **If architecture docs already exist**: Understand their structure and extend them + +### Step 2: Analyze System Structure + +Focus on the targeted area: + +1. Identify the major layers or modules and their responsibilities +2. Trace the dependency graph — what depends on what, in which direction +3. Identify communication patterns — synchronous calls, events, shared state, message passing +4. Look for boundary enforcement — interfaces, ports, adapters, API contracts +5. Find key design decisions — patterns chosen (hexagonal, layered, CQRS, etc.) and evidence of why +6. Note where the architecture is inconsistent — places where different patterns coexist + +**Stay within the requested scope.** If asked to document the API layer's architecture, don't document the entire system. + +### Step 3: Write Architecture Documentation + +Follow the project's existing doc style. If none exists, use this structure: + +```markdown +# Architecture + +## Overview + + +## Design Principles + +- : +- : + +## Structure + +### +- **Responsibility**: +- **Boundaries**: +- **Dependencies**: + +### +... + +## Communication Patterns + +- : + +## Key Design Decisions + + +| Decision | Choice | Rationale | Alternatives Considered | +|----------|--------|-----------|------------------------| +| ... | ... | ... | ... | + +## Constraints + +``` + +#### Mermaid Diagrams + +Architecture docs should include a mermaid diagram showing how the major parts relate. Place it in or after the Structure section to give humans an instant visual overview. + +Choose the diagram type based on what you're showing: + +- **Flowchart** (`flowchart TD/LR`): Best for showing layers, dependency direction, and data flow between components. +- **Sequence diagram** (`sequenceDiagram`): Best when showing how components interact over time (e.g., request lifecycle). + +Guidelines: +- Show structure and relationships, not process steps — those belong in process docs +- Use subgraphs to group layers or modules +- Label edges with what flows between components (data, calls, events) +- Keep it high-level — detailed internal flows belong in process or component docs + +### Step 4: Update AGENTS.md Pointers + +If new documentation files were created, propose adding a pointer in AGENTS.md: + +```markdown +## Architecture +See `docs/architecture/.md` for . +``` + +**Never put architecture details into AGENTS.md itself** — only add a pointer. + +## Integration with Other Skills + +- **documenting-domain**: Architecture docs reference domain entities (e.g., "the auth layer manages User sessions — see domain/users.md"). Never redefine domain terms here. +- **documenting-business-processes**: Process docs explain how business workflows traverse the architecture +- **documenting-components**: Component docs explain internals; architecture docs explain how components relate to each other +- **project-feature-planning**: The planning skill's Phase 2 benefits enormously from architecture docs — agents understand system structure without reverse-engineering it from code + +## Rules + +- **Never document the entire system architecture at once** — only the targeted area +- **Never redefine domain concepts** — reference domain docs instead +- **Never describe component internals** — that belongs in component docs; architecture describes how components relate +- **Document reality, not aspirations** — if the code doesn't match the intended architecture, document what exists and note the drift +- **Rationale is mandatory** — every design decision must include "why", not just "what" +- **Use reference-style links** — when linking to other docs or source files, use reference links (`[text][ref]` with `[ref]: path` at the bottom of the file) rather than inline links. They read better in source and are easier to maintain. +- **Propose structure first** — if no architecture docs exist yet, propose a directory structure and format before creating files diff --git a/dot_claude/skills/documenting-business-processes/SKILL.md b/dot_claude/skills/documenting-business-processes/SKILL.md new file mode 100644 index 0000000..6bbf2cb --- /dev/null +++ b/dot_claude/skills/documenting-business-processes/SKILL.md @@ -0,0 +1,142 @@ +--- +name: documenting-business-processes +description: Document business processes and workflows that a system implements. Describes end-to-end flows like user registration, order fulfillment, or payment processing — how domain entities move through the system. Use when (1) business workflows are undocumented, (2) a flow spans multiple components and no single component's docs tell the full story, (3) agents need to understand end-to-end behavior to implement changes, or (4) stakeholders need visibility into how the system handles a business process. NOT for development processes — those belong in skills and contribution guidelines. +--- + +# Documenting Business Processes + +Document the business processes and workflows a system implements: how domain entities move through the system, what triggers each step, what the outcomes are, and what can go wrong. Business process docs tell the **end-to-end story** that no single component's documentation can tell on its own. + +## Core Principles + +1. **End-to-End Perspective**: Process docs describe a complete flow from trigger to outcome. They cross component boundaries — that's their purpose. +2. **Business Language**: Describe processes in business terms, referencing domain concepts. "User submits registration form" not "POST /api/v1/users handler validates input." +3. **NOT Development Processes**: This skill documents business workflows the system implements (user registration, order fulfillment). Development processes (how to test, deploy, contribute) belong in skills and contribution guidelines — not here. +4. **No Duplication Across Levels**: Reference domain docs for entity definitions and architecture docs for system structure. Process docs describe the FLOW — how entities traverse the architecture. Don't redefine domain terms or re-explain architectural patterns. +5. **Include Failure Paths**: Happy paths are easy. Document what happens when things go wrong — failed payments, validation errors, timeouts, partial completions. + +## Documentation Hierarchy + +``` +Domain ← Defines the entities involved in processes + ↓ +Architecture ← Defines the system structure processes traverse + ↓ +Business Processes ← You are here (end-to-end flows across the system) + ↓ +Components ← Implements individual steps of processes +``` + +## Workflow + +### Step 1: Discover Existing Documentation + +Before writing anything: + +1. Check for existing process docs, flow diagrams, or sequence diagrams +2. Read AGENTS.md for pointers to existing documentation +3. Check domain and architecture docs for references to processes +4. **If process docs already exist**: Understand their structure and extend them + +### Step 2: Trace the Process + +Follow the targeted process through the codebase: + +1. Identify the trigger — what initiates this process (user action, scheduled job, external event) +2. Trace the happy path step by step across component boundaries +3. Identify decision points — where the flow branches based on conditions +4. Map failure modes — what can go wrong at each step and how the system handles it +5. Identify the outcomes — what state changes when the process completes (or fails) +6. Note any asynchronous steps, retries, or eventual consistency patterns + +**Stay within the requested scope.** Document one process at a time. + +### Step 3: Write Process Documentation + +Follow the project's existing doc style. If none exists, use this structure: + +```markdown +# + +## Overview + + +## Trigger + + +## Actors + +- : + +## Diagram + + +## Flow + +### Happy Path +1. +2. +3. ... + + +### Failure Scenarios + +#### +- **Trigger**: +- **At step**: +- **Handling**: +- **User impact**: + +#### +... + +## State Changes + +- : + +## Dependencies + +``` + +#### Mermaid Diagrams + +Every process doc should include a mermaid diagram placed **before** the textual flow description. The diagram gives humans an instant visual overview; the text provides the detail. + +Choose the diagram type based on the process shape: + +- **Flowchart** (`flowchart TD`): Best for most processes — decision branches, parallel paths, error terminals. Use subgraphs to group related phases. +- **Sequence diagram** (`sequenceDiagram`): Best when the process is a back-and-forth between distinct actors or systems (e.g., sourcing chain, API handshakes). + +Guidelines: +- Keep diagrams focused — show the main flow and key decision points, not every edge case +- Use descriptive node labels in business language, not function names +- Mark error terminals distinctly (e.g., red styling or stop symbols) +- Use subgraphs to separate phases when a process has distinct stages + +### Step 4: Update AGENTS.md Pointers + +If new documentation files were created, propose adding a pointer in AGENTS.md: + +```markdown +## Business Processes +See `docs/processes/.md` for . +``` + +**Never put process details into AGENTS.md itself** — only add a pointer. + +## Integration with Other Skills + +- **documenting-domain**: Process docs reference domain entities (e.g., "creates a new User — see domain/users.md for the User entity definition"). Never redefine domain terms here. +- **documenting-architecture**: Process docs reference architectural patterns when relevant (e.g., "this step publishes an event via the event bus — see architecture/event-bus.md"). Never re-explain the architecture here. +- **documenting-components**: Component docs describe how individual steps are implemented; process docs describe the end-to-end flow across components. +- **project-feature-planning**: Process docs help agents understand the full impact of changes — modifying one step of a process affects the entire flow. + +## Rules + +- **Never document development processes** — testing, deployment, and CI/CD belong in skills and contribution guidelines +- **Never document all processes at once** — only the targeted process +- **Never redefine domain concepts or architectural patterns** — reference the appropriate docs +- **Always include failure paths** — happy-path-only docs are incomplete and misleading +- **Business language first** — describe what happens from the business perspective, then note which components are involved +- **Use reference-style links** — when linking to other docs or source files, use reference links (`[text][ref]` with `[ref]: path` at the bottom of the file) rather than inline links. They read better in source and are easier to maintain. +- **Propose structure first** — if no process docs exist yet, propose a directory structure and format before creating files diff --git a/dot_claude/skills/documenting-components/SKILL.md b/dot_claude/skills/documenting-components/SKILL.md new file mode 100644 index 0000000..64d70a6 --- /dev/null +++ b/dot_claude/skills/documenting-components/SKILL.md @@ -0,0 +1,115 @@ +--- +name: documenting-components +description: Create documentation for specific components or areas of a codebase. Analyzes targeted code sections and produces structured documentation useful to both humans and AI agents. Use when (1) documenting an undocumented component or module, (2) building initial docs for a new area, (3) an agent discovers documentation gaps during codebase exploration, or (4) onboarding documentation is needed for a complex subsystem. Always targets a specific component — never documents the entire codebase at once. +--- + +# Documenting Components + +Create focused, accurate documentation for specific components or areas of a codebase. Targets individual components — **never** attempts to document an entire codebase in one pass. + +## Core Principles + +1. **Targeted Scope**: Document one component, module, or area at a time. Never scan or document the entire codebase. +2. **Human-First**: Write for human developers. If a human wouldn't find it useful, don't write it. +3. **Agent-Friendly Structure**: Structure docs so agents can selectively read what's relevant — documentation is lazy-loaded on demand, unlike AGENTS.md which is eager-loaded into every session. +4. **Accurate Over Comprehensive**: Only document what you can verify from the code. Never invent or assume behavior. +5. **Discover, Don't Assume**: Find the project's existing documentation structure before creating new files. +6. **No Duplication Across Levels**: Before documenting a concept, check if it already exists at a higher documentation level (domain, architecture, or business processes). If it does, **reference it** instead of redefining it. Component docs are the lowest layer — they reference all layers above. + +## Documentation Hierarchy + +``` +Domain ← Defines business concepts (referenced by this layer) + ↓ +Architecture ← Defines system structure (referenced by this layer) + ↓ +Business Processes ← Defines end-to-end flows (referenced by this layer) + ↓ +Components ← You are here (specific module internals and interfaces) +``` + +## Workflow + +### Step 1: Discover Documentation Structure + +Before writing anything: + +1. Check for existing documentation directories (`docs/`, `doc/`, `documentation/`, etc.) +2. Read existing docs to understand format, style, and level of detail +3. Check AGENTS.md for documentation pointers or conventions +4. **If no docs exist**: Propose a directory structure and format to the user before creating files — don't unilaterally decide + +### Step 2: Analyze the Target Component + +Focus **only** on the specified component: + +1. Read the relevant source files +2. Identify key interfaces, types, and exported functions +3. Trace direct dependencies and integration points +4. Note patterns, conventions, and architectural decisions +5. Identify non-obvious behavior — implicit contracts, gotchas, edge cases that would trip up a newcomer or an agent + +**Do not explore unrelated parts of the codebase.** Stay within the component boundary. + +### Step 3: Write Documentation + +Create documentation following the project's existing style. If no style exists, use this structure as a starting point: + +```markdown +# + +## Overview + + +## Architecture + + +## Key Interfaces + + +## Dependencies + + +## Patterns & Conventions + + +## Non-Obvious Behavior + +``` + +**Adapt to the project's conventions** — don't introduce a conflicting format if docs already exist. + +### Step 4: Update AGENTS.md Pointers + +If new documentation files were created, propose adding a pointer in AGENTS.md: + +```markdown +##
+See `docs/.md` for . +``` + +**Never put the documentation content into AGENTS.md** — only add a one-line pointer. AGENTS.md is an index, not an encyclopedia. + +## Integration with Other Skills + +This skill can be invoked: + +- **Manually**: When you want to document a specific component +- **By the planning skill**: When Phase 2 (Codebase Exploration) discovers undocumented areas critical to the plan +- **By executing agents**: When an agent working on a sub-plan encounters an undocumented subsystem it needs to understand + +After documentation is created, future planning sessions and executing agents benefit from it automatically — they read the docs instead of re-exploring code. + +- **documenting-domain**: Component docs reference domain entities (e.g., "handles User creation — see domain/users.md"). Never redefine domain terms. +- **documenting-architecture**: Component docs reference architectural patterns (e.g., "implements the repository port — see architecture/data-layer.md"). Never re-explain the architecture. +- **documenting-business-processes**: Component docs describe their step in a process; process docs describe the end-to-end flow. + +## Rules + +- **Never document the entire codebase at once** — only the targeted component +- **Never invent behavior** — only document what's verifiable in the code +- **Match existing doc style** — don't introduce a new format if docs already exist +- **Propose, don't force** — if unsure about structure, location, or scope, ask the user +- **Keep it maintainable** — shorter accurate docs beat comprehensive stale docs +- **Use reference-style links** — when linking to other docs or source files, use reference links (`[text][ref]` with `[ref]: path` at the bottom of the file) rather than inline links. They read better in source and are easier to maintain. +- **No meta-commentary** — don't add "this doc was auto-generated" or session timestamps diff --git a/dot_claude/skills/documenting-domain/SKILL.md b/dot_claude/skills/documenting-domain/SKILL.md new file mode 100644 index 0000000..0659327 --- /dev/null +++ b/dot_claude/skills/documenting-domain/SKILL.md @@ -0,0 +1,114 @@ +--- +name: documenting-domain +description: Document business domain concepts, terminology, entity relationships, and domain rules for a project. Produces documentation that establishes the shared language used by both humans and AI agents. Use when (1) a project's domain concepts are undocumented, (2) agents misinterpret business terminology, (3) onboarding new team members who need to understand the business model, or (4) domain knowledge is scattered across code and needs consolidation. This is the most foundational documentation layer — all other docs reference it. +--- + +# Documenting Domain + +Document the business domain of a project: its terminology, entities, relationships, rules, and mental models. This is the **most foundational documentation layer** — architecture, processes, and components all reference domain concepts. + +## Core Principles + +1. **Ubiquitous Language**: Define terms precisely. Every entity, state, and concept should have one clear definition that the entire team (and every agent) uses consistently. +2. **Business-First (What and Why, Not How)**: Write from the business perspective, not the implementation perspective. Define what concepts ARE and why they exist — never describe step-by-step flows or how things happen at runtime. "A workspace contains projects" is domain; "the workspaces table has a foreign key to projects" is implementation; "when a user creates a workspace, the system first validates..." is a process. If you find yourself writing sequential steps, that content belongs in a process doc. +3. **Accurate Over Comprehensive**: Only document domain concepts that actually exist in the codebase. Don't invent domain models the project doesn't implement. +4. **Non-Technical Where Possible**: Domain docs should be readable by non-technical stakeholders. Minimize code references — save those for component docs. +5. **No Duplication Across Levels**: Domain docs are the canonical source for business concepts. Architecture, process, and component docs **reference** domain docs — they never redefine domain terms. If you find a concept documented elsewhere, consolidate it here and replace the duplicate with a reference. + +## Documentation Hierarchy + +``` +Domain ← You are here (foundation — all other layers reference this) + ↓ +Architecture ← References domain concepts + ↓ +Business Processes ← References domain concepts and architecture + ↓ +Components ← References all of the above +``` + +## Workflow + +### Step 1: Discover Existing Documentation + +Before writing anything: + +1. Check for existing documentation directories and domain docs +2. Read AGENTS.md for pointers to existing documentation +3. Check if domain concepts are already documented (even informally) in READMEs, comments, or other docs +4. **If domain docs already exist**: Understand their structure and extend them — don't create a parallel system + +### Step 2: Identify Domain Concepts + +Analyze the targeted area of the codebase: + +1. Read key model/entity definitions — struct names, type names, database schemas +2. Identify the core entities and their relationships +3. Look for business rules encoded in validation logic, state machines, or invariants +4. Note domain-specific terminology used in naming (variables, functions, modules) +5. Identify entity lifecycles — how entities are created, transition between states, and are retired + +**Stay within the requested scope.** If asked to document the "billing domain", don't wander into authentication. + +### Step 3: Write Domain Documentation + +Follow the project's existing doc style. If none exists, use this structure: + +```markdown +# + +## Overview + + +## Key Concepts + +### + + +- **Lifecycle**: +- **Relationships**: +- **Key Rules**: + +### +... + +## Domain Rules + +- +- + +## Glossary + + +| Term | Definition | +|------|-----------| +| ... | ... | +``` + +### Step 4: Update AGENTS.md Pointers + +If new documentation files were created, propose adding a pointer in AGENTS.md: + +```markdown +## Domain +See `docs/domain/.md` for . +``` + +**Never put domain knowledge into AGENTS.md itself** — only add a pointer. + +## Integration with Other Skills + +- **documenting-architecture**: Architecture docs reference domain concepts (e.g., "the auth module handles User authentication — see domain/users.md for the User entity definition") +- **documenting-business-processes**: Process docs describe flows between domain entities (e.g., "the registration process creates a User and assigns them to a Workspace") +- **documenting-components**: Component docs reference domain terms without redefining them +- **project-feature-planning**: The planning skill's Phase 2 benefits from domain docs — agents understand the business context without re-exploring code + +## Rules + +- **Never document the entire domain at once** — only the targeted area +- **Never define concepts from an implementation perspective** — describe what they ARE, not how they're stored +- **No code snippets** — domain docs describe the business model; component docs show the implementation +- **One definition per concept** — if a term is already defined in domain docs, other layers must reference it, not redefine it +- **Defer process details to process docs** — if a concept involves a multi-step flow (loading chain, resolution sequence, initialization steps), define the concept here and link to the process doc for the "how" +- **Use reference-style links** — when linking to other docs or source files, use reference links (`[text][ref]` with `[ref]: path` at the bottom of the file) rather than inline links. They read better in source and are easier to maintain. +- **Propose structure first** — if no domain docs exist yet, propose a directory structure and format to the user before creating files diff --git a/dot_claude/skills/feature-planning/SKILL.md b/dot_claude/skills/feature-planning/SKILL.md deleted file mode 100644 index 538f54d..0000000 --- a/dot_claude/skills/feature-planning/SKILL.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -name: feature-planning -description: "Create implementation plans for features with rigorous requirement gathering. Use when planning new features, refactoring efforts, or any multi-step implementation. Never assumes or fills in gaps - always asks for clarification until requirements are complete." ---- - -# Feature Planning - -Create thorough, actionable implementation plans by first ensuring all requirements are fully understood. **Never assume or guess** - ask until every gap is filled. - -## Core Principles - -1. **No Assumptions**: If something is unclear, ambiguous, or missing - ask. Do not fill in gaps with reasonable defaults or best guesses. -2. **Relentless Clarification**: Ask as many questions as needed. A plan built on assumptions is worse than no plan. -3. **User-Controlled Output**: Plans go to `.claude/plans/.md` unless the user specifies otherwise. -4. **Iterative Refinement**: The user reviews and approves before the plan is finalized. - -## Workflow - -### Phase 1: Requirement Gathering - -Before writing any plan, gather complete information: - -1. **Understand the goal**: What problem does this solve? What does success look like? -2. **Identify scope**: What's in scope? What's explicitly out of scope? -3. **Map dependencies**: What existing code/systems does this touch? -4. **Clarify constraints**: Performance requirements? Backward compatibility? Tech stack restrictions? -5. **Define acceptance criteria**: How will we know it's done correctly? - -**Ask questions until you can answer all of the above confidently.** - -If the user says "just figure it out" or "use your judgment": -1. **First, educate**: Present the options you see, explain trade-offs, and help them make an informed decision -2. **If they persist**: Respect their choice to "vibe-code" and proceed with your best judgment, but document your assumptions clearly in the plan - -### Phase 2: Codebase Exploration - -Once requirements are clear: - -1. Search for relevant existing code, patterns, and conventions -2. Identify files that will need modification -3. Note any architectural constraints or patterns to follow -4. Flag potential conflicts or risks - -Share findings with the user and confirm understanding before proceeding. - -### Phase 3: Plan Creation - -Only after Phases 1-2 are complete: - -1. Generate a meaningful, descriptive plan filename based on the feature being planned -2. Write a structured plan with: - - Summary of requirements (as confirmed with user) - - Files to modify/create - - Step-by-step implementation tasks - - Risks and mitigation strategies - - Open questions (if any remain) - -### Phase 4: Review and Approval - -Present the plan for user review. Incorporate feedback. Only mark as ready when the user explicitly approves. - -## Plan File Structure - -```markdown -# Plan: - -## Summary - - -## Requirements - - -## Scope -- **In scope**: ... -- **Out of scope**: ... - -## Files Affected - - -## Implementation Steps -1. -2. -... - -## Risks & Mitigations -| Risk | Mitigation | -|------|------------| -| ... | ... | - -## Acceptance Criteria -- [ ] -- [ ] -... -``` - -## Rules (Non-Negotiable) - -- **Never write a plan based on incomplete information** -- **Never invent requirements the user didn't specify** -- **Save plans to the repository's local `.claude/plans/.md`** - not to the global `~/.claude/` directory, and never with random/generated filenames -- **Ask for clarification even if it feels repetitive** - it's better than introducing garbage diff --git a/dot_claude/skills/planning-project-features/SKILL.md b/dot_claude/skills/planning-project-features/SKILL.md new file mode 100644 index 0000000..fa09c47 --- /dev/null +++ b/dot_claude/skills/planning-project-features/SKILL.md @@ -0,0 +1,329 @@ +--- +name: planning-project-features +description: Create implementation plans for features within a single project. Decomposes work into self-contained sub-plans with iterative multi-agent review. Use when planning new features, refactoring efforts, or any multi-step implementation. Never assumes or fills in gaps - always asks for clarification until requirements are complete. +--- + +# Planning Project Features + +Create thorough, actionable implementation plans for features within a single project. **Never assume or guess** — ask until every gap is filled. + +Plans are decomposed into a **master plan** (high-level orchestration) and **sub-plans** (self-contained, independently executable units). Before finalization, plans go through an **iterative multi-agent review loop** that surfaces architectural issues, risks, and implementation problems. This structure ensures that even the least capable executing agent can pick up a sub-plan and succeed without additional context. + +## Core Principles + +1. **No Assumptions**: If something is unclear, ambiguous, or missing — ask. Do not fill in gaps with reasonable defaults or best guesses. +2. **Relentless Clarification**: Ask as many questions as needed. A plan built on assumptions is worse than no plan. +3. **Atomic Decomposition**: Break work into the smallest self-contained sub-plans possible. Each sub-plan should be executable in isolation. +4. **Embedded Context**: Each sub-plan includes everything an executing agent needs — no reliance on reading other sub-plans or external documents. +5. **Convergent Review**: Plans are reviewed iteratively by specialized sub-agents until no new issues are found. + +## Workflow + +### Phase 1: Requirement Gathering + +Before writing any plan, gather complete information: + +1. **Understand the goal**: What problem does this solve? What does success look like? +2. **Identify scope**: What's in scope? What's explicitly out of scope? +3. **Map dependencies**: What existing code/systems does this touch? +4. **Clarify constraints**: Performance requirements? Backward compatibility? Tech stack restrictions? +5. **Define acceptance criteria**: How will we know it's done correctly? + +**Ask questions until you can answer all of the above confidently.** + +If the user says "just figure it out" or "use your judgment": +1. **First, educate**: Present the options you see, explain trade-offs, and help them make an informed decision +2. **If they persist**: Respect their choice to "vibe-code" and proceed with your best judgment, but document your assumptions clearly in the plan + +### Phase 2: Codebase Exploration + +Once requirements are clear: + +1. **Read existing documentation first**: Check AGENTS.md for documentation pointers, then read relevant docs (domain, architecture, business processes, components). Existing documentation is dramatically cheaper than re-exploring code from scratch. +2. **Explore code only for gaps**: Search for relevant code, patterns, and conventions that documentation doesn't cover. +3. Identify files that will need modification +4. Note any architectural constraints or patterns to follow +5. Flag potential conflicts or risks +6. **Identify required skills**: Determine which skills (both global from `~/.claude/skills/` and local from `.claude/skills/`) an executing agent will need to follow project conventions correctly (e.g., `writing-go-code` for Go changes, `managing-chezmoi` for dotfile edits). Check the project's `AGENTS.md` for documented skill mappings. +7. **Flag documentation gaps**: If critical areas needed for the plan are undocumented, note them. Recommend the appropriate documenting skill: + - Missing domain knowledge → `documenting-domain` + - Missing architecture overview → `documenting-architecture` + - Missing business workflow docs → `documenting-business-processes` + - Missing component docs → `documenting-components` + + Present gaps to the user — they may want to create docs before planning continues, or accept the gap and proceed. + +Share findings with the user and confirm understanding before proceeding. + +### Phase 3: Decomposition + +This is the most critical phase. Break the feature into sub-plans: + +1. **Identify natural boundaries**: Look for seams in the work — different layers (data model, API, UI), different domains, or different files/modules. +2. **Minimize dependencies**: Each sub-plan should depend on as few other sub-plans as possible. Where dependencies exist, make them explicit and one-directional. +3. **Embed all necessary context**: Each sub-plan must include the interfaces, data shapes, conventions, and file contents an executing agent needs. Don't assume the agent has read the master plan or any other sub-plan. +4. **Define clear inputs and outputs**: If sub-plan B depends on sub-plan A, sub-plan B must specify exactly what it expects to exist (e.g., "a `UserService` interface in `internal/service/user.go` with methods `Create(ctx, user) error` and `GetByID(ctx, id) (User, error)`"). +5. **Keep sub-plans small**: A good sub-plan should be completable in a single focused session. If it feels too big, split it further. + +Present the decomposition to the user for review before writing the actual plan files. + +### Phase 4: Plan Creation, Reviewer Assignment & Model Selection + +Only after Phases 1-3 are complete: + +1. **Create the plan directory and files**: + +``` +.claude/plans// +├── 00-master.md # Master plan: overview, ordering, dependencies +├── 01-.md # Sub-plan 1 +├── 02-.md # Sub-plan 2 +├── reviews/ # Review output (created during Phase 5) +└── ... +``` + +2. **Discover available local reviewers**: Read the project's `.claude/agents/` directory to find reviewer agents. Match each sub-plan to the most appropriate available reviewer based on the agent's description and the sub-plan's domain. + +3. **Assign reviewers**: Write the chosen reviewer's name into each sub-plan's `## Reviewer` field. + +4. **Validate**: If no suitable local reviewer exists for a sub-plan's domain, **warn the user** with a specific recommendation (e.g., "sub-plan 03 covers database migrations but no reviewer with that expertise exists in `.claude/agents/`"). Ask how to proceed — do not skip the review silently. + +5. **Assign execution models**: For each sub-plan, assess complexity and recommend an execution model. This enables cost optimization by using cheaper models for straightforward work while reserving Opus for planning and review. + +**Model Selection Decision Tree**: + +| Use Haiku When | Use Sonnet When | Keep Opus For | +|----------------|-----------------|---------------| +| Following established patterns | Novel implementation approaches | Planning & decomposition | +| CRUD operations | Complex business logic | Architecture review | +| Straightforward integrations | Multiple edge cases to consider | Risk assessment | +| Test writing for existing code | Integration of multiple systems | Synthesis & coordination | +| Configuration changes | Performance-critical code | Multi-step reasoning | +| Documentation updates | Security-sensitive operations | Ambiguous requirements | +| File moves/renames | State machine implementations | | +| Simple data transformations | Error handling with recovery logic | | + +**Assessment criteria**: +- **Haiku-appropriate**: Task follows clear patterns, has well-defined inputs/outputs, requires minimal decision-making +- **Sonnet-appropriate**: Task requires some architectural thinking, handles moderate complexity, balances multiple concerns +- **Opus-appropriate**: Rare for execution; only when sub-plan has residual ambiguity or requires creative problem-solving + +Document the recommendation in each sub-plan's `## Execution Model` field with a brief rationale. + +### Phase 5: Review Loop + +After plan creation and reviewer assignment, run an iterative review process. The loop continues until all reviewers report no new findings. + +#### Reviewer Agents + +The review loop uses two types of reviewer agents: + +**Global reviewers** (from `~/.claude/agents/`) — generic, project-agnostic: +- **`plan-architect-reviewer`** — Evaluates the decomposition, boundaries between sub-plans, dependency graph, and whether the pieces will fit together when assembled. +- **`plan-risk-reviewer`** — Identifies technical risks the planner missed: migration pitfalls, backward-compatibility landmines, missing rollback strategies, and sub-plans that may be harder or more complex than they appear. + +**Local reviewers** (from `.claude/agents/`) — project-specific, domain-specialized: +- Each project defines its own reviewer agents tailored to the domains it works with (e.g., API, UI, database, infrastructure). These reviewers can preload project-specific skills via the `skills` frontmatter field for deep domain knowledge. +- The planner does not assume naming conventions — it discovers available agents and matches them to sub-plans by reading their descriptions. + +#### Review Output Location + +All review output is written to `reviews/` within the plan directory, named `..md`: + +``` +.claude/plans//reviews/ +├── 00-master.architect.md # Architecture review of master plan +├── 00-master.risk.md # Risk review of master plan +├── 01-data-model.codebase.md # Codebase review of sub-plan 01 +├── 02-api-layer.codebase.md # Codebase review of sub-plan 02 +└── ... +``` + +This directory is ephemeral — already covered by the `.claude/plans/` ignore rule — but persists locally across sessions for reference. + +#### Step 1: Master Plan Review + +Launch `plan-architect-reviewer` and `plan-risk-reviewer` against the master plan (in parallel — they are independent). Pass the plan directory path so they can read all plan files and cross-reference against the codebase. Instruct each reviewer to write its output to `reviews/00-master..md`. + +Incorporate findings into both the master plan and affected sub-plans. + +#### Step 2: Sub-Plan Review + +After the master plan review is resolved, launch each sub-plan's assigned reviewer (from the `## Reviewer` field) against it. Sub-plan reviews can run in parallel — even when different sub-plans use different reviewers. Each reviewer writes its output to `reviews/..md`. + +**Output normalization**: If a local reviewer's output doesn't follow the standard format (Verdict, Critical Findings, Concerns, Observations), normalize it before incorporating. The planner interprets the reviewer's findings and translates them into actionable changes to the plan. + +Incorporate findings into the sub-plans. If a sub-plan review surfaces an issue that affects the master plan (e.g., a missed dependency, a boundary that needs to shift), update the master plan and re-run affected master plan reviewers. + +#### Step 3: Convergence + +Repeat Steps 1-2 only for affected parts until no reviewer produces new findings. Do NOT restart the entire review — only re-review plans that changed. + +The user may also request additional specialized reviewers (e.g., security, performance) for specific sub-plans. Add these on request, but they are not part of the default flow. + +### Phase 6: User Approval + +Present the fully reviewed plan (master + sub-plans) along with a summary of review findings and how they were addressed. Only mark as ready when the user explicitly approves. + +### Post-Execution: Documentation Updates + +After sub-plans have been executed, the `updating-documentation` skill should be run to keep project documentation in sync with the changes. This is not part of the planning workflow itself, but should be noted in the master plan as a final step: + +```markdown +## Post-Execution +After all sub-plans are complete, run the `updating-documentation` skill to update affected docs. +``` + +This ensures that the documentation investment compounds — each feature execution improves docs for the next planning session. + +## Master Plan Structure + +The master plan is the orchestration document. It does NOT contain implementation details — those live in sub-plans. + +```markdown +# Master Plan: + +## Summary + + +## Requirements + + +## Scope +- **In scope**: ... +- **Out of scope**: ... + +## Sub-Plans + +| # | Sub-Plan | Depends On | Model | Description | +|----|-------------------------|------------|--------|--------------------------------------| +| 01 | `01-.md` | — | Haiku | | +| 02 | `02-.md` | 01 | Sonnet | | +| 03 | `03-.md` | — | Haiku | | +... + +## Execution Order + +- **Parallel group 1**: 01, 03 (no dependencies) +- **Sequential**: 02 (after 01) +... + +## Team Execution (Agent Teams) + +**Use Agent Teams when**: +- ✅ Plan has 2+ sub-plans with meaningful scope +- ✅ Sub-plans are self-contained (minimal cross-dependencies) +- ✅ Sub-plans touch different files (avoid conflicts) +- ✅ Parallelization offers significant time savings + +**Skip Agent Teams when**: +- ❌ Single sub-plan (just execute directly) +- ❌ Tiny sub-plans (overhead > benefit, e.g., "add one import") +- ❌ Highly coupled sub-plans (too much coordination needed) + +**Setup**: +1. Enable Agent Teams: `export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` +2. Create the team: + ``` + Create an agent team to execute .claude/plans//00-master.md + ``` + +**Team Lead Instructions**: +- Use this master plan as the roadmap +- Assign sub-plans to teammates based on the dependency graph +- Each teammate should load the Required Skills listed in their assigned sub-plan before starting +- Use the recommended models from the Sub-Plans table above +- Coordinate handoffs when dependencies complete +- Synthesize results when all sub-plans finish + +**Suggested Team Structure**: +``` +Create a team with teammates to execute .claude/plans//00-master.md: +- Teammate 1: Execute 01-.md using Haiku (load skills: ) +- Teammate 2: Execute 02-.md using Sonnet (load skills: , requires 01 complete) +- Teammate 3: Execute 03-.md using Haiku (load skills: , can start immediately) +... +``` + +**File Ownership** (prevent conflicts): +| Sub-Plan | Primary Files | +|----------|---------------| +| 01 | | +| 02 | | +... + +**Communication Points**: + +- After 01 completes: Notify teammate 2 that dependencies are ready +- If : Broadcast to all teammates about +... + +## Risks & Mitigations +| Risk | Mitigation | +|------|------------| +| ... | ... | + +## Post-Execution +After all sub-plans are complete, run the `updating-documentation` skill to update affected project documentation. +``` + +## Sub-Plan Structure + +Each sub-plan is a **self-contained execution unit**. An agent should be able to pick up a sub-plan and execute it without reading anything else. + +```markdown +# Sub-Plan: + +## Objective + + +## Required Skills + +- `skill-name` — reason it's needed + +## Reviewer + + +## Execution Model +**Recommended**: Haiku | Sonnet | Opus +**Rationale**: + +Examples: +- Haiku: "Standard CRUD implementation following existing patterns in the codebase" +- Sonnet: "Complex business logic with multiple edge cases and error handling scenarios" +- Opus: "Novel architectural approach requiring creative problem-solving" (rare) + +## Prerequisites + +- +- Or: "None — this sub-plan has no dependencies" + +## Context + + +## Primary Files + +- `path/to/file.ext` (create | modify) +- `path/to/other.ext` (modify) + +## Implementation Steps +1. +2. +... + +## Acceptance Criteria +- [ ] +- [ ] +... +``` + +## Rules (Non-Negotiable) + +- **Never write a plan based on incomplete information** +- **Never invent requirements the user didn't specify** +- **Always decompose into sub-plans** — a single monolithic plan is a failure mode +- **Each sub-plan must be self-contained** — embed context, don't reference other sub-plans +- **Always list required skills in every sub-plan** — an executing agent without the right skills will produce subpar results or get stuck +- **Always run the review loop before presenting to the user** — unreviewed plans are draft plans, not finished plans +- **Save plans to `.claude/plans//`** in the local repository — not to `~/.claude/`, and never with random/generated filenames +- **Ask for clarification even if it feels repetitive** — it's better than introducing garbage diff --git a/dot_claude/skills/skill-creator/LICENSE.txt b/dot_claude/skills/skill-creator/LICENSE.txt deleted file mode 100644 index 7a4a3ea..0000000 --- a/dot_claude/skills/skill-creator/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/dot_claude/skills/skill-creator/SKILL.md b/dot_claude/skills/skill-creator/SKILL.md deleted file mode 100644 index b7f8659..0000000 --- a/dot_claude/skills/skill-creator/SKILL.md +++ /dev/null @@ -1,356 +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. -license: Complete terms in LICENSE.txt ---- - -# 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 - -## Core Principles - -### Concise is Key - -The context window is a public good. Skills share the context window with everything else Claude needs: system prompt, conversation history, other Skills' metadata, and the actual user request. - -**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?" and "Does this paragraph justify its token cost?" - -Prefer concise examples over verbose explanations. - -### Set Appropriate Degrees of Freedom - -Match the level of specificity to the task's fragility and variability: - -**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach. - -**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior. - -**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed. - -Think of Claude as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom). - -### 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) - -Every SKILL.md consists of: - -- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that Claude reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used. -- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all). - -#### 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 - -#### What to Not Include in a Skill - -A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including: - -- README.md -- INSTALLATION_GUIDE.md -- QUICK_REFERENCE.md -- CHANGELOG.md -- etc. - -The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxilary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion. - -### 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 because scripts can be executed without reading into context window) - -#### Progressive Disclosure Patterns - -Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them. - -**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files. - -**Pattern 1: High-level guide with references** - -```markdown -# PDF Processing - -## Quick start - -Extract text with pdfplumber: -[code example] - -## Advanced features - -- **Form filling**: See [FORMS.md](FORMS.md) for complete guide -- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods -- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns -``` - -Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed. - -**Pattern 2: Domain-specific organization** - -For Skills with multiple domains, organize content by domain to avoid loading irrelevant context: - -``` -bigquery-skill/ -├── SKILL.md (overview and navigation) -└── reference/ - ├── finance.md (revenue, billing metrics) - ├── sales.md (opportunities, pipeline) - ├── product.md (API usage, features) - └── marketing.md (campaigns, attribution) -``` - -When a user asks about sales metrics, Claude only reads sales.md. - -Similarly, for skills supporting multiple frameworks or variants, organize by variant: - -``` -cloud-deploy/ -├── SKILL.md (workflow + provider selection) -└── references/ - ├── aws.md (AWS deployment patterns) - ├── gcp.md (GCP deployment patterns) - └── azure.md (Azure deployment patterns) -``` - -When the user chooses AWS, Claude only reads aws.md. - -**Pattern 3: Conditional details** - -Show basic content, link to advanced content: - -```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) -``` - -Claude reads REDLINING.md or OOXML.md only when the user needs those features. - -**Important guidelines:** - -- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md. -- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so Claude can see the full scope when previewing. - -## Skill Creation Process - -Skill creation involves these steps: - -1. Understand the skill with concrete examples -2. Plan reusable skill contents (scripts, references, assets) -3. Initialize the skill (run init_skill.py) -4. Edit the skill (implement resources and write SKILL.md) -5. Package the skill (run package_skill.py) -6. Iterate based on real usage - -Follow these steps in order, skipping 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 --path -``` - -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. Include 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. - -#### Learn Proven Design Patterns - -Consult these helpful guides based on your skill's needs: - -- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic -- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns - -These files contain established best practices for effective skill design. - -#### 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/`. - -Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion. - -Any example files and directories not needed for the skill should be deleted. 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 Guidelines:** Always use imperative/infinitive form. - -##### Frontmatter - -Write the YAML frontmatter with `name` and `description`: - -- `name`: The skill name -- `description`: This is the primary triggering mechanism for your skill, and helps Claude understand when to use the skill. - - Include both what the Skill does and specific triggers/contexts for when to use it. - - Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Claude. - - Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks" - -Do not include any other fields in YAML frontmatter. - -##### Body - -Write instructions for using the skill and its bundled resources. - -### Step 5: Packaging a Skill - -Once development of the skill is complete, it must be packaged into a distributable .skill 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 -``` - -Optional output directory specification: - -```bash -scripts/package_skill.py ./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 .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension. - -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/dot_claude/skills/skill-creator/references/output-patterns.md b/dot_claude/skills/skill-creator/references/output-patterns.md deleted file mode 100644 index 073ddda..0000000 --- a/dot_claude/skills/skill-creator/references/output-patterns.md +++ /dev/null @@ -1,82 +0,0 @@ -# Output Patterns - -Use these patterns when skills need to produce consistent, high-quality output. - -## Template Pattern - -Provide templates for output format. Match the level of strictness to your needs. - -**For strict requirements (like API responses or data formats):** - -```markdown -## Report structure - -ALWAYS use this exact template structure: - -# [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 -``` - -**For flexible guidance (when adaptation is useful):** - -```markdown -## Report structure - -Here is a sensible default format, but use your best judgment: - -# [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. -``` - -## Examples Pattern - -For skills where output quality depends on seeing examples, provide input/output pairs: - -```markdown -## Commit message format - -Generate commit messages following these examples: - -**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 in reports -Output: -``` -fix(reports): correct date formatting in timezone conversion - -Use UTC timestamps consistently across report generation -``` - -Follow this style: type(scope): brief description, then detailed explanation. -``` - -Examples help Claude understand the desired style and level of detail more clearly than descriptions alone. diff --git a/dot_claude/skills/skill-creator/references/workflows.md b/dot_claude/skills/skill-creator/references/workflows.md deleted file mode 100644 index a350c3c..0000000 --- a/dot_claude/skills/skill-creator/references/workflows.md +++ /dev/null @@ -1,28 +0,0 @@ -# Workflow Patterns - -## Sequential Workflows - -For complex tasks, break operations into clear, sequential steps. It is often helpful to give Claude an overview of the process towards the beginning of SKILL.md: - -```markdown -Filling a PDF form involves these steps: - -1. Analyze the form (run analyze_form.py) -2. Create field mapping (edit fields.json) -3. Validate mapping (run validate_fields.py) -4. Fill the form (run fill_form.py) -5. Verify output (run verify_output.py) -``` - -## Conditional Workflows - -For tasks with branching logic, guide Claude through decision points: - -```markdown -1. Determine the modification type: - **Creating new content?** → Follow "Creation workflow" below - **Editing existing content?** → Follow "Editing workflow" below - -2. Creation workflow: [steps] -3. Editing workflow: [steps] -``` \ No newline at end of file diff --git a/dot_claude/skills/skill-creator/scripts/init_skill.py b/dot_claude/skills/skill-creator/scripts/init_skill.py deleted file mode 100755 index 329ad4e..0000000 --- a/dot_claude/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 --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 --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/dot_claude/skills/skill-creator/scripts/package_skill.py b/dot_claude/skills/skill-creator/scripts/package_skill.py deleted file mode 100755 index 5cd36cb..0000000 --- a/dot_claude/skills/skill-creator/scripts/package_skill.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python3 -""" -Skill Packager - Creates a distributable .skill file of a skill folder - -Usage: - python utils/package_skill.py [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 .skill file. - - Args: - skill_path: Path to the skill folder - output_dir: Optional output directory for the .skill file (defaults to current directory) - - Returns: - Path to the created .skill 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() - - skill_filename = output_path / f"{skill_name}.skill" - - # Create the .skill file (zip format) - try: - with zipfile.ZipFile(skill_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: {skill_filename}") - return skill_filename - - except Exception as e: - print(f"❌ Error creating .skill file: {e}") - return None - - -def main(): - if len(sys.argv) < 2: - print("Usage: python utils/package_skill.py [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/dot_claude/skills/skill-creator/scripts/quick_validate.py b/dot_claude/skills/skill-creator/scripts/quick_validate.py deleted file mode 100755 index d9fbeb7..0000000 --- a/dot_claude/skills/skill-creator/scripts/quick_validate.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python3 -""" -Quick validation script for skills - minimal version -""" - -import sys -import os -import re -import yaml -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_text = match.group(1) - - # Parse YAML frontmatter - try: - frontmatter = yaml.safe_load(frontmatter_text) - if not isinstance(frontmatter, dict): - return False, "Frontmatter must be a YAML dictionary" - except yaml.YAMLError as e: - return False, f"Invalid YAML in frontmatter: {e}" - - # Define allowed properties - ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata'} - - # Check for unexpected properties (excluding nested keys under metadata) - unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES - if unexpected_keys: - return False, ( - f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. " - f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}" - ) - - # 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 = frontmatter.get('name', '') - if not isinstance(name, str): - return False, f"Name must be a string, got {type(name).__name__}" - name = name.strip() - if name: - # 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" - # Check name length (max 64 characters per spec) - if len(name) > 64: - return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters." - - # Extract and validate description - description = frontmatter.get('description', '') - if not isinstance(description, str): - return False, f"Description must be a string, got {type(description).__name__}" - description = description.strip() - if description: - # Check for angle brackets - if '<' in description or '>' in description: - return False, "Description cannot contain angle brackets (< or >)" - # Check description length (max 1024 characters per spec) - if len(description) > 1024: - return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters." - - return True, "Skill is valid!" - -if __name__ == "__main__": - if len(sys.argv) != 2: - print("Usage: python quick_validate.py ") - 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 diff --git a/dot_claude/skills/updating-documentation/SKILL.md b/dot_claude/skills/updating-documentation/SKILL.md new file mode 100644 index 0000000..465dfe0 --- /dev/null +++ b/dot_claude/skills/updating-documentation/SKILL.md @@ -0,0 +1,125 @@ +--- +name: updating-documentation +description: Update existing project documentation to reflect changes made during a session. Analyzes what changed in code and surgically updates only affected documentation. Use when (1) a coding session has modified component behavior or interfaces, (2) implementation work is complete and docs need to stay in sync, (3) refactoring changed patterns or conventions, or (4) code was deleted and docs may reference removed things. Run at the end of a session — "when it's all said and done." +--- + +# Updating Documentation + +Surgically update existing documentation to reflect changes made during a coding session. Run this **after implementation work is complete** — when it's all said and done. + +## Core Principles + +1. **Surgical Updates**: Only touch documentation affected by the session's changes. Never rewrite unrelated docs. +2. **Change-Driven**: Start from what changed (git diff, modified files), then trace to affected docs. Never explore the codebase looking for things to update. +3. **Preserve Style**: Match the existing documentation's tone, format, and level of detail. +4. **No Fabrication**: Only document changes you can verify. Don't speculate about intent or future plans. +5. **Minimal Disruption**: Small, precise edits over wholesale rewrites. +6. **Respect the Hierarchy**: Changes may affect docs at multiple levels. A renamed domain entity needs updates in domain docs, which may cascade to architecture, process, and component docs that reference it. Always update from the top down. + +## Documentation Hierarchy + +This skill updates documentation across all levels. When tracing affected docs, check every level: + +``` +Domain ← Entity definitions, terminology, domain rules + ↓ +Architecture ← System structure, design decisions, layer boundaries + ↓ +Business Processes ← End-to-end workflows, failure scenarios + ↓ +Components ← Module internals, interfaces, behavior +``` + +A single code change can affect multiple levels. For example, renaming a domain entity touches domain docs (definition), architecture docs (references), process docs (flow descriptions), and component docs (interface signatures). + +## Workflow + +### Step 1: Identify What Changed + +1. Review the session's changes (`git diff`, modified/created/deleted files) +2. Categorize changes by documentation impact: + - **New components**: May need new documentation (flag for docs-writer) + - **Modified interfaces**: Existing docs may describe old signatures + - **Behavioral changes**: Existing docs may describe old behavior + - **Deleted code**: Docs may reference things that no longer exist + - **New patterns or conventions**: May need documenting if they deviate from existing norms + +### Step 2: Find Affected Documentation + +1. Read AGENTS.md for documentation pointers +2. Search existing docs for references to changed components, functions, types, or files +3. Check if changed files have associated documentation (e.g., `docs/auth.md` for `src/auth/`) +4. Identify docs that describe interfaces, behaviors, or patterns that were modified + +**If no documentation exists for the changed areas**, skip to Step 4 — there's nothing to update. + +### Step 3: Make Targeted Updates + +For each affected doc: + +1. **Read the current doc** to understand what it says +2. **Compare against the changes** to identify what's now wrong or incomplete +3. **Make surgical edits** — update specific sections, don't rewrite the whole file +4. **Add new sections** only if the changes introduced genuinely new concepts within the existing component's scope + +Types of updates: + +| Change Type | Doc Update | +|---|---| +| Interface change (signatures, params, returns) | Update the Key Interfaces section | +| Behavioral change (logic, flow, error handling) | Update descriptions of how things work | +| New dependency added | Update the Dependencies section | +| Dependency removed | Remove stale references | +| Pattern change (new convention adopted) | Update the Patterns & Conventions section | +| Code deleted | Remove references to removed components | + +### Step 4: Handle Documentation Gaps + +If the session's changes introduced undocumented areas: + +1. **Do not write full docs** — that's the job of the appropriate documenting skill +2. **Flag the gap with a specific recommendation**: + - New domain concepts introduced → recommend `documenting-domain` + - Architectural changes (new layers, patterns) → recommend `documenting-architecture` + - New business workflows → recommend `documenting-business-processes` + - New modules or components → recommend `documenting-components` +3. **Update AGENTS.md pointers** only if new doc files were actually created in this session + +### Step 4.5: Check for Duplication + +While updating, watch for concepts that are duplicated across documentation levels: + +1. If a domain term is redefined in component docs, consolidate to domain docs and replace with a reference +2. If an architectural pattern is re-explained in process docs, consolidate to architecture docs and replace with a reference +3. Flag any duplication found to the user — don't silently reorganize large sections + +### Step 5: Verify Consistency + +After updates: + +1. Check that AGENTS.md pointers still point to valid files +2. Ensure no docs reference removed code or renamed interfaces +3. Confirm updated docs accurately reflect the new state + +## Integration with Other Skills + +This skill is designed to run **after other work completes**: + +- **After plan execution**: When an agent finishes implementing a sub-plan, run this to keep documentation in sync +- **After refactoring**: When code structure changes, docs referencing old structure need updates +- **After bug fixes**: If the fix changed documented behavior or revealed incorrect documentation + +This skill does **not** create documentation from scratch — it only updates what exists. For undocumented areas, recommend the appropriate documenting skill: +- `documenting-domain` — for business concepts and terminology +- `documenting-architecture` — for system design and structure +- `documenting-business-processes` — for end-to-end business workflows +- `documenting-components` — for specific modules and interfaces + +## Rules + +- **Never rewrite docs that weren't affected by the session's changes** +- **Never create comprehensive documentation from scratch** — that's the docs-writer's job; only make targeted updates here +- **Always start from the diff** — changes drive updates, not exploration +- **Preserve the original author's voice** — edit surgically, don't rewrite +- **Flag gaps, don't fill them** — if something needs full documentation, recommend docs-writer instead +- **No meta-commentary** — don't add "updated by AI" or session timestamps to docs diff --git a/installer/README.md b/installer/README.md deleted file mode 100644 index ae6fff2..0000000 --- a/installer/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# Dotfiles Installer - -[![License](https://img.shields.io/github/license/MrPointer/dotfiles_installer)](https://github.com/MrPointer/dotfiles_installer) -[![Go Report Card](https://goreportcard.com/badge/github.com/MrPointer/dotfiles_installer)](https://goreportcard.com/report/github.com/MrPointer/dotfiles_installer) -[![GitHub](https://img.shields.io/github/v/release/MrPointer/dotfiles_installer?logo=github&sort=semver)](https://github.com/MrPointer/dotfiles_installer) -[![CI](https://github.com/MrPointer/dotfiles_installer/workflows/CI/badge.svg)](https://github.com/MrPointer/dotfiles_installer/actions?query=workflow%3ACI) -[![codecov](https://codecov.io/gh/MrPointer/dotfiles_installer/branch/main/graph/badge.svg)](https://codecov.io/gh/MrPointer/dotfiles_installer) - -The installer of my dotfiles, used to bootstrap the system - -> [!WARNING] -> **Dotfiles Installer is in early development and is not yet ready for use** - -![caution](./img/caution.png) - -## Project Description - -## Features - -- **Shell Source Control**: Choose where your default shell comes from with `--shell-source`: - - `auto` (default) — use existing shell if available, otherwise try Homebrew then system package manager - - `brew` — force Homebrew's shell binary - - `system` — force the system package manager (apt/dnf) -- **Hierarchical Progress Display**: Shows npm-style progress indicators with spinners and timing information -- **Automatic Cursor Cleanup**: Ensures terminal cursor is always visible after program exit, even on interruption -- **Signal Handling**: Gracefully handles Ctrl+C and other termination signals with proper cleanup -- **Verbosity Control**: Multiple verbosity levels from minimal to extra-verbose output -- **Non-Interactive Mode**: Supports automated installations without user prompts - -## Installation - -Compiled binaries for all supported platforms can be found in the [GitHub release]. There is also a [homebrew] tap: - -```shell -brew install MrPointer/tap/dotfiles_installer -``` - -## Quickstart - -### Credits - -This package was created with [copier] and the [FollowTheProcess/go_copier] project template. - -[copier]: https://copier.readthedocs.io/en/stable/ -[FollowTheProcess/go_copier]: https://github.com/FollowTheProcess/go_copier -[GitHub release]: https://github.com/MrPointer/dotfiles_installer/releases -[homebrew]: https://brew.sh diff --git a/installer/docker/README.md b/installer/docker/README.md deleted file mode 100644 index e2111b2..0000000 --- a/installer/docker/README.md +++ /dev/null @@ -1,288 +0,0 @@ -# Multi-OS Docker Testing Environment - -This directory contains Docker configurations for creating consistent testing environments across different operating systems with all required prerequisites pre-installed. - -## Supported Operating Systems - -The Docker environment supports the following operating systems based on `../internal/config/compatibility.yaml`: - -- **Ubuntu Latest** - All prerequisites via `apt-get` -- **Debian Latest** - All prerequisites via `apt-get` -- **Fedora Latest** - All prerequisites via `dnf` - -Each OS includes: -- Build tools (gcc, make, development packages) -- Process utilities (ps, procps) -- Network tools (curl) -- File utilities (file command) -- Version control (git) -- SSL certificates (ca-certificates) - -## Quick Start - -### List Available Operating Systems -```bash -task list -``` - -### Ubuntu Environment -```bash -# All-in-one development command -task ubuntu:dev - -# Or step by step: -task ubuntu:start # Start Ubuntu environment -task ubuntu:shell # Enter the container shell -task ubuntu:stop # Stop when done -``` - -### Debian Environment -```bash -task debian:dev # Start Debian and enter shell -task debian:validate # Run validation tests -task debian:stop # Stop environment -``` - -### Fedora Environment -```bash -task fedora:dev # Start Fedora and enter shell -task fedora:validate # Run validation tests -task fedora:stop # Stop environment -``` - -## Available Tasks - -Run `task --list` to see all available tasks. Here are the main patterns: - -### Per-OS Tasks -Each OS (`ubuntu`, `debian`, `fedora`) supports: -- `task :start` - Build and start the environment -- `task :stop` - Stop the environment -- `task :shell` - Enter the container shell -- `task :dev` - Start environment and enter shell (recommended) -- `task :validate` - Run validation tests -- `task :rebuild` - Rebuild the Docker image from scratch -- `task :clean` - Clean up containers and images - -### Multi-OS Tasks -- `task status` - Show status of all environments -- `task stop-all` - Stop all running environments -- `task clean-all` - Clean up all environments -- `task validate-all` - Run validation on all environments - -## Directory Structure - -``` -docker/ -├── README.md # This file -├── Taskfile.yml # Multi-OS task definitions -├── validate.sh # OS-aware validation script -├── ubuntu/ # Ubuntu-specific files -│ ├── Dockerfile -│ └── docker-compose.yml -├── debian/ # Debian-specific files -│ ├── Dockerfile -│ └── docker-compose.yml -└── fedora/ # Fedora-specific files - ├── Dockerfile - └── docker-compose.yml -``` - -## Features - -- **Multiple OS support** - Test across Ubuntu, Debian, and Fedora -- **OS-specific prerequisites** - Each image has the correct packages for that OS -- **Non-root user setup** - All containers run as `testuser` with sudo privileges -- **Volume mounting** - Your installer code is mounted at `/workspace/installer` -- **Persistent caches** - Separate Docker volumes for each OS build artifacts -- **Clean environments** - Fresh OS installation every time -- **Comprehensive validation** - OS-aware validation script -- **Task automation** - Streamlined workflow with OS-namespaced tasks - -## Usage Examples - -### Development Workflow -```bash -# Start your preferred OS environment -task ubuntu:dev # Ubuntu development -# or -task debian:dev # Debian development -# or -task fedora:dev # Fedora development - -# The container will start and you'll be dropped into a shell -# Your installer code is available at /workspace/installer -``` - -### Testing Across Multiple OS -```bash -# Validate all environments work -task validate-all - -# Check status of all environments -task status - -# Clean up everything when done -task clean-all -``` - -### Validation Results -```bash -task ubuntu:validate -# Example output: -# 🧪 Running Ubuntu validation tests... -# [PASS] Running as testuser -# [PASS] Sudo access without password works -# [PASS] GCC (build-essential) is available -# [PASS] All prerequisites installed -# ✅ All tests passed! Ubuntu environment is ready for development. -``` - -### OS-Specific Testing -```bash -# Test Ubuntu-specific behavior -task ubuntu:start -task ubuntu:shell -# ... do Ubuntu-specific testing ... - -# Switch to Fedora for RPM-based testing -task fedora:start -task fedora:shell -# ... test dnf/rpm behavior ... -``` - -## Troubleshooting - -### Permission Issues -All containers run as `testuser` (UID 1000) by default. The mounted installer directory inherits permissions from your host filesystem. - -### Rebuilding After Changes -If you modify any Dockerfile: -```bash -task :rebuild # Rebuild specific OS -# or -task clean-all # Clean everything and rebuild as needed -``` - -### Container Conflicts -Each OS uses separate containers and volumes: -- Ubuntu: `installer-test-ubuntu-env` -- Debian: `installer-test-debian-env` -- Fedora: `installer-test-fedora-env` - -### Cleaning Up -```bash -# Clean specific OS -task ubuntu:clean - -# Clean everything -task clean-all - -# Nuclear option - remove all Docker artifacts -docker system prune -a -``` - -## Interactive GPG Testing - -⚠️ **SAFETY WARNING**: When testing locally, the scripts use isolated test environments (`/tmp/test-*-home`) to prevent any damage to your real system. Never run the installer directly on your system during development! - -This directory also contains tools for testing the dotfiles installer's interactive GPG setup functionality using automated expect scripts. - -### Prerequisites for Interactive Testing - -**Install expect:** - -macOS: -```bash -brew install expect -``` - -Ubuntu/Debian: -```bash -sudo apt-get install expect -``` - -### Interactive Testing Script - -The `./test-interactive-gpg.exp` script automates GPG key setup during interactive installation using the `expect` tool. - -**Basic Usage:** -```bash -# Use defaults (from installer directory) -./test-interactive-gpg.exp - -# Specify custom parameters -./test-interactive-gpg.exp [installer_path] [email] [name] [passphrase] -``` - -**Examples:** -```bash -# Test with default values -./test-interactive-gpg.exp - -# Test with custom GPG info -./test-interactive-gpg.exp \ - "./dotfiles-installer" \ - "your@email.com" \ - "Your Full Name" \ - "your-secure-passphrase" - -# Test with built binary in Docker environment -./test-interactive-gpg.exp \ - "./dist/dotfiles_installer_linux_amd64_v1/dotfiles-installer" \ - "test@example.com" \ - "Test User" \ - "test-passphrase" -``` - -### GPG Prompts Handled - -The expect script handles these GPG-specific interactive prompts: - -- ✅ GPG email address input -- ✅ GPG full name input -- ✅ GPG passphrase input -- ✅ GPG "okay" confirmation (sends "O" as required by GPG) -- ✅ GPG key generation parameters (size, expiration) -- ✅ GPG key type selection -- ✅ GPG comment field - -### Interactive Testing Workflow - -1. **Build the installer:** - ```bash - cd installer - goreleaser build --skip before --snapshot --clean - ``` -2. **Start Container** (e.g. Ubuntu) - ```bash - task ubuntu:dev - ``` -3. **Run interactive test:** - ```bash - ./test-interactive-gpg.exp - ``` - -### Troubleshooting Interactive Tests - -**Script hangs or times out:** -- Enable debug mode by editing the script and setting `exp_internal 1` -- Run manually and observe the exact GPG prompt text - -**GPG errors in containers:** -- This is expected in containerized environments -- The script handles these gracefully for CI testing - -**Custom GPG prompts not handled:** -- Add new patterns to the `expect` block in the script -- Use case-insensitive regex patterns: `(?i).*your_pattern` - -## Development Tips - -- Use `task status` to see which environments are running -- Each OS has its own cache volume for faster rebuilds -- The validation script automatically detects the OS and runs appropriate tests -- You can run multiple OS environments simultaneously for comparison testing -- All environments mount the same installer code, so changes are immediately available -- Interactive GPG testing works in both Docker environments and locally -- The expect script uses a 5-minute timeout to prevent hanging in CI