CLAUDE.md
CLAUDE.mdCLAUDE.mdroot
Quality
76/100
Scores the file, not the repository.Length
5,573 words
77 headings · 13 code blocksRepository
515
— · pushed 8 days agoLast changed
3 days ago
First indexed 3 days ago.1# Plugin Development Guide23Development documentation for the Elixir/Phoenix Claude Code plugin.45## Overview67This plugin provides **agentic workflow orchestration** with specialist agents and reference skills for Elixir/Phoenix/LiveView development.89## Workflow Architecture1011The plugin implements a **Plan → Work → Review → Compound** lifecycle:1213```14/phx:plan → /phx:work → /phx:review → /phx:compound15 │ │ │ │16 ↓ ↓ ↓ ↓17plans/{slug}/ (in namespace) (in namespace) solutions/18```1920> **Migration note**: The `--depth` flag replaces the old21> `--detail` flag. Use `quick|standard|deep` instead of22> `minimal|more|comprehensive`.2324**Key principle**: Filesystem is the state machine. Each phase reads from previous phase's output. Solutions feed back into future cycles.2526### Workflow Commands2728| Command | Phase | Input | Output |29|---------|-------|-------|--------|30| `/phx:plan` | Planning | Feature description | `plans/{slug}/plan.md` |31| `/phx:plan --existing` | Enhancement | Plan file | Enhanced plan with research |32| `/phx:brief` | Understanding | Plan file | Interactive walkthrough (ephemeral) |33| `/phx:work` | Execution | Plan file | Updated checkboxes, `plans/{slug}/progress.md` |34| `/phx:review` | Quality | Changed files | `plans/{slug}/reviews/` |35| `/phx:compound` | Knowledge | Solved problem | `solutions/{category}/{fix}.md` |36| `/phx:full` | All | Feature description | Complete cycle with compounding |3738### Artifact Directories3940Each plan owns all its artifacts in a namespace directory:4142```43.claude/44├── plans/{slug}/ # Everything for ONE plan45│ ├── plan.md # The plan itself46│ ├── interview.md # Brainstorm → plan contract (requirements handoff)47│ ├── research/ # Research agent output48│ ├── reviews/ # Review agent output (individual tracks)49│ ├── summaries/ # Context-supervisor compressed output50│ ├── progress.md # Progress log51│ └── scratchpad.md # Auto-written decisions, dead-ends, handoffs52├── audit/ # Audit namespace (not plan-specific)53│ ├── reports/ # 5 specialist agent outputs54│ └── summaries/ # Supervisor compressed output55├── reviews/ # Fallback for ad-hoc reviews (no plan)56├── skill-metrics/ # Skill effectiveness dashboards and recommendations57│ ├── dashboard-{date}.json # Per-skill aggregate metrics58│ └── recommendations-{date}.md # Improvement recommendations59└── solutions/{category}/ # Global compound knowledge (unchanged)60 ├── ecto-issues/61 ├── liveview-issues/62 └── ...63```6465### Context Supervisor Pattern6667Orchestrators that spawn multiple sub-agents use a generic68`context-supervisor` (haiku) to compress worker output before69synthesis. This prevents context exhaustion in the parent:7071```72Orchestrator (thin coordinator)73 └─► context-supervisor reads N worker output files74 └─► writes summaries/consolidated.md75 └─► Orchestrator reads only the summary76```7778Used by: planning-orchestrator, parallel-reviewer, audit skill, docs-validation-orchestrator.7980**Subagent nesting depth budget.** Claude Code 2.1.217–2.1.218 defaulted81`CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` to **1**; 2.1.219+ defaults to **3**.82An explicit environment value overrides that default. The current deepest83supported chain is **depth 3** — `/phx:full` → workflow-orchestrator →84parallel-reviewer → review specialists. Public skills must preflight the value85and keep orchestration in the main conversation when the configured depth is86too small; never launch an orchestrator that cannot perform its fan-out.87`/phx:full` and planning/investigation orchestrators need depth 3; call-tracer88alone needs depth 2. At lower depths, spawn the same leaf specialists directly89and preserve the workflow's decisions, artifacts, and gates. A nested90investigation track must apply trace procedures directly rather than spawning91call-tracer, which would create a depth-4 chain. A plugin hook cannot raise the92parent process's environment.9394**Background is the default (CC 2.1.198).** Subagents now run in the background by95default and inherit the session's extended-thinking config (a free quality lift for96review/research/council workers). Orchestrators already `run_in_background: true` and97wait for all workers before compressing — that bg-then-wait model is now automatic98even for workers spawned without the flag. Keep the explicit flag for self-documentation;99no change is required to benefit.100101## Structure102103```104claude-elixir-phoenix/105├── .claude-plugin/106│ └── marketplace.json107├── .claude/ # Contributor tooling (NOT distributed)108│ ├── agents/109│ │ ├── phoenix-project-analyzer.md # Analyze external codebases110│ │ └── docs-validation-orchestrator.md # Plugin docs compatibility111│ ├── commands/112│ │ ├── psql-query.md113│ │ └── techdebt.md114│ └── skills/115│ ├── cc-changelog/ # /cc-changelog — track CC changelog impact116│ ├── docs-check/ # /docs-check — validate against Claude Code docs117│ ├── plugin-dev-workflow/ # plugin development workflow guide118│ ├── promote/ # /promote — release promotion posts119│ ├── release/ # /release — cut a plugin release120│ ├── session-scan/ # /session-scan — Tier 1 metrics121│ ├── session-deep-dive/ # /session-deep-dive — Tier 2 analysis122│ ├── session-trends/ # /session-trends — trend reporting123│ └── skill-monitor/ # /skill-monitor — skill effectiveness dashboard124├── scripts/125│ └── fetch-claude-docs.sh # Download Claude Code docs for validation126├── plugins/127│ └── elixir-phoenix/128│ ├── .claude-plugin/129│ │ └── plugin.json130│ ├── agents/ # 26 specialist agents131│ │ ├── workflow-orchestrator.md # Full cycle coordination132│ │ ├── planning-orchestrator.md133│ │ ├── context-supervisor.md # Generic output compressor (haiku)134│ │ └── ...135│ ├── hooks/136│ │ └── hooks.json # Format, progress tracking, Stop warning137│ └── skills/ # 51 skills138│ ├── work/ # Execution phase139│ ├── full/ # Autonomous cycle140│ ├── plan/ # Planning + deepening (--existing)141│ ├── review/ # Enhanced: Todo creation142│ ├── compound/ # Knowledge capture phase143│ ├── compound-docs/ # Solution documentation system144│ ├── investigate/145│ └── ...146├── CLAUDE.md147└── README.md148```149150## Conventions151152### Agents153154Agents are specialist reviewers that analyze code without modifying it.155156**Frontmatter:**157158```yaml159---160name: my-agent161description: Description with "Use proactively when..." guidance162tools: Read, Grep, Glob, Bash163disallowedTools: Write, Edit, NotebookEdit164permissionMode: bypassPermissions165model: sonnet166effort: medium167memory: project168skills:169 - relevant-skill170---171```172173**Rules:**174175- Use `sonnet` model by default — the `sonnet` alias resolves to Sonnet 5 (Claude Code's176 default model since CC 2.1.197, native 1M context), which achieves near-opus quality at lower cost177- Use `opus` for primary workflow orchestrators and security-critical agents only178- Use `sonnet` for secondary orchestrators (investigation, tracing) and judgment-heavy tasks179- Use `haiku` for mechanical tasks: compression, verification, dependency analysis180- Set `effort:` to match cognitive load: `low` for haiku/mechanical agents, `medium` for sonnet specialists, `high` for opus orchestrators and security-critical agents181- Review agents are **read-only** (`disallowedTools: Write, Edit, NotebookEdit`)182- Use `permissionMode: bypassPermissions` for all agents — `default` causes "Bash command permission check failed"183 when agents run in background (safety system scans skill content for shell-like patterns)184 - **Docs-drift note**: current Claude Code docs state that *plugin* subagents IGNORE `permissionMode`185 (also `hooks` and `mcpServers`). The field stays for backward-compat with older CC versions, and186 `.claude/agents/` (non-plugin) agents still honor it.187- Use `memory: project` for agents that benefit from cross-session learning (orchestrators, pattern analysts).188 Note: `memory` auto-enables Read, Write, Edit — only add to agents that already have Write access189- Preload relevant skills via `skills:` field190- Add `omitClaudeMd: true` for read-only agents (no Write tool) — they don't need commit/PR/lint191 guidelines from CLAUDE.md. Iron Laws are injected via SubagentStart hook. Enforced by eval.192 - **Iron Laws injection ≠ CLAUDE.md inclusion.** `omitClaudeMd: true` skips the project193 CLAUDE.md body (commit rules, lint guidance, scope cues). It does NOT suppress Iron Laws —194 the `SubagentStart` hook injects them via `hookSpecificOutput.additionalContext` on every195 subagent spawn. Set `omitClaudeMd: true` freely on read-only agents; Iron Laws stay enforced.196- Keep under 300 lines197198### Skills199200Skills provide domain knowledge with progressive disclosure.201202**Structure:**203204```205skills/{name}/206├── SKILL.md # ~100 lines max207└── references/ # Detailed content208 └── *.md209```210211**Rules:**212213- SKILL.md: ~100 lines max (~500 tokens)214- Include "Iron Laws" section for critical rules215- Move detailed examples to `references/`216- Set `effort:` to match skill complexity: `low` for mechanical (verify, quick, compound), `medium` for reference skills, `high` for complex reasoning (plan, full, investigate, review)217- Use `${CLAUDE_SKILL_DIR}/references/` for reference file paths (not bare `references/`)218- No `triggers:` field (use `description` for auto-loading)219- **Description must be under 250 characters** — this is a plugin-side budget discipline,220 not a hard CC cap. CC raised `MAX_LISTING_DESC_CHARS` from 250 to 1,536 in v2.1.105, but221 the skill-listing budget is still ~1% of the context window (~8K chars default). With222 ~40 skills in this plugin, every description has ~200 chars of listing budget on average.223 Longer descriptions crowd out other skills in the listing, hurting routing accuracy across224 the whole plugin. Target under 200 chars. Enforced by eval.225226### Workflow Skills227228Workflow skills (plan, work, review, compound, full) have special structure:229230- Define clear input/output artifacts231- Reference other workflow phases232- Include integration diagram showing position in cycle233- Document state transitions234235### Compound Knowledge Skills236237The compound system captures solved problems as searchable institutional knowledge:238239- `compound-docs` — Schema and reference for solution documentation240- `compound` (`/phx:compound`) — Post-fix knowledge capture skill241Solution docs use YAML frontmatter (see `compound-docs/references/schema.md`).242243### Hooks244245Defined in `hooks/hooks.json`:246247```json248{249 "hooks": {250 "PreToolUse": [...], // Block dangerous ops + deps-audit gate + freeze edit-scope gate251 "PostToolUse": [...], // Format + Iron Law verify + security + progress + plan STOP + debug stmt252 "PostToolUseFailure": [...], // Elixir failure hints + error critic for mix commands253 "UserPromptSubmit": [...], // route-intent.sh — inject /phx: workflow suggestions254 "SubagentStart": [...], // Iron Laws injection into all subagents255 "SessionStart": [...], // Setup dirs + Tidewave + Ash detection + resume detection256 "PreCompact": [...], // Re-inject workflow rules before compaction257 "PostCompact": [...], // Verify plan state survived compaction258 "StopFailure": [...], // Log API failures to scratchpad for resume259 "Stop": [...] // Warn if uncompleted tasks260 }261}262```263264**Current hooks:**265266- `PreToolUse` (Bash): Block destructive operations (`mix ecto.reset/drop`, `git push --force`, `MIX_ENV=prod`) before execution267- `PreToolUse` (Bash, `"if": "Bash(*mix deps.*)"`): `deps-audit-gate.sh` — blocks unvetted dep operations after `/phx:deps-audit` flags them268- `PreToolUse` (Edit|Write|NotebookEdit): `freeze-gate.sh` — enforces `/phx:freeze` edit-scope locks (sentinel-backed read-only/dir-scoped locks)269- `PostToolUse` (Edit): Auto `mix format --check-formatted`, **programmatic Iron Law verification**,270 **debug statement detection** — all use `if` conditions to only fire on `.ex`/`.exs` files271 (e.g., `"if": "Edit(*.ex)"`) to avoid unnecessary shell spawns on non-Elixir files272- `PostToolUse` (Write): Same Elixir checks as Edit + plan STOP reminder with `"if": "Write(*plan.md)"`273- `PostToolUse` (Edit|Write): Security Iron Laws for auth files, async progress logging274 (these fire on all file types — no `if` filtering)275- `PostToolUseFailure` (Bash): Elixir-specific debugging hints and **error critic** —276 both use `"if": "Bash(*mix*)"` to only fire on mix command failures (via `additionalContext`)277- `UserPromptSubmit`: `route-intent.sh` — inject one-line `/phx:` workflow suggestions for high-signal278 intents (PR URLs → `/phx:pr-review`, Tidewave current-page + stack traces → `/phx:investigate`).279 Gated on `mix.exs`, one suggestion per category per session, always exits 0280- `SubagentStart`: Inject all Iron Laws into every spawned subagent via `additionalContext` (addresses zero skill auto-loading gap)281- `PreCompact`: Re-inject workflow rules (plan/work/full) before compaction via JSON `systemMessage`282- `SessionStart` (all): Setup `.claude/` directories + Tidewave detection + Ash detection (`detect-ash.sh`) (`async: true`)283- `SessionStart` (startup|resume|fork only): Scratchpad check + resume workflow detection (`check-resume.sh` —284 gated on `mix.exs` OR an existing `.claude/plans/*/plan.md`; sole owner of the resume/no-plan banner285 after the duplicate echo hook was removed) + branch freshness (`async: true`) + workflow hints286- `PostCompact`: Verify active plan state survived compaction, warn Claude to re-read plan and scratchpad287- `StopFailure`: Log API failure to plan scratchpad for resume detection in next session288 (CC ignores StopFailure exit code/output — the scratchpad **write** is the whole job)289- `Stop` (`check-pending-plans.sh`): user-visible `systemMessage` reminder, gated on running290 `background_tasks[]` / `session_crons[]` (a forgotten `mix phx.server` / scheduled job).291 Stays silent on clean stops — pending plans + dirty tree are already surfaced at292 `SessionStart`, so it does NOT re-warn them every turn. Deliberately NOT `additionalContext`293 (that would force Claude to continue on every stop)294295**Hook output patterns (important for contributors):**296297- `PostToolUse` stdout is **verbose-mode only** — use `exit 2` + stderr to feed messages to Claude298- `PreCompact` has **no stdout context injection** — use JSON `systemMessage`299- `SessionStart` stdout IS added to Claude's context (one of two exceptions along with `UserPromptSubmit`)300- `SubagentStart` uses `hookSpecificOutput.additionalContext` to inject context into subagents301- `PostToolUseFailure` uses `hookSpecificOutput.additionalContext` for debugging hints302- `PostCompact` uses `exit 2` + stderr to warn Claude (same pattern as PostToolUse)303- `Stop` stdout is **debug-log only** — to reach the user use JSON `systemMessage` (Claude still304 stops); `additionalContext`/`exit 2` instead **continue the turn**, so reserve them for cases305 where you actually want Claude to keep working306- `StopFailure` output and exit code are **ignored by CC** — it can't block or message; persist307 state to a file (scratchpad) that a later `SessionStart` hook reads instead308309**MCP tool hooks (CC 2.1.118+)** — hooks can call MCP tools directly via310`type: "mcp_tool"`. Required fields: `server`, `tool`; optional `input` with311`${tool_input.field}` substitution. Caveat: SessionStart and Setup fire before312MCP servers finish connecting, so for service detection prefer a direct probe313(see `detect-tidewave.sh`); reserve `mcp_tool` hooks for PreToolUse / PostToolUse314/ Stop where the connection is already live.315316### Tidewave Integration317318When Tidewave MCP available:319320- Prefer `mcp__tidewave__get_docs` over web search321- Prefer `mcp__tidewave__project_eval` over test scripts322- Prefer `mcp__tidewave__execute_sql_query` over psql323324## Development325326### Testing locally327328```bash329# Option A: Test plugin directly, including its public command namespaces330claude \331 --plugin-dir ./plugins/elixir-phoenix \332 --plugin-dir ./plugins/ecto \333 --plugin-dir ./plugins/lv334335# Option B: Add as local marketplace336/plugin marketplace add .337/plugin install elixir-phoenix338```339340The marketplace/install identity is `elixir-phoenix`, but the canonical341manifest namespace must stay `phx` so existing `/phx:*` commands remain valid.342The `ecto` and `lv` dependencies preserve `/ecto:*` and `/lv:*`. Claude Code343uses plugin namespaces plus skill directory names for effective slash commands;344frontmatter `name` alone does not preserve these public names.345346When editing skills, agents, or hooks mid-session, run `/reload-plugins` to347pick up changes without restarting Claude Code (v2.1.98+). Skills now hot-reload348through this command even when provided by installed plugins.349350### Testing workflow351352```bash353# Test individual workflow phase354/phx:plan Test feature for workflow355# Check: .claude/plans/ has checkbox plan356357/phx:work .claude/plans/test-feature/plan.md358# Check: Checkboxes update, progress logged in plans/test-feature/progress.md359```360361### Adding new agent3623631. Create `plugins/elixir-phoenix/agents/{name}.md`3642. Add frontmatter with all required fields3653. Keep under 300 lines366367### Adding new skill3683691. Create `plugins/elixir-phoenix/skills/{name}/SKILL.md` (~100 lines)3702. Create `references/` with detailed content3713. For workflow skills, document integration with cycle372373### Setup374375```bash376npm install # Pre-commit hooks + linting377```378379### Quality Commands (use `make`)380381```bash382make help # Show all commands383make lint # Lint markdown384make lint-fix # Auto-fix lint385make test # Pytest suites for the eval framework and port tooling386make eval # Quick: lint + structurally score changed skills/agents387make eval-all # Structurally score all 51 skills + 26 agents388make eval-full # Structural checks + fresh per-skill behavioral gate389make eval-fix # Auto-fix lint + show failures + suggest autoresearch390make eval-tournament # Run tournament on weak skills (<75% trigger accuracy)391make ci # Full CI pipeline: lint + test + validate + eval + security392```393394### Eval Framework (lab/eval/)395396The plugin has seven deterministic structural dimensions plus a neutral397behavioral slot for skills, and five deterministic dimensions for agents.398**Run `make eval` after every skill/agent edit.**399400**When editing skills/agents, ALWAYS verify your changes pass eval:**4014021. Edit the skill or agent file4032. Run `make eval` — checks only changed files4043. If FAIL: run `make eval-fix` to see exact failures and get fix suggestions4054. Fix the issues and re-run until PASS406407**What eval checks** (skills — 7 structural dimensions + behavioral slot):408409- completeness (sections, Iron Laws, frontmatter)410- accuracy (cross-references valid)411- conciseness (line counts, section limits)412- triggering (description keywords, "Use when..." structure)413- safety (Iron Laws, prohibitions, no dangerous patterns)414- clarity (action density, no duplication, step coverage)415- specificity (code examples, concrete vs vague)416- behavioral (neutral during structural scoring; `make eval-full` runs a fresh417 Haiku gate and requires every skill to reach 75% trigger accuracy)418419**What eval checks** (agents — 5 dimensions):420421- completeness (frontmatter: name, description, tools, model, effort)422- accuracy (preloaded skills exist, tools valid)423- conciseness (line limits per agent type)424- safety (bypassPermissions, read-only enforcement)425- consistency (model matches effort level)426427## Size Guidelines428429| Component | Target | Hard Limit | Notes |430|-----------|--------|------------|-------|431| SKILL.md (reference) | ~100 | ~150 | Iron Laws + quick patterns |432| SKILL.md (command) | ~100 | ~185 | Command skills need complete execution flow inline |433| references/*.md | ~350 | ~350 | Detailed patterns |434| agents (specialist) | ~300 | ~365 | Design guidance beyond preloaded skill patterns |435| agents (orchestrator) | ~300 | ~535 | Subagent prompts + flow control must be inline |436437### Why orchestrators and command skills exceed targets438439Even with `permissionMode: bypassPermissions`, plugin files live in `~/.claude/plugins/cache/` — outside the project.440This means agents **cannot reliably read** skill `references/*.md` at runtime.441442Content must be inline (in agent prompt or preloaded SKILL.md) to be available:443444| Location | Auto-available? | Reliable? |445|----------|----------------|-----------|446| Agent system prompt | Yes | Yes |447| Preloaded skill SKILL.md (`skills:` field) | Yes | Yes |448| Skill `references/*.md` | No — needs Read call | **No** — permission prompt |449450Orchestrators embed subagent prompts (~80 lines × 4 agents = 320 lines minimum).451Command skills drive execution — removing a step breaks the workflow.452Only trim when content is purely informational and not execution-critical.453454## Checklist455456### New agent457458- [ ] Frontmatter complete459- [ ] `disallowedTools: Edit, NotebookEdit` for review agents (Write remains460 available only for findings artifacts; the read-only source rule is also an461 explicit instruction, not a tool-enforced security boundary)462- [ ] `Write` allowed for agents that output reports (research agents, reviewers, context-supervisor). Only agents that neither review nor research should have Write disallowed.463- [ ] `permissionMode: bypassPermissions`464- [ ] `effort:` set (low for haiku, medium for sonnet, high for opus/security)465- [ ] `omitClaudeMd: true` for report-only agents (Write allowed for own report, Edit disallowed). They don't need commit/lint guidelines. Iron Laws injected via SubagentStart hook.466- [ ] Skills preloaded467- [ ] Description under 250 characters468- [ ] Under target (300 lines), hard limit only if justified by inline subagent prompts469470### New skill471472- [ ] SKILL.md under target (~100 lines), hard limit for command skills (~185)473- [ ] "Iron Laws" section474- [ ] `references/` paths use `${CLAUDE_SKILL_DIR}/references/`475- [ ] `effort:` set (low/medium/high)476- [ ] No `triggers:` field477- [ ] Description under 250 characters (CC internal budget cap)478479### New workflow skill480481- [ ] Clear input/output artifacts482- [ ] Integration diagram with cycle position483- [ ] State transitions documented484- [ ] References previous/next phases485486### Release487488- [ ] All markdown passes linting489- [ ] Version bumped together in the `elixir-phoenix`, `ecto`, and `lv` plugin manifests490- [ ] `CHANGELOG.md` updated with all changes under new version heading491- [ ] README updated492- [ ] `/phx:intro` tutorial content still accurate (commands, agents, features)493- [ ] Public `/phx:*`, `/ecto:*`, and `/lv:*` command names still match skill directories and compatibility dependencies494495> **Tagging note**: `claude plugin tag` (CC 2.1.118+) does NOT work for this496> repo. It expects `.claude-plugin/plugin.json` at the repo root, but this497> is a marketplace layout — the plugin lives at498> `plugins/elixir-phoenix/.claude-plugin/plugin.json`. Tagging stays manual:499> `git tag vX.Y.Z && git push --tags`.500501### Versioning502503The plugin uses [semantic versioning](https://semver.org/):504505- **MAJOR**: Breaking changes (workflow redesign, removed commands)506- **MINOR**: New features (new hooks, skills, agents, commands)507- **PATCH**: Bug fixes, doc updates, description improvements508509**IMPORTANT**: Users only receive updates when the version in `plugin.json`510changes. If you push code without bumping the version, existing users won't511see the changes due to caching.512513When making changes, ALWAYS update `CHANGELOG.md` under the current514`[Unreleased]` section. Use categories: Added, Changed, Fixed, Removed.515On release, rename `[Unreleased]` to `[X.Y.Z] - YYYY-MM-DD` and bump516`plugin.json`.517518---519520# Claude Code Behavioral Instructions521522**CRITICAL**: These instructions OVERRIDE default behavior for Elixir/Phoenix projects in this codebase.523524## Automatic Skill Loading525526When working on Elixir/Phoenix code, ALWAYS load relevant skills based on file context:527528| File Pattern | Auto-Load Skills | Check References |529|--------------|------------------|------------------|530| `*_live.ex`, `*_component.ex` | `liveview-patterns` | `references/async-streams.md` |531| `*_channel.ex`, `*socket*` | `liveview-patterns` | `references/channels-presence.md` |532| `*/workers/*`, `*_worker.ex`, `*_worker_test.exs`, `*_job.ex`, `*_agent.ex` | `oban` | `references/worker-patterns.md` |533| `*/migrations/*`, `*_schema.ex`, `*changeset*`, `schema "` | `ecto-patterns` | `references/queries.md`, `references/changesets.md` |534| `*auth*`, `*session*`, `*password*` | `security` | `references/authentication.md`, `references/authorization.md` |535| `*_test.exs`, `*factory*`, `*fixtures*` | `testing` | `references/exunit-patterns.md`, `references/mox-patterns.md`, `references/factory-patterns.md` |536| `config/runtime.exs`, `Dockerfile`, `fly.toml` | `deploy` | `references/docker-config.md` |537| `*/contexts/*`, `lib/*/[a-z]*.ex` | `phoenix-contexts` | `references/context-patterns.md` |538| `lib/mix/tasks/*` | `elixir-idioms` | `references/mix-tasks.md` |539| `*.sface` | `liveview-patterns` | `references/components.md` |540| `priv/resource_snapshots/**` | `ash-framework` | NEVER edit snapshots manually — owned by `mix ash.codegen` |541| Any `.ex` or `.exs` file | `elixir-idioms` | Always check Iron Laws |542543### Skill Loading Behavior5445451. When opening/editing a file matching patterns above, silently load the skill5462. Apply Iron Laws from loaded skills as validation rules5473. If code violates Iron Law, **stop and explain** before proceeding5484. Reference detailed docs from `references/` when making implementation decisions549550## Workflow Routing (Hook-Driven)551552High-signal intents are detected by the `route-intent.sh` UserPromptSubmit553hook, which injects a one-line `/phx:` suggestion directly into context:554PR URLs / review-feedback phrasing → `/phx:pr-review`; Tidewave555`<context name="current-page">` blocks → `/phx:investigate`; Elixir stack556traces → `/phx:investigate`. One suggestion per category per session,557silent on explicit slash commands. (CLAUDE.md prose routing measured ~0%558firing across 400 sessions — detection lives in the hook now.)559560For ambiguous multi-step requests not covered by the hook, the561`intent-detection` skill's routing table still applies: suggest once,562never block, skip for trivial tasks.563564### Debugging Loop Detection565566The `error-critic.sh` hook automatically detects repeated mix failures and567escalates from generic hints (attempt 1) to structured critic analysis568(attempt 3+). It tracks failure count per command and consolidates error569history. This implements the Critic→Refiner pattern from AutoHarness570(Lou et al., 2026): structured error consolidation before retry prevents571debugging loops more effectively than unstructured retry.572573If the hook hasn't triggered (e.g., non-mix failures), manually detect:574when 3+ consecutive Bash commands are `mix compile` or `mix test` with failures,575suggest: "Looks like a debugging loop. Want me to run `/phx:investigate` for structured analysis?"576577### Custom MIX_ENV Awareness578579Some projects use non-standard Mix environments (e.g., `MIX_ENV=int_test` for E2E tests). When you see:580581- `config/int_test.exs` or other non-standard env config files582- `MIX_ENV=` in mix.exs aliases583- User running `MIX_ENV=<custom> mix compile/test`584585Then use that MIX_ENV for ALL compile, test, and format commands on those files. Do NOT use default MIX_ENV for files that only compile under the custom env.586587### Scoped Format and Compile Checks588589When running `mix format --check-formatted` or `mix compile`, **always scope to the files you changed**590when possible. If a full-project check fails on files you didn't edit, report it as pre-existing591and continue — do NOT waste time debugging unrelated format failures.592593### Sibling File Check594595When fixing a bug in a file that has named variants (e.g., `seller_account/form.ex`,596`buyer_account/form.ex`, `occupier_account/form.ex`), proactively grep for all sibling files and597check if the same bug exists in each variant. Do this BEFORE implementing the fix, not after.598599## Iron Laws Enforcement (NON-NEGOTIABLE)600601These rules are NEVER violated. If code would violate them, **STOP and explain** before proceeding:602603### LiveView Iron Laws6046051. **NO unconditional DB queries in mount** - Mount runs twice. Default: `assign_async`. SEO routes: `connected?` + cache-backed disconnected branch (dead-render IS the crawler-indexed HTML)6062. **ALWAYS use streams for lists >100 items** - Regular assigns = O(n) memory per user6073. **CHECK `connected?/1` before PubSub subscribe** - Prevents double subscriptions608609### Ecto Iron Laws6106114. **NEVER use `:float` for money** - Use `:decimal` or `:integer` (cents)6125. **ALWAYS pin values with `^` in queries** - Never interpolate user input6136. **SEPARATE QUERIES for `has_many`, JOIN for `belongs_to`** - Avoids row multiplication614615### Oban Iron Laws6166177. **Jobs MUST be idempotent** - Safe to retry6188. **Args use STRING keys, not atoms** - Pattern match `%{"user_id" => id}`6199. **NEVER store structs in args** - Store IDs, not `%User{}`620621### Security Iron Laws62262310. **NO `String.to_atom` with user input** - Atom exhaustion DoS62411. **AUTHORIZE in EVERY LiveView `handle_event`** - Don't trust mount authorization62512. **NEVER use `raw/1` with untrusted content** - XSS vulnerability626627### OTP Iron Laws62862913. **NO process without runtime reason** - Processes model concurrency/state/isolation, NOT code structure63014. **SUPERVISE ALL LONG-LIVED PROCESSES** - Never bare `GenServer.start_link`/`Agent.start_link` in production. Use supervision trees631632### Ecto Iron Laws (continued)63363415. **NO IMPLICIT CROSS JOINS** - `from(a in A, b in B)` without `on:` creates Cartesian product635636### Elixir Iron Laws63763816. **@external_resource FOR COMPILE-TIME FILES** - Modules reading files at compile time MUST declare `@external_resource`639640### Ecto Iron Laws (continued)64164217. **DEDUP BEFORE `cast_assoc` WITH SHARED DATA** - Deduplicate shared child records before building changesets, not inside them643644### LiveView Iron Laws (continued)64564618. **CHECK CHANGESET ERRORS BEFORE UI DEBUGGING** - When a form save produces no visible error but no expected side effect, check `{:error, changeset}` first647648### Ecto Iron Laws (continued)64965019. **HIDDEN INPUTS FOR ALL REQUIRED EMBEDDED FIELDS** - Every required field in an embedded schema MUST have a `hidden_input` if not directly editable651652### Elixir Iron Laws (continued)65365420. **WRAP THIRD-PARTY LIBRARY APIs** - Always facade external dependency APIs behind a project-owned module. Enables swapping libraries without touching callers655656### LiveView Iron Laws (continued)65765821. **NEVER use `assign_new` for values refreshed every mount** - `assign_new` skips the function if the key exists. Use `assign/3` for locale, current user, or any value that must be set on every mount659660### Verification Iron Laws66166222. **VERIFY BEFORE CLAIMING DONE** - Never say "should work" or "this fixes it." Run `mix compile && mix test` and show the result. If you can't verify, explicitly state what remains unverified663664### Elixir Iron Laws (continued)66566623. **MIX TASKS START ONLY WHAT THEY NEED** - `Mix.Task.run("app.config")` + `Application.ensure_all_started/1`, never `Mix.Task.run("app.start")` (boots full tree: endpoint port, Oban consuming)667668### LiveView Iron Laws (continued)66967024. **MATCH `{:error, %Ecto.Changeset{}}` EXPLICITLY** - Bare `{:error, _}` merges changeset and non-changeset errors; the form never re-renders validation errors. Handle others separately671672### Elixir Iron Laws (continued)67367425. **CAPTURE LOCALE BEFORE SPAWNING** - Gettext/CLDR locale is process-local. Read it in the caller and pass it explicitly — a spawned Task/GenServer starts with the default locale675676### Code Style Iron Laws67767826. **COMMENTS AREN'T COMMIT MESSAGES** - A change's reasoning belongs in the commit/PR — git persists it, not code. No issue tags inline. Keep only durable facts: footguns, invariants, quirks679680### Violation Response681682When detecting a potential Iron Law violation:683684```685STOP: This code would violate Iron Law [number]: [description]686687What you wrote:688[problematic code]689690Correct pattern:691[fixed code]692693Should I apply this fix?694```695696## Framework Detection697698### Ash Framework Detection699700If the project uses Ash Framework (detected by `:ash` in mix.exs, `use Ash.Resource`, or `use Ash.Domain`):7017021. **Load** the `ash-framework` skill — it owns Ash-specific patterns for data access, resources, and actions7032. **Research first**: `mix usage_rules.search_docs "<topic>" -p ash -p ash_phoenix -p ash_postgres -p ash_authentication -p ash_oban`7043. **Module lookup**: `mix usage_rules.docs Ash.Resource`7054. **Generators first**: `mix ash.gen.resource`, `mix ash.codegen`, `mix ash.gen.domain`7065. **Data access**: prefer Ash actions via domain code interfaces over direct `Repo` calls — Ash is a complement to Phoenix/Ecto, not a replacement. LiveView, security, and OTP Iron Laws still apply.707708### Phoenix Version Detection709710Check `mix.exs` for Phoenix version:711712- **Phoenix 1.8+**: Scopes are available, recommend scope-first patterns713- **Phoenix 1.7.x**: No scopes, use traditional plug-based auth (see `references/scopes-auth.md` Pre-Scopes section)714715## Greenfield Project Detection716717If project has <10 `.ex` files (new project):7187191. **Use simpler planning** (no parallel agents needed)7202. **Suggest initial setup**: Tidewave, Credo, test factories721722## Reference Auto-Loading723724When working on code, automatically consult relevant reference documentation before implementing.725726### Auto-Load Rules727728| File/Code Pattern | Skill | References to Consult |729|-------------------|-------|----------------------|730| `*_live.ex` | liveview-patterns | async-streams.md, components.md |731| `*_live.ex` + form code | liveview-patterns | forms-uploads.md |732| `*_live.ex` + JS hooks | liveview-patterns | js-interop.md |733| `*_channel.ex`, `*socket*` | liveview-patterns | channels-presence.md |734| `Presence` in code | liveview-patterns | channels-presence.md |735| `priv/repo/migrations/*` | ecto-patterns | migrations.md |736| `use Ecto.Schema`, `*changeset*` | ecto-patterns | changesets.md |737| `from(` or `Repo.` | ecto-patterns | queries.md |738| `*/workers/*`, `*_worker.ex`, `*_worker_test.exs`, `*_agent.ex` | oban | worker-patterns.md |739| `use Oban.Worker` | oban | worker-patterns.md, queue-config.md |740| `*auth*`, `*session*` | security | authentication.md, authorization.md |741| `oauth`, `ueberauth` | security | oauth-linking.md |742| `*_test.exs` | testing | exunit-patterns.md |743| `*factory*`, `*fixtures*`, `*_factory.ex` | testing | factory-patterns.md |744| `*_live_test.exs` | testing | liveview-testing.md |745| `Mox.` in tests | testing | mox-patterns.md |746| `lib/*/[a-z]*.ex` (context) | phoenix-contexts | context-patterns.md |747| `*.sface` | liveview-patterns | components.md |748| `router.ex` | phoenix-contexts | routing-patterns.md, plug-patterns.md |749| `*_controller.ex` + JSON | phoenix-contexts | json-api-patterns.md |750| `plug` in router/controller | phoenix-contexts | plug-patterns.md |751| `Dockerfile`, `fly.toml` | deploy | docker-config.md, flyio-config.md |752| `use GenServer` | elixir-idioms | otp-patterns.md |753| `lib/mix/tasks/*` | elixir-idioms | mix-tasks.md |754755### Consultation Behavior7567571. **Before implementing**, read relevant reference for correct pattern7582. **Silently apply** patterns (don't narrate unless complex)7593. **Check Iron Laws** from skill before and after implementation7604. **Security code ALWAYS gets reference consultation** (authentication.md, authorization.md)761762## Command Suggestions763764| User Intent | Command |765|-------------|---------|766| "Which command should I use?" | `/phx:help` |767| New to the plugin | `/phx:intro` |768| Bug fix, debug | `/phx:investigate` |769| Small UI fix, CSS tweak, config change | `/phx:quick` |770| Small change (<50 lines) | `/phx:quick` |771| Brainstorm, explore ideas, unclear scope | `/phx:brainstorm` |772| New feature (clear scope) | `/phx:plan` then `/phx:work` |773| Understand a plan | `/phx:brief` |774| Enhance existing plan | `/phx:plan --existing` |775| Large feature (new domain) | `/phx:full` |776| Review code | `/phx:review` |777| Triage review findings | `/phx:triage` |778| Capture solved problem | `/phx:compound` |779| Run checks | `/phx:verify` |780| Research topic | `/phx:research` |781| Evaluate a Hex library | `/phx:research --library` |782| Resume work | `/phx:work --continue` |783| N+1 queries | `/ecto:n1-check` |784| LiveView memory | `/lv:assigns` |785| PR review comments | `/phx:pr-review` |786| Waiting on CI / reviewers | `/phx:watch-pr` |787| Codex review before PR (codex CLI installed) | `/phx:review --codex` |788| Autonomous cycle + Codex second opinion | `/phx:full --codex` |789| Fix until Codex review is clean | `/phx:codex-loop` |790| Codex cloud review loop on a PR | `/phx:watch-pr N --codex` |791| Update dependencies | `/phx:deps-update` |792| "Have we done this before?" | `/phx:recall` |793| Performance analysis | `/phx:perf` |794| Project health | `/phx:audit` |795| Reduce permission prompts | `/phx:permissions` |796| Scan sessions for metrics | `/session-scan` |797| Deep-analyze sessions | `/session-deep-dive` |798| View session trends | `/session-trends` |799| Monitor skill effectiveness | `/skill-monitor` |800| Validate plugin against docs | `/docs-check` |801802**Workflow Commands**: `/phx:brainstorm` (optional) -> `/phx:plan` -> `/phx:brief` (optional) -> `/phx:plan --existing` (optional) -> `/phx:work` -> `/phx:review` -> `/phx:triage` (optional) -> `/phx:compound`803804**Review → Follow-up Plan**: After `/phx:review`, if findings reveal scope gaps or missing coverage, use `/phx:plan .claude/plans/{slug}/reviews/{review}.md` to create a follow-up plan from review output.805806**Standalone**: `/phx:quick`, `/phx:full`, `/phx:investigate`, `/phx:verify`, `/phx:research`, `/phx:brainstorm`, `/phx:help`, `/phx:permissions`, `/phx:codex-loop` (needs codex CLI)807808**Analysis**: `/ecto:n1-check`, `/lv:assigns`, `/phx:boundaries`, `/phx:trace`, `/phx:techdebt`809810**Session Analytics (dev-only, requires ccrider MCP)**: `/session-scan`, `/session-deep-dive`, `/session-trends`811812**Skill Monitoring (dev-only)**: `/skill-monitor` — per-skill effectiveness dashboard and improvement recommendations813814**Plugin Maintenance (dev-only)**: `/docs-check` — validate plugin against latest Claude Code documentation815816## Workflow Patterns (from Claude Code team)817818### Challenge Mode819820When I say "grill me" or "challenge this":821822- Review my changes as a senior Elixir engineer would823- Check for: N+1 queries, missing error handling, OTP anti-patterns, untested paths824- Diff behavior between `main` and current branch825- Don't approve until issues are addressed826827### Elegance Reset828829When I say "make it elegant" or "knowing everything you know now":830831- Scrap the current approach832- Implement the idiomatic Elixir solution833- Prefer pattern matching over conditionals834- Prefer `with` chains over nested `case`835- Prefer streams/`Enum` pipelines over imperative loops836- Use proper OTP patterns where applicable837838### Auto-Fix Patterns839840When I say:841842- "fix CI" → Run `mix compile --warnings-as-errors && mix test --failed` and fix all failures843- "fix it" → Look at the error/bug context and autonomously fix without asking questions844- "fix credo" → Run `mix credo --strict` and fix all issues845846### Learn From Mistakes847848After ANY correction I make:849850- Ask: "Should I update CLAUDE.md so this doesn't happen again?"851- If yes, add a concise rule preventing the specific mistake852- Keep rules actionable: "Do NOT X — instead Y"853854### Intro Tutorial Maintenance855856When adding, removing, or renaming commands/skills/agents, check if857`plugins/elixir-phoenix/skills/intro/references/tutorial-content.md` needs updating.858The tutorial is new users' first impression — stale command references erode trust.859Quick check: does the cheat sheet in Section 4 still match reality?860861### Interesting Findings Log862863When you discover something noteworthy during work — a surprising metric, a864counter-intuitive finding, a useful pattern from research, or a before/after865improvement stat — **append it to `lab/findings/interesting.jsonl`** immediately.866867Format (one JSON per line):868869```json870{"date": "2026-03-25", "category": "behavioral", "title": "Plan skill has 0% recall", "detail": "Haiku never routes 'build a chat feature' to plan skill despite description saying 'multi-file feature'. Use-case phrases needed, not technical terms.", "source": "trigger_scorer.py", "tags": ["autoresearch", "trigger", "description"]}871```872873Categories: `behavioral`, `performance`, `research`, `pattern`, `bug`, `metric`, `user-insight`874875This log feeds blog posts, release notes, and Twitter threads. Don't filter —876write anything that made you think "that's interesting". The file is gitignored.877
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| bagisto/bagistoCLAUDE.md · 28k | CLAUDE.md | setupbuildteststyle+5 | 100/100 | 3 days ago | |
| livewire/livewireCLAUDE.md · 24k | CLAUDE.md | setupbuildteststyle+4 | 100/100 | 3 days ago | |
| nimbalyst/nimbalystpackages/android/CLAUDE.md · 1.4k | CLAUDE.md | setupbuildstylearch+2 | 100/100 | 3 days ago | |
| dotCMS/corecore-web/CLAUDE.md · 949 | CLAUDE.md | teststylearchtesting-strategy+3 | 100/100 | 3 days ago | |
| microsoft/playwrightCLAUDE.md · 94k | CLAUDE.md | buildtestlint-formatstyle+7 | 100/100 | 3 days ago | |
| filamentphp/filamentCLAUDE.md · 32k | CLAUDE.md | buildtestlint-formatstyle+7 | 100/100 | 3 days ago | |
| Adit-Jain-srm/NightmareNetCLAUDE.md · 45 | CLAUDE.md | buildtestlint-formatstyle+6 | 100/100 | 3 days ago | |
| dotCMS/coreCLAUDE.md · 949 | CLAUDE.md | setupbuildteststyle+7 | 99/100 | today |
