# claude-toolkit — full docs corpus (generated by scripts/gen-llms-full.sh) ===== docs/README.md ===== # Documentation Welcome to the claude-toolkit documentation. This repo configures [Claude Code](https://docs.anthropic.com/en/docs/claude-code) and [Cursor IDE](https://www.cursor.com/) with opinionated enforcement of TDD, signed commits, worktree-based development, and agent-driven workflows. ## Guides | Document | Description | |----------|-------------| | [Getting Started](getting-started.md) | Prerequisites, installation, verification, and first workflow | | [Engineering Discipline](engineering-discipline.md) | The six ideas the toolkit enforces, each linked to its shipped implementation | | [Architecture](architecture.md) | Deep-dive into the coordination-branch and worktree architecture with diagrams | | [Graphify Code Graph](graphify.md) | Install the CLI, build a code graph, and query it before grepping | ## Reference | Document | Description | |----------|-------------| | [Claude Code Configuration](claude-code.md) | Hooks, settings, plugins, and policies | | [Cursor Configuration](cursor.md) | Agents, commands, rules, and hooks | | [Deployment Scripts](deployment.md) | deploy.sh, capture.sh, and diff.sh explained | | [Skills & Commands Reference](skills-and-commands.md) | Complete reference of all slash commands and skills | | [Skill README Template](skill-readme-template.md) | The standard for per-skill README pages — agent-facing SKILL.md vs human-facing README.md | | [Testing Agent Models](testing-agent-models.md) | How to verify Cursor agents are configured with the intended model settings | ===== docs/getting-started.md ===== # Getting Started Welcome to the claude-toolkit repo. This guide walks you through installing the configuration, verifying it works, and running your first workflow. If you are new to Claude Code or Cursor, that is fine — this guide explains what everything does as you go. For a deeper look at why things are structured this way, see [Architecture](architecture.md); for the principles the toolkit enforces, see [Engineering Discipline](engineering-discipline.md). --- ## Prerequisites You need the following tools installed before deploying these dotfiles. ### macOS or Linux Windows and WSL have not been tested. macOS (12 Monterey or later) and common Linux distributions (Ubuntu 22.04+, Fedora 38+) are known to work. ### Git 2.20+ Required for `git worktree` support, which is central to this workflow. ```bash # macOS brew install git # Ubuntu / Debian sudo apt update && sudo apt install git # Verify git --version ``` ### jq Used by hooks that parse JSON configuration and output. ```bash # macOS brew install jq # Ubuntu / Debian sudo apt install jq # Verify jq --version ``` ### GPG with a signing key Commits made during Claude Code sessions are enforced to be signed. You need GPG installed and a signing key configured. ```bash # macOS brew install gnupg # Ubuntu / Debian sudo apt install gnupg # Generate a key if you do not have one gpg --gen-key # List your keys to confirm gpg --list-keys # Configure Git to use your key (replace KEY_ID with the fingerprint shown above) git config --global user.signingkey git config --global commit.gpgsign true ``` ### rsync Used by `deploy.sh` and `capture.sh` to sync files between the repo and your home directory. ```bash # macOS (the system rsync is usually sufficient, but brew provides a newer version) brew install rsync # Linux — rsync is typically pre-installed. If not: sudo apt install rsync # Ubuntu / Debian sudo dnf install rsync # Fedora ``` --- ## Installation ### 1. Clone the repository ```bash git clone https://github.com/ArangoGutierrez/claude-toolkit.git cd claude-toolkit ``` ### 2. Preview what will be deployed Run a dry-run first so you can see exactly which files will be installed and what will be backed up: ```bash ./scripts/deploy.sh --dry-run ``` This shows the rsync output without writing anything to disk. ### 3. Deploy ```bash ./scripts/deploy.sh ``` What this does: - Rsyncs `.claude/` from the repo into `~/.claude/` - Rsyncs `.cursor/` from the repo into `~/.cursor/` - Creates a timestamped backup of any existing files at `~/.config/dotfiles-backup/` before overwriting them (for example: `~/.config/dotfiles-backup/dotfiles-backup-20260220-143000.tar.gz`) The script is safe to re-run. Each run creates a fresh backup before making changes, so you can always roll back. For a full explanation of `deploy.sh`, `capture.sh`, and `diff.sh`, see [Deployment Scripts](deployment.md). --- ## Verify Installation After deploying, run the following checks to confirm everything is in place. ### Hooks are executable ```bash ls -la ~/.claude/hooks/ ``` Verify the scripts are present and executable. To see how many hooks were installed: ```bash ls ~/.claude/hooks/*.sh | wc -l ``` All hooks should have executable permissions (`-rwxr-xr-x`). See [Claude Code Configuration](claude-code.md) for the full list of hooks and what each one does. If any file is missing the executable bit: ```bash chmod +x ~/.claude/hooks/*.sh ``` ### Signed commit enforcement Open a Claude Code session inside any Git repository and ask it to commit something without the `-s -S` flags. The `sign-commits.sh` hook should block the commit and ask you to use `git commit -s -S -m "..."` instead. ### TDD guard In a Claude Code session, ask it to write an implementation file (for example, a new `.go` or `.py` file) without first creating a corresponding test file. The `tdd-guard.sh` hook should block the write and prompt you to write the test first. To bypass for a one-off case (for example, when adding a config file that genuinely has no test), export the variable before the file write/edit operation that triggers the hook: ```bash export SKIP_TDD_GUARD=1 # then perform the write/edit operation that triggers tdd-guard.sh ``` ### Claude Code plugins loaded Open Claude Code and run `/status` (or check the settings panel) to confirm plugins are enabled. You should see entries for at minimum: - `superpowers` — brainstorming, CoVe verification, and planning commands - `code-review` — structured code review slash command - `code-simplifier` — complexity reduction slash command - `gopls-lsp` — Go language server integration --- ## Your First Workflow This repo enforces a worktree-based development model. You never commit implementation work directly to `main` or `master`. Instead: 1. A local coordination branch serves as your planning hub (never pushed to remote). 2. All feature work happens in `.worktrees//`, each on its own branch. Here is a minimal walkthrough. ### Step 1: Set up the coordination branch From inside the project you want to work in, run the shipped setup script: ```bash ~/.claude/scripts/setup-workbench.sh ``` This creates the local-only coordination branch and seeds an `AGENTS.md`. The branch is where you plan work, write `AGENTS.md`, and keep `.agents/plans/` documents; the `prevent-push-workbench.sh` hook keeps it from ever being pushed, and `enforce-worktree.sh` keeps source code read-only on it. See [Architecture](architecture.md) for the exact branch name and the enforcement details. ### Step 2: Create a worktree for your feature Always branch from the remote ref (not local `main`) to avoid working from a stale base: ```bash git fetch origin BASE="origin/$(git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@')" git worktree add .worktrees/my-feature -b feat/my-feature "$BASE" cd .worktrees/my-feature ``` ### Step 3: Write a failing test first The TDD guard requires a test file to exist before you can write implementation. Create your test: ```bash # Example for a Go project touch pkg/myfeature/myfeature_test.go # Write your failing test, then run it to confirm it fails go test ./pkg/myfeature/... ``` ### Step 4: Write the implementation Now that a test file exists, the TDD guard will allow implementation files. Write the minimum code to make the test pass. ### Step 5: Commit with signing flags The `sign-commits.sh` hook enforces both a DCO sign-off (`-s`) and a GPG signature (`-S`): ```bash git add . git commit -s -S -m "feat: add myfeature" ``` ### Step 6: Push and open a PR ```bash git push -u origin feat/my-feature gh pr create --title "feat: add myfeature" --body "..." ``` ### Step 7: Clean up after merge Once the PR is merged, remove the worktree: ```bash git worktree remove .worktrees/my-feature ``` For the full architectural rationale behind this workflow, see [Architecture](architecture.md). --- ## Customization ### Disable a hook Hooks are registered in `~/.claude/settings.json` under the `hooks` array. To disable one, remove its entry from that array. You can also edit the source in `.claude/hooks/` and re-deploy. ### Change Claude Code permissions The `allow`, `deny`, and `ask` lists in `~/.claude/settings.json` control what actions Claude Code can take without prompting. Edit these lists to match your risk tolerance. See [Claude Code Configuration](claude-code.md) for the full reference. ### Add a Cursor agent Create a `.md` file in `.cursor/agents/` with the appropriate frontmatter (`name`, `description`, `model`). Deploy with `./scripts/deploy.sh` to sync it to `~/.cursor/agents/`. See [Cursor Configuration](cursor.md) for the frontmatter schema. ### Add a Cursor command Create a `.md` file in `.cursor/commands/`. Commands group agents and define multi-step workflows. See [Cursor Configuration](cursor.md) for examples and the full reference. --- ## Troubleshooting ### "GPG not found" or signing fails ```bash # Install GPG brew install gnupg # macOS sudo apt install gnupg # Ubuntu / Debian # Generate a key if you do not have one gpg --gen-key # Find your key ID gpg --list-secret-keys --keyid-format=long # Configure Git (replace KEY_ID with the long key ID shown above) git config --global user.signingkey git config --global commit.gpgsign true ``` If you are on macOS and Git cannot find the GPG binary: ```bash git config --global gpg.program gpg ``` ### "Permission denied" on hooks ```bash chmod +x ~/.claude/hooks/*.sh ``` ### Worktree conflicts If a worktree was deleted without being removed from Git's tracking: ```bash # List all registered worktrees git worktree list # Remove stale entries git worktree prune ``` ### TDD guard blocking unexpectedly The guard checks for the presence of a test file before allowing implementation writes. If it is blocking something that genuinely does not need a test (configuration files, generated files, documentation): ```bash export SKIP_TDD_GUARD=1 # then perform the write/edit operation that triggers tdd-guard.sh ``` Use this sparingly. The guard exists to enforce TDD discipline. Note that `SKIP_TDD_GUARD` is checked by the Write/Edit hook, not by `git commit`, so it must be set in the environment before the file operation. ### Deploy overwrote my local changes Check the automatic backups created before each deploy: ```bash ls ~/.config/dotfiles-backup/ ``` Each entry is a timestamped `.tar.gz` archive. Extract the one you need: ```bash tar -xzf ~/.config/dotfiles-backup/claude-.tar.gz -C /tmp/restore/ ``` Then copy the files you need back into place. --- ## Next Steps - [Engineering Discipline](engineering-discipline.md) — The six ideas the toolkit enforces, each linked to its shipped hook, rule, or skill - [Architecture](architecture.md) — Deep-dive into the coordination-branch model, hook internals, and design decisions - [Claude Code Configuration](claude-code.md) — Full reference for hooks, settings, plugins, and policies - [Cursor Configuration](cursor.md) — Agents, commands, rules, and hooks for Cursor IDE - [Deployment Scripts](deployment.md) — How `deploy.sh`, `capture.sh`, and `diff.sh` work - [Skills and Commands Reference](skills-and-commands.md) — Complete reference for all slash commands ===== docs/engineering-discipline.md ===== # Engineering Discipline: Tuning Claude Code Into a System A coding agent is fast and tireless, and it will happily skip the boring parts: the failing test you were supposed to write first, the signature on the commit, the command that proves the change actually works. Convention documents do not stop it — under any pressure at all, "just this once" becomes the norm, and a few weeks later the convention lives only in a file nobody reads. This toolkit takes a different position: **discipline that matters is enforced at the toolchain level, not written down and hoped for.** The configuration in this repository turns a handful of engineering principles into machinery that fires on every relevant action, produces evidence instead of claims, and makes regressions announce themselves. This page walks the six ideas the toolkit is built on. Each one links to the shipped artifact that implements it, so you can read the source, run its tests, and adapt it to your own stack. Cross-references: [Architecture](architecture.md) | [Claude Code Configuration](claude-code.md) | [Skills & Commands](skills-and-commands.md) --- ## 1. Enforcement over convention — hooks fire every time A [hook](claude-code.md#hooks) is a small shell script Claude Code runs at a lifecycle event. It reads the event JSON on stdin, does exactly one thing, and exits. The contract is deterministic: `exit 0` allows the action, `exit 2` blocks it and sends the script's stderr back to the model as feedback. No model call, no judgment — the same input always produces the same decision. That determinism is the whole point. A hook cannot be talked out of its rule, cannot forget under deadline, and applies identically to a human and to an agent that has no idea your team even has the convention. The shipped enforcement hooks each close one recurring gap: | Hook | Fires on | Closes the gap | |------|----------|----------------| | `sign-commits.sh` | every `git commit` | commits missing `-s` (DCO) or `-S` (GPG) | | `tdd-guard.sh` | Write/Edit of an implementation file | implementation written before any test exists | | `enforce-worktree.sh` | Write/Edit on the coordination branch | source edited on the wrong branch | | `prevent-push-workbench.sh` | every `git push` | the local-only coordination branch leaking to a remote | | `validate-year.sh` | new-file creation | a stale training-data year in a copyright header | The lesson generalizes past this list: when a rule is worth having, express it as a hook that blocks the violation with an actionable message, not as a bullet in a style guide. The full hook reference — every event, matcher, and error message — lives in [Claude Code Configuration](claude-code.md#hooks), and the scripts themselves are in [`.claude/hooks/`](https://github.com/ArangoGutierrez/claude-toolkit/tree/main/.claude/hooks/). --- ## 2. Evidence over claims — verification pipelines An agent that says "all tests pass" has told you nothing you can act on. The claim and the evidence for it are different things, and only one of them survives review. The toolkit ships two hooks that make evidence structural rather than optional. **`verify-gate.sh`** is a `Stop` hook. It scans the session transcript: if source files changed this session but no test, build, or lint command ran, it blocks the stop once with a nudge to actually verify. It does not judge pass or fail — the bar is simply "a verification command ran." It fails open on any error and honors `export VERIFY_GATE=off` as an escape hatch. The full contract is in [`verify-gate.README.md`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/hooks/verify-gate.README.md). **`bash-audit-log.sh`** is a `PostToolUse` hook. It appends one line per Bash command the agent runs to a dated log under `~/.claude/audit/`, folding compound commands onto a single line so every sub-command shares the session marker, and redacting URL-embedded credentials and `--token` / `--password` / `--api-key` / `--secret` values before anything is written. It always exits 0 — an audit log must never block the work it records. Together they encode a single habit: **produce the evidence as you go, and keep a record of what was actually run.** Registration snippets for both hooks are in [`.claude/hooks/README.md`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/hooks/README.md). --- ## 3. Budget governance Long agent sessions and fanned-out subagents burn output tokens in ways that are easy to lose track of until the bill arrives. **`budget-governor.sh`** is a `Stop` hook that sums output tokens across the session transcript and any subagent transcripts, then emits a one-time advisory as spend crosses 80% and 100% of a declared budget. It is purely advisory — always exits 0, never blocks — and it degrades silently when its one input is absent, so it is safe to wire before anything produces the input. That input is a per-session goal file; the last `Budget: ` line in it (for example `Budget: 200k`) sets the ceiling. No goal file or no budget line means the hook stays quiet. Overrides and the full contract are documented in [`.claude/hooks/README.md`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/hooks/README.md). The principle: make cost visible at the moment it is spent, as a gentle signal rather than a hard wall, so budget awareness becomes ambient instead of a post-hoc surprise. --- ## 4. Tests are contracts — theater-test discipline The most expensive test is the one that passes whether or not the code works. A green suite full of tautologies is worse than no suite: it manufactures confidence with no coverage behind it. The toolkit's [`constitution.md`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/rules/constitution.md) rule — loaded into every session — makes the standard explicit and non-negotiable: - **A test must fail when its subject is broken.** If deleting the code under test leaves the test green, the test proves nothing. Delete it and write a real one. - **Every assertion compares to an independently-derived value.** Re-computing the expected result the same way the implementation does is a mirror, not a check. Derive it by a different path — a literal, a hand-count, a known-good fixture. - **After green, name the bug this test catches.** If you cannot name one, the test is theater. - **Mutation-check the guard.** For a test that guards against a specific regression, reintroduce the regression (or delete the guard) and confirm the test goes red. If it stays green, it never protected anything. The `test-quality-lint.sh` hook flags the most common theater patterns automatically, but the constitution is the standard the hook approximates. When in doubt, delete the code the test claims to cover and watch what the test does. --- ## 5. Failure → Eval A note that says "remember not to do X" is a reminder that decays. The moment the person who wrote it moves on, X comes back. The toolkit's answer is a convention with teeth: > **A failure observed twice ships its fix *with* an executable check that fails > when the fix regresses.** The check — an *eval* — is the fix's guardrail. Evals live in [`.claude/evals/`](https://github.com/ArangoGutierrez/claude-toolkit/tree/main/.claude/evals/). Each one is a small, self-contained script that checks exactly one thing and prints a verdict as its last line. The exit-code contract is narrow on purpose: | Exit | Verdict | Effect on the run | |------|---------|-------------------| | `0` | PASS | the guarded regression is absent | | `1` | FAIL | the regression is back — the run goes red | | `2` | SKIP | cannot run in this environment | `scripts/run-evals.sh` discovers every eval, runs it, and returns non-zero if any failed — wire it into a weekly job and regressions announce themselves. [`TEMPLATE.eval.sh`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/evals/TEMPLATE.eval.sh) is a runnable skeleton to copy. The discipline that makes an eval worth shipping is the same one from the constitution: **the assertion must discriminate.** An eval that re-derives the implementation, or that passes on any error rather than the exact one, is theater in a different costume. Sanity-check by mutation before you trust it. The full framework — writing, testing, and the red-until-deploy nuance — is in [`.claude/evals/README.md`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/evals/README.md). --- ## 6. The orchestrator pattern — a pattern, not a magic command The most reliable multi-agent setup does not run on trust. It runs on fully-specified briefs, isolated workspaces, written reports, and an adversarial review that treats every report as an unverified claim until the evidence checks out. The toolkit ships the pieces to run this yourself: - **Fully-specified briefs.** One agent implements exactly one task from a written brief — the requirements, the working directory, the report path, and the exact commit format. Ambiguity is escalated, not guessed. The [`team-plan`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/team-plan/README.md) skill decomposes work into briefs like this. - **Isolated worktrees.** Each worker implements in its own Git worktree, so concurrent work is physically separated (see [Architecture](architecture.md)). The [`team-execute`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/team-execute/README.md) skill spawns the workers; [`team-shutdown`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/team-shutdown/README.md) retires them. - **Report files with a status vocabulary.** Each worker writes a report and returns a status: `DONE`, `DONE_WITH_CONCERNS`, `BLOCKED`, or `NEEDS_CONTEXT`. The vocabulary forces an honest signal — "done, but here is what I am unsure about" is a first-class outcome, not a footnote. - **An adversarial review gate.** Before anything merges, a reviewer reads the work against its brief and treats the implementer's report as claims to verify, not facts to accept. The shipped [`principal-engineer`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/agents/principal-engineer.md) (architecture, conventions, security) and [`qa-engineer`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/agents/qa-engineer.md) (test quality, mutation checks, CI replication) agents are this gate. Note what is **not** here: no single command runs the whole plan → execute → review → merge loop end to end. The conductor that sequences all of the above is deliberately left out, because the right orchestration depends on your repository, your CI, and your risk tolerance. What ships is the *pattern* and its building blocks — wire them into a loop that fits your project. Documenting the pattern is the point; a one-command black box would hide exactly the decisions you should be making. --- ## Where to go next - [Architecture](architecture.md) — the worktree and coordination-branch model these principles run on top of. - [Claude Code Configuration](claude-code.md) — the full hook, settings, and permission reference. - [Getting Started](getting-started.md) — install the toolkit and watch the enforcement fire on your first session. ===== docs/architecture.md ===== # Architecture: Agents-Workbench Deep-Dive This document explains the agents-workbench architecture from first principles. It is written for the broader developer community, including people new to Git worktrees and hook-based enforcement. Cross-references: [Engineering Discipline](engineering-discipline.md) | [Claude Code Configuration](claude-code.md) | [Cursor Configuration](cursor.md) | [Getting Started](getting-started.md) --- ## 1. The Problem Modern AI coding assistants — Claude Code, Cursor, GitHub Copilot — are powerful. They can write entire features, refactor large codebases, and produce reasonable code from a short prompt. But out of the box, they introduce a specific class of risks that traditional developer workflows were not designed to handle. ### What goes wrong without guardrails **Edits land directly on main.** An AI agent running in your working tree will happily write to any file in the repo. There is no concept of "this is the wrong branch" — the agent writes where it is told. Without isolation, features, experiments, and half-finished work all accumulate on whatever branch happens to be checked out. **No test discipline.** AI agents optimize for satisfying the prompt. If the prompt says "implement this feature," the agent will write implementation code. It will not spontaneously write a failing test first unless something forces it to. Left to their own devices, AI agents produce implementation-first, test-maybe-later code — exactly the pattern that TDD was designed to eliminate. **Unsigned commits.** Without enforcement, AI agents issue plain `git commit` commands. These commits carry no Developer Certificate of Origin (DCO) signoff and no GPG signature. In any project that requires auditability of authorship — open-source with DCO requirements, regulated industries, security-sensitive codebases — this is a compliance problem. It is also philosophically important: as AI-assisted development blurs the line between human and machine authorship, signed commits provide the only mechanical record of who took responsibility for what. **No isolation between concurrent features.** AI agents can run in parallel — multiple Claude Code sessions, multiple Cursor agents, all working in the same checkout. Without separate working directories, concurrent agents step on each other's work. One agent's in-progress refactor corrupts another agent's feature branch. The only safe model for concurrency is isolation at the filesystem level. **Stale years from training data leak into copyright headers.** AI models have a training cutoff. When writing new files with copyright headers, they frequently insert the year from their training data rather than the actual current year. For any project with license compliance requirements, this creates legally incorrect headers that must be manually audited and corrected after the fact. ### The solution: layered enforcement This configuration solves these problems with a three-layer architecture: 1. **Isolation via worktrees.** Every feature is developed in its own Git worktree — a separate directory that shares the same `.git` database but has an independent working tree. Agents are confined to their worktree. Concurrent work is physically separated. 2. **Discipline via hooks.** A suite of Claude Code and Cursor hooks fire automatically on every relevant action. The core enforcement hooks covered in this document handle signed commits, TDD discipline, branch isolation, year correctness, and protection against dangerous commands; the toolkit ships more hooks for verification, audit logging, and budget governance (see [Engineering Discipline](engineering-discipline.md)). Hooks are not suggestions — they mechanically block non-compliant actions. 3. **Coordination via a read-only workbench branch.** A local-only branch called `agents-workbench` serves as the planning and coordination hub. Source code is read-only on this branch. Agents plan here and implement in worktrees. The workbench is never pushed to any remote. The rest of this document explains each layer in detail. --- ## 2. Core Concepts ### The `agents-workbench` Branch The `agents-workbench` branch is a local Git branch that serves as the control tower for all development activity. It has three defining properties: **It is local-only.** The `prevent-push-workbench.sh` hook mechanically blocks any attempt to push this branch to any remote. It will never appear in your GitHub/GitLab repository. This is intentional: the workbench is ephemeral planning state, not permanent project history. Feature branches are the only thing that gets pushed. **Source code is read-only.** The `enforce-worktree.sh` hook fires on every Write and Edit operation while on the `agents-workbench` branch. If an agent or developer attempts to edit any source file — anything that is not a coordination file — the hook blocks the operation and explains how to create a worktree instead. The following files and directories are the only ones writable on the workbench: - `AGENTS.md` — the coordination hub: active tasks, branch inventory, conventions - `.agents/*` — agent configuration, plan documents - `docs/plans/*` — design documents and implementation plans - `CLAUDE.md` — Claude Code system prompt - `.cursor/rules/*` — Cursor rules files - `.cursor/AGENTS.md` — Cursor-specific agent coordination - `.gitignore`, `.cursorrules`, `.claudeignore` — ignore and rules configs Everything else — application code, tests, scripts, configuration files for the application itself — is blocked on the workbench. This prevents the most common accident: an AI agent editing source code while on the wrong branch. **It is the planning hub.** Before any implementation work begins, plans are written to `docs/plans/`, task breakdowns go into `AGENTS.md`, and design decisions are documented. Only after planning is complete does work move into a worktree. ### Git Worktrees A Git worktree is a separate working directory linked to the same Git repository. The `.git` database is shared — commits, refs, objects — but each worktree has its own independent checkout of a different branch. You can have multiple worktrees open simultaneously, each on a different branch, each with independent changes. In this architecture, every feature is developed in its own worktree, created in the `.worktrees/` directory (which is gitignored so it does not appear in commits): ``` .worktrees/ ├── feature-a/ # branch: feat/feature-a, independent working tree ├── feature-b/ # branch: feat/feature-b, independent working tree └── bugfix-c/ # branch: fix/bugfix-c, independent working tree ``` Key properties of this layout: - **Complete isolation.** Changes in `.worktrees/feature-a/` have no effect on `.worktrees/feature-b/`. Agents working on different features cannot interfere with each other. - **Shared Git database.** All worktrees share the same commit history, refs, and objects. A commit pushed from one worktree is immediately visible in all others. - **Always branched from the remote ref.** Worktrees are created with `git worktree add` pointing at the remote ref (`origin/main`, `upstream/main`), never at the local branch. This is critical: local main can become stale after force-pushes, rebases, or simple forgetting to pull. The remote ref is always the authoritative state. ### Hook Enforcement The architecture is not just convention — it is mechanically enforced by shell scripts that run as hooks in Claude Code and Cursor. You cannot violate the architecture without explicitly disabling hooks. This matters because: - Conventions are forgotten under deadline pressure. "Just this once" becomes the norm. - AI agents do not know what they do not know. They cannot self-enforce discipline they were not trained to apply. - Hooks fire automatically, every time, without requiring anyone to remember. Claude Code hooks fire via the `hooks` section of `.claude/settings.json`. Cursor hooks are configured via `.cursor/hooks.json` and `.cursor/hooks/*` and wired into the Cursor hook system. Both sets of hooks are deployed to the appropriate config locations by `scripts/deploy.sh`. --- ## 3. Architecture Diagram ```mermaid graph TD subgraph "Remote (GitHub)" ORIGIN["origin/main"] end subgraph "Local Repository" AWB["agents-workbench branch
LOCAL ONLY · Source READ-ONLY"] subgraph "Coordination Files" AGENTS["AGENTS.md"] PLANS["docs/plans/*"] AGENTDIR[".agents/*"] end subgraph ".worktrees/" WT1["feature-a/
branch: feat/feature-a"] WT2["feature-b/
branch: feat/feature-b"] end end ORIGIN -->|"git fetch"| AWB ORIGIN -->|"git worktree add"| WT1 ORIGIN -->|"git worktree add"| WT2 WT1 -->|"git push"| ORIGIN WT2 -->|"git push"| ORIGIN AWB -.->|"plan & coordinate"| AGENTS AWB -.->|"design docs"| PLANS ``` The diagram shows the information flow: - The remote is the authoritative source. Worktrees always branch from it. - The `agents-workbench` branch pulls from the remote (to stay current with the default branch) but never pushes. - Feature worktrees pull from the remote and push feature branches back to it. - The workbench coordinates planning but never pushes source code changes. --- ## 4. Lifecycle of a Feature This section walks through the complete lifecycle of a feature using the agents-workbench workflow, from planning to merge. ### Phase 1: Plan (on `agents-workbench`) All planning happens on the `agents-workbench` branch before any code is written. ```bash git checkout agents-workbench ``` On this branch, you (or an AI agent) will: 1. Brainstorm at least three approaches to the problem 2. Write a design document to `docs/plans/YYYY-MM-DD-feature-name-design.md` 3. Choose an approach and document the rationale 4. Break the feature into tasks in `AGENTS.md` The `enforce-worktree.sh` hook ensures that no source code can be written here. If an agent tries to write a `.go`, `.py`, `.ts`, or any other source file, the hook blocks the operation and prints instructions for creating a worktree. This forces the plan-first discipline. Example design doc location: `docs/plans/2026-02-20-auth-refresh-design.md` ### Phase 2: Create Worktree (from Remote Ref) Once planning is complete, create a worktree branched from the remote ref: ```bash # Detect the right remote (upstream for forks, origin otherwise) git fetch upstream 2>/dev/null && \ BASE="upstream/$(git symbolic-ref refs/remotes/upstream/HEAD 2>/dev/null | \ sed 's@^refs/remotes/upstream/@@' || echo main)" || \ { git fetch origin && \ BASE="origin/$(git symbolic-ref refs/remotes/origin/HEAD | \ sed 's@^refs/remotes/origin/@@')"; } git worktree add .worktrees/auth-refresh -b feat/auth-refresh "$BASE" cd .worktrees/auth-refresh ``` **Why branch from the remote ref, not local main?** Local branches can become stale in several ways: - Someone force-pushed to main after a rebase. Your local `main` points to the old history. - You are working in a fork. Your local `main` has diverged from `upstream/main`. - You simply forgot to `git pull` before starting work. When you branch from a stale local ref, you build on an outdated foundation. The PR will show unexpected diffs, merge conflicts arise from code that was already merged, and CI may fail against changes already in main. Branching from the remote ref — fetched immediately before worktree creation — eliminates this entire class of problem. The detection logic handles both fork setups (where `upstream` is the authoritative remote) and direct-clone setups (where `origin` is the authoritative remote). ### Phase 3: TDD Cycle (in Worktree) All implementation happens inside the worktree. The TDD cycle is enforced mechanically by `tdd-guard.sh`. **[RED] — Write a Failing Test First** Before writing any implementation code, write a test that describes the desired behavior: ```bash # In .worktrees/auth-refresh/ # Write the test first $EDITOR pkg/auth/refresh_test.go ``` The `tdd-guard.sh` hook watches for writes to implementation files. If you attempt to write `pkg/auth/refresh.go` before any test file has been modified in the current Git session, the hook blocks the write: ``` TDD GUARD: No test file found for implementation file. File: pkg/auth/refresh.go Write the failing test FIRST (Red phase), then implement. Expected test file locations: pkg/auth/refresh_test.go pkg/auth/refresh.test.go pkg/auth/tests/refresh_test.go ``` Run the test to confirm it fails. This is the Red phase. A test that has never failed is a test that has never proven it can catch the bug it is supposed to catch. **[GREEN] — Write Minimum Code to Pass** Write the minimum implementation to make the failing test pass. Do not over-engineer. Do not add features not required by the test. The goal is green, not elegant. ```bash $EDITOR pkg/auth/refresh.go ``` Run the tests again. All tests should now pass. The `tdd-guard.sh` hook allows the implementation write because a test file has been modified in the current session. **Critical rule: never modify tests and implementation in the same turn.** If your implementation requires changing the test, that means the test was wrong. Stop, reconsider the design, and fix the test in a separate step before continuing with implementation. **[REFACTOR] — Clean Up After Green** With tests passing, clean up the implementation: improve naming, extract helpers, reduce duplication, improve error messages. Do not change behavior. Tests must still pass after refactoring. If the refactor touches more than three files or more than fifty lines of code, checkpoint first: commit the green state before refactoring, so you can always return to a known-good point. **Tests are contracts.** Never weaken, delete, or modify tests to make implementation fit. If a test is inconvenient, the implementation is wrong, not the test. ### Phase 4: Commit and Push All commits must be signed. The `sign-commits.sh` hook (for both Claude Code and Cursor) blocks any `git commit` command that does not include both `-s` (DCO signoff) and `-S` (GPG signature): ```bash git add pkg/auth/refresh.go pkg/auth/refresh_test.go git commit -s -S -m "feat(auth): implement token refresh with retry logic" ``` If you attempt `git commit` without those flags, the hook blocks and explains: ``` Blocked: All commits must be signed. Add -s (signoff) and -S (GPG signature) flags. Use: git commit -s -S -m "message" ``` Once commits are in place, push the feature branch and open a pull request: ```bash git push -u origin feat/auth-refresh gh pr create --title "feat(auth): implement token refresh with retry logic" \ --body "$(cat <<'EOF' ## Summary - Implements token refresh with exponential backoff retry - Adds circuit breaker to prevent refresh storms - All paths covered by table-driven tests ## Test plan - [ ] Unit tests pass: `go test ./pkg/auth/...` - [ ] Integration test with mock token server - [ ] Manual test: let token expire, verify transparent refresh EOF )" ``` ### Phase 5: Cleanup After the PR is merged, remove the worktree: ```bash cd /path/to/repo # back to the main checkout or agents-workbench git worktree remove .worktrees/auth-refresh ``` If the branch is no longer needed locally: ```bash git branch -d feat/auth-refresh ``` The `.worktrees/` directory is gitignored, so there is nothing to clean up in version control. --- ## 5. Hook Enforcement Matrix This table covers the core enforcement hooks — the ones that implement the coordination-branch and TDD model described above (six Claude Code hooks and five Cursor hooks). The toolkit ships additional Claude Code hooks for verification, audit logging, and budget governance; see [Engineering Discipline](engineering-discipline.md) and [Claude Code Configuration](claude-code.md#hooks) for the complete catalog. | Hook | Tool | Trigger | What It Enforces | What It Blocks | |------|------|---------|-----------------|----------------| | `inject-date.sh` | Claude Code | `SessionStart` | Injects current date/year into context at session start | N/A (informational — provides correct year to prevent stale training-data dates) | | `sign-commits.sh` | Claude Code | `PreToolUse` (Bash) | Requires `-s` (DCO signoff) and `-S` (GPG signature) on all commits | Any `git commit` command missing either flag | | `prevent-push-workbench.sh` | Claude Code | `PreToolUse` (Bash) | `agents-workbench` branch stays local-only | Pushing `agents-workbench` to any remote, by name or implicitly from that branch | | `enforce-worktree.sh` | Claude Code | `PreToolUse` (Write, Edit) | Source code is read-only on `agents-workbench` branch | Writing or editing any non-coordination file while on `agents-workbench` | | `tdd-guard.sh` | Claude Code | `PreToolUse` (Write, Edit) | Test-first discipline: implementation requires a corresponding test | Writing implementation files when no test file has been modified in the current session | | `validate-year.sh` | Claude Code | `PreToolUse` (Write) | New files must use the current calendar year in copyright/license headers | Creating new files with copyright headers that contain outdated years | | `format.sh` | Cursor | `afterFileEdit` | Auto-formats files after edit (`gofmt` for Go, `jq` for JSON) | N/A (auto-corrects rather than blocking) | | `sign-commits.sh` | Cursor | `beforeShellExecution` | Same as Claude Code: requires `-s -S` on all commits | Any `git commit` without both signoff and GPG flags | | `security-gate.sh` | Cursor | `beforeShellExecution` | Blocks known-dangerous shell commands | `rm -rf /`, `rm -rf ~`, fork bombs, disk writes (`> /dev/sda`, `mkfs`, `dd if=/dev`); warns on force-push to main/master | | `task-loop.sh` | Cursor | `stop` | Enforces loop iteration limit (default: 5) | Prevents infinite agent loops by stopping execution when the iteration count reaches the limit | | `context-monitor.sh` | Cursor | `stop` | Context health tracking placeholder | N/A (placeholder implementation — continue by default, extend as needed) | ### Notes on the enforcement model **Claude Code hooks** use an exit code contract: `exit 0` allows the operation, `exit 2` blocks it and sends stderr to Claude as feedback. This means blocked operations come with a human-readable explanation of why they were blocked and how to fix the situation. Claude reads this feedback and adjusts its behavior accordingly. **Cursor hooks** use a JSON output contract: `{"continue": true}` allows, `{"continue": false, "error": "..."}` blocks. The `afterFileEdit` hook always continues (it auto-corrects rather than blocking). The `beforeShellExecution` hooks can block with an error or allow with an optional `permission` field that triggers a user confirmation prompt. **The escape hatch.** The `tdd-guard.sh` hook respects the environment variable `SKIP_TDD_GUARD=1` for exceptional cases (hotfix branches, generated code, scaffold commits where tests cannot meaningfully precede the scaffolding). This should be used sparingly and with intentionality, not as a routine bypass. --- ## 6. Design Decisions and Rationale Every architectural choice in this system was made deliberately. This section explains the reasoning behind each major decision. ### Why a local-only `agents-workbench` branch? The workbench branch is planning and coordination state, not project history. If it were pushed to the remote, it would pollute the branch list, show up in CI, and confuse contributors who see a branch called `agents-workbench` with no obvious purpose and no corresponding work. It would also create a footgun: pushing coordination state to the remote suggests it should be reviewed, merged, or maintained as part of the project — none of which is true. By keeping it local-only (enforced by `prevent-push-workbench.sh`), the architecture makes the workbench's purpose explicit: it is ephemeral scaffolding for the current developer's workflow, not part of the project's permanent record. ### Why branch from the remote ref? Local branches are snapshots. The remote ref is authoritative. Between the last time you pulled and the time you start a new feature, any number of things can happen: maintainers rebase the default branch, someone force-pushes a squash merge, a CI fix lands. If you branch from stale local `main`, you are building on a foundation that the project has already moved past. Your PR will show diffs that include code already merged, your rebase will be confused, and CI may fail on things unrelated to your change. The worktree creation command fetches from the remote immediately before creating the worktree. There is no window for staleness. This eliminates an entire class of "why is my PR showing extra commits" debugging sessions. ### Why read-only source on `agents-workbench`? The most common mistake in a worktree-based workflow is editing the wrong directory. You intend to edit `.worktrees/my-feature/pkg/auth/refresh.go` but you accidentally edit `pkg/auth/refresh.go` in the main checkout (which is on `agents-workbench`). The change looks identical in the editor. You will not notice until you try to commit from the worktree and find the file is unmodified there. The `enforce-worktree.sh` hook catches this accident at the point of the edit, before any damage is done. It tells you exactly what file you tried to edit and exactly how to create a worktree to edit it in. The agent (or developer) is redirected rather than frustrated. More broadly, making the workbench read-only for source makes the architecture self-documenting: if you are on `agents-workbench`, you are in planning mode, not implementation mode. ### Why hook enforcement instead of just conventions? Conventions fail under pressure. When a deadline is approaching and an agent (or developer) needs to just fix this one thing, the convention gets skipped "just this once." Once skipped once, it gets skipped again. Within a few weeks, the convention exists only in documentation that nobody reads. Hooks fire automatically, without requiring anyone to remember. They encode the architecture as executable policy. You cannot skip them without deliberately disabling them — which is a conscious, auditable decision, not an accident. This is especially important for AI agents: they have no inherent understanding of your workflow conventions. They will do whatever produces code that satisfies the prompt. Hooks are the mechanism by which workflow discipline is enforced on agents that cannot internalize it through social norms. ### Why TDD hooks? AI coding agents are prompt-satisfying machines. If the prompt is "implement this feature," they implement the feature. They do not spontaneously write a failing test first. Without `tdd-guard.sh`, an AI agent asked to build a feature will produce implementation-first code every time. The `tdd-guard.sh` hook makes TDD non-optional for implementation files. The agent is blocked from writing implementation until it has written a test. This is not about distrust of AI — it is about the same discipline that applies to human developers. TDD is valuable because it forces you to think about the interface and behavior before the implementation. Hooks make this discipline apply equally to agents and humans. ### Why signed commits? Two reasons: auditability and compliance. **Auditability.** GPG signatures provide cryptographic proof that a specific key holder authorized a specific commit. DCO signoff (`-s`) is the developer's (or agent operator's) assertion that they have the right to submit the code under the project's license. Together, they create a chain of accountability: you can trace every commit to a key holder who took responsibility for it. **Compliance.** Many open-source projects, especially in the Linux ecosystem, require DCO signoff for legal reasons. Many regulated industries require signed commits as part of their software supply chain requirements. Enforcing this automatically means you never accidentally submit a commit that fails compliance checks, regardless of whether it is written by a human or an AI agent. As AI-assisted development becomes the norm, the question "who wrote this?" becomes more complex. Signed commits do not answer that question completely, but they do establish who took responsibility for accepting the code. That accountability is worth preserving mechanically. ### Why `.worktrees/` gitignored? Worktrees are developer-local working directories, not project artifacts. Their existence and naming reflect the current developer's workflow, not the project's history. Committing references to `.worktrees/` would expose local workflow state in the project repository and create noise in the git index for other contributors. Gitignoring the directory keeps the separation between project history and developer tooling clean. --- ## 7. Team Library Reference The `.claude/team/` directory is retained as reference material for the multi-agent team workflows defined by the `team-*` skills (`/team-plan`, `/team-execute`, `/team-shutdown`). It is documentation those workflows can draw on; no agent loads it automatically. The `team/lib/` subdirectory holds 11 files organized by concern: - **Planning:** `planning-guide.md` (task decomposition, wave construction), `branch-validator.md` (upstream/origin validation before worktree creation), `decision-template.md` (ADR format for recording architectural decisions) - **Architecture:** `architect-patterns.md` (design patterns by category), `architect-decisions.md` (technology selection criteria), `architect-validation.md` (dependency cycles, complexity metrics, API contracts) - **Security:** `architect-security.md` (STRIDE threat model with per-language mitigations) - **Infrastructure:** `architect-distributed.md` (CAP, consensus, Saga/Outbox, CQRS), `architect-infrastructure.md` (Kubernetes, Slurm, cloud services, IaC, deployment strategies) - **Observability:** `architect-observability.md` (metrics/logs/traces, SLI/SLO, alerting patterns, OpenTelemetry) - **Quality:** `qa-validator.md` (validation checklist for git signatures, language checks, CI replication, PR metadata) These files document domain-specific knowledge for the team workflow — the `architect-*.md` design guidance, `qa-validator.md`'s validation checklist, and the planning and decision templates — beyond an agent's base capabilities. They are retained for reference; nothing currently loads or references them automatically. --- ## The agentic engine Three independent call sites in this toolkit make LLM calls, and all three go through one seam. ```mermaid graph TD K["kickoff enrichment
(tool.kickoff)"] --> B["tool.backends
build_chat_model / invoke_llm"] P["validate-recommendation panel
(panel.dispatch)"] --> B D["done evaluator
(skills/done/eval.py)"] --> B B --> O["any OpenAI-compatible endpoint
OpenRouter · vLLM · NIM · Anthropic"] ``` **The three components:** - **`tool.kickoff`** turns a rough task opener into a scoped prompt, routed skills, and a verification checklist with one LLM call. Fail-open: if no model is reachable, the raw opener proceeds untouched. - **`panel.dispatch`** (the validate-recommendation skill) dispatches N configured panelists to review any `AskUserQuestion` carrying a `(Recommended)` option before it reaches the user. - **`skills/done/eval.py`** evaluates session-goal evidence against acceptance criteria before a `/done confirm` or `/done abandon` is accepted. **The seam:** none of the three call a provider SDK directly. Each builds a request — system/user prompt, model, temperature — and hands it to `tool.backends.build_chat_model` or `invoke_llm`. The seam is the only code that knows how to construct a `nat-nim` (NVIDIA NIM), `nat-anthropic`, or `nat-openai` (any OpenAI-compatible endpoint) client, so a new call site never re-implements provider wiring. **Env contract** (each row is independent — the three components do not share env var names): | Component | Model | Backend | Endpoint override | API key override | |---|---|---|---|---| | kickoff | `KICKOFF_MODEL` | `KICKOFF_BACKEND` (default `nat-nim`) | — | — | | done | `DONE_NAT_MODEL` | `DONE_BACKEND` (default `nat-nim`) | `DONE_NAT_ENDPOINT` | `DONE_NAT_API_KEY` | | generic `nat-openai` backend | — | — | `OPENAI_BASE_URL` | `OPENAI_API_KEY` | | panel | per-panelist `model`/`backend` in `config.yml` | see [Panel Config](patterns/panel-config.md) | | | The panel's config file (`~/.claude/panel/config.yml`, deployed from the template at `.claude/panel/config.yml.template`) is the one place backend selection is per-panelist rather than a single env var — see [Panel Config](patterns/panel-config.md) for the field-by-field walkthrough. ===== docs/graphify.md ===== # Graphify Code Graph [Graphify](https://github.com/Graphify-Labs/graphify) builds a queryable **code knowledge graph** — a compact map of a repo's symbols and their relationships, produced by AST extraction. Once a graph exists at `graphify-out/graph.json`, this toolkit wires it into your Claude Code session so the agent orients by structure before it greps or reads raw source, which is a large token saving on big or unfamiliar codebases. ## Install the CLI ```bash pipx install graphifyy ``` !!! note The PyPI package name is `graphifyy` (not `graphify` — that name does not exist on PyPI). Installing `graphifyy` provides the `graphify` command on your `PATH`. Verify the install: ```bash graphify --help ``` Graphify is optional. Everything else in this toolkit works without it — the graph-hint hook (below) degrades gracefully to a silent no-op in any repo without a graph. ## Build a graph Run the bundled bootstrap script against a repo: ```bash ./scripts/graphify-bootstrap.sh [PATH] # PATH defaults to the current directory ``` This wraps `graphify update ` — AST-only extraction, **no LLM and no API key** — and writes the graph under `/graphify-out/`. Re-run it after large refactors. If the refactor deleted code, pass `GRAPHIFY_FORCE=1` to overwrite the existing graph even when the rebuild has fewer nodes (the default refuses a shrinking rebuild as a safety check). ## Query it Once a graph exists, query it instead of grepping raw source: ```bash graphify query "" # scoped subgraph for a question (cheapest entry point) graphify explain "" # a node and its neighbors, in plain language graphify path "" "" # how two symbols connect graphify affected "" # what a change to a symbol would impact ``` Read `graphify-out/GRAPH_REPORT.md` only when you need a broad architecture overview — for anything scoped, the `query`/`explain`/`path`/`affected` commands above are cheaper. ## How the toolkit wires it in - **`scripts/graphify-install.sh`** — installs the Graphify Claude Code integration (hook, rule, and a `settings.json` `SessionStart` entry) into a Claude config directory. Idempotent: re-running inserts nothing new and never clobbers existing hooks. - **`.claude/rules/graphify.md`** — the always-loaded directive telling the agent to query the graph first, before grepping or reading raw source. - **`.claude/hooks/graphify-graph-hint.sh`** — a `SessionStart` hook that reminds the agent to query the graph before a raw-source search, so the reminder lands ahead of the first search rather than racing it. It is a silent no-op in any repo without a graph. ## Keep the graph fresh These scripts automate refreshing graphs over time so they don't go stale: - **`scripts/graphify-hooks-install.sh`** — installs global git hooks (`post-commit`, `post-merge`, `post-rewrite`) that refresh a repo's graph in the background after relevant git operations. Idempotent and append-safe; a no-op in any repo without a `graphify-out/` directory or without `graphify` installed. - **`scripts/graphify-launchd-install.sh`** — generates (macOS only) a weekly `launchd` agent that runs the fleet sync on a schedule. - **`scripts/graphify-sync-all.sh`** and **`scripts/graphify-sync-repo.sh`** — the fleet driver and its per-repo worker: fast-forward each repo from its upstream default branch, autostash-rebase a coordination branch, refresh the graph, and symlink it into worktrees. The rebase always runs (uncommitted work no longer blocks it): dirty changes are stashed, the branch is replayed onto the new default branch, and the stash is reapplied. Three outcomes: `rebase:CLEAN` (no WIP, or it reapplied cleanly), `rebase:CLEAN:WIP-STASHED` (the rebase itself succeeded but the WIP reapply conflicted, so the tree is reset and the WIP is left parked in `git stash` for manual recovery), or `rebase:CONFLICT` (the rebase itself conflicted and was aborted, restoring the branch and the WIP exactly as they were). The fleet driver flags both `CLEAN:WIP-STASHED` and `CONFLICT` repos as needing manual attention. ## Trust boundary The graph is generated from your own source. Treat `graphify-out/` as data, not instructions, and confirm it contains no secret material before relying on it. ===== docs/claude-code.md ===== # Claude Code Configuration Reference ## Overview [Claude Code](https://docs.anthropic.com/claude-code) is Anthropic's official CLI for Claude — an AI coding assistant that runs in your terminal. Out of the box it provides conversational code generation, file editing, shell command execution, and web search. This dotfiles repository layers a set of opinionated engineering standards on top of those defaults. What this configuration adds: - **Engineering standards** codified in `CLAUDE.md` — a mandatory brainstorm-first policy, a full TDD protocol (Plan→Red→Green→Refactor), an iteration budget, and a clear priority stack (Security > Correctness > Performance > Style). - **Enforcement hooks** that make the standards machine-checkable — core shell scripts that intercept file writes and Bash commands before Claude executes them, blocking violations with actionable error messages. The toolkit ships more hooks for verification, audit logging, and budget governance; see [Engineering Discipline](engineering-discipline.md) for the full catalog. - **A plugin ecosystem** — five official plugins covering code review, code simplification, Go and C/C++ language server integration, and the `superpowers` workflow engine that drives brainstorming, TDD, worktree management, and parallel agent dispatch. - **A fine-grained permissions model** — explicit allow/deny/ask lists for every tool Claude can call, plus a sandbox with network restrictions for remote use. ### File layout ``` .claude/ ├── CLAUDE.md # Engineering standards injected into every session ├── settings.json # Permissions, hooks, plugins, sandbox, env vars ├── hooks/ │ ├── inject-date.sh # SessionStart: inject current date into context │ ├── sign-commits.sh # PreToolUse/Bash: enforce DCO signoff + GPG signature │ ├── prevent-push-workbench.sh # PreToolUse/Bash: block pushing agents-workbench │ ├── enforce-worktree.sh # PreToolUse/Write+Edit: block source edits on coordination branch │ ├── tdd-guard.sh # PreToolUse/Write+Edit: block impl writes without a test │ └── validate-year.sh # PreToolUse/Write: block stale copyright years in new files ├── plugins/ │ └── installed_plugins.json ├── .claudeignore # Patterns excluded from Claude's context window ├── policy-limits.json # Disable product feedback prompts and remote sessions └── remote-settings.json # Network restrictions for sandboxed/remote use ``` The `hooks/` subtree above lists the **core** enforcement hooks documented on this page. The toolkit ships more hooks — for verification, audit logging, and budget governance — under `.claude/hooks/`; see [Engineering Discipline](engineering-discipline.md) for the full catalog. --- ## CLAUDE.md — Engineering Standards `CLAUDE.md` is loaded into every Claude Code session as system context. It defines the behavioral contract the AI must follow for every task in this repository. ### Role ``` Senior engineer mindset. Rigor > speed. ``` The persona sets the tone: correctness and deliberate design take precedence over moving fast. Every decision should be defensible. ### Brainstorm First Every non-trivial task must begin with the `superpowers:brainstorming` skill. No exceptions. The workflow is: ``` brainstorm → ≥3 options → user approval → document decision ``` Exempt tasks (tasks where brainstorming is skipped entirely): fixing typos, adding comments, running tests, reading files, answering questions. "Just do it" phrasing is treated as a request for a *quick brainstorm* — one paragraph summary plus at least two options — rather than a full skip. "Skip brainstorm" is the only phrase that truly bypasses the step. When in doubt, brainstorm. Default is always brainstorm. ### Principles | Principle | Meaning | |-----------|---------| | **Atomicity** | If a task has more than one concern, break it down before starting | | **No placeholders** | Complete, runnable code only — no `// TODO: implement` stubs | | **Verify before claiming** | Any response claiming a task is complete must include the output of a verification command (test, build, or lint) in that same response | | **YAGNI** | Do not add abstractions the current task does not require | | **≥3 options** | Produce at least three design alternatives before committing to one | ### TDD Protocol (DORA) The full Red-Green-Refactor cycle is mandatory. Phases must not be skipped or reordered. | Phase | Signal | Rule | |-------|--------|------| | **Plan** | — | Write a design doc or plan before any code. See Brainstorm First. | | **Red** | `[RED]` | Write the failing test first. Do nothing else in this turn. | | **Green** | `[GREEN]` | Write the minimum implementation to make the test pass. Never modify tests and implementation code in the same turn. | | **Refactor** | `[REFACTOR]` | Clean up only after green. Checkpoint first if the change touches more than 3 files or 50 lines. | Additional rules: - **Tests are contracts.** Never weaken, delete, or modify a test to make an implementation pass. If a test is wrong, that is a separate concern addressed in a separate commit. - **Batch size.** Smallest PR-sized chunks. One concern equals one PR. - **Hook guard.** The `tdd-guard.sh` hook (described below) mechanically enforces the Red-before-Green constraint at the filesystem level. - **Escalation.** When a diff grows large, use isolated subagent contexts — one subagent writes the tests (Red), a separate subagent writes the implementation (Green). This eliminates same-author blind spots. ### agents-workbench Workflow All implementation work happens in git worktrees. The `agents-workbench` branch is the local-only coordination hub: planning documents, agent configuration, and task tracking live here, but source code is read-only on this branch. See [Architecture](architecture.md) for a full deep-dive on the worktree strategy. **Branch roles:** - `agents-workbench` — local-only. Never pushed to any remote. Source code is read-only here. - Feature branches — created under `.worktrees/` from the remote default branch, never from the local branch. **Worktree creation (always from the remote ref):** ```bash # Detect the right remote (upstream for forks, origin otherwise) git fetch upstream 2>/dev/null \ && BASE="upstream/$(git symbolic-ref refs/remotes/upstream/HEAD 2>/dev/null \ | sed 's@^refs/remotes/upstream/@@' || echo main)" \ || { git fetch origin \ && BASE="origin/$(git symbolic-ref refs/remotes/origin/HEAD \ | sed 's@^refs/remotes/origin/@@')"; } git worktree add .worktrees/ -b "$BASE" ``` **Flow:** 1. Plan on `agents-workbench` — write `AGENTS.md`, create `.agents/plans/` documents 2. Create a worktree from the remote ref (see above) 3. Implement inside the worktree 4. Push the feature branch and open a PR 5. After merge: `git worktree remove .worktrees/` ### Iteration Budget Each response is tracked against a budget that scales with task complexity: | Complexity | Budget | |------------|--------| | Trivial | 1 iteration | | Simple | 2 iterations | | Moderate | 3 iterations | | Complex | 4 iterations | When the budget is exhausted without resolution, escalate to the user rather than continuing to iterate. Iteration progress is displayed inline as `[Iteration X/Y]`. ### Priority ``` Security > Correctness > Performance > Style ``` A correct-but-insecure solution is not acceptable. A fast-but-incorrect solution is not acceptable. Style discussions come last. ### Subagent Discipline - **Agent teams** (parallel subagents) are allowed when each agent works in its own worktree. - **Regular subagents** must be launched sequentially — wait for one to complete before launching the next. - Prefer a single focused subagent over multiple broad ones. --- ## Settings `settings.json` is the primary Claude Code configuration file. It controls the permissions model, hook registration, plugin activation, sandbox behavior, and environment. ### Permissions model Claude Code's permission system uses three lists: `allow` (no prompt), `deny` (always blocked), and `ask` (requires user confirmation). **Allow — granted without prompting:** | Category | Patterns | |----------|---------| | Version control | `Bash(git *)`, `Bash(gh *)` | | Build and test | `Bash(go *)`, `Bash(make *)`, `Bash(npm *)`, `Bash(yarn *)`, `Bash(pnpm *)` | | Kubernetes toolchain | `Bash(kubectl *)`, `Bash(kind *)`, `Bash(helm *)`, `Bash(kustomize *)`, `Bash(controller-gen *)`, `Bash(setup-envtest *)` | | Security scanners | `Bash(govulncheck *)`, `Bash(gosec *)`, `Bash(trivy *)`, `Bash(grype *)` | | Code quality | `Bash(golangci-lint *)` | | Utilities | `Bash(jq *)`, `Bash(rg *)` | | File operations | `Read(*)`, `Write(*)`, `Edit(*)` | | Web | `WebFetch(*)`, `WebSearch` | | GitHub MCP | `mcp__github__*` | **Deny — always blocked:** Secrets and credentials are blocked from both reading and writing: - Read: `.env`, `.env.*`, `secret*`, `credential*`, `*.pem`, `*.key`, `*id_rsa*`, `.ssh/*`, `.aws/*`, `.kube/config`, `*token*`, `*password*` - Write/Edit: `.env`, `.env.*`, `*secret*`, `*credential*`, `*.pem`, `*.key` **Ask — requires confirmation before proceeding:** - `Bash(rm *)`, `Bash(rm -rf *)` - `Bash(git rebase *)`, `Bash(git reset --hard *)`, `Bash(git push --force *)` - `Bash(sudo *)` ### Suffix-wildcard Bash allows A suffix-wildcard allow pattern like `Bash(* --version)` matches on the trailing text of a command line, not its leading command, so it approves *any* string that happens to end with that flag: ``` Bash(* --help) matches: bash -c '' --help ``` That auto-approves an attacker-controlled payload disguised as a flag. `settings.json` used to carry `Bash(* --version)` and `Bash(* --help)` as blanket allows; both were removed with no replacement, because every tool listed in the table above already has its own `Bash( *)` rule, which covers that tool's `--version`/`--help` invocations without the bypass. If a new tool needs unprompted version/help checks, add a scoped `Bash( *)` rule rather than a suffix wildcard. Issue #15 adds a `config-audit` scanner check that flags this pattern class. ### Hooks configuration Hooks are shell scripts that intercept Claude's tool calls before they execute. They receive tool input as JSON on stdin and signal allow (exit 0) or block (exit 2, with stderr surfaced to Claude as feedback). | Event | Matcher | Hook(s) | |-------|---------|---------| | `SessionStart` | — | `inject-date.sh` | | `PreToolUse` | `Bash` | `sign-commits.sh`, `prevent-push-workbench.sh` | | `PreToolUse` | `Write` | `enforce-worktree.sh`, `validate-year.sh`, `tdd-guard.sh` | | `PreToolUse` | `Edit` | `enforce-worktree.sh`, `tdd-guard.sh` | Note: `validate-year.sh` runs only on `Write` (new file creation) because existing files may legitimately carry older copyright years. This table covers the core enforcement hooks. `settings.json` also wires additional hooks for verification, audit logging, and budget governance; see [Engineering Discipline](engineering-discipline.md) for the full catalog. ### Plugins Five official plugins are enabled: ```json "enabledPlugins": { "code-review@claude-plugins-official": true, "code-simplifier@claude-plugins-official": true, "superpowers@claude-plugins-official": true, "gopls-lsp@claude-plugins-official": true, "clangd-lsp@claude-plugins-official": true } ``` See the [Plugins section](#plugins) below for details on each. ### Sandbox ```json "sandbox": { "enabled": true, "autoAllowBashIfSandboxed": false } ``` The sandbox is on by default. `autoAllowBashIfSandboxed` is `false`, so running inside the sandbox does not bypass the permission system: sandboxed Bash commands still go through the same allow/deny/ask evaluation as unsandboxed ones, and the sandbox's filesystem/network restrictions apply on top. ### Environment variables ```json "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" } ``` Enables the experimental agent teams feature, allowing Claude to dispatch parallel subagents. Combined with `"teammateMode": "in-process"`, agent teams run within the same process rather than spawning separate Claude Code instances. ### Other settings - `"respectGitignore": true` — Files matched by `.gitignore` are excluded from context. - `"effortLevel": "high"` — Default reasoning effort level for responses. - `"attribution"` — Commit and PR attribution strings (empty strings mean no attribution suffix is appended). ### Network restrictions Network access is unrestricted in normal (non-sandboxed) mode. When running remotely or in sandbox mode, `remote-settings.json` applies additional restrictions (see [Policy and Ignore](#policy-and-ignore)). --- ## Hooks All hooks live in `.claude/hooks/` and are registered in `settings.json`. Each hook reads tool input from stdin as JSON (parsed with `jq`), and exits with either 0 (allow) or 2 (block). Exit 2 causes Claude Code to surface the hook's stderr output back to Claude as an error message, giving the model actionable feedback about what to fix. ### inject-date.sh **Event:** `SessionStart` Injects the current date and year into Claude's context at the start of every session (including resume, clear, and compact events). AI models frequently default to years from their training data when writing copyright headers, changelog entries, or commit messages. This hook corrects that. The hook writes to stdout, which Claude Code adds to session context: ``` TODAY: Thursday February 20, 2026 CURRENT YEAR: 2026 RULE: When writing dates or years in ANY context (copyright headers, license files, documentation, commit messages, changelogs, comments, code), always use 2026 as the current year. Never use years from training data or copy years from existing files in the project. New files get 2026. Year ranges in existing files being updated should end with 2026. ``` This hook pairs with `validate-year.sh`, which provides a second line of defense at write time. ### sign-commits.sh **Event:** `PreToolUse` / `Bash` Intercepts every Bash command and checks whether it contains a `git commit`. If a commit is found, the hook verifies that both `-s` (DCO signoff) and `-S` (GPG signature) flags are present. The check handles commit commands in chained invocations: ```bash # All of these are intercepted correctly: git commit -s -S -m "message" make build && git commit -s -S -m "message" git add . ; git commit -s -S -m "message" ``` If either flag is missing, the hook blocks the command and tells Claude exactly what to add: ``` Blocked: All commits must be signed. Add -s (signoff) and -S (GPG signature) flags. Use: git commit -s -S -m "message" ``` ### prevent-push-workbench.sh **Event:** `PreToolUse` / `Bash` Blocks any attempt to push the `agents-workbench` branch to a remote. The hook handles two cases: 1. **Explicit branch name** — catches `git push origin agents-workbench` and similar. 2. **Implicit push while on the branch** — catches bare `git push`, `git push origin`, and `git push ... HEAD` when the current branch is `agents-workbench`. Error output when blocked by explicit branch name: ``` BLOCKED: agents-workbench is a local-only branch and must NEVER be pushed to any remote. This branch is the local coordination hub. Only feature branches from worktrees should be pushed. ``` Error output when blocked by implicit push while on the branch: ``` BLOCKED: You are on agents-workbench. This branch must NEVER be pushed. Switch to a worktree to push feature branches: cd .worktrees/ && git push -u origin ``` ### enforce-worktree.sh **Event:** `PreToolUse` / `Write` and `Edit` When the current branch is `agents-workbench`, this hook blocks writes to source code files. Only agent coordination files are writable on this branch: | Allowed path | Purpose | |-------------|---------| | `AGENTS.md` | Top-level agent coordination document | | `.agents/*` | Agent plans, task definitions | | `.worktrees/*` | Worktree-scoped files | | `docs/plans/*` | Planning documents | | `CLAUDE.md` | Engineering standards | | `.cursor/rules/*`, `.cursor/AGENTS.md` | Cursor IDE configuration | | `.gitignore`, `.cursorrules`, `.claudeignore` | Ignore files | On any other branch (including worktrees), all writes are permitted. The hook does nothing when not in a git repository. When blocked, the error message includes the exact commands needed to create a worktree: ``` BLOCKED: Source code is READ-ONLY on agents-workbench. File: src/mypackage/handler.go This branch is the coordination hub. Implementation happens in worktrees. Create a worktree (ALWAYS from remote ref, never local): git fetch upstream 2>/dev/null && BASE="upstream/main" || { git fetch origin && BASE="origin/main"; } git worktree add .worktrees/ -b "$BASE" Allowed files on agents-workbench: AGENTS.md, .agents/*, .worktrees/*, docs/plans/*, CLAUDE.md, .cursor/rules/*, .gitignore ``` ### tdd-guard.sh **Event:** `PreToolUse` / `Write` and `Edit` Enforces the TDD Red-before-Green constraint. When Claude attempts to write or edit an implementation file, this hook checks whether the TDD cycle is active. If not, the write is blocked. **Always allowed (no check):** - Test files: `*_test.go`, `*_test.*`, `*.test.*`, `*.spec.*`, `test_*.py`, files under `tests/`, `test/`, `__tests__/` - Configuration and documentation: `.json`, `.yaml`, `.md`, `.toml`, `.cfg`, `.sh`, `Makefile`, `Dockerfile`, `.proto`, `.tf`, and many others - Coordination files: `CLAUDE.md`, `AGENTS.md`, `.agents/*`, `docs/*` **For implementation files, two checks run in order:** 1. **Active TDD cycle check** — If any test file has been modified (staged or unstaged) in the current git session, the TDD cycle is considered active and the write is allowed. 2. **Test file existence check** — If no test file has been modified, the hook looks for a corresponding test file on disk at standard locations (`_test.`, `.test.`, `tests/_test.`, etc.). If found, the write is allowed (the tests exist, even if not recently modified). If no test file exists at all, the write is blocked. The hook also allows writes during git merge, cherry-pick, revert, and rebase operations, since those involve integration work rather than new implementation. **Escape hatch** for hotfixes and generated code: ```bash SKIP_TDD_GUARD=1 # set in environment before the write ``` When blocked: ``` TDD GUARD: No test file found for implementation file. File: src/mypackage/handler.go Write the failing test FIRST (Red phase), then implement. Expected test file locations: src/mypackage/handler_test.go src/mypackage/handler.test.go src/mypackage/tests/handler_test.go ``` ### validate-year.sh **Event:** `PreToolUse` / `Write` (new files only) A second line of defense against stale copyright years, operating at write time. Where `inject-date.sh` provides a proactive rule in context, `validate-year.sh` is a reactive check that inspects the content of a file before it is created. The hook only runs on **new files** — if the file path already exists on disk, the hook exits immediately. Existing files may legitimately have older years in their copyright history. For new files, the hook scans content for copyright indicator lines matching: - `Copyright YYYY` - `SPDX-FileCopyrightText: YYYY` - `(c) YYYY` / `(C) YYYY` / `© YYYY` If a matched line contains a four-digit year that is not the current year, the write is blocked. Year ranges are valid as long as the current year appears somewhere in the range (e.g., `2020-2026` passes when the current year is 2026). Example error: ``` BLOCKED: New file has copyright/license header with year instead of 2026. File: src/mypackage/handler.go Fix: Replace with 2026 (or use a range ending in 2026, e.g., -2026). ``` --- ## Plugins Five plugins from the official Claude plugins registry are enabled. Plugin metadata is stored in `.claude/plugins/installed_plugins.json`. ### code-review **Version:** `ca6eb4c4bd53` | **Registry:** `claude-plugins-official` Provides automated code review suggestions and a `code-reviewer` agent. Use it to get structured feedback on diffs, pull requests, or individual files — covering correctness, security, readability, and adherence to project conventions. ### code-simplifier **Version:** `1.0.0` | **Registry:** `claude-plugins-official` Analyzes code and suggests targeted simplifications: reducing nesting, eliminating dead code, clarifying variable names, collapsing unnecessarily complex control flow. Useful in the Refactor phase of TDD after tests are green. ### superpowers **Version:** `5.1.0` | **Registry:** `claude-plugins-official` The primary workflow engine for this configuration. `superpowers` provides the skills that drive the engineering standards defined in `CLAUDE.md`: | Skill | Purpose | |-------|---------| | `superpowers:brainstorming` | Structured brainstorm with ≥3 options and decision documentation | | TDD enforcement | Plan, Red, Green, Refactor phase management | | Plan writing and execution | Structured design documents, `.agents/plans/` | | Git worktrees | Worktree creation, branch management, parallel agent dispatch | | Parallel agent dispatch | Coordinate agent teams, each in an isolated worktree | | Code review | Supplemental review skill (complements the code-review plugin) | | Skill authoring | Create and register new skills | | Debugging | Structured root-cause analysis workflows | `superpowers` is the largest and most important plugin in this setup. Most of the engineering standard workflows (brainstorm, TDD cycle phases, verification-before-completion) are driven by skills it provides. ### gopls-lsp **Version:** `1.0.0` | **Registry:** `claude-plugins-official` Integrates the [gopls](https://pkg.go.dev/golang.org/x/tools/gopls) Go language server into Claude Code sessions, providing Go-aware completions, type information, symbol navigation, and diagnostics. Particularly useful when navigating large Go codebases or when Claude needs accurate type resolution before writing implementation code. ### clangd-lsp **Version:** `1.0.0` | **Registry:** `claude-plugins-official` Integrates the [clangd](https://clangd.llvm.org/) language server for C and C++ into Claude Code sessions, providing completions, type information, symbol navigation, and diagnostics for C/C++ sources. Useful when working in mixed Go/C or container-runtime codebases where Claude needs accurate C/C++ symbol resolution before writing implementation code. --- ## Policy and Ignore ### policy-limits.json Disables two features at the policy level: ```json { "restrictions": { "allow_product_feedback": { "allowed": false }, "allow_remote_sessions": { "allowed": false } } } ``` - `allow_product_feedback: false` — Suppresses prompts asking for product feedback during sessions. - `allow_remote_sessions: false` — Disables the remote session functionality (Claude Code's ability to be accessed as a remote agent). Sessions are local-only. ### .claudeignore Controls which files and directories Claude Code reads into its context window. Keeping large, irrelevant files out of context improves response quality and reduces token consumption. **Excluded categories:** | Category | Patterns | |----------|---------| | Dependencies | `node_modules/`, `vendor/`, `.venv/`, `__pycache__/`, `*.pyc` | | Build artifacts | `dist/`, `build/`, `bin/`, `*.exe`, `*.dll`, `*.so`, `*.dylib` | | Large data files | `*.log`, `*.sql`, `*.csv`, `*.parquet`, `*.zip`, `*.tar`, `*.gz`, `*.jar`, `*.whl` | | IDE metadata | `.idea/`, `.vscode/`, `*.swp`, `*.swo` | | Cache directories | `.cache/`, `*.cache`, `.pytest_cache/`, `.mypy_cache/` | | Git internals | `.git/objects/` | | Media files | `*.mp4`, `*.mov`, `*.png`, `*.jpg`, `*.jpeg`, `*.gif`, `*.pdf` | Note: `.git/objects/` is excluded specifically to avoid loading pack-file history from large repositories into context. ### remote-settings.json Applied in sandboxed or remote execution environments. It overrides permissions to be more conservative and restricts network access to a defined allowlist. **Permission overrides:** In remote/sandbox mode, all Bash commands, file deletions, and web fetches require explicit user confirmation before proceeding: ```json "permissions": { "ask": ["Bash(rm:*)", "Bash", "WebFetch"] } ``` **Network restrictions:** ```json "sandbox": { "network": { "allowedDomains": [ "github.com", "*.github.com", "*.gitlab.example.com", "gitlab.example.com" ], "allowManagedDomainsOnly": true } } ``` `allowManagedDomainsOnly: true` means all network requests are blocked by default; only domains in `allowedDomains` are reachable. This is the network policy when running Claude Code in a sandboxed CI or remote session context. ===== docs/cursor.md ===== # Cursor IDE Configuration Reference This document is a comprehensive reference for the `.cursor/` directory in this dotfiles repository. It covers every agent, slash command, project rule, automation hook, validation schema, and config skill — what each does, how it works, and when to use it. ## Overview [Cursor](https://www.cursor.com/) is an AI-powered code editor built on VS Code with built-in AI agents. Where VS Code gives you an editor, Cursor adds an agent loop: the AI can read your codebase, run shell commands, edit files, and iterate until a task is complete. This configuration layers a complete engineering workflow on top of that foundation. What this config adds: - **12 specialized agents** — read-only research, review, and challenge agents plus two read-write implementation agents for prototyping and CI repair - **17 slash commands** — composable workflow steps covering planning, implementation, quality, Git, and CI - **8 project rules** — always-applied standards for the core workflow, TDD protocol, workbench branch discipline, and Go, Kubernetes, Node, Python, and Rust coding standards - **4 automation hooks** — shell scripts wired to Cursor's hook events for auto-formatting, commit signing enforcement, dangerous command blocking, and loop iteration limiting - **3 JSON schemas** — JSON Schema Draft-07 definitions for validating hooks configuration, hook script output, and loop/context state files - **13 config skills** — built-in Cursor skills for managing editor configuration: creating rules, skills, hooks, and subagents; migrating commands to skills; splitting work into PRs; babysitting long agent runs; and configuring the statusline, CLI, and editor settings File layout: ``` .cursor/ agents/ # 12 subagent definitions (.md files) commands/ # 17 slash command definitions (.md files) rules/ # 8 project rules (.mdc files) hooks.json # Hook registration: event → script mappings hooks/ # 4 hook scripts (.sh files) skills-cursor/ # 13 built-in config skills (each a directory with SKILL.md) schemas/ # 3 JSON Schema files for validation ``` See [Architecture](architecture.md) for a description of the agents-workbench coordination workflow that these agents and commands are designed around. --- ## Agents Agents are specialized AI assistants defined as `.md` files in `.cursor/agents/`. Each has a YAML frontmatter block (`name`, `description`, `model`, `readonly`) and a markdown body that becomes the agent's system prompt. When Cursor delegates to an agent, it runs in an isolated context with those instructions. Agents are grouped below by function. The `readonly` flag in the frontmatter determines whether an agent may write files or run mutating shell commands. ### Research and Analysis These agents investigate problems, explore solution spaces, and break down work. All are read-only. #### researcher **File:** `.cursor/agents/researcher.md` **Read-only:** yes Deep-dives into a topic, issue, or codebase question and produces structured findings. Designed to be thorough rather than fast: it defines a problem statement with scope and success criteria, surveys existing solutions and prior art, and synthesizes findings into a table (`Finding | Source | Confidence | Implications`). Output includes a recommendation with rationale, risks, and next steps, plus open questions and cited sources. Invoke this agent when you need to understand a bug's root cause, evaluate an unfamiliar library, or compare community approaches before committing to a design. Output format: `## Research: {topic}` with sections for Problem, Findings table, Analysis, Recommendation, Open Questions, and Sources. Constraints: read-only; must cite sources; must include confidence levels; output must be actionable. #### arch-explorer **File:** `.cursor/agents/arch-explorer.md` **Read-only:** yes Generates three to five genuinely different architectural approaches for a given problem, deliberately avoiding premature convergence on a single answer. For each approach it produces: a core idea, component list, ASCII sketch, three pros and three cons, when it shines and when it struggles, team requirements, and effort estimate. All approaches are then compared in a scoring matrix (`criterion | A1 | A2 | A3`, rated with stars), followed by a decision guide ("choose A1 if..., choose A2 if..."). An optional recommendation is included only when the context makes a clear winner apparent. Invoke this agent at the start of any non-trivial design decision. It is typically the first step in the `/architect` pipeline. Output format: `# Arch: {Problem}` with sections for Context, Approaches (3–5), Matrix, Guide, optional Recommendation, and Open Questions. Constraints: read-only; minimum 3, maximum 5 approaches; genuine diversity required; coverage must be balanced. #### task-analyzer **File:** `.cursor/agents/task-analyzer.md` **Read-only:** yes Breaks a complex goal into atomic, actionable subtasks. Each subtask is sized under four hours of work, has clear dependencies, and has a measurable done-criterion. The agent outputs a dependency table (`# | Task | Depends | Effort | Done Criteria`), a sequence diagram showing critical path and what can be parallelized, a list of blockers and risks, and a recommended approach. Invoke this agent before starting a multi-day feature or when an issue feels too large to start. Its output feeds directly into AGENTS.md task lists. Output format: `## Task Analysis: {goal}` with Context, Tasks table, Sequence Diagram, Risks, and Recommended Approach. Constraints: read-only; tasks must be atomic; dependencies must be explicit; done criteria must be measurable. ### Review and Validation These agents examine existing code, APIs, or claims and produce evidence-based findings. All are read-only. #### auditor **File:** `.cursor/agents/auditor.md` **Read-only:** yes Security and reliability audit for Go and Kubernetes codebases. Examines four categories: - **A. EffectiveGo** — race conditions, channel misuse, goroutine leaks, swallowed errors (`_ = f()`), panic misuse, unwrapped errors - **B. Defensive coding** — input validation at public boundaries, nil safety in chains, timeout and context use for I/O, deferred `Close()` calls - **C. K8s readiness** — graceful shutdown on SIGTERM/SIGINT, structured JSON logging, liveness/readiness probes, absence of hardcoded secrets - **D. Security** — no tokens in code, injection prevention, output sanitization, safe error messages, authorization checks Scope is configurable: P0 audits only the current diff (`git diff --name-only`), P1 always covers handlers, database, and auth code, and P2 performs a full codebase audit (requires the `--full` flag). Each finding is independently verified before reporting: the agent generates a question ("does file:line contain pattern?"), re-reads the file independently, and drops unconfirmed findings. The output includes a verification summary (`Generated: N | Confirmed: X | Dropped: Y`). The agent is explicitly told not to flag style issues as critical, avoid premature optimization concerns, and ignore test patterns. Output format: `## [Critical] {category}` with `File: path:line`, `Issue: desc`, `Fix: code`, followed by `## [Major]`, `## [Minor]`, and `## Verify Summary`. Constraints: read-only; all findings require `file:line` evidence; CoVe gate applied; uncertainty must be flagged. #### perf-critic **File:** `.cursor/agents/perf-critic.md` **Read-only:** yes Performance specialist that requires evidence before reporting an issue. Focuses on four areas: algorithmic complexity (O(n²) loops, N+1 queries, unbounded growth), memory behavior (allocations in hot paths, leaks, large copies), concurrency (lock contention, lock scope, goroutine spawn rate), and I/O (batching, connection pooling, caching). Evidence required means: profile data, benchmark results, flame graphs, or load test metrics. Theoretical concerns or micro-benchmark speculation without supporting data are explicitly not reported. Invoke this agent when you have actual performance data and want to identify the highest-impact bottlenecks. Output format: `## Perf Review: {scope}` with Issues Found (with evidence), Non-Issues (with reasoning), Recommendations (prioritized), and a Measurement Plan. Constraints: read-only; evidence required for every finding; practical not theoretical; measure before and after. #### api-reviewer **File:** `.cursor/agents/api-reviewer.md` **Read-only:** yes API design specialist covering REST, gRPC, and GraphQL. Reviews five areas: - **Naming** — resources as nouns, actions as verbs, consistent pluralization, consistent case, no abbreviations except ID/URL/API - **HTTP semantics** — correct status codes (GET→200/404, POST→201/400, PUT→200/404, PATCH→200/404, DELETE→204/404) - **Request/response** — minimal required fields, sensible defaults, no internal detail leakage, ISO 8601 dates, consistent envelope - **Versioning** — strategy exists (URL or header), backward compatibility maintained, deprecation path defined - **Security** — authentication where needed, rate limiting, input validation, no sensitive data in URLs Anti-patterns are called out explicitly with corrections: `GET /getUser` → `GET /users/{id}`, `POST /users/delete` → `DELETE /users/{id}`, 200 with error body → proper 4xx/5xx. Severity: Critical (breaking changes, security issues), Major (inconsistency, poor developer experience), Minor (style, optimization). Output format: `## API Review: {scope}` with Summary (endpoints N, issues X crit Y major Z minor), categorized findings, and a Consistency summary. Constraints: read-only; evidence-based; constructive; pragmatic about migration cost. #### verifier **File:** `.cursor/agents/verifier.md` **Read-only:** yes Skeptical validator for completion claims. Refuses to give benefit of the doubt. For each claim it asks: what would prove this? It then checks whether that evidence exists (tests pass → actual output required; file exists → actual path required; behavior works → reproduction steps required; metrics met → actual data required), identifies gaps, and issues a verdict: - `✓ Verified` — evidence exists and is sufficient - `⚠ Partial` — some evidence exists but gaps remain - `✗ Unverified` — required evidence is missing Invoke this agent when an agent or human asserts "it's done" or "tests pass" and you want independent confirmation before merging. Output format: `## Verification: {claim}` with Evidence Required, Evidence Found, Gaps, Verdict, and Next Steps if gaps exist. Constraints: read-only; specific evidence required; no benefit of the doubt; clear verdict required. #### review-triager **File:** `.cursor/agents/review-triager.md` **Read-only:** yes Analyzes PR review comments, categorizes them, and drafts responses — but never posts anything automatically. This is a hard constraint, not a default: the agent's output is always drafts for human review. Process: fetch all reviews and comments (`gh pr view --comments` or `gh api`), then categorize each as blocking (change-requested, security concern, correctness issue), non-blocking (style suggestion, nit, question, praise), actionable (has a concrete code change), or discussion (requires human judgment). Blocking and actionable items are prioritized first. For each comment, draft an appropriate response: fix description for actionable items, talking points for discussions, acknowledgment for nits. Surfaces unresolved threads, conflicting reviews, and stale reviews. Output format: `## Review-Triage: {pr}` with Summary counts, Blocking table, Non-Blocking table, Recommended Actions, and Needs Human section. Constraints: read-only; never post; categorize all comments; surface conflicts. ### Challenge and Synthesis These agents attack proposals from adversarial or integrative angles. Both are read-only. #### devil-advocate **File:** `.cursor/agents/devil-advocate.md` **Read-only:** yes Contrarian reviewer that steel-mans a proposal first, then challenges it systematically. The process: state the proposal in own words, identify all claims being made, then challenge by category: - Blockers (red) — issues that would prevent the approach from working at all - Major risks (orange) — issues that could cause significant problems - Minor concerns (yellow) — issues worth addressing but not fatal - Questions (blue) — things that need clarification For each issue: state the assumption being made, describe the problem scenario, list questions to verify, and propose a mitigation if the issue were addressed. Ends with genuine positives (the steel-man), priority-ordered mitigations, and a "kill test" — the single strongest argument against the proposal. Invoke this agent on any significant architecture decision, technical proposal, or approach before committing to implementation. Output format: `# Devil's Advocate: {Topic}` with My Understanding, Blockers, Major, Minor, Questions, What I Like, Recommendations, and Kill Test. Constraints: read-only; constructive not destructive; specific not vague; mitigations required. #### synthesizer **File:** `.cursor/agents/synthesizer.md` **Read-only:** yes Combines multiple agent outputs into a single unified recommendation. Used as the final step in multi-agent pipelines (e.g., `/architect`, `/quality`). Process: catalog all inputs with source and key finding; identify consensus points with confidence; surface conflicts with analysis of why sources disagree and which is correct; weight evidence (prototype results outweigh theory, measured data outweighs opinion); then synthesize into a final recommendation with rationale, risks and mitigations, what is being traded away, and a confidence level (High/Medium/Low with reasoning). Invoke this agent after running arch-explorer, devil-advocate, and prototyper and you need one actionable decision. Output format: `# Synthesis: {Topic}` with Inputs, Consensus, Contentious, Recommendation (decision + evidence + risks + confidence), Dissenting views, and Next Steps. Constraints: read-only; must attribute all sources; no new analysis introduced; clear recommendation required; uncertainty acknowledged. ### Implementation These agents write code and make changes. Both are read-write and require working in isolated git worktrees. #### prototyper **File:** `.cursor/agents/prototyper.md` **Read-only:** no (read-write) Rapid prototype implementation for validating architectural assumptions. All prototype code is created in an isolated worktree — never written directly to the agents-workbench branch. The worktree is created at `.worktrees/prototype-{name}/` from the default branch, and prototype code lives under `.prototypes/{name}/` inside that worktree. Process: define what to validate (one to two sentences) with success criteria and a time-box; create the worktree; implement the minimal code needed with a README containing run instructions; validate whether it works and what was learned; document findings (validated assumptions, invalidated assumptions, surprises); clean up by pushing the branch if keeping results or removing the worktree when done. The prototype is disposable by design. Working code matters more than clean code. Gold-plating is explicitly forbidden. Output format: `.prototypes/{name}/` directory with `README.md`, working code, and a `## Findings` section covering validated, invalidated, and surprising results. Constraints: minimal; disposable; document learnings; no gold-plating; worktree required. #### ci-doctor **File:** `.cursor/agents/ci-doctor.md` **Read-only:** no (read-write) Diagnoses and fixes CI failures. Scope is intentionally limited to what can be fixed automatically and safely: lint errors, type errors, and simple test assertion mismatches. Anything else (flaky tests, infrastructure failures, timeouts, dependency conflicts, ambiguous failures) is skipped with a notification. All code fixes happen in an isolated worktree created from the PR's head branch at `.worktrees/ci-fix-{number}/`. The agent fetches CI logs via `gh run view`, classifies the failure, creates the worktree, applies a minimal fix, commits with `-s -S` and conventional format (`fix(ci): {what}`), pushes, and monitors via `gh run watch`. Maximum two fix attempts per failure; after that, the issue is escalated to human attention. Guardrails: no force-push; never modify test expectations to make them pass; never touch files outside the failure scope; never modify source code on agents-workbench. Output format: `## CI-Doctor: {run_id}` with a table (`Failure | Category | In-Scope | Action | Result`), Diagnosis, Fix Applied, and Escalations. Constraints: no gold-plating; minimal diff; explain all fixes; respect scope boundary; commit conventions; worktree required. --- ## Commands Commands are slash commands defined as `.md` files in `.cursor/commands/`. They are invoked by typing `/commandname` in the Cursor chat. Each command file is plain markdown (no frontmatter) that becomes the agent's instructions for that workflow step. Commands are grouped below by workflow phase. ### Planning and Research #### /architect **File:** `.cursor/commands/architect.md` Full architecture exploration using a four-phase agent pipeline: ``` arch-explorer → devil-advocate → [prototyper × 2] → synthesizer | | | | 3-5 options challenge top parallel impl recommend ``` Phase 1 (Explore): launches `arch-explorer` to produce three to five approaches plus a comparison matrix. Phase 2 (Challenge): launches `devil-advocate` on the top recommendation to surface risks and blockers. Phase 3 (Prototype): launches two `prototyper` instances simultaneously, each validating a different approach in `.prototypes/{approach}/`. Phase 4 (Synthesize): launches `synthesizer` to combine all findings into a final recommendation with evidence. Usage: ``` /architect {problem} /architect {problem} --quick # skip prototypes: explorer → advocate → synthesizer /architect {problem} --proto N # prototype top N approaches (default: 2) ``` The `--quick` flag is appropriate for early discussions or reversible decisions where prototype overhead is not justified. Output: `# Architecture Decision: {Problem}` with Summary, Approaches table, Recommendation (with evidence, trade-offs, and risks), and Next Steps. #### /research **File:** `.cursor/commands/research.md` **Read-only** Deep research on a topic or GitHub issue. Accepts a GitHub issue number (`#N`), a freeform topic, or a `brainstorm: {idea}` prefix. For GitHub issues: fetches title, body, labels, state, comments, and linked PRs; classifies the issue by type (bug/feat/refactor/docs/perf/sec), severity (critical/high/medium/low), scope (local/cross-cutting/architectural), and complexity (trivial/moderate/complex/unknown); investigates related files and tests; verifies understanding against the code; then compares two to three solutions with effort/risk/maintainability ratings. For brainstorm mode: extracts concept, problem, audience, and assumptions; searches for competitors and feasibility data; analyzes through four lenses (User, Tech, Business, Risk); runs a SWOT analysis; evaluates assumptions; explores angles including MVP and full vision; outputs prioritized actions (P0/P1/P2). Output format: `# Research: #{n} - {title}` with Summary (type and severity), Problem, Root Cause (with `file:line`), Solutions (2–3 with recommendation), and Open Questions. #### /issue **File:** `.cursor/commands/issue.md` Analyzes a GitHub issue and produces a task plan. Fetches issue details from GitHub (`gh`), classifies it by type and complexity, researches affected files and existing patterns, designs two or three approaches with effort/risk/trade-off table, breaks the chosen approach into atomic tasks (one task = one change = one test = one commit), and verifies the analysis against current code. Output goes to two places: a console summary (`## #{n}: {title}` with type, complexity, branch, and tasks), and an AGENTS.md file (created or updated, preserving existing content) with the task table in `|#|Task|Status|Commit|` format. Branch naming convention: `{type}/issue-{n}-{slug}`. #### /code **File:** `.cursor/commands/code.md` Executes the next TODO task from AGENTS.md. No arguments picks the next `[TODO]` task; `#{N}` targets a specific task number. Flow: read AGENTS.md and find the next TODO; display the task and update its status to `[WIP]`; implement only that task with minimal changes; verify compilation, task acceptance criteria, and absence of unrelated changes; commit with `-s -S` and conventional format including issue ref and task progress (`Task: N/total`); update AGENTS.md status to `[DONE]` with the commit hash; report the commit, changed files, and next task. Commit format: `{type}({scope}): {desc}\n\nRefs: #{issue}\nTask: {N}/{total}` One task equals one commit. No batch commits. #### /task **File:** `.cursor/commands/task.md` Full task workflow from understanding through implementation to verification. Accepts a description, a GitHub issue number, `--plan` (stop after planning for review), or `--tdd` (enforce Red/Green/Refactor). Five phases: Understand (10% of effort — fetch context, ask at most two clarifying questions), Specify (15% — define inputs/outputs/constraints/acceptance/edge cases/out-of-scope), Plan (design two or more approaches with effort/risk/trade-off, stop for "GO" approval if `--plan`), Implement (TDD cycle if `--tdd`; update AGENTS.md throughout), Verify (compile, tests, acceptance criteria, edge cases). Iteration budget: Trivial→1, Simple→2, Moderate→3, Complex→4; escalate to user beyond budget. Commits use `-s -S` with conventional format. PR created with `gh pr create`; no auto-merge. #### /loop **File:** `.cursor/commands/loop.md` Iterative execution that repeats a task until a completion phrase appears in output or a maximum iteration count is reached. ``` /loop {task} --done "{phrase}" --max {N} ``` Defaults: `--done "DONE"`, `--max 10`. State is tracked in `.cursor/loop-state.json` (task, completion phrase, max, current iteration count, status). The `task-loop.sh` hook enforces the limit by stopping the agent when `iteration >= limit`. Common use: `/loop Work through AGENTS.md --done "Status: DONE" --max 15` to automatically work through all TODO tasks. To cancel: say "cancel loop" — status is set to `cancelled` and AGENTS.md is updated. #### /parallel **File:** `.cursor/commands/parallel.md` Runs independent tasks concurrently via subagents (maximum four concurrent agents). ``` /parallel task1 | task2 | task3 /parallel --analyze # check AGENTS.md for parallelizable TODOs /parallel --from-agents # auto-run all parallelizable TODOs from AGENTS.md ``` Dependency detection: tasks that share a file, have explicit "after X"/"needs X" annotations, or where one tests the other are run sequentially. Tasks in different directories or covering different concerns run in parallel. Results are merged and AGENTS.md is updated. Output: `## /parallel Results` with execution count (parallel vs sequential), changes per task, and remaining work. #### /worktree **File:** `.cursor/commands/worktree.md` Worktree lifecycle management for isolated feature development. All operations use the repo's default branch as the base unless overridden. ``` /worktree create # create .worktrees/, branch from default /worktree create # create from specific base branch /worktree list # show all worktrees with merged/active status /worktree status # current worktree info, branch, dirty state /worktree done # remove worktree + delete local + remote branch /worktree done --all # clean up all merged worktrees ``` Safety rails: unmerged branches require explicit confirmation before deletion; worktrees with uncommitted changes produce a warning and abort; all commits in worktrees use `-s -S`; worktree names match branch names. ### Quality and Review #### /audit **File:** `.cursor/commands/audit.md` Security and reliability audit using the same four-category framework as the `auditor` agent (EffectiveGo, Defensive, K8sReady, Security). Scope: P0 = current diff only (default), P1 = handlers/db/auth (always included), P2 = full codebase (requires `--full`). ``` /audit # P0 diff + P1 critical paths /audit --full # P2 full codebase /audit --fix # generate and apply fixes for Critical and Major findings ``` Each finding is independently verified (generate question → re-read file independently → confirm or drop) before appearing in the report. With `--fix`: each Critical/Major finding is verified, fixed, tested, and re-audited; fix commits use `fix({scope}): {desc} - Audit finding`. Output written to `AUDIT_REPORT.md` with Critical, Major, Minor sections and a summary of generated vs confirmed vs dropped findings. #### /quality **File:** `.cursor/commands/quality.md` Multi-perspective review using a parallel agent pipeline: `auditor` (security, races, leaks), `perf-critic` (N+1 queries, complexity), `api-reviewer` (if handler files are in scope), and `verifier` (test suite status). All applicable agents run simultaneously; results are synthesized into a unified report. ``` /quality # review git diff /quality {path} # review file or directory /quality #{PR} # review GitHub PR /quality --fast # auditor + verifier only /quality --api # api-reviewer focus /quality --perf # perf-critic focus ``` Output: `## Quality Report: {scope}` with Risk indicator (red/yellow/green), a category table (Security/Perf/API/Tests with issue counts and severities), Blocking items (must fix), and a Verdict (Ready / Fix Required / Blocked). Critical or High severity findings always block. #### /test **File:** `.cursor/commands/test.md` Detects the project's test framework and runs tests. Framework detection: `go.mod` → `go test ./...`, `package.json` → `npm test`, `pyproject.toml` or `requirements.txt` → `pytest`, `Cargo.toml` → `cargo test`. ``` /test # full test suite /test --quick # tests covering files changed since HEAD~1 /test --file {p} # tests for a specific file ``` Reports: Status (PASS/FAIL), test count (pass/total), and duration. On failure: lists failing tests with errors and suggested fixes, then chains to `/code` and back to `/test`. Updates AGENTS.md: pass → `[DONE]`, fail → `[BLOCKED: tests failing]`. #### /self-review **File:** `.cursor/commands/self-review.md` Reviews the agent's own changes against main before pushing. Diffs `main..HEAD`, then evaluates each changed file across four aspects: Correct (logic, edge cases, bugs), Style (patterns, naming, debug code), Sec (secrets, input validation, error safety), and Tests (new code covered, tests meaningful). Output uses three symbols: `✅ Good`, `⚠ Consider (file:line + suggestion)`, `❌ Fix (file:line + required)`. Summary aspect table (`Correct | Style | Sec | Tests → ✓/⚠/✗`) and Verdict (Ready / Minor fixes / Needs work). Updates AGENTS.md self-review task to `[DONE]`. #### /review-pr **File:** `.cursor/commands/review-pr.md` Reviews a GitHub PR for security, bugs, and architecture. Skips closed, draft, or trivial (docs-only) PRs with "LGTM". Three review passes: Security (credentials, injection, input validation, authorization bypass, sensitive data in errors), Bugs (logic errors, nil dereference, unhandled errors, leaks — changed code only), Architecture (patterns, separation of concerns, test coverage). Confidence scoring: each finding starts at zero and gains +20 for each of: exact `file:line` reference, belongs to this PR, justified reasoning, independently verified, fix provided. Only findings with confidence ≥ 80 are reported. Findings between 51 and 79 become questions; findings below 50 are dropped. Output: `## PR Review: #{n}` with Summary (files, risk areas), Blocking findings (≥80 confidence with `file:line` and fix), Health notes, Questions, and Verdict (Approved / Changes Requested / Blocked). ### Git and CI #### /push **File:** `.cursor/commands/push.md` Safe push with pre-flight checks. Verifies: all tasks in AGENTS.md are `[DONE]`, tests pass (runs `/test`), and self-review is done (runs `/self-review`). Warns if any check is not satisfied. On success: pushes with `git push -u origin HEAD`, creates a PR with `gh pr create` using a structured body (Closes #N, Summary, Changes from commits, Checklist, Testing). Updates AGENTS.md with `Status: PR_OPEN`, PR number, and link. On failure: lists what is missing and suggests remediation steps. #### /git-polish **File:** `.cursor/commands/git-polish.md` Rewrites local commits to be atomic, signed, and in conventional format. Sets up GPG signing via SSH key if not already configured. Soft-resets to a target commit, groups changes by type (chore for config, refactor for renames, feat/fix for logic by domain), verifies each group (single concern, compiles, message accurate), then commits each group with `git commit -S -s -m "type(scope): desc"`. Verifies signatures with `git log --show-signature`. #### /merge-train **File:** `.cursor/commands/merge-train.md` Orchestrates merging multiple PRs in dependency order. Handles the full lifecycle: dependency graph construction, cycle detection, CI repair, rebase, and sequential merging. ``` /merge-train # all open approved PRs targeting default branch /merge-train #12 #34 #56 # specific PRs /merge-train --label ready-to-merge # PRs with this label /merge-train --milestone v2.1 # PRs in this milestone /merge-train --dry-run # build DAG and plan only, no execution /merge-train --auto # skip confirmation gates ``` Five phases: 1. **Discover** — fetch PR candidates, validate (exclude drafts/closed/merged), print summary table 2. **Dependency DAG** — detect stacked branches (B targets A's head → B depends on A), explicit "depends on #N" references, and file overlap heuristics; detect cycles; print the graph with topological sort order 3. **Plan** — for each PR in sort order, assess CI status, unresolved threads, draft state, rebase need; print the full plan table; gate on `--dry-run` or user confirmation 4. **Execute** — process each PR sequentially: assess (fresh state), fix (review comments + CI failures in worktree), rebase (inside worktree with `--force-with-lease`, pre-rebase backup tag), wait-ci (15-minute timeout), merge (squash via `gh pr merge --squash --delete-branch`), verify and clean up worktree, retarget stacked downstream PRs 5. **Report** — print final table with status, actions taken, and merge SHA for each PR; note backup refs All code modifications happen in per-PR worktrees at `.worktrees/mt-{number}/`. Draft replies to review comments are always presented to the user for approval before posting. Max one retry cycle per CI failure category before escalating to human. Pauses on conflict, unapproved PR, or unresolvable CI failure. Safety rails: no `--no-verify`; only `--force-with-lease` never bare `--force`; no auto-post of review replies; max one retry cycle; pre-rebase backup tags; no force-push to default branch; sequential execution only; cycle detection blocks execution; worktree cleanup after each merge. #### /context-reset **File:** `.cursor/commands/context-reset.md` Resets or inspects context health tracking state. The `context-monitor.sh` hook estimates token usage based on weighted factors: each iteration adds 8%, each file touched adds 2%, each completed task adds 15%, and each `/summarize` run recovers 25%. ``` /context-reset # reset state files /context-reset --status # show current health ``` Health states: | Score | State | Action | |-------|-------|--------| | 0–50% | Healthy | Continue | | 50–75% | Filling | Consider `/summarize` | | 75–90% | Critical | Run `/summarize` | | 90%+ | Degraded | Start new session | State is persisted in `.cursor/context-state.json`. Reset removes that file and the lock file. Use after `/summarize` to recalibrate, when stuck detection produces false positives, or at the start of a fresh session. --- ## Rules Rules are `.mdc` files in `.cursor/rules/`. Each has YAML frontmatter controlling when Cursor applies it (`alwaysApply: true` for every session, `globs` for file-type-specific application). The body is injected into the agent's context when the rule is active. #### core.mdc **File:** `.cursor/rules/core.mdc` **Applied:** always (`alwaysApply: true`) Core workflow and invariants that apply to every session. Workflow phases: brainstorm → plan → code → verify → PR → review → address → CI → merge. Commit standards: always sign with `git commit -s -S` (DCO + GPG), never use `--no-verify`, never force-push to main/master. TDD invariant: RED before GREEN (no implementation without a failing test), one phase per turn (never mix test and implementation edits), tests are contracts (never weaken tests to make implementation pass). Verification standard: evidence before claim — run tests, lints, and scans before asserting success; `file:line` references must exist before being cited. Date rule: source of truth is the system context date, not training data. New files always use the current year. Year ranges only when history applies. Context economy: reference file paths rather than pasting code inline; use tables over prose; show only deltas. #### tdd.mdc **File:** `.cursor/rules/tdd.mdc` **Applied:** conditionally (not always-apply; loaded when working on implementation tasks) Detailed TDD protocol with phase signals and checkpoint gating. Phase signals (prefix every implementation response): `[PLAN]` when designing, `[RED]` when writing a failing test, `[GREEN]` when writing minimum passing code, `[REFACTOR]` when cleaning up after green, `[CHECKPOINT]` when requesting human commit before a large refactor. Hard rules: RED before GREEN, one phase per turn, tests are contracts (never modify to fit implementation), each PR covers at most one concern. Checkpoint protocol: before any REFACTOR that touches more than three files or more than 50 lines of code, signal `[CHECKPOINT]`, summarize the current GREEN state, ask for human review and commit, wait for confirmation, then begin REFACTOR as a new atomic change. Context verification: at implementation start, confirm you have API docs for external services, team conventions for the language, and existing test patterns in the repo. If any are missing, ask before writing code. Security scans required before claiming completion: for Go — `govulncheck ./...`, `gosec ./...`, `trivy fs .`; for any project — `trivy fs .`. #### workbench.mdc **File:** `.cursor/rules/workbench.mdc` **Applied:** always (`alwaysApply: true`) Branch detection and worktree discipline for the agents-workbench workflow. Before editing any source code, check `git branch --show-current`. If the current branch is `agents-workbench`, source code is READ-ONLY — suggest a worktree instead. If inside a `.worktrees/` path, proceed normally. On any other branch, follow normal development conventions. On the `agents-workbench` branch: coordination files are editable (AGENTS.md, `.agents/*`, `docs/plans/*`, CLAUDE.md, `.cursor/rules/*`) and any file is readable for context, but source code must not be modified directly. Feature implementation always happens in worktrees created with `git worktree add .worktrees/ -b `. All commits in worktrees use `-s -S`. Worktrees are cleaned up after the PR merges. In agent team setups: the lead agent stays on agents-workbench and coordinates via AGENTS.md; worker agents each operate in their own worktree for parallel implementation. #### go.mdc **File:** `.cursor/rules/go.mdc` **Applied:** when editing `**/*.go` files Go coding standards for Kubernetes-targeted projects. Lint chain (run in order): `gofmt` → `go vet` → `golangci-lint` → `go test`. Documentation: lines at most 80 characters; package-level comments required for all public packages. Patterns: accept interfaces, return concrete structs; wrap errors with `fmt.Errorf("%w", err)`; context (`ctx`) is always the first parameter; always `defer Close()` for resources. Naming: exported identifiers use PascalCase; unexported use camelCase; acronyms are consistent (URL or Url, not mixed). Error handling: never discard with `_ = f()`; always wrap with context; use sentinel errors sparingly. Concurrency: use mutex or channels for shared state; goroutines must have an exit strategy; always use context cancellation. Tests: table-driven; safe to call `t.Parallel()`; test files named `*_test.go`. Kubernetes patterns: graceful shutdown on SIGTERM/SIGINT, structured JSON logging, liveness/readiness probes, no hardcoded secrets. Security scans (verify phase): `govulncheck ./...`, `gosec ./...`, `trivy fs .` — all three before claiming implementation complete. #### k8s.mdc **File:** `.cursor/rules/k8s.mdc` **Applied:** when editing `**/*.yaml`, `**/*.yml`, `**/k8s/**`, `**/manifests/**`, `**/deploy/**` Kubernetes manifest and operator standards. API: use feature gates for alpha/beta APIs; document version-dependent assumptions. Manifests: resource limits (`requests` and `limits`) required; liveness and readiness probes required; prefer environment variables or ConfigMaps over mounted volumes for configuration. Security: no plain secrets in manifests; RBAC permissions minimal (least privilege); network policies defined; pod security standards enforced. Operator patterns: reconcile loop must be idempotent; use the status subresource for conditions; finalizers required for cleanup; leader election required for multi-replica operators. Helm: values schema (`values.schema.json`) required; README required; upgrade path must be tested. --- ## Hooks Hooks are shell scripts in `.cursor/hooks/` wired to Cursor agent events via `.cursor/hooks.json`. The registration file maps three event types to scripts: ```json { "version": 1, "hooks": { "afterFileEdit": [ { "command": "~/.cursor/hooks/format.sh" } ], "beforeShellExecution": [ { "command": "~/.cursor/hooks/sign-commits.sh" }, { "command": "~/.cursor/hooks/security-gate.sh" } ], "stop": [ { "command": "~/.cursor/hooks/task-loop.sh" }, { "command": "~/.cursor/hooks/context-monitor.sh" } ] } } ``` Hook scripts receive JSON on stdin describing the event and must write JSON to stdout describing what to do. The `hook-output.schema.json` schema defines valid responses: allow, ask (prompt user), block, modify (rewrite the command), followup (message to the agent), or error. #### format.sh **Event:** `afterFileEdit` (runs after every file the agent edits) Auto-formats files based on extension. For `.go` files: runs `gofmt -w {file}` if `gofmt` is available. For `.json` files: runs `jq '.' {file}` and writes the result back if `jq` is available. Gracefully skips with `{"continue":true}` if the required tool is not installed. Errors in formatting are suppressed (`|| true`) so a format failure never blocks the agent. Timeout: 5 seconds (configured in hooks.json). #### sign-commits.sh **Event:** `beforeShellExecution` (intercepts every shell command before execution) Enforces `-s` (DCO sign-off) and `-S` (GPG signing) on all `git commit` commands. Passes non-commit commands through immediately. For commit commands, checks whether both flags are already present. If both are present, allows unchanged. If either is missing, checks whether a signing key is configured (`git config user.signingkey` or `git config gpg.format`); if a signing key exists, adds the missing flags and returns a modified command. If no signing key is configured, adds only `-s`. The modified command is returned in the hook response so Cursor executes the corrected version transparently. #### security-gate.sh **Event:** `beforeShellExecution` Blocks genuinely dangerous commands before they execute. Blocked patterns: `rm -rf /`, `rm -rf ~`, the fork bomb `:(){ :|:& };:`, filesystem overwrite `> /dev/sda`, `mkfs`, and `dd if=/dev`. Any command matching a blocked pattern receives `{"continue":false,"error":"Blocked: potentially destructive command"}`. Force pushes to main or master (`git push` with `--force` or `-f` targeting `main`/`master`) produce a warning and ask for user confirmation rather than blocking outright. Timeout: 10 seconds (configured in hooks.json). Falls through with allow if `jq` is unavailable. #### task-loop.sh **Event:** `stop` (called when the agent is about to stop at the end of each iteration in loop mode) Prevents infinite agent loops by enforcing an iteration limit. Reads `loop_iteration` and `loop_limit` from the event JSON. If `iteration >= limit`, returns `{"decision":"stop","reason":"Loop limit reached"}`. Otherwise returns `{"decision":"continue"}`. The default limit is 5 (set in hooks.json under the `loop_limit` key for this hook entry). Used by `/loop` to enforce the `--max` parameter. #### context-monitor.sh **Event:** `stop` Placeholder for context health monitoring. Currently always returns `{"decision":"continue"}` — the logic for token estimation and health state transitions lives in `/context-reset` and the state file tracked by the agent, not in this hook. The hook file exists as the integration point for future extension. --- ## Schemas Three JSON Schema Draft-07 files in `.cursor/schemas/` validate the shape of configuration and state files. They are used for CI validation of the Cursor configuration. #### hooks.schema.json **File:** `.cursor/schemas/hooks.schema.json` Validates `.cursor/hooks.json`. Requires `version` (integer ≥ 1) and `hooks` (object with three optional arrays: `afterFileEdit`, `beforeShellExecution`, `stop`). Each entry in `afterFileEdit` and `beforeShellExecution` must have a `command` field matching the pattern `~/.cursor/hooks/[a-z-]+\.sh`. Stop hook entries additionally allow a `loop_limit` integer (1–100). No additional properties are permitted in any object. #### hook-output.schema.json **File:** `.cursor/schemas/hook-output.schema.json` Validates the JSON that hook scripts write to stdout. Defines seven valid response shapes using `oneOf`: - **allow** — `{"continue":true,"permission":"allow"}` — proceed unchanged - **ask** — `{"continue":true,"permission":"ask","user_message":"...","agent_message":"..."}` — prompt user - **block** — `{"continue":false,"error":"..."}` — prevent execution - **modify** — `{"continue":true,"permission":"allow","command":"..."}` — rewrite the command - **followup** — `{"followup_message":"..."}` — send a message back to the agent (stop hooks) - **error** — `{"error":"..."}` — hook execution failure - **empty** — `{}` — no action needed (stop hooks) #### state-file.schema.json **File:** `.cursor/schemas/state-file.schema.json` Validates `.cursor/loop-state.json` and `.cursor/context-state.json`. Defines two object shapes: `loopState` — tracks `/loop` execution: `status` (running/stopped/complete/budget_exceeded), `task`, `max_iterations` (1–100, default 10), `current_iteration`, `completion_promise` (default "DONE"), `started_at`, and `completed_at`. `contextState` — tracks context health: `conversation_id`, `iterations`, `files_touched`, `tasks_completed`, `summarize_count`, `health` (healthy/filling/critical/degraded), `last_recommendation`, and stuck-detection fields (`stuck_iterations`, `last_done_count`, `last_todo_count`). --- ## Skills (skills-cursor) The `.cursor/skills-cursor/` directory contains 13 built-in Cursor config skills. These are Cursor's own internal skills for managing the editor configuration and are distinct from project skills (`.cursor/skills/`) or personal skills (`~/.cursor/skills/`). Each is a directory containing a `SKILL.md` with frontmatter and instructions. #### create-rule **File:** `.cursor/skills-cursor/create-rule/SKILL.md` Guides creation of new `.mdc` rule files in `.cursor/rules/`. Gathers purpose, scope, and file patterns (asking whether the rule should always apply or only for specific file types). Produces a rule with correct frontmatter (`description`, `globs`, `alwaysApply`) and body under 500 lines. Best practices enforced: one concern per rule, actionable content, concrete examples, no verbose prose. Triggered when: asked to create a rule, add coding standards, set up project conventions, or configure file-specific patterns. #### create-skill **File:** `.cursor/skills-cursor/create-skill/SKILL.md` Guides creation of new agent skills. Distinguishes personal skills (`~/.cursor/skills/`) from project skills (`.cursor/skills/`). Produces a directory with `SKILL.md` (required) and optional `reference.md`, `examples.md`, and `scripts/`. Enforces concise descriptions (written in third person, including both WHAT and WHEN), body under 500 lines, progressive disclosure, and consistent terminology. Covers four authoring patterns: template, examples, workflow, and conditional workflow. Explicitly warns against creating skills in `~/.cursor/skills-cursor/`. Triggered when: asked to create, write, or author a new skill. #### create-subagent **File:** `.cursor/skills-cursor/create-subagent/SKILL.md` Guides creation of new agent definition files in `.cursor/agents/` (project) or `~/.cursor/agents/` (personal). Produces a `.md` file with YAML frontmatter (`name`, `description`) and a markdown body that becomes the system prompt. Covers scope selection (project vs personal), writing effective descriptions that include trigger terms and "use proactively" language, and the step-by-step creation workflow. Triggered when: asked to create a new subagent, set up a task-specific agent, or configure a code reviewer/debugger/domain-specific assistant. #### migrate-to-skills **File:** `.cursor/skills-cursor/migrate-to-skills/SKILL.md` Converts existing rules and commands to the skills format. Rules are migrated if they have a `description` but no `globs` and no `alwaysApply: true` (i.e., "Applied intelligently" rules). All commands are migrated. Conversion: rules get `name` added and `globs`/`alwaysApply` removed; commands get full frontmatter added including `disable-model-invocation: true` (so they remain user-triggered, not auto-suggested). Body content is copied character-for-character with no reformatting. Triggered when: asked to migrate rules or commands to skills, or to convert `.mdc` files to `SKILL.md` format. #### update-cursor-settings **File:** `.cursor/skills-cursor/update-cursor-settings/SKILL.md` Reads and modifies the Cursor/VS Code `settings.json` file. Knows the platform-specific paths (macOS: `~/Library/Application Support/Cursor/User/settings.json`, Linux: `~/.config/Cursor/User/settings.json`). Always reads existing settings before modifying, preserves all unrelated settings, and validates JSON before writing. Covers editor, workbench, files, terminal, and Cursor-specific settings. Notes when a restart or window reload is required. Triggered when: asked to change editor settings, preferences, themes, font size, tab size, format-on-save, auto-save, or any `settings.json` value. ===== docs/deployment.md ===== # Deployment Scripts Reference ## Overview This repository is a bare mirror of `~/.claude/` and `~/.cursor/` — the configuration directories for Claude Code and Cursor respectively. Three scripts manage synchronization between the repository and the live environment on a given machine. ```mermaid graph LR REPO["Repository
.claude/ · .cursor/"] -->|"deploy.sh"| LIVE["Live Environment
~/.claude/ · ~/.cursor/"] LIVE -->|"capture.sh"| REPO REPO <-.->|"diff.sh"| LIVE ``` The three scripts and their roles: - `scripts/deploy.sh` — pushes config from the repo into `~/`, with automatic backup and post-deploy verification. - `scripts/capture.sh` — pulls config from `~/` back into the repo so changes made in the live environment can be reviewed and committed. - `scripts/diff.sh` — compares the repo against the live environment without modifying either, reporting files that are repo-only, live-only, or differ in content. **Typical workflows:** Edit in the live environment first, then bring changes into version control: ``` edit ~/.claude/ or ~/.cursor/ → capture.sh → git diff → git add -p → commit → push ``` Edit in the repo first, then push to the live environment: ``` edit repo → deploy.sh --dry-run → deploy.sh → verify output ``` All three scripts share the same exclude lists (see [Exclude Lists](#exclude-lists)) so that runtime state, caches, and machine-specific files are never synced in either direction. --- ## deploy.sh Rsyncs `.claude/` and `.cursor/` from the repository into `~/`. Before overwriting any files, the script creates a timestamped backup tarball of the existing live directories, so you can roll back if needed. After the sync completes, the script runs a verification pass that checks: - Key files are present (`~/.claude/settings.json`, `~/.claude/CLAUDE.md`, `~/.cursor/mcp.json`, `~/.cursor/rules`). - All hook scripts under `~/.claude/hooks/` and `~/.cursor/hooks/` are executable. - JSON config files (`settings.json`, `policy-limits.json`, `remote-settings.json`, `mcp.json`, `hooks.json`) parse without errors using `python3`. Verification only runs on a real deploy, not during `--dry-run`. ### Backup behaviour The backup is created at `~/.config/dotfiles-backup/dotfiles-backup-.tar.gz` and captures exactly the directories that will be overwritten (`.claude/`, `.cursor/`, or both depending on scope flags). Pass `--force` to skip the backup step. ### Flags | Flag | Effect | |------|--------| | `--dry-run` | Preview changes without applying them | | `--force` | Skip the automatic backup step | | `--claude-only` | Deploy only `.claude/` configuration | | `--cursor-only` | Deploy only `.cursor/` configuration | | `--no-plugins` | Skip `plugins/` directory from `.claude/` deployment | | `--delete` | Pass `--delete` to rsync (removes files in `~/` not in repo — use with caution) | `--claude-only` and `--cursor-only` are mutually exclusive. ### Examples ```bash ./scripts/deploy.sh --dry-run # see what would change ./scripts/deploy.sh # full deploy with backup ./scripts/deploy.sh --claude-only # only update Claude Code config ./scripts/deploy.sh --force # deploy without creating a backup ./scripts/deploy.sh --delete # sync exactly — remove live files absent from repo ``` ### Overlay repos Some people layer a second config repo — private, or team-specific — on top of this one. `deploy.sh` must not overwrite the files that repo owns. Point it at the overlay with `scripts/deploy-overlay.local`, a single line holding the overlay repo's absolute path. That file is machine-local and gitignored. Every `.claude/` path the overlay **tracks** is then excluded from the deploy. The exclusion set is computed live from the overlay's git index on each run, never from a stored snapshot. It fails closed: a pointer naming a directory that is missing, or that is not a git repo, aborts the deploy with exit code `4` rather than deploying over overlay-owned paths. With no pointer file, none of this applies. #### Declaring deletions Tracking cannot express a deletion, and that gap is a trap worth understanding. An overlay file is excluded *because the overlay tracks it*. Delete that file from the overlay and it stops being tracked, so it stops being excluded — and the next deploy writes this repo's copy back into `~/.claude/`. **The deletion silently undoes itself.** To make a deletion stick, list it in a manifest at the overlay repo's root, named: ```text .claude-deploy-deletions ``` One repo-relative path per line: ```text # Paths this overlay deliberately removes. The toolkit must not restore them. .claude/agents/doc-writer.md .claude/rules/report-style.md ``` | Case | Behaviour | |------|-----------| | Manifest absent | No-op — the deploy behaves exactly as it does without one. Most overlays never need a manifest | | Manifest empty | No-op, not an error | | Blank line | Ignored | | `#` as the first non-blank character | The whole line is a comment. This is gitignore's rule, so a `#` inside a filename is never mistaken for one | | Whitespace around an entry | Trimmed | | Entry not starting with `.claude/` | Aborts with exit `4`. A manifest that can exclude arbitrary paths is a footgun | | Entry containing a `..` segment | Aborts with exit `4` | | Entry the overlay still tracks | Warns on stderr, then excludes it anyway. Either the entry is redundant or the deletion was never actually made | Entries are anchored at the transfer root the same way tracked paths are, so `.claude/rules/report-style.md` excludes exactly that file and not a same-named file somewhere deeper. The manifest lives in the overlay repo on purpose. It is versioned in the same commit as the deletion it describes, so the two cannot drift apart. A list kept next to the pointer instead would be machine-local state that a human has to remember to update — which is the failure this feature exists to prevent. `deploy.sh` reads the working-tree copy, so a manifest edit takes effect immediately; commit it so other machines get it too. Deploy output reports the two sources on separate lines, so the tracked-path count keeps its original meaning: ```text >> overlay: excluding 34 overlay-owned paths (from /path/to/overlay) >> overlay: honouring 2 declared deletion(s) (from /path/to/overlay/.claude-deploy-deletions) ``` The second line appears only when the manifest contributes at least one entry. --- ## capture.sh The reverse of deploy: rsyncs `~/.claude/` and `~/.cursor/` from the live environment back into the repository working tree. Nothing is committed automatically — the intent is to stage and review changes with `git diff` before deciding what to commit. ### Symlink resolution capture.sh passes `--copy-links` to rsync. This is important because some files in `~/.cursor/` (notably command scripts) may be symlinks. `--copy-links` dereferences them, so the repo stores the actual file content rather than a dangling symlink. ### Leak sweep After copying, capture.sh scans every file it actually refreshed **this run** — not the whole tree — for identity-bearing content that must never land in this public repo: - **Generic patterns** (always active, defined in `scripts/sync-lib.sh`): `/Users/` and `/home/` path prefixes. - **Local patterns** (optional, machine-specific): one ERE per line, loaded from `LEAK_PATTERNS_FILE` (default `scripts/leak-patterns.local`, gitignored — never committed). Use this for real names, machine usernames, or private project paths. Blank lines and `#`-prefixed lines are skipped. - If `LEAK_PATTERNS_FILE` is absent, capture.sh prints a loud warning to stderr (`WARNING: scripts/leak-patterns.local not found — leak sweep running with generic patterns only`) and proceeds with generic patterns alone — it never fails silently. - **Placeholder exemption**: documented example paths that legitimately appear in tracked docs and fixtures — `/Users/foo`, `/Users/me`, `/Users/you`, `/home/user` — are exempted from the generic patterns so they don't flag forever. The exemption is per-match, not per-line: a line combining an exempt placeholder with a real path (e.g. a stray `/Users/testuser`) still flags. ### Exit codes | Code | Meaning | |------|---------| | `0` | Capture completed; leak sweep found nothing | | `1` | Leak sweep found possible identity-bearing content (see the `LEAK?` lines printed above the summary). The copies are still made — that's safe, since they're uncommitted working-tree changes — but review with `git diff` and revert an individual file with `git checkout -- ` before committing | ### Flags | Flag | Effect | |------|--------| | `--claude-only` | Capture only `.claude/` | | `--cursor-only` | Capture only `.cursor/` | `--claude-only` and `--cursor-only` are mutually exclusive. ### Workflow after capture ```bash ./scripts/capture.sh # capture both git diff # review what changed git add -p # stage selectively git commit -s -S -m "config: update settings" ``` --- ## diff.sh Compares the repository config against the live environment and reports any differences, without modifying either side. This is useful as a pre-deploy sanity check, for CI drift detection, or to verify that a capture run picked up everything. ### Output categories Each file that is not identical in both places is reported under one of three labels: | Label | Meaning | |-------|---------| | `REPO ONLY` | File exists in the repo but not in the live environment | | `CHANGED` | File exists in both places but the contents differ | | `LIVE ONLY` | File exists in the live environment but not in the repo | | `LEAK?` | Advisory only, printed under a `CHANGED` entry when the live copy matches a leak-sweep pattern (see [capture.sh's Leak sweep](#leak-sweep)) — does not change diff.sh's exit code | A per-directory summary line shows the count in each category. If everything matches, the section prints `(in sync)`. ### Exit codes | Code | Meaning | |------|---------| | `0` | Everything in sync | | `1` | One or more differences found | ### Flags | Flag | Effect | |------|--------| | `--claude-only` | Compare only `.claude/` | | `--cursor-only` | Compare only `.cursor/` | ### Examples ```bash ./scripts/diff.sh # compare everything ./scripts/diff.sh --cursor-only # just check Cursor config echo $? # 0 = in sync, 1 = differences ``` --- ## Exclude Lists All three scripts use the same exclude lists, so runtime state is consistently ignored regardless of which direction data is flowing. Files and directories that match these patterns are never synced, captured, or compared. ### Claude excludes | Pattern | Reason | |---------|--------| | `debug/` | Runtime debug logs | | `projects/` | Claude project-specific state | | `teams/`, `tasks/`, `todos/`, `team/` | Runtime team/task state | | `cache/`, `plugins/cache/` | Downloaded plugin caches | | `plugins/known_marketplaces.json`, `plugins/marketplaces/` | Marketplace registry cache | | `file-history/` | Claude file edit history | | `session-env/`, `shell-snapshots/` | Session-specific environment state | | `paste-cache/` | Clipboard paste cache | | `telemetry/` | Telemetry data | | `backups/` | Local backup archives | | `ide/` | IDE integration state | | `history.jsonl` | Conversation history | | `stats-cache.json` | Usage statistics | | `settings.local.json` | Machine-specific overrides (not portable) | | `plans/` | Runtime plan state | | `commands/` | Runtime commands | | `docs/` | Documentation (managed separately in repo root) | ### Cursor excludes | Pattern | Reason | |---------|--------| | `extensions/` | Cursor extension state | | `projects/` | Project-specific Cursor state | | `ai-tracking/`, `snapshots/` | AI session tracking data | | `ide_state.json` | Window and editor layout state | | `argv.json` | Launch arguments | | `unified_repo_list.json` | Cursor's internal repo registry | | `worktrees/` | Runtime worktree tracking | | `blocklist` | Runtime blocklist | | `.deploy-version` | Deployment versioning marker | | `docs/` | Documentation (managed separately in repo root) | | `skills/` | Runtime skill state | ===== docs/skills-and-commands.md ===== # Skills and Commands Reference This document is the complete reference for all slash commands and skills available across Claude Code and Cursor IDE in this configuration. Both tools support extensible automation through commands and skills, and both enforce the same engineering workflow: brainstorm before implementing, write failing tests first, isolate work in git worktrees, sign every commit, and submit work for structured review before merging. **Claude Code** uses "skills" provided by the superpowers plugin. Skills are workflow templates stored as markdown files that guide the AI through structured processes — brainstorming, TDD cycles, debugging investigations, verification, and code review. They are invoked as `/superpowers:skill-name` or triggered automatically by the AI when the context makes them relevant. **Cursor** uses two distinct extension points: - **Commands** (`.cursor/commands/`): Slash commands invoked by the user. Each command defines a multi-step workflow, often orchestrating several specialized agents. - **Skills** (`.cursor/skills-cursor/`): Configuration management skills for creating and updating Cursor artifacts like rules, agents, and commands. These are built-in to this configuration and managed automatically. Both ecosystems are complementary. You can run Claude Code in the terminal and Cursor in the editor simultaneously on the same repository. The same hooks, the same commit conventions, and the same worktree model apply in both. For configuration details, see [Claude Code Configuration](claude-code.md) and [Cursor Configuration](cursor.md). --- ## Claude Code Skills (Superpowers Plugin) These skills are provided by the superpowers plugin and live in the Claude Code plugin registry. Invoke them explicitly with `/superpowers:`, or let the AI invoke them automatically when the workflow calls for it. | Skill | Purpose | When Used | |-------|---------|-----------| | `brainstorming` | Collaborative design exploration: generates 2–3 options with trade-offs, requires explicit user approval before proceeding | MANDATORY before any implementation task. The only exemptions are typos, comments, running tests, reading files, and answering questions | | `writing-plans` | Creates detailed implementation plans with TDD phases, exact file paths, shell commands, and a numbered task list | After a design option has been approved in brainstorming | | `executing-plans` | Executes an approved plan task-by-task in a separate session, with checkpoints between tasks for review | For launching plan execution in a fresh context, reducing context-window pollution | | `subagent-driven-development` | Dispatches a fresh subagent per task with a two-stage review gate (spec review + quality review) | For executing a plan within the current session, where per-task isolation matters | | `dispatching-parallel-agents` | Detects independent tasks and launches them concurrently, each in its own worktree | When two or more tasks have no shared state or file overlap | | `test-driven-development` | Enforces the RED → GREEN → REFACTOR cycle with explicit phase signals; blocks implementation without a failing test | During any implementation work. Pairs with the `tdd-guard.sh` hook | | `systematic-debugging` | Structured bug investigation: reproduce → isolate → hypothesize → verify → fix. Requires evidence before proposing a change | When encountering bugs, test failures, or unexpected behavior | | `using-git-worktrees` | Creates an isolated git worktree branched from the remote default ref, placing it in `.worktrees//` | Before starting any feature work. Enforced by the `enforce-worktree.sh` hook | | `finishing-a-development-branch` | Guides branch completion: runs verification, presents options (merge, open PR, or clean up), and updates `AGENTS.md` | When implementation is complete and all tests pass | | `verification-before-completion` | Requires running the actual verification commands (build, test, lint) and confirming their output before claiming a task is done | Before committing or opening a PR | | `requesting-code-review` | Formats and submits work for review with a structured report covering changes, test coverage, and open questions | After completing implementation and passing verification | | `receiving-code-review` | Handles incoming review feedback with technical rigor — evaluates each comment on merit, not deference | When receiving feedback on a PR or in-session review | | `writing-skills` | Creates and validates new skill files before adding them to the plugin registry; checks format, description quality, and trigger coverage | When creating a new skill to add to the superpowers plugin | | `using-superpowers` | Introduction to the skill system: explains what skills exist, how to find them, and how to invoke them | At the start of a new conversation, or when onboarding to this toolchain | ### Invocation Patterns ``` # Explicit invocation /superpowers:brainstorming # With context passed inline /superpowers:writing-plans implement the OAuth2 refresh-token flow # The AI will invoke automatically in many cases, e.g.: # "Let me brainstorm before we proceed..." → triggers brainstorming # "There's a test failure, let me investigate..." → triggers systematic-debugging ``` --- ## Local Claude Code Skills (this repo) These skills ship in `.claude/skills/` and deploy to `~/.claude/skills/`. Each has a human-facing README following the standard in [skill-readme-template.md](skill-readme-template.md) — what it does, when to use it, worked examples, setup, and gotchas. The `SKILL.md` beside each README is the machine-facing procedure the agent follows; the README explains *use*, the SKILL.md owns the *procedure*. | Skill | What it does | |-------|--------------| | [`/cmux-sprint-orchestrator`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/cmux-sprint-orchestrator/README.md) | Orchestrate a sprint across cmux worker panes: a read-only planning phase gated on explicit approval, then bounded dispatch to Codex and Claude workers with per-task verification | | [`/done`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/done/SKILL.md) | Close a session by grading the collected evidence against the goal — a NAT-backed evaluator (`skills/done/eval.py`) returning AGREE / DISAGREE / INSUFFICIENT_EVIDENCE, with `DONE_BACKEND` / `DONE_NAT_MODEL` selecting the provider and model. See [Done on OpenRouter](examples/done-openrouter.md) | | [`/eureka`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/eureka/README.md) | Capture a breakthrough before it evaporates | | [`/go-review`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/go-review/README.md) | Systematic Go code review for correctness, concurrency, and performance | | [`/goal`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/goal/README.md) | Record the session goal and acceptance criteria | | [`/handoff`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/handoff/README.md) | Capture session state for a fresh start | | [`/js-review`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/js-review/README.md) | JavaScript/TypeScript/Node review — async correctness, TS strictness, dependency hygiene, JS security | | [`/k8s-debug`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/k8s-debug/README.md) | Ordered triage for Kubernetes GPU workload failures | | [`/k8s-review`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/k8s-review/README.md) | Kubernetes review — YAML and Helm correctness, API best practices, RBAC least-privilege | | [`/kickoff`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/kickoff/README.md) | Turn a rough idea into a scoped, goal-tracked start. Backed by the shared agentic engine (the `tool.kickoff` package under `.claude/tool/`), with `KICKOFF_BACKEND` / `KICKOFF_MODEL` selecting the provider and model. See [Kickoff on OpenRouter](examples/kickoff-openrouter.md) | | [`/pr-review`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/pr-review/README.md) | Review a PR with a content-aware reviewer fan-out and post the findings as one GitHub review | | [`/pr-review-ingest`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/pr-review-ingest/README.md) | Turn PR review comments into rule proposals | | [`/python-review`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/python-review/README.md) | Python review for AI/MLOps/agent code — typing, async correctness, agent-loop invariants, reproducibility, serialization safety | | [`/reflection`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/reflection/README.md) | Turn session mistakes into curated rules | | [`/skill-eval`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/skill-eval/README.md) | Measure skill discoverability | | [`/tdd-protocol`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/tdd-protocol/README.md) | The Red → Green → Mutate → Refactor cycle | | [`/team-plan`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/team-plan/README.md) | Scope a multi-task project before spawning an agent team | | [`/team-execute`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/team-execute/README.md) | Spawn the agent team to implement an approved plan | | [`/team-shutdown`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/team-shutdown/README.md) | Retire a completed team engagement | | [`/test-review`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/test-review/README.md) | Test and CI review — theater-test detection, e2e quality, GitHub Actions and Prow correctness | | [`/validate-recommendation`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/validate-recommendation/README.md) | Review every `(Recommended)` option in an `AskUserQuestion` via configured panelists — a `PreToolUse` hook, per-role personas, and a `panel/config.yml` (copied from `config.yml.template`) where each panelist's backend and model are set. See [Panel Config](patterns/panel-config.md) and [Panel on OpenRouter](examples/panel-openrouter.md) | | [`/worktree-guide`](https://github.com/ArangoGutierrez/claude-toolkit/blob/main/.claude/skills/worktree-guide/README.md) | Branch model and commands for agents-workbench worktrees | The engine-backed skills — `/kickoff`, `/done`, and `/validate-recommendation` — share one agentic engine under `.claude/tool/` (its provider seam is `tool.backends`); their `KICKOFF_*` / `DONE_*` env vars and the panel `config.yml` choose the backend and model. `/done` is procedure-only — its `SKILL.md` and `eval.py`, without a standalone README yet — so its row links the `SKILL.md`. The `/team-plan`, `/team-execute`, and `/team-shutdown` slash names are defined solely by the three `team-*` skills listed above. Earlier copies of these commands also lived in `.claude/commands/`, but those copies drifted from the skills and have been removed — the skills are now the single source of truth for the team workflow. The reference material the workflow draws on is listed below. --- ## Team Reference Material The `team-*` skills above coordinate multi-agent implementation. Shared reference material lives under `.claude/team/lib/` — retained for reference; nothing currently loads or references it automatically. For the team structure, roles, and communication protocol, see the per-skill READMEs linked in the skills table above. | File | Used by | Purpose | |------|---------|---------| | `team/lib/planning-guide.md` | `team-plan` skill | Task decomposition methodology and wave construction rules | | `team/lib/branch-validator.md` | `team-plan`, `team-execute` skills | Validates branch source is up-to-date before creating worktrees | | `team/lib/qa-validator.md` | QA Engineer | Full validation checklist: git signatures, language checks, CI replication, PR metadata | | `team/lib/decision-template.md` | Principal Engineer | ADR template for recording architectural decisions | | `team/lib/architect-*.md` (7 files) | Principal Engineer | Reference material covering patterns, security, distributed systems, infrastructure, observability, decisions, validation | --- ## Cursor Slash Commands Commands are markdown files in `.cursor/commands/`. Each defines a workflow that the AI follows when you type the corresponding slash command in Cursor. Many commands orchestrate multiple specialized subagents in sequence or in parallel. ### Planning and Research These commands help you understand a problem before touching any code. | Command | Description | Agents Orchestrated | |---------|-------------|-------------------| | `/architect {problem}` | Full architecture exploration with parallel prototyping. Generates 3–5 options, stress-tests the top recommendation, runs two parallel prototypes, and synthesizes a final recommendation with evidence. Use `--quick` to skip prototyping for early or reversible decisions; use `--proto N` to control how many prototypes run | `arch-explorer` → `devil-advocate` → `prototyper` x2 (parallel) → `synthesizer` | | `/research #{n}` or `/research {topic}` | Deep research on a GitHub issue or codebase topic. For issues: fetches title, body, labels, comments, and linked PRs; classifies type, severity, scope, and complexity; traces to source files; compares 2–3 solution approaches. For a brainstorm idea (`brainstorm: {idea}`): runs a SWOT analysis with bull/bear/base cases | `researcher` | | `/issue #{n}` | Analyzes a GitHub issue end-to-end: fetches metadata, classifies it, traces affected files, designs 2–3 approaches, breaks the work into atomic tasks (1 task = 1 commit), and writes or updates `AGENTS.md` with the task list and a feature branch name | `task-analyzer` | ### Implementation These commands execute work. They all assume an `AGENTS.md` task list exists (created by `/issue` or `/task`). | Command | Description | Key Features | |---------|-------------|-------------| | `/code` | Executes the next `[TODO]` task in `AGENTS.md`. Marks it `[WIP]`, implements only that task, verifies it compiles and meets the acceptance criteria, commits with `-s -S`, and marks it `[DONE]` with the commit hash. Use `/code #N` to target a specific task | Atomic: one task, one commit. Refuses to touch out-of-scope files | | `/task {desc}` or `/task #{n}` | Full task workflow with budget tracking. Five phases: Understand (10%), Specify (15%), Plan (with `--plan` flag, pauses for "GO"), Implement (with `--tdd` flag for TDD cycle), Verify. Budget: Trivial=1 iteration, Simple=2, Moderate=3, Complex=4 | Structured specification table (inputs, outputs, constraints, acceptance criteria, edge cases, out-of-scope) | | `/loop {task} --done "{phrase}" --max {N}` | Iterative execution: runs the task repeatedly until the completion phrase appears in output or `AGENTS.md` reaches `Status: DONE`, up to `--max` iterations (default 10). Tracks state in `.cursor/loop-state.json` | Useful with `/loop Work through AGENTS.md --done "Status: DONE" --max 15` to fully drain a task list | | `/parallel task1 \| task2 \| task3` | Runs independent tasks concurrently via subagents (max 4). Detects dependencies by file overlap and explicit markers ("after X", "needs X"). Dependent tasks fall back to sequential execution. Use `--analyze` to check `AGENTS.md` for parallel opportunities without executing | Dependency detection prevents conflicting parallel writes to the same file | | `/worktree create \| list \| status \| done` | Full worktree lifecycle management. `create ` branches from the remote default ref. `list` shows all worktrees with merged/active status. `status` shows current branch and dirty state. `done ` verifies the branch is merged before removing the worktree and deleting the branch locally and remotely. `done --all` cleans up all merged worktrees | Never deletes unmerged branches without explicit confirmation | ### Quality and Review These commands check your work before it reaches a reviewer. | Command | Description | Key Features | |---------|-------------|-------------| | `/audit` | Security and reliability audit of changed files. Default scope (P0): `git diff` only. Add `--full` for full codebase. Add `--fix` to automatically apply Critical and Major fixes, commit each with `-s -S`. Categories: effective Go patterns, defensive coding, Kubernetes readiness, and security. Each finding is independently verified before reporting | Generates `AUDIT_REPORT.md` with confirmed/dropped counts | | `/quality` | Multi-perspective review run in parallel. Default: auditor (security, races, leaks), perf-critic (N+1 queries, complexity), api-reviewer (if HTTP handlers present), verifier (tests pass). Use `--fast` for auditor + verifier only. Use `--api` or `--perf` to focus. Critical or High findings block the verdict | Parallel agent execution required; synthesis into a single report required | | `/test` | Detects the test runner from project files (`go.mod`, `package.json`, `pyproject.toml`, `Cargo.toml`) and runs the suite. Reports `PASS/FAIL`, count, and duration. On failure, lists failing tests with errors and suggested fixes. Use `--quick` to run only tests for files changed in the last commit. Use `--file {path}` for a single file | Updates `AGENTS.md`: passing tests → `[DONE]`, failing → `[BLOCKED:tests failing]` | | `/self-review` | Reviews your own changes against `main`. Reads `git diff main..HEAD`, evaluates each file across four dimensions: correctness, style, security, and test coverage. Reports per-file verdicts: Good / Consider (with file:line) / Fix (with file:line and required action). Final verdict: Ready / Minor fixes / Needs work | Updates `AGENTS.md` self-review task to `[DONE]` | | `/review-pr #{n}` | Reviews a pull request with confidence scoring. Only reports findings with confidence >= 80/100. Three passes: security (high-risk patterns), bugs (changed lines only), architecture. Each finding is re-read independently to verify before reporting. Skip conditions: closed, draft, or trivial (docs-only) PRs | Confidence scoring prevents noise: 0–50 → drop, 51–79 → question only, 80–100 → report with fix | ### Git and CI These commands manage the git workflow from commit to merge. | Command | Description | Key Features | |---------|-------------|-------------| | `/push` | Safe push with pre-flight checks. Verifies all `AGENTS.md` tasks are `[DONE]`, tests pass, and self-review is complete. Warns on any unchecked items. Runs `git push -u origin HEAD` then creates a PR via `gh pr create` with a structured body (summary, changes, checklist, testing notes). Updates `AGENTS.md` with `Status: PR_OPEN` and the PR link | Will not auto-merge. Reports the PR number and URL | | `/git-polish` | Rewrites the local commit history into atomic, signed, conventional commits. Asks how many commits to rewrite, soft-resets to that point, groups changes by concern (chore/config, refactor/rename, feat or fix by domain), verifies each commit is single-concern, and commits with `-S -s` and a `type(scope): desc` message. Verifies signatures at the end | Requires GPG or SSH signing configured. Use before push, not after | | `/merge-train` | Merges multiple PRs in correct dependency order. Five phases: Discover (fetch and validate PRs), DAG (build dependency graph, detect cycles), Plan (assess readiness, print merge order), Execute (sequential: assess → fix → rebase → wait-CI → merge → verify → retarget downstream), Report. Supports `--dry-run`, `--auto`, `--label`, `--milestone`. All code fixes happen in isolated worktrees (`.worktrees/mt-{number}/`) | Never force-pushes to the default branch. Pauses on any failure and reports what to do next | | `/context-reset` | Resets the context tracking state managed by `context-monitor.sh`. Use `--status` to see current health score (0–100%) and recommendation. Use without flags to clear `.cursor/context-state.json` and recalibrate. Health bands: 0–50% Healthy, 50–75% Filling, 75–90% Critical, 90%+ Degraded | Run after `/summarize` to recalibrate the score | --- ## Cursor Skills (Configuration Management) These are built-in skills in `.cursor/skills-cursor/`. They are invoked by the AI when you ask it to create or modify Cursor configuration artifacts. They are not typically invoked by slash command — instead they are triggered by natural-language requests like "create a new rule for TypeScript" or "add a subagent for database queries". | Skill | Purpose | |-------|---------| | `create-rule` | Generates a new `.mdc` project rule in `.cursor/rules/`. Prompts for scope (always-apply vs file-specific) and glob patterns, then produces a properly formatted frontmatter + markdown rule file. Rules should be under 50 lines with concrete examples | | `create-skill` | Guides creation of a new Cursor skill: determines purpose, storage location (personal `~/.cursor/skills/` vs project `.cursor/skills/`), trigger scenarios, and output format. Produces a `SKILL.md` with valid frontmatter, concise body (under 500 lines), and a specific third-person description that includes both what the skill does and when to invoke it | | `create-subagent` | Generates a new agent configuration as a `.md` file in `.cursor/agents/` or `~/.cursor/agents/`. Produces required frontmatter (`name`, `description`) and a markdown system prompt that defines the agent's role, invocation workflow, constraints, and output format | | `migrate-to-skills` | Converts legacy command files from an older format to the current skills format. Preserves behavior while updating structure to match the current `SKILL.md` schema | | `update-cursor-settings` | Programmatically modifies Cursor configuration files, such as `~/.cursor/context-config.json`, without requiring manual JSON editing | --- ## How They Relate Claude Code skills and Cursor commands enforce the same engineering workflow from two different vantage points. **Claude Code skills focus on process discipline.** They are the guardrails that prevent skipping steps. The `brainstorming` skill ensures you explore options before committing to an approach. The `test-driven-development` skill enforces the RED → GREEN → REFACTOR cycle. The `verification-before-completion` skill blocks you from claiming done before running the commands that prove it. These skills operate at the level of a single engineer working in the terminal. **Cursor commands focus on agent orchestration.** They coordinate multiple specialized agents to accomplish broader tasks. `/architect` runs four agents in sequence to explore an architecture decision. `/quality` fans out to four agents in parallel to review different risk dimensions. `/merge-train` manages a multi-PR pipeline from dependency analysis through post-merge verification. These commands operate at the level of a team — each agent is a specialist, and the command is the workflow that coordinates them. **The same hooks enforce the same rules in both tools.** Signed commits (`sign-commits.sh`), TDD discipline (`tdd-guard.sh`), and worktree isolation (`enforce-worktree.sh`) run as Claude Code hooks. The Cursor commands independently enforce these same rules in their own flows: `/git-polish` requires `-S -s` flags, `/worktree` always branches from the remote ref, `/code` commits atomically with `-s -S`. **You can use both tools on the same codebase.** Use Claude Code in the terminal for planning, TDD cycles, and hook-enforced discipline. Use Cursor in the editor for architecture exploration, quality reviews, and parallel execution of independent tasks. The `AGENTS.md` file serves as the shared task ledger that both tools read and update. Cursor agents are the "specialists" (`arch-explorer`, `devil-advocate`, `auditor`, `perf-critic`). Cursor commands are the "workflows" that orchestrate them. Claude Code skills are the "discipline layer" that enforces process regardless of which tool is doing the work. ===== docs/skill-readme-template.md ===== # Skill README standard Every skill and command in this toolkit ships a `README.md` next to its `SKILL.md`. The `SKILL.md` is the **agent-facing protocol** (loaded into model context on invocation — keep it lean). The `README.md` is the **human-facing page**: what the skill is for, when to reach for it, and concrete examples. The central [`docs/skills-and-commands.md`](skills-and-commands.md) is the index; each row links to one of these per-skill READMEs. Copy the structure below. Keep it concrete — every example shows an actual invocation and the outcome a user should expect. ```markdown # / — <1–2 sentences: what it does and the value it delivers. This opening paragraph IS the "purpose" — do not add a `## Purpose` heading. Name the trigger (e.g. `/ `) and any fail-open / safety behavior.> ## When to use it <3–6 bullets of concrete situations — the problems it solves and the triggers. End with a `**Not for:**` bullet naming the common mis-reach and where that work should go instead (most of these skills have a near-neighbor).> ## Examples <2–3 worked examples. Each is the invocation, then what happens / the expected outcome. Use a 4-space-indented block with a literal `>` line for the command and a `→` line for the observable result — not prose, not a fenced block.> > / → ## Setup ## Notes ``` ## Rules - **Title & slash prefix**: use `# / — ` only if the skill is user-invocable as a slash command; for auto-triggered skills use `# — ` with no slash. Every title carries a tagline. - **World-safe** (this repo is public): no internal hostnames, model ids, employer-specific references, tokens, or private paths (never `/Users//…` — use `~/…`). Use placeholders (`https://your-endpoint`, `$YOUR_API_KEY`). - **Examples must be real**: every example and any command you cite (a `Verify:` line, a test invocation) must reflect actual behavior and point at a file that exists — run it if unsure. Don't invent output. - **Don't duplicate `SKILL.md`**: the README explains *use*; the SKILL.md defines the *procedure*. Link, don't copy. - **Plain and technical**: no emoji, no marketing adjectives ("powerful", "seamless", "effortless", "revolutionary"). Imperative or second person. - **One screen**: target ~40–90 lines; a reader should grasp purpose + an example without scrolling for minutes. - **Links**: a skill README sits at `.claude/skills//README.md`, so the index is three levels up — link it with code-styled text: ``[`docs/skills-and-commands.md`](../../../docs/skills-and-commands.md)``. Link a sibling skill as ``[``](..//)``; mention superpowers-plugin skills as plain code spans (`superpowers:`), never as links. ===== docs/testing-agent-models.md ===== # Testing Agent Model Configurations This guide explains how to test and verify that Cursor agents are correctly configured with their model settings. ## Quick Test Validate that deployed agents have correct frontmatter by inspecting them directly: ```bash ls ~/.cursor/agents/*.md | head -5 head -10 ~/.cursor/agents/api-reviewer.md ``` This confirms: - All agents have valid `model` fields - Model values use correct format (`sonnet`, `opus`, `haiku`, `fast`, `inherit`, or full model IDs) - Required frontmatter fields (`name`, `description`) are present ## Manual Testing in Cursor ### Method 1: Invoke an Agent Directly 1. **Deploy agents** (if not already deployed): ```bash ./scripts/deploy.sh ``` 2. **Restart Cursor** to load the new configurations 3. **Test an agent**: - Open Cursor chat - Type: `/quality` (triggers multiple agents including `api-reviewer`, `auditor`, `perf-critic`, `verifier`) - Or mention directly: `@api-reviewer review this API endpoint` 4. **Verify model usage**: - Check response quality (Sonnet 4.5 should provide more detailed, nuanced responses than `fast`) - Look for model indicators in Cursor's UI (if available) - Compare responses between agents with different model settings ### Method 2: Compare Model Behavior Create a simple test to compare agents: 1. **Use an agent with `model: sonnet`**: ``` @api-reviewer review this endpoint: GET /users/{id} ``` 2. **Note the response quality**: - Depth of analysis - Detail level - Reasoning quality 3. **Compare with `model: fast`** (if you temporarily change one): - `fast` should be quicker but less detailed - `sonnet` should be more thorough ## Automated Validation ### CI/CD Integration The GitHub Actions workflow (`.github/workflows/validate-cursor.yml`) now validates: - Agent frontmatter structure - Model field format (if present) - Required fields Run locally: ```bash # Simulate the CI validation act -j validate-structure ``` Or push to trigger the workflow automatically. ### Validation Inspect deployed agent frontmatter to confirm model fields are set correctly: ```bash grep -r "^model:" ~/.cursor/agents/ ``` Expected output shows each agent's model value (`sonnet`, `opus`, `haiku`, `fast`, `inherit`, or a full model ID). ## Valid Model Values Cursor accepts these model values: | Value | Description | |-------|-------------| | `claude-4-5-sonnet` | Claude Sonnet 4.5 (recommended format) | | `claude-4-5-opus` | Claude Opus 4.5 | | `sonnet` | Claude Sonnet (alias, may use latest) | | `opus` | Claude Opus (alias, may use latest) | | `haiku` | Claude Haiku (fastest, cost-effective) | | `fast` | Fast model (optimized for speed) | | `inherit` | Inherit model from parent conversation | | `claude-sonnet-4-5-20250929` | Full model identifier with date | ## Troubleshooting ### Model Not Being Used If an agent doesn't seem to be using the specified model: 1. **Check deployment**: ```bash ls -la ~/.cursor/agents/ ``` 2. **Verify frontmatter**: ```bash head -10 ~/.cursor/agents/api-reviewer.md ``` 3. **Restart Cursor** completely 4. **Check Cursor logs** (if available) for model selection ### Invalid Model Format If you see errors about invalid model values: 1. **Check the format**: - ✅ Correct: `model: claude-4-5-sonnet` - ✅ Correct: `model: sonnet` (alias) - ❌ Wrong: `model: Claude sonnet 4.5` - ❌ Wrong: `model: "sonnet"` (quotes not needed) 2. **Run validation**: ```bash grep -r "^model:" ~/.cursor/agents/ ``` 3. **Fix invalid values**: - Use aliases: `sonnet`, `opus`, `haiku`, `fast`, `inherit` - Or full IDs: `claude-sonnet-4-5-20250929` ## Testing Checklist - [ ] Deploy agents: `./scripts/deploy.sh` - [ ] Verify model fields: `grep -r "^model:" ~/.cursor/agents/` - [ ] Restart Cursor - [ ] Test `/quality` command - [ ] Verify agent responses show expected quality - [ ] Check CI validation passes (if applicable) ## Next Steps - See [Cursor Configuration](cursor.md) for agent capabilities and how agents are invoked ===== docs/agents.md ===== # Agents This page is for an AI agent (or a human scripting one) that wants to pull this repo's documentation into context programmatically, without cloning the repo or rendering the MkDocs site. ## Raw-md URL scheme Every page in this repo is plain Markdown, fetchable directly from GitHub's raw-content host at a predictable URL: ``` https://raw.githubusercontent.com/ArangoGutierrez/claude-toolkit/main/ ``` For example, this page itself is: ``` https://raw.githubusercontent.com/ArangoGutierrez/claude-toolkit/main/docs/agents.md ``` No authentication, no rate-limit surprises beyond GitHub's normal unauthenticated raw-content limits, and no HTML to strip — just the source Markdown, exactly as it renders in the MkDocs site. ## `llms.txt` — the root index [`llms.txt`](https://raw.githubusercontent.com/ArangoGutierrez/claude-toolkit/main/llms.txt) is a hand-curated index in the [llmstxt.org](https://llmstxt.org) format: an H1 title, a one-line summary, and grouped link lists (`## Docs`, `## Patterns`, `## Examples`, `## Engine source`), one link per line. Start here if you want to decide which pages are relevant before fetching them — it is small enough to fit in a single context window alongside your own task. ## `llms-full.txt` — the single-fetch corpus [`llms-full.txt`](https://raw.githubusercontent.com/ArangoGutierrez/claude-toolkit/main/llms-full.txt) concatenates every page linked from `llms.txt`, in the order `llms.txt` lists them, each preceded by a `===== =====` header. Fetch this one file to get the entire documentation corpus in a single request — useful when you'd rather pay one fetch than N, or when your fetch tool doesn't handle a fan-out well. It is generated, not hand-written: `scripts/gen-llms-full.sh` reads `llms.txt`, resolves every linked `.md` file back to its path in this repo, and concatenates them. Regenerate it whenever `llms.txt` changes, or whenever any page it links changes: ```bash scripts/gen-llms-full.sh ``` The script fails loudly (non-zero exit, `MISSING: ` on stderr) if `llms.txt` ever links a path that doesn't exist in the tree, so a stale link can't silently ship in the generated corpus. ## The stable-heading promise Every page under [`docs/patterns/`](patterns/openrouter-free-tier.md) uses the same four H2 headings, in the same order: `## What`, `## How`, `## Env`, `## Pitfalls`. An agent that has parsed one pattern page can jump straight to the section it needs on any other pattern page without re-parsing the whole document — `## Pitfalls` always answers "what breaks and why," `## Env` always answers "what variables does this read." This structure is a contract: new pattern pages are expected to follow it, and a page that doesn't should be treated as a bug. ===== docs/orchestration.md ===== # Orchestration: Loops → Graphs > "Here's your monthly reminder that you shouldn't be prompting coding > agents anymore. You should be designing loops that prompt your agents." > — [Peter Steinberger, June 2026](https://x.com/steipete/status/2063697162748260627) > > "Are we still talking loops or did we shift to graphs yet?" > — [Peter Steinberger, July 2026](https://x.com/steipete/status/2078277297791189132) Agent orchestration has a maturity model. Each stage changes what *you* produce: prompts produce answers, loops produce automation, graphs produce verified systems of agents. This page names the stages, tells you when each one is enough, and maps them to the pieces this toolkit ships. ## The three stages **Stage 1 — Prompts.** You type, the agent acts, you read, you type again. You are the control flow. Perfectly fine for exploration, one-off fixes, and anything you'd finish before automation could pay for itself. **Stage 2 — Loops.** The insight of loop engineering: stop being the control flow. A loop re-invokes the agent on a schedule or a trigger — "check CI and fix what broke", "keep the dependency PRs merged", "refresh the code graph weekly". The agent gets re-prompted by a *program*, not by you. Loops excel at recurring maintenance with a stable prompt. Their limit: a loop is one agent thinking alone — no fan-out, no independent verification, no structured hand-offs. **Stage 3 — Graphs.** Work becomes a DAG of agents: fan-out over independent subtasks, barriers where synthesis genuinely needs everything, adversarial verification as a first-class node between "found" and "reported", checkpointed state so a killed run resumes instead of restarting. The orchestration is deterministic code; the agents supply judgment inside well-defined boxes. This is where "one agent with a long prompt" becomes "a system with structural quality guarantees". There is a fourth axis the loops-vs-graphs debate tends to miss: **knowledge graphs**. Orchestration graphs coordinate *work*; knowledge graphs give agents a cheap, queryable map of *the territory* (code structure, prior decisions) so every node starts oriented instead of grepping from zero. ## When each stage is enough | You are doing… | Stay at | |---|---| | Exploring, spiking, one-off edits | Prompts | | Recurring maintenance, a stable prompt, one agent suffices | Loops | | Review/audit where findings must be verified, migrations over many files, work needing independent perspectives | Graphs | Do not cargo-cult upward. A loop that works beats a graph that impresses; every stage you climb adds cost, latency, and moving parts. Climb when the *shape* of the work demands it — verification, fan-out, or scale one context window can't hold — not when a tweet does. ## What this toolkit ships per stage | Stage | Component | What it does | |---|---|---| | Loops | `/loop` (Cursor command) | re-run a task until its completion phrase appears, bounded by `--max` iterations | | Loops | scheduled tasks (cron/launchd) | headless recurring runs, e.g. weekly graph refresh | | Graphs | [Workflow Library](patterns/workflow-library.md) | named, reusable orchestration DAGs (`/review-verify`, `/chief-dispatch`, `/weekly-audit`) | | Graphs | [kickoff enrichment](architecture.md) | compiles a rough goal into a scoped prompt, acceptance checks, and a dispatch plan | | Knowledge graphs | [Graphify](graphify.md) | AST-derived code graph agents query before grepping | ## Composing the layers The stages compose — that's the point. A **loop** can launch a **graph**: ```text # weekly, headless: the loop is the scheduler, the graph does the work claude -p "/weekly-audit" ``` Schedule that line with cron or launchd and you have recurring, parallel, adversarially-synthesized repo hygiene — a loop prompting a graph of agents, none of it prompted by you. ## Cost and safety rails Graphs multiply agents, so the toolkit treats orchestration spend as opt-in, never inferred: - Multi-agent workflows run only on explicit user opt-in (a typed `/` command is exactly that). - Verification is structural: `review-verify` refuses to report a finding no refuter attacked; `chief-dispatch` refuses to accept an implementer's report as evidence. - Workflows never push, post, or merge — external writes stay with the human operator. ## Further reading - [Claude Code workflows documentation](https://code.claude.com/docs/en/workflows) - [Workflow Library reference](patterns/workflow-library.md) - [Engineering Discipline](engineering-discipline.md) — the verification culture the graphs encode ===== docs/patterns/openrouter-free-tier.md ===== # Pattern: OpenRouter Free-Tier Backend ## What The toolkit's [agentic engine](../architecture.md#the-agentic-engine) can run its LLM calls — kickoff enrichment, the validate-recommendation panel, the done evaluator — against a zero-cost model instead of a paid API key. OpenRouter publishes `:free` variants of several catalog models; pointed through the `nat-openai` backend, they work as a drop-in for local development, CI dry runs, or trying the toolkit before committing to a paid provider. ## How Install the engine's Python dependencies first (Python 3.12+): pip install langchain-openai pyyaml requests (`langchain-openai` pulls the OpenAI-compatible client; the panel's config loader needs `pyyaml`; the engine's HTTP timeout shim needs `requests`. Backends other than nat-openai need their own langchain provider package.) `nat-openai` is one of three backends `tool.backends` knows how to build a chat client for (the others are `nat-nim` and `nat-anthropic`). It targets any OpenAI-compatible `/chat/completions` endpoint, OpenRouter included. 1. Create a free OpenRouter account and API key. 2. Point the generic OpenAI-compatible env vars at OpenRouter: ```bash export OPENAI_BASE_URL=https://openrouter.ai/api/v1 export OPENAI_API_KEY= ``` 3. Select a `:free` catalog model. The toolkit's own default is `nvidia/nemotron-3-ultra-550b-a55b:free` — a 1M-context model at $0 on OpenRouter's free tier. It is used as the fallback default in `tool/kickoff.py` and `skills/done/eval.py`. 4. Route the component you're using to the `nat-openai` backend, e.g. `KICKOFF_BACKEND=nat-openai` or `DONE_BACKEND=nat-openai`, or set `backend: nat-openai` for a panelist in `~/.claude/panel/config.yml`. ## Env | Var | Purpose | |---|---| | `OPENAI_BASE_URL` | `https://openrouter.ai/api/v1` for OpenRouter | | `OPENAI_API_KEY` | your OpenRouter API key | | `KICKOFF_BACKEND` / `DONE_BACKEND` / panel `backend:` | set to `nat-openai` to route through this pattern | | `KICKOFF_MODEL` / `DONE_NAT_MODEL` / panel `model:` | a `:free`-suffixed catalog ID, e.g. `nvidia/nemotron-3-ultra-550b-a55b:free` | ## Pitfalls - **Privacy.** OpenRouter :free routes may log prompts for provider training; use a paid route or a self-hosted endpoint for sensitive work. - **Rate limits.** Free-tier routes are throttled more aggressively than paid routes; expect occasional 429s under sustained use (e.g. a long kickoff enrichment loop). - **Model availability.** OpenRouter can retire or rename `:free` variants without notice — pin the exact ID you tested against and re-verify it resolves (`curl` the OpenRouter models endpoint) before relying on it in CI. - **Never use a hub-form ID here.** OpenRouter (and every public catalog) expects single-namespace IDs like `nvidia/nemotron-3-ultra-550b-a55b:free`. Double-namespace ("hub-form") IDs are an internal-catalog artifact and will simply 404 against a public endpoint — see [Model ID Hygiene](model-id-hygiene.md). ===== docs/patterns/model-id-hygiene.md ===== # Pattern: Model ID Hygiene ## What Model catalog IDs come in two shapes: **single-namespace** public catalog IDs (`nvidia/nemotron-3-ultra-550b-a55b:free`) and **double-namespace ("hub-form")** IDs, where an org's name is repeated as both the top-level namespace and a sub-namespace underneath it. Hub-form IDs are internal-catalog references — they resolve only against a private endpoint and must never ship in a public repo. The toolkit's sync gate treats this as a mechanical leak check, not a style nit: an internal default sailing through a capture into this repo would be a silent leak of internal infrastructure shape. ## How The carve-out policy is one rule: **single-namespace IDs are always fine; double-namespace hub-form IDs are always flagged**, regardless of which file they appear in. This is enforced by a generic leak pattern in `scripts/sync-lib.sh` (`GENERIC_LEAK_PATTERNS`), the shared library sourced by both `scripts/capture.sh` (refresh this repo from the live `~/.claude`) and `scripts/diff.sh` (compare without refreshing). Run the gate directly: ```bash scripts/capture.sh --claude-only # refreshes + gates in one pass # or, to check without touching any files: scripts/diff.sh --claude-only ``` A hub-form ID anywhere in a refreshed/diffed file produces a non-zero exit and a `LEAK?` line naming the file: ``` LEAK? .claude/tool/cfg.py ``` A single-namespace catalog ID in the same file passes clean — no `LEAK?`, exit 0. This is what test case T13 in `scripts/sync-gate_test.sh` verifies: a fixture carrying a repeated-org hub-form ID must flip the gate, and a fixture carrying `nvidia/nemotron-3-ultra-550b-a55b:free` must not. ## Env This pattern has no runtime env vars of its own — it's a static text scan. `REPO_DIR` and `HOME` (both overridable, mainly for the test harness) control which trees `capture.sh`/`diff.sh` compare. ## Pitfalls - **The pattern is substring-based, not semantic.** It flags the hub-form shape wherever it appears — comments, fixtures, docstrings — not just live model-selection code. If you need to document the shape itself, keep the example generic (e.g. an `acme/acme/model-x` placeholder) rather than writing out the real internal org's repeated-namespace form, or the documentation would trip its own gate. - **New files aren't auto-covered.** `capture.sh` only refreshes files already tracked in this repo (allowlist model) — a brand-new file with a leaked ID won't be caught until it's `git add`ed and captured/diffed at least once. - **Curated files are exempt from refresh, not from the gate.** Files listed in `CURATED` in `sync-lib.sh` are never overwritten by capture, but they are still hand-maintained — review them for hub-form IDs manually. ===== docs/patterns/panel-config.md ===== # Pattern: Panel Config ## What The validate-recommendation panel reviews every `AskUserQuestion` whose option labels carry `(Recommended)`. A `PreToolUse` hook fires the panel skill, which dispatches N configured panelists and produces one verdict: **HOLD** (auto-proceed with the recommended option), **DISSENT** (re-ask the question, augmented with panelist reasoning), or **ERROR** (re-ask the original question — a panelist failed to respond usefully). The panel's behavior is entirely driven by one file, `config.yml`. At the wire level an unblinded panelist emits HOLD or OVERTURN (see the worked example) and a blinded one emits a CHOICE, which the aggregator maps onto the same two votes: agreement with the recommended option is HOLD, any other choice is OVERTURN naming that option. The aggregator then maps OVERTURN votes into SOFT-DISSENT or HARD-DISSENT by the severity threshold. ## How Copy the template into place and adjust it: ```bash cp .claude/panel/config.yml.template ~/.claude/panel/config.yml ``` The template ships three enabled panelists: an adversarial `DA`, which is told which option was recommended and argues against it, plus a blinded `PE` and `QA`, which are not told and rank the options on their merits. Three is the smallest odd N at which a single dissenting panelist produces a SOFT-DISSENT rather than a hard interrupt. Set `CLAUDE_PANEL_PROFILE=solo` to fall back to `DA` alone for one dispatch. Each entry under `panelists:` is independent: | Field | Meaning | |---|---| | `id` | short identifier used in trace/telemetry output | | `role` | `DA` (devil's advocate), `PE` (principal engineer), `QA`, or a custom role | | `enabled` | panelists can be toggled off without deleting their config | | `blind` | withhold the recommendation from this panelist (`claude-subagent` only) | | `backend` | `nat-openai`, `nat-anthropic`, `nat-nim`, or `claude-subagent` | | `model` | catalog ID (only for the three `nat-*` backends) | | `subagent_type` | which agent definition to spawn (only for `claude-subagent`) | | `max_tokens`, `temperature`, `timeout_seconds` | per-panelist request tuning | A blinded panelist gets a prompt with the recommendation removed, the `(Recommended)` marker stripped from every label, and the options deterministically reordered — it cannot tell which option the assistant favoured, so its agreement is evidence rather than an echo. Two other blocks matter beyond the panelist list: `severity.hard_threshold` (how many panelists must agree to force a re-ask) and `re_brainstorm` (whether/how many times a DISSENT triggers an augmented re-ask before surfacing to the user as-is). ## Env Panel backends resolve credentials the same way as every other `tool.backends` caller — see the [engine env contract](../architecture.md#the-agentic-engine). For a `nat-openai` panelist, that means `OPENAI_BASE_URL` / `OPENAI_API_KEY` in the environment the panel runs in (see [OpenRouter Free-Tier Backend](openrouter-free-tier.md) for a concrete zero-cost setup). `claude-subagent` panelists need no extra env — they run in-process as a spawned agent. ## Pitfalls - **`blind` must match the panelist's persona.** A blinded panelist never sees the recommendation, so its persona asks for `CHOICE: