
all-skills
Meta-plugin that installs all skills from all plugins in the marketplace
- version
- 0.4.187
- GitHub stars
- 27
Install
/plugin install all-skills@vinnie357Run it inside Claude Code after adding the marketplace with /plugin marketplace add vinnie357/claude-skills.
Contents
Discovered from sourceSkills 109
Agent Loop
Defines the standard workflow for agents working epics, issues, and tasks through a 4-phase execution model with a 6-tier prompt hierarchy.
Forge — the default operating model
Forge is the name for how this skill works an issue: paired teams of strong-model principals and cheap read-only hands, fanned out across the issue's slices, with reviewers on the best-thinker model. Forge is the implied default for all work — the lead applies it without being told to "use the 5/6-tier system."
Activate Forge by work phrasing ("work epic/issue ", acting on bees ready), by forge <id> in a mission / spawn prompt, or by the /work command in an interactive session — all load this skill and run Forge on the target.
Two disciplines make Forge cheap and reliable:
- Hands do the searching and the running. Principals (planners, reviewers) never run their own
Grep/Glob/large-Readsweeps, and never run their own commands. They spawn focused read-only hands for research and execution hands for bounded commands. Seereferences/reviewer.mdandreferences/researcher.md. - Paired teams fan out. Every issue runs the same paired structure; fan-out width
N= the planner's slice count (N=1for a small issue, same path). Seereferences/forge.md.
The process these rules implement — durable vs ephemeral artifacts, reviewer and output rules — is in references/process.md.
Required plugins
Assumes both core@vinnie357 (this plugin) and extras-claude-code@vinnie357 (agent/team file formats, referenced by name in spawning steps) are installed. Standalone core still describes the workflow, but cross-plugin skill names like /extras-claude-code:claude-agents won't resolve until extras-claude-code@vinnie357 is installed too — treat those references as procedural-only until then.
4-Phase Execution
Every agent, regardless of tier, follows these four phases:
| Phase | Name | Purpose |
|---|---|---|
| 1 | Pre-flight | Load skills, check tracker, verify branch, understand assignment |
| 2 | Working | Execute work items. Before any spawn: re-verify core skills loaded, load /extras-claude-code:claude-agents always, load /extras-claude-code:claude-teams for ≥2 parallel workers. |
| 3 | Validation | Run strictest CI suite, iterate with fix agent until clean |
| 4 | Submit | Create PR, wait for CI, report to upstream, clean up after merge |
Phase 1.5: Decomposition Gate
Between Phase 1 (pre-flight) and Phase 2 (spawn), the Team Leader checks two deterministic signals — no file searching:
- bees:
bees list --epic <slug>— does the epic already have issues? DECOMPOSITION_PATHenv var: is it set AND does the file it points at exist? This is the canonical signal an upstream process sets to hand off a pre-computed proposal.
| State | bees | DECOMPOSITION_PATH | Action |
|---|---|---|---|
| A | Has issues | Unset, OR set+missing | Skip Phase 1.5a. Spot-check each issue (AC, skill labels, dep edges). Flag gaps, proceed. |
| B | Empty | Unset, OR set+missing | Run Phase 1.5a — produce the decomposition from the epic objective + AC, record assumptions, decompose into bees. Ask only on a genuine fork or hard blocker. |
| C | Empty | Set + file exists | Consume the proposal verbatim — bees create one issue per proposed item with AC, skill labels, and dep edges as written. Topological order (deps before dependents); map depends_on titles to bee IDs returned by prior bees create calls as you go. If any cycle is detected in the dep graph (2-cycle X↔Y, 3-cycle A→B→C→A, or longer), halt and report all cycle members — create zero issues. No clarifying questions. Spot-check after, proceed. |
| D | Has issues | Set + file exists | Resume gap — diff proposal titles vs existing bees titles. Materialize each missing proposed item with the same rules as State C (topological order, cycle detection). Spot-check the complete set, proceed. Never re-ask, never re-decompose. |
Robustness:
- Empty string (
"") forDECOMPOSITION_PATH= unset — no log, proceed as State A or B per the bees-state column. - Set but file missing: emit exactly one line —
agent-loop: DECOMPOSITION_PATH=<value> not found; proceeding as State <B|A>(B if bees empty, A if bees has issues). No retry, no search, no crash. - Never search for proposal files outside
DECOMPOSITION_PATH. Unset or empty = no proposal, full stop.
Proposal file format: this skill mandates only the consumption rules above; the file's on-disk schema is defined by whatever upstream process produces it. A minimum interoperable shape is a JSON array of issues each carrying title, acceptance_criteria (list), labels (list), and depends_on (list of titles or stable local keys that resolve to other entries in the same file).
Phase 1.5a: Default to proceeding (State B only)
Plan presence, not who is at the keyboard, is the operative question. A plan is PRESENT when DECOMPOSITION_PATH is set and the file exists, OR bees already has issues, OR an upstream proposal exists. States A / C / D are plan-present — consume, spot-check, or resume and proceed; never ask clarifying questions there.
State B is plan-absent: the lead PRODUCES the decomposition from the epic objective and acceptance criteria, records assumptions as a bees comment (audit trail), and proceeds on the most reasonable interpretation.
Reserve AskUserQuestion for a genuine architectural fork the user owns that can't be responsibly defaulted, or a hard blocker: missing repository, missing credential, or contradictory acceptance criteria with no clear winner. A preference question — "approach A or B?" — is NOT a blocker; pick the reasonable default, record it, proceed.
When escalating, group related questions into a single AskUserQuestion call (max 4 questions, 2–4 options each) — never one at a time. Once a decision is judged a genuine fork the user owns, ask rather than guess. Doesn't apply to single-file mechanical refactors, status checks, or log diagnosis.
Applies in every context: a host running without a human supplies the plan (State C fires); with no plan, the default is still proceed-on-reasonable-default.
6-Tier Prompt Hierarchy
These six tiers describe authority — who reports to whom across an epic. For the orthogonal axis of how a single issue flows through staged agents, see "Five-Tier Decomposition Pipeline" below.
| Tier | Role | Scope | Default model tier | Reference |
|---|---|---|---|---|
| 0 | Epic Author | Write machine-executable epics | human | references/epic-authoring.md |
| 1 | Team Leader | Four-state gate (spot-check / consume proposal / ask+decompose / resume gap); spawn agents | deep reasoning | references/team-leader.md |
| 2 | Sub-team Leader | Decompose issue into tasks, manage workers | general | references/sub-team-leader.md |
| 3 | Agent Worker | Execute a single task with TDD | smallest fast | references/agent-worker.md |
| 4 | Validator | Run CI, report all failures, never fix | smallest fast | references/validator.md |
| 5 | Fix Agent | Receive failures, fix code, re-run tests | smallest fast | references/fix-agent.md |
Model overrides (env-var convention)
Model defaults per tier are exactly that — defaults. Each tier honors an env var so a deployment can swap models when a new family ships, without changing the spawn script (12-factor config):
| Tier | Env var | Default |
|---|---|---|
| 1 Team Leader | AGENT_LOOP_LEAD_MODEL | deep reasoning |
| 2 Sub-team Leader | AGENT_LOOP_SUBLEAD_MODEL | general |
| 3 Agent Worker | AGENT_LOOP_WORKER_MODEL | smallest fast |
| 4 Validator | AGENT_LOOP_VALIDATOR_MODEL | smallest fast |
| 5 Fix Agent | AGENT_LOOP_FIX_MODEL | smallest fast |
| Plan Reviewer | AGENT_LOOP_PLAN_REVIEWER_MODEL | strongest reasoning, falling back to strongest fallback |
| Test Reviewer | AGENT_LOOP_TEST_REVIEWER_MODEL | strongest reasoning, falling back to strongest fallback |
| Reviewer | AGENT_LOOP_REVIEWER_MODEL | strongest reasoning, falling back to strongest fallback |
| Final Reviewer | AGENT_LOOP_FINAL_REVIEWER_MODEL | strongest reasoning, falling back to strongest fallback |
| Research hands (text) | AGENT_LOOP_HANDS_MODEL | smallest fast |
| Research hands (vision) | AGENT_LOOP_HANDS_VISION_MODEL | multimodal |
| Execution hands | AGENT_LOOP_HANDS_MODEL | smallest fast |
The hands vars follow the same contract as the tier vars: the launching process resolves them and passes the model to the spawn; no model name appears as a literal in the prompt body. The vision var is set by capability, not by a fixed name — the available multimodal model shifts with the harness and model family. See references/researcher.md. Per-harness model ids and effort settings: references/model-tiers.md.
Contract: whoever launches the spawning process (shell command, CI job, parent Claude session, external orchestrator) sets these env vars; the spawn script reads $AGENT_LOOP_* and passes the resolved model to the Task tool invocation (subagent_type/model argument) — never as a literal in the prompt body. An empty string (AGENT_LOOP_LEAD_MODEL="") is treated identically to unset, falling through to the default, so orchestrators can emit "" to mean "use default" without special-casing.
Each AGENT_LOOP_<ROLE>_MODEL has an AGENT_LOOP_<ROLE>_EFFORT; empty resolves to the ADR 0001 decision 5 default. The launcher passes it wherever the harness accepts an effort setting (references/model-tiers.md).
One AGENT_LOOP_* var selects something other than a model, and the Contract above does not apply to it — the launcher sets it, but no spawn resolves it to a model:
| Selects | Env var | Default |
|---|---|---|
| Merge actor | AGENT_LOOP_MERGE_POLICY | operator |
Its two values are operator and approval, defined in /core:git "Merge authorization"; the default authorizes no agent merge.
The four Forge reviewer vars added above default to a capability fallback: attempt the strongest
reasoning tier, and retry the strongest fallback tier if that spawn fails due to unavailability.
This is explicitly the REVERSE of the smallest-fast-to-general-to-deep-reasoning escalation-on-failure
ladder described next — that one promotes on repeated failure of the task itself; this one degrades
on model unavailability and never fires because a review came back unfavorable. The mechanism is
already shipped and documented on core:comment-reviewer (plugins/core/agents/comment-reviewer.md,
"Model fallback" section); these four vars reuse that exact contract rather than defining a second
one.
The escalation chain is also overridable: AGENT_LOOP_ESCALATION_CHAIN (comma-separated tier names; default smallest fast, general, deep reasoning).
Model Escalation
Default assignment starts at the smallest fast tier. On repeated failure (2 attempts on same work item):
smallest fast -> general -> deep reasoning
Maximum 2 promotions per agent. If the deep reasoning tier fails, escalate to the upstream tier (sub-lead to lead, lead to user).
This ladder is failure-driven and applies to task-executing tiers; it is not the reviewer capability fallback described under Model overrides above — that one degrades on unavailability and never fires on a bad review.
Five-Tier Decomposition Pipeline
The 6-tier hierarchy above describes WHO reports to whom (authority). The five-tier pipeline below describes HOW one work item flows through five sequential agents (process). They are orthogonal: a Sub-team Leader (tier 2 authority) dispatches a pipeline (process) to deliver one issue.
The five roles below are the linear N=1 form; Forge (references/forge.md) is the canonical shape that generalizes them to paired teams and N-slice fan-out, with identical role-to-model defaults and adversarial separation.
For each issue, the Sub-team Leader spawns distinct Agent invocations in order. No shared context across stages — each stage is adversarial against the next.
| Pipeline Stage | Model | Responsibility | Forbidden |
|---|---|---|---|
| P1 Test Planner | deep reasoning | Translate acceptance criteria into ordered test list + edge cases | Writing code or tests |
| P2 Test Author | general | Write failing tests against P1's spec | Reading impl source; modifying after handoff |
| P3 Implementer | general | Make tests pass | Modifying test files; reading P2's chat context |
| P4 CI Runner | smallest fast | Run CI, capture verbatim output, report green/red | Judging correctness; touching code |
| P5 Reviewer | strongest reasoning | Verify tests exercise AC, no overfit, no missed edges | Authoring fixes (sends back to P2 or P3 with findings); running tests, CI, builds, or the app |
Each stage owes the restraint ladder its phase duty — see /core:restraint's agent-loop-phases reference for the row mapping (P1 → Test planning, P2 → Test authoring, P3 → Implementation, P5 → Review).
P1 Test Planner and Forge's Plan-pair Test Planner both stay on the deep reasoning tier — decomposition errors compound downstream, so the planner stays on the deepest-reasoning tier available. P2 Test Author and P3 Implementer stay on the general tier, per the Model Selection table's general row below. P4 stays on the smallest fast tier. Only P5 moves from deep reasoning to strongest reasoning, tracking Forge's Reviewer row in the pairs table — the same role in different fan-out shapes, not two roles.
When to apply
Apply for multi-file changes, public API surfaces (HTTP/exported/schema), cross-repo work, or any issue carrying explicit acceptance criteria. Single-agent stays acceptable for one-liners, mechanical refactors, status checks, and log diagnosis. When in doubt, decompose.
Fan-out happens at the Sub-team Leader, not at the epic decomposer or the bees-worker. Decomposition produces one bees issue per slice; the leader picking up the issue is the one that spawns the five stages.
Orchestration rules
- Each stage is a separate Agent invocation (no SendMessage continuations between tiers). This bans a finished stage from performing the next stage's work inside its own context — it does not ban reporting up to the dispatching leader. A stage spawned with a
namestill callsSendMessageto deliver its report; that call is not a continuation. - The leader verifies stage transitions before dispatching the next: test commit present before P3, test files unmodified before P5.
- P4 reports verbatim CI output; on red the leader dispatches a fresh P3 (no chat continuity).
- P5 reads
git diff main...HEAD, tests, and the acceptance criteria; approves with one line or rejects with a structured findings list. P5 reviews per/core:code-review, including its Restraint and Scope checklist item. P5 obtains evidence and reports perreferences/reviewer.md. - bees issues carry a single
complexity:complexorcomplexity:triviallabel, not tier labels. The Sub-team Leader picks up the issue, reads complexity, and (for complex) dispatches the five stages internally — each Task spawn prompt names its tier (team:opus-planner...team:opus-review) as dispatch-time metadata. Tier labels never land on bees rows. See/core:bees. - The five stages run as Task spawns by default. When Claude Code workflows are available and the operator opts in, encode them as one workflow script instead — the stage gates become deterministic assertions. See "Optional: workflow execution substrate" below and
references/workflows-execution.md.
Avoiding pipeline collapse
Single agents tend to merge planning + test-writing + implementation into one pass, defeating the adversarial separation. The leader prompt MUST explicitly name the stage (You are P2 — test author for issue <id>) and forbid out-of-stage activity.
Delegated research — the hands pattern
The costly principals (Plan Reviewer, Test Planner, Test Reviewer, Reviewer, Final Reviewer) delegate all search to research hands and all command execution to execution hands (see the Forge disciplines above). Select the hands model by capability, set in config — never a hardcoded name: text and code research use the smallest fast model (AGENT_LOOP_HANDS_MODEL); research that requires vision (images, screenshots, rendered web pages, visual PDFs, Playwright or visual MCP output) uses a multimodal-capable model the harness offers (AGENT_LOOP_HANDS_VISION_MODEL); execution hands use the smallest fast model (AGENT_LOOP_HANDS_MODEL). Full contract in references/researcher.md; references/dispatch-discipline.md carries the delegate-before-you-search rule.
Core Skills (Mandatory)
Every agent at every tier loads these before any work, with one bounded exemption below:
/core:anti-fabrication
/core:git
/core:tdd
/core:twelve-factor
/core:restraint
/core:security
/core:mise
/core:nushell
/core:agent-loop
/core:bees
Skill weight (how much each skill costs once loaded — reduced by claude-skills-288's skeleton+references conversion) and mandatory count (which skills must be force-invoked at all — this list, claude-skills-295) are two separate, additive reductions to the same token-loading tax. Cutting the mandatory list does not make the remaining skills lighter, and a lighter skeleton does not reduce how many skills a session force-invokes — both landed, neither substitutes for the other.
This block is the canonical copy. test/validate-core-list.nu drift-checks it against the ten sites it lists — this skill, six tier references (including the two subsetting satellites below, each checked against its declared subset rather than the full list), /core:work, the core session-start hook, and the operator CLAUDE.md template. Other files that enumerate core skills are not covered; add a site to that script when it starts carrying the full stack.
The exemption: a tier may omit an individual skill its role cannot exercise — nothing more. Apply the test per skill, not per tier. /core:tdd is the worked case: references/validator.md runs the suite and reports failures without writing code, so it omits /core:tdd; references/fix-agent.md writes the fix, so it keeps it. /core:anti-fabrication is never omissible — every tier reports, and a fabricated pass is worse than a red build. A subsetting tier states what it omits and why in its own pre-flight step, so the omission is a decision on the record rather than an accident.
Two limits on how far this is enforced. What a subsetting tier names is checked: the invocations check in test/validate-skills-quality.nu scans references/ and fails the run on any /plugin:skill token that does not resolve, so a stale or misspelled name cannot survive a core-list change. What a tier omits is checked only for satellites that register their declared subset (expected: [...]) in test/validate-core-list.nu's SATELLITES — today references/validator.md and references/fix-agent.md (claude-skills-152): dropping a name from the subset, or adding one beyond it, both fail CI. A subsetting tier that has not registered its subset is still unchecked on omission — dropping a skill it should carry passes CI, and only review catches it.
Domain-specific skills activate from their own Use when descriptions — that is the discovery mechanism at every tier. Two rules descriptions cannot express:
- Tracker state: a repo tracked by beads loads
/beads:beadsin place of/core:bees. - Issue labels: load the domain-plugin skills named by the issue's labels, by exact name.
Enforcement, not description, carries a third rule: leaders name every skill explicitly in the spawn prompt's ## Load skills block — globs do not expand, and listed is not loaded.
Skills to load before spawning
When a leader (Tier 1 or Tier 2) prepares to spawn an agent, load these by exact name with the Skill tool:
/extras-claude-code:claude-agents— always. Carries agent file format, tool allowlists, and model selection./extras-claude-code:claude-teams— if forming a team or spawning ≥2 parallel workers. Carries peer-to-peer messaging, shared task list, Agent SDK patterns./extras-claude-code:plugin-marketplace— when the spawned agent needs a skill not already in the team's load list.
Glob patterns like /core:* do not expand in Agent prompts. List skill names explicitly.
Key Conventions
- Tracker: Use bees (
bees ready,bees close) for issue management - Commits: Conventional commits, no attribution, no Co-Authored-By
- PRs: Minimal format (title + bullet list), no templates, no attribution
- Every Git/forge write: No robot emoji, "Generated with Claude Code", or assistant signatures in commits, branches, tags, PRs, MRs, issues, descriptions, comments, reviews or releases. Check outgoing fields before publishing, including generated body files; follow
/core:git. - TDD: Code without tests is not complete
- Merge gates (three): Gate 1 — local
mise run cigreen before every commit; Gate 2 — local + remotegh pr checksgreen; Gate 3 — adversarial review of the PR by a separate agent on the strongest available model, findings addressed or answered. All three before any squash merge (see/core:gitThree-Gate Merge Policy). Gate 3 is distinct from this skill's pipeline reviewers, including Forge's Final Reviewer — it is identified by its two-question brief (see/core:gitThree-Gate Merge Policy), not by when it runs. - Branches: One feature branch per epic (
feature/<epic-slug>) - Merge: Squash merge only, per the deployment's merge policy — see
/core:git"Merge authorization". The default authorizes no agent merge. - Agent naming: Spawn names are
<issue>-<role>-<model>-<n>(e.g.318-test-author-sonnet-1) — see/extras-claude-code:claude-agents"Agent Spawning Naming Convention" for the segment definitions and the counter rule
Agent Worker Execution Order
Every agent worker (Tier 3) follows these steps:
- Create feature branch
- Write tests first (TDD)
- Implement
- Gate 1 — Run local CI (
mise run ci) — fix until 0 failures - Commit without attribution
- Run gitleaks scan on committed changes — fix if secrets detected
- Push, create PR
- Gate 2 — Watch remote CI (
gh pr checks --watch) — fix and push until local + remote are green - Close bees issue, notify leader of PR status and URL by calling
SendMessage. A named agent's plain final text is never delivered to the leader — ending the turn without callingSendMessagereports nothing. The PR is NOT merge-ready yet: Gate 3 — adversarial review by a separate agent — is the leader's to arrange, and merge waits on it
A tier-3 worker never merges, and that follows from the gates rather than from an axiom. Gate 3 does not exist when the worker reports (step 9 above), so the Gate 3 record precondition is unsatisfiable by construction. One feature branch per epic means a worker merge lands sibling workers' partial slices on main. A worker's PR is frequently stacked on the epic branch, which fires no CI and fails the at-least-one-SUCCESS rule. Merge authority sits with the tier that dispatches Gate 3 and holds its record: Team Leader, Sub-team Leader, and a bees-worker or beads-worker acting as one. The worker reports the PR URL to the team leader via SendMessage.
Agent Prompt Template
Team leaders structure agent prompts with these sections:
## Load skills
<every name from "Core Skills (Mandatory)", one per line — never this placeholder, never a glob>
<domain skills for this task, per the issue's labels and the tracker-state rule>
## Reporting back
<on completion the agent MUST call `SendMessage` with its full report — always, whether or not
this spawn passes a `name`. An agent cannot inspect its own spawn call, so it never decides
this for itself. If the spawn passed a `name`, the agent is a teammate and that call is the
only channel reaching the leader — its plain final text is never delivered. If the spawn passed
no name, the call is harmless redundancy. Address the leader by the name given in this
spawn prompt, or by the agent's own identity context if no name was given here — never hardcode
a literal leader name.>
## Working directory
cd /path/to/repo
## Bees issue
<issue-id>: <title>
## Context
<what exists, what's needed, why>
## What to implement
<specific files, existing functions to reuse, code patterns>
## Rules
<project-specific constraints>
## Execution order
<the 9 steps above>
Canonical list: /core:agent-loop "Core Skills (Mandatory)"; drift-checked in CI.
Key: always reference existing code and functions to reuse. "Implement X" is vague — "add import/2 action to WorkflowController, reuse serialize_workflow/1 from line 28" is machine-executable.
Proof of loading
Require each spawned agent to quote one sentence from each loaded skill in its first response. Do not proceed with the agent's work until proof is received. Listing skill names in the prompt is not the same as the agent loading them — proof prevents skipped loads.
Exemption (claude-skills-295): /core:anti-fabrication, /core:restraint, /core:git, and /core:security are exempt from the quote-back — their standing-principle-broad nature means a citation adds no verification value beyond "I invoked it." Agents still must invoke these four by exact name; only the quote requirement is dropped. Every other loaded skill — the six situational core skills (/core:tdd, /core:twelve-factor, /core:mise, /core:nushell, /core:agent-loop, /core:bees) plus any domain skills — still owes the quote-back in full.
Two sites intentionally stay stricter than this exemption pending separate follow-up bees issues: /core:bees's bees-manager agent definition and this skill's skillProof schema in references/workflows-execution.md both still require full proof-of-loading for every skill, including the four exempt here. That is not drift — a carve-out permits skipping the quote, it does not prohibit carrying it — so a future reader should not "fix" those two sites to match this exemption without a tracked issue first.
Leader spawn — concrete example
See references/leader-spawn-example.md for a worked Phoenix-endpoint Task-tool prompt. The mandatory /core:* skill list at the top of any spawn prompt is enumerated in "Core Skills (Mandatory)" above — never use globs in spawn prompts (they don't expand).
Model Selection
Scale the team to the work — choose by role, not by a trivial-vs-complex guess:
| Role | Model | Examples |
|---|---|---|
| Multi-file implementation | general | New API endpoint, adapter refactor |
| Test planning, architecture design | deep reasoning (or Plan subagent) | Test-list design, system integration |
| Simple ops, monitoring, status checks | smallest fast | Deploy monitor, log reader, port check |
| Text-based search / inventory | smallest fast | Hands passes, file:line index building, catalog sweeps |
| Running test / CI commands | smallest fast | mise run ci runner, verbatim log capture, green/red report |
| Playwright- or MCP-tool-driving agents | general | Browser-driven QA, Tidewave runtime introspection |
Hands and reviewer models follow the Forge convention — see "Model overrides" above and references/forge.md.
Secret Safety
Agents must NEVER read, print, or report actual secret values (API keys, tokens, passwords). Only confirm secrets exist and are non-empty:
# WRONG — exposes the secret
op item get "KEY" --vault Vault --fields credential --reveal
# RIGHT — confirms it's set without exposing
test -n "$(op item get KEY --vault Vault --fields credential 2>/dev/null)" && echo "set" || echo "empty"
Tool Preferences
- JSON parsing: Use
jq, notpython3 -c "import json..." - Scripting: Nushell (
.nu), not bash — cross-platform, structured data - Infrastructure: parameterized workflow tools, not direct SSH
- Tool management: mise, not brew — portable across macOS and Linux
- Issue tracking: bees, not beads
The Layered Model
- Epic -- what the user writes. Objective, skills, constraints. No implementation details.
- Issues -- created by team leader. Independently deliverable slices with acceptance criteria.
- Tasks -- created by agents. Granular implementation steps, invisible to the user.
- Per
references/process.md: Epic lives in the external system of record; Issues and Tasks are ephemeral bees, pruned from main; decisions land in ADRs; intent lives in user stories.
Usage
Load the reference matching your assigned role:
Team Leader -> Read references/team-leader.md
Sub-team Leader -> Read references/sub-team-leader.md
Agent Worker -> Read references/agent-worker.md
Validator -> Read references/validator.md
Fix Agent -> Read references/fix-agent.md
Epic Author -> Read references/epic-authoring.md
Spec-Driven Epics (optional)
Epics may include a spec: field pointing to a .allium behavioral spec file (e.g., spec: docs/specs/<epic-slug>.allium). When present:
- The team leader checks for the spec in Phase 1. On a refactor epic without a
spec:field, run/allium:distillto derive a baseline spec from existing code before decomposition. - Agent workers invoke
/allium:propagateto seed failing test skeletons before implementation. - The validator invokes
/allium:weedafter CI passes to flag spec/code divergence.
Epics WITHOUT a spec: field behave exactly as today — all spec-driven steps are no-ops. Requires the upstream allium plugin: /plugin install allium@juxt. See /allium:allium for full integration details.
Optional: workflow execution substrate
Claude Code dynamic workflows are an optional runtime for the five-tier pipeline. When available and opted-in, the Sub-team Leader encodes one issue's pipeline as a workflow script instead of dispatching five Task spawns — the adversarial separation and stage gates (test files unmodified before P5, mise run ci green before review) become deterministic script assertions, model escalation becomes a retry ladder, and the validator↔fix iteration becomes a bounded loop. isolation: 'worktree' gives each parallel implementer its own worktree inside the workflow run, removed only if the agent leaves it unchanged; a Task-spawn session instead hand-creates one worktree per issue or PR per /core:git "Worktrees" and reuses it across review rounds. See "Worktree isolation, workflow-scoped vs session-scoped" in references/workflows-execution.md for the scoping.
The boundary: decomposition, any Phase 1.5a escalation (the rare fork-or-blocker AskUserQuestion), and the merge decision stay in the interactive loop — a workflow has no mid-run user input. Who may take that decision is set by the deployment's merge policy (/core:git "Merge authorization"); the default leaves it with the operator. The workflow executes already-decomposed issues (gate States A/C/D); it never decomposes them.
The Forge shape encodes the same way at larger fan-out: templates/forge-issue.workflow.js is the runnable /forge-issue workflow — a startup-index hands pass per principal, planner slicing, dep-wave parallel() implementor + test-runner fan-out, and the remediation pair.
Workflows are a research preview on paid plans. When disabled, the default Task-spawn path applies unchanged. See references/workflows-execution.md and the /extras-claude-code:claude-workflows skill.
References
references/process.md-- Per claude-skills ADR 0001: durable vs ephemeral artifacts, epic-to-team relationship, reviewer evidence discipline, capability-tier model selection, tracker-id banreferences/reviewer.md-- Reviewer evidence mechanism: judging inputs vs execution hands, the WAIT verdict with evidenceRequests when a reviewer cannot spawn, reading RESULT/EXCERPT before LOG, output formatreferences/model-tiers.md-- Per-harness model ids and effort settings for each capability tier, keyed to claude/codex/agy; the only place a model id or effort value appearsreferences/forge.md-- The Forge operating model: paired teams (principal + cheap hands), implementation fan-out (N pairs by slice), reviewers as the best-thinker tier, startup-index handoff, gates between pairsreferences/researcher.md-- The hands pattern: read-only focused research and bounded-command execution hands, startup vs on-demand modes, thefile:lineindex output contract, capability-basedAGENT_LOOP_HANDS_MODEL/AGENT_LOOP_HANDS_VISION_MODELselectionreferences/team-leader.md-- Epic decomposition, team formation, orchestrationreferences/sub-team-leader.md-- Issue decomposition, worker management, model escalationreferences/agent-worker.md-- Task execution with TDD, skill loading, reportingreferences/validator.md-- Strictest CI per language, structured failure reportingreferences/fix-agent.md-- CI failure remediation, test fixing, escalationreferences/epic-authoring.md-- User guide for writing machine-executable epicsreferences/leader-spawn-example.md-- Worked Phoenix-endpoint Team Leader spawn prompt with explicit/core:*+/elixir:*skill listreferences/dep-doc-introspection.md— Staged-pipeline prompts name the runtime-introspection tools AND the specific deps touched, never abstract "use the introspection tools"references/no-todos.md— Implementer prompts ban TODO/FIXME/XXX/HACK/KLUDGE/DEFERRED markers, enforced by pre-commit grep; tempted workers escalate-or-implement-now instead of punting scope via a commentreferences/dispatch-discipline.md— Spawn-prompt rules: explicit model, specialized subagent types, lead delegates all execution, fresh worktree offorigin/main, read-only agents never mutate the shared repository or its worktrees (scratchpad clone instead), no polling, host-inspection over claims, ADR search before proposing architecture, worktree exclusivity during reviewreferences/memory-guidance.md— Memory entries must generalize across sessions, repos, and contexts; also covers the work-vs-fact boundary, five decay checks for existing entries, and the retiredprojectmetadata typereferences/secret-provisioning.md— Tier 1 plans include symmetric secret provisioning (generation, store creation, prod/dev deploy diffs); Tier 5 blocker checkreferences/workflows-execution.md— Optional workflow substrate for the five-tier pipeline: pipeline-as-script, stage gates, escalation ladder, teams-of-teams; decomposition/merge stay interactivetemplates/five-tier-issue.workflow.js— RunnableN=1five-tier pipeline template: stage prompts,skillProofschemas, diff-boundary gate, escalation ladder, bounded fix looptemplates/forge-issue.workflow.js— Runnable Forge workflow: startup-index hands, planner slicing, dep-wave fan-out, strongest-reasoning reviewers paired with smallest-fast hands, remediation pair
Anti-Fabrication
Strict requirements for ensuring factual, measurable, and validated outputs in all work products including documentation, research, reports, and analysis.
Core Principles
Evidence-Based Outputs
- Base all outputs on actual analysis of real data using tool execution
- Execute Read, Glob, Bash, or other validation tools before making claims
- Never assume file existence, system capabilities, or feature presence without verification
- Validate integration recommendations through actual framework detection
Explicit Uncertainty
- Mark uncertain information as "requires analysis", "needs validation", or "requires investigation"
- State when information cannot be verified: "Unable to confirm without [specific check]"
- Acknowledge knowledge limitations rather than fabricating plausible-sounding content
Hedges vs directives
Hedge about the world. Never hedge about the instruction.
- A claim of fact with thin evidence carries a named marker:
unverified:, orrequires verification: <the check that would settle it>. - A directive carries no hedging verb. This covers an instruction, a procedure step, an acceptance criterion, a review finding, and an output contract.
- Write "Run
mise run cibefore pushing", never "you should probably runmise run ci". - The named-marker form replaces bare conditionals on claims too. "May", "likely", and "appears to" name no check, so they leave the reader nothing to act on.
Test a sentence by putting "You" in front of it. If it still reads as advice, it is a directive, so strip the hedge. If it answers "is this true?", keep the uncertainty and name the check.
Factual Language
- Use precise, factual language without superlatives or unsubstantiated performance claims
- Replace vague statements with specific, measurable observations
- Report what was actually observed, not what should theoretically be true
- Distinguish between verified facts and reasonable inferences
Prohibited Language and Claims
Superlatives to Avoid
Never use unverified superlatives:
- ❌ "excellent", "comprehensive", "advanced", "optimal", "perfect"
- ❌ "best practice", "industry-leading", "cutting-edge", "state-of-the-art"
- ❌ "robust", "scalable", "production-ready" (without specific evidence)
Instead, use factual descriptions:
- ✅ "follows the specification defined in [source]"
- ✅ "implements [specific pattern] as documented in [reference]"
- ✅ "tested with [specific conditions] and produced [specific results]"
Unsubstantiated Metrics
Never fabricate quantitative data:
- ❌ Percentages without measurement: "improves performance by 30%"
- ❌ Success rates without testing: "has a 95% success rate"
- ❌ Arbitrary scores: "code quality score of 8/10"
- ❌ Made-up statistics: "reduces memory usage significantly"
Instead, provide verified measurements:
- ✅ "benchmark shows execution time decreased from 150ms to 98ms"
- ✅ "passed 47 of 50 test cases (94%)"
- ✅ "static analysis tool reports complexity score of 12"
Assumed Capabilities
Never claim features exist without verification:
- ❌ "This system supports authentication" (without checking)
- ❌ "The API provides rate limiting" (without reading docs/code)
- ❌ "This handles edge cases correctly" (without testing)
Instead, verify before claiming:
- ✅ Use Read tool to check configuration files
- ✅ Use Grep to search for specific implementations
- ✅ Use Bash to test actual behavior
- ✅ State "requires verification" if tools cannot confirm
Time and Effort Estimation Rules
Never Estimate Without Analysis
Do not provide time estimates without factual basis:
- ❌ "This will take 15 minutes"
- ❌ "Should be done in 2 hours"
- ❌ "Quick task, won't take long"
- ❌ "Simple fix"
Data-Backed Estimates Only
If estimates are requested, execute tools first:
- Count files that need modification (using Glob)
- Measure code complexity (using Read and analysis)
- Assess dependencies (using Grep for imports/references)
- Review similar past work (if available)
Then provide estimate with evidence:
- ✅ "Requires modifying 12 files based on grep search, estimated X hours"
- ✅ "Analysis shows 3 integration points, complexity suggests Y time"
- ✅ "Timeline requires analysis of [specific factors not yet measured]"
When Unable to Estimate
Be explicit about limitations:
- ✅ "Cannot provide time estimate without analyzing [specific aspects]"
- ✅ "Requires investigation of [X, Y, Z] before estimating"
- ✅ "Complexity assessment needed before timeline projection"
Validation Requirements
File Claims
Before claiming files exist or contain specific content:
1. Use Read tool to verify file exists and check contents
2. Use Glob to find files matching patterns
3. Use Grep to verify specific code or content is present
4. Never state "file X contains Y" without tool verification
Example violations:
- ❌ "The config file sets the timeout to 30 seconds" (without reading it)
- ❌ "There are multiple test files for this module" (without globbing)
Correct approach:
- ✅ Read the config file first, then report actual timeout value
- ✅ Use Glob to find test files, then report count and names
System Integration
Before claiming system capabilities:
1. Use Bash to check installed tools/dependencies
2. Read package.json, requirements.txt, or equivalent
3. Verify environment variables and configuration
4. Test actual behavior when possible
Framework Detection
Before claiming framework presence or version:
1. Read package.json, Gemfile, mix.exs, or dependency file
2. Search for framework-specific imports or patterns
3. Check for framework configuration files
4. Report specific version found, not assumed capabilities
Test Results
Only report test outcomes after actual execution:
1. Execute tests, or cite an attributable execution-hands record per the Execution evidence record in `/extras-claude-code:claude-output-styles` `assets/ci-evidence-format.md`
2. Capture and read actual output, or reference the documented execution record
3. Report specific pass/fail counts and error messages
4. Never claim "tests pass" or "all tests successful" without execution verification
Performance Claims
Only make performance statements based on measurement:
1. Run benchmarks or profiling tools
2. Capture actual timing/memory data
3. Report specific measurements with conditions
4. State testing methodology used
Anti-Patterns to Avoid
Fabricated Testing
❌ "The code has been thoroughly tested" ❌ "All edge cases are handled" ❌ "Test coverage is good"
✅ "Executed test suite: 45 passing, 2 failing" ✅ "Tests pass per execution-hands record: mise run ci @ <40-hex oid>, exit 0" ✅ "Coverage report shows 78% line coverage" ✅ "Tested with inputs [X, Y, Z], observed [specific results]"
Unverified Architecture Claims
❌ "This follows microservices architecture" ❌ "Uses event-driven design patterns" ❌ "Implements SOLID principles"
✅ Use Grep to find specific patterns, then describe what exists ✅ "Found 12 service definitions in [location]" ✅ "Code shows [specific pattern] in [specific files]"
Generic Quality Statements
❌ "This is high-quality code" ❌ "Well-structured implementation" ❌ "Follows best practices"
✅ "Code follows [specific standard] as verified by linter" ✅ "Matches patterns from [specific reference documentation]" ✅ "Static analysis shows complexity metrics of [specific values]"
Validation Workflow
When creating any factual content:
- Identify Claims: List all factual assertions being made
- Check Evidence: For each claim, determine what tool can verify it
- Execute Validation: Run Read, Grep, Glob, Bash, or other tools
- Report Results: State only what tools confirmed
- Mark Uncertainty: Clearly label anything not verified
Examples
Documentation Writing
Bad approach:
This API is highly performant and handles thousands of requests per second.
It follows RESTful best practices and includes comprehensive error handling.
Good approach:
This API implements REST endpoints as defined in [specification link].
Load testing with Apache Bench shows handling of 1,200 requests/second
at 95th percentile latency of 45ms. Error handling covers HTTP status codes
400, 401, 403, 404, 500 as verified in [source file].
Research Output
Bad approach:
React hooks are the modern way to write React components and are much
better than class components. They improve performance and code quality.
Good approach:
React hooks (introduced in React 16.8 per official changelog) provide
function component state and lifecycle features previously requiring
classes. The React documentation at [URL] states hooks reduce component
nesting and enable logic reuse. Performance impact requires measurement
for specific use cases.
Implementation Planning
Bad approach:
This should be a quick implementation, probably 2-3 hours.
We'll add authentication which is straightforward, then deploy.
Good approach:
Implementation requires:
- Authentication integration (12 files need modification per grep analysis)
- Configuration of [specific auth provider]
- Testing of login/logout flows
Complexity assessment needed before timeline estimation. Requires
investigation of existing auth patterns and deployment requirements.
Integration with Other Skills
This skill should be active alongside:
- Documentation: Ensures docs contain verified information
- Code Review: Validates claims about code quality and patterns
- Research: Grounds research in verifiable sources
- Git Operations: Ensures accurate commit messages and PR descriptions
References
- Agent Skills Specification: Factual, validated skill content
- Scientific Method: Observation before conclusion
- Verification Principle: Trust but verify through tool execution
Bees - Lightweight SQLite-Backed Issue Tracker
This skill activates when working with Bees for issue tracking, dependency management, and AI-augmented workflows.
What is Bees?
Bees is a lightweight, local-first issue tracker designed for AI-augmented development:
- SQLite storage: WAL-mode SQLite database for fast queries
- Single binary: Written in Zig, compiles to a small static binary
- AI-augmented:
bees primedumps a workflow cheatsheet for agents,bees syncexports JSONL,--jsonflags on read commands - Dependency-aware: Query ready issues with
bees ready, supports blocks/related/parent-child - Local-first: No server required, everything stored in
.bees/directory
Installation
Install via mise: add [tools."github:ctxshift/bees"] with version = "latest" to mise.toml (see templates/mise.toml), then mise install. Full install matrix, platform asset patterns, pre-built binaries, and source build: references/installation.md.
Getting Started
Initialize Bees
bees init
Creates the .bees/ directory with SQLite database and configuration.
Create an Issue
bees create "Implement user authentication"
List Issues
bees list
Show Issue Details
bees show <id>
Close an Issue
bees close <id>
Find Ready Issues
bees ready
Returns issues with no unresolved dependencies.
Commands Reference
Per-flag syntax for the 13 day-to-day subcommands (create, list, show, update, close, ready, dep, label, comment, config, sync, import, prime): references/commands.md. bees 0.4.0 has 19 top-level commands; for the rest (upgrade, edit, rename-prefix, daemon, version, and the ls alias) run bees <cmd> --help — except bees upgrade --help, which executes a real database migration instead of printing help (see Troubleshooting).
No Enum Validation — a Typo Silently Breaks the Queue
bees 0.4.0 does not validate enum-shaped values against the sets --help documents. bees create -t, bees update --status/-t, and bees dep add -t all accept and store any string verbatim — a typo does not error, it is stored, and it breaks queue behavior later with no indication why.
Verified against bees 0.4.0 in a throwaway .bees/:
$ bees update <id> --status bogus
Updated <id> # exit 0
$ bees list --json | jq '.[] | select(.id=="<id>") | .status'
"bogus"
The issue then silently disappears from bees ready — no error, no warning, nothing distinguishing it from a real closed or deferred state. The same pattern holds for bees dep add <id> <blocker> -t nonsense (exit 0, nonsense stored as the dependency type) and bees create <title> -t garbage (exit 0, garbage stored as issue_type).
Documented value sets, none of them enforced:
create -t/update -t(issue type):task, bug, feature, epic, storyper--help—bees prime's cheatsheet listschorein place ofstory; both are accepted since nothing validates either.update -s/--status:open, in_progress, closed, deferreddep add -t:blocks, related, parent-childper--help— this doc's own table below usesparent; both spellings are accepted since nothing validates either.
Mitigation: after bees update --status or bees dep add -t, verify with bees show <id> --json (check .status) or bees dep list <id> --json (check .depends_on[].type) rather than trusting a zero exit code. An issue missing from bees ready with no explicit close and no blocking dependency is the tell of a typo'd status, not a real state transition.
This is upstream bees behavior, not a docs defect in this skill — worth a feature request against ctxshift/bees for enum validation on create -t, update -s/-t, and dep add -t.
.bees/ Is Found by Walking Up, Like .git/
bees list, bees ready, bees create, and every other bees command that needs a tracker walk up from the current directory to the nearest ancestor .bees/, the same way git walks up to .git/. There is no scoping to "this project" — a subdirectory of an already-initialized tree silently participates in the parent's tracker instead of getting its own.
Verified against bees 0.4.0: from an uninitialized child directory of an already-initialized parent, bees create writes the new issue into the parent's tracker (ID prefixed with the parent's project prefix) with no local .bees/ created and no error — behaviorally indistinguishable from having its own tracker until bees show <id> or bees list --json is checked. Beads has the identical behavior: bd status from the child reports the parent's .beads/ stats, again with no local .beads/ and no error.
Mitigation: don't infer "already initialized here" from a zero exit code on bees list/bees ready (or bd status) — that only proves an ancestor tracker exists somewhere on the path, not that it belongs to the current directory. Check for the directory itself:
test -d .bees # bees — true only if THIS directory owns a tracker
test -d .beads # beads — same caveat
This is the same failure class as the enum-validation trap above: a command that exits 0 and looks correct while quietly doing the wrong thing. A cd that lands anywhere under a bees-tracked tree — not just the tracker root — followed by bees create, silently files into that tree's tracker with no indication the write landed somewhere other than intended.
Dependency Management
Dependency Types
Bees supports three relationship types between issues. Argument order is a gotcha — the dependent issue comes first:
bees dep add <id> <blocker-id> # id depends on blocker-id
| Type | Flag | Behavior |
|---|---|---|
| blocks | -t blocks (default) | Prevents bees ready from showing dependent issue |
| related | -t related | Informational link, no blocking |
| parent | -t parent | Parent-child hierarchy |
--help spells this type parent-child; both parent and parent-child are accepted as literal, distinct stored values since neither is validated — see "No Enum Validation" above.
Ready Queue
bees ready returns issues where:
- Status is
open - No open
blocksdependencies remain
Only blocks-type dependencies gate readiness. parent-child and related dependencies never do — a child issue stays in bees ready whether its parent is open or closed (verified against bees 0.4.0). To make a child wait on its parent, add an explicit blocks edge.
Cycles are NOT rejected — check before adding a reverse edge
Bees does not detect circular dependencies. Both edges are accepted, and the pair then
deadlocks: each blocks the other, so neither ever appears in bees ready.
bees dep add taskA taskB # accepted
bees dep add taskB taskA # ALSO accepted, exit 0 — no cycle error
bees ready # "No ready issues." — both are now unreachable
Verified against bees 0.4.0. Inspect bees dep list <id> before adding an edge in the reverse
direction; nothing else will stop you.
AI Integration
bees sync (JSONL Export)
Export all issues to JSONL for external tooling:
bees sync
# Writes .bees/issues.jsonl
The JSONL file contains one JSON object per line, compatible with standard data processing tools.
bees prime (Agent Workflow Cheatsheet)
Dump the static workflow-context cheatsheet for AI agents:
bees prime
The output is a fixed markdown dump of workflow rules and essential commands — it contains no issue data (verified against bees 0.4.0: a repo with 4 issues produced zero mentions of any issue id). It takes no flags. For issue context — titles, descriptions, labels, dependencies, status — use bees list --json and bees show <id> --json.
--json flag coverage and jq scripting recipes: references/commands.md.
Storage and File Structure
.bees/
├── bees.db # SQLite database (WAL mode) - primary storage
├── issues.jsonl # JSONL export (created by bees sync)
├── metadata.json # Repository metadata
├── config.json # Local configuration
└── .gitignore # Excludes bees.db from version control
SQLite as Primary Storage
Unlike beads (which uses JSONL as primary with SQLite cache), bees uses SQLite as the primary data store:
- WAL mode for concurrent read access
bees syncexports to JSONL for portabilitybees importrebuilds the database fromissues.jsonl(drops and re-createsbees.db) — use after pulling a newissues.jsonl
Workflow Examples
PR-Based Development Workflow
Session Start
git pull --ff-only # Advance the primary; never checkout a branch here
bees ready # Find available issues
bees show <id> # Read requirements
Issue Execution
bees update <id> --status in_progress # Run from the primary
git fetch origin
git worktree add "$WORKTREE_ROOT/<repo>-<slug>" -b feature/<name> origin/main
cd "$WORKTREE_ROOT/<repo>-<slug>"
# Do the work:
# - Read existing code to understand patterns
# - Implement following project conventions
# - Run quality gates (tests, linters, formatters)
git add <files>
git commit -m "type(scope): description"
See /core:git "Worktrees" for $WORKTREE_ROOT and the location rules.
PR Creation
git push -u origin <branch>
gh pr create --title "type(scope): description" --body "- Change one
- Change two"
Watch CI and Close
gh pr checks --watch
bees close <id> from the primary, then land the .bees/issues.jsonl export as its own
chore(bees) PR — see /core:git "Worktrees", "Bees runs from the primary."
Cleanup
After the user merges, see /core:git "Worktrees", "Cleanup, merged-only" for the current
removal precondition, then:
git worktree remove <path> # Never rm -rf
git branch -D <branch> # -d refuses after a squash merge
git pull --ff-only # In the primary
bees ready # Find next issue
AI Agent Task Loop
An automated task-loop script (poll bees ready --json, work, close, sync): references/commands.md.
Bees vs Beads
| Feature | Bees | Beads |
|---|---|---|
| Storage | SQLite (WAL mode) | Dolt (version-controlled SQL DB, .beads/embeddeddolt/); JSONL is export-only |
| Language | Zig | Go |
| Binary | Single static binary | Go binary |
| Sync model | One-directional export (bees sync) | Bidirectional git sync (bd sync/bd pull) |
| AI context | bees prime (static workflow cheatsheet); issue data via --json flags | --json flags only |
| Init modes | Local-first only | Full, stealth, contributor |
| Comments | bees comment add | bd comment |
| Dependency types | blocks, related, parent (-t flag) | blocks only |
| Rebuild from JSONL | bees import | bd import (upsert; there is no bd rebuild) |
Best Practices
Priorities and Labels
type:bug, type:feature, type:chore
priority:high, priority:medium, priority:low
status:wip, status:blocked, status:review
sprint:42, epic:auth
skill:git, skill:security, skill:rust
complexity:trivial, complexity:complex
Complexity labels (drives the pipeline decision)
Bees issues carry one of two complexity labels. The label tells the picker whether to dispatch a single agent or the full five-tier pipeline:
complexity:trivial→ dispatch one haiku worker (see "Workflow Examples")complexity:complex→ dispatch the five-tier pipeline internally (see/core:agent-loop"Five-Tier Decomposition Pipeline")
Apply with bees label add <id> <label>, one label per invocation — bees update has no --labels flag, and a comma-separated string becomes a single literal label. Adding a priority:pN label does not change the issue's priority field; set that separately with bees update <id> -p <N>.
Bees never carries team:* labels. The five tier names (team:opus-planner, team:sonnet-test, team:sonnet-impl, team:haiku-ci, team:opus-review) are dispatch-time strings the Sub-team Leader puts inside each Task spawn prompt. They identify the stage being dispatched, not the bees row.
One bees issue == one slice. A complex slice still gets ONE bees issue; the five pipeline stages produce intermediate artifacts (bees comments on the same issue, git commits, PR comments), not five chained bees rows.
Dependencies
- Keep dependency chains shallow (< 5 levels)
- Use
bees readyto find actionable issues - Prefer
blockstype for ordering constraints - Use
relatedtype for informational links
AI Integration Tips
- Use
bees primeto inject the workflow cheatsheet into agent prompts; inject issue context withbees list --json/bees show <id> --json - Use
bees ready --jsonfor automated task queue polling - Use
bees syncto create portable JSONL snapshots - Close issues atomically after completion
Comments
Use bees comment add to record progress notes:
bees comment add <id> "Completed initial implementation"
bees comment list <id>
Claude-teams-aware bee format
Bees that an agent loop picks up directly need structured labels and a structured description body. Single-paragraph bees are appropriate for operator-only notes; agent-targeted bees follow this shape:
Labels (apply via bees label add <id> <label>, one label per call; set priority itself with bees update <id> -p <N>):
team:*— the agent team that owns the work (e.g.,team:opus-planner,team:sonnet-impl)skill:<plugin>:<skill>— domain skills the worker loads (e.g.,skill:elixir:phoenix)model:<model>— initial model assignment (model:haiku,model:sonnet,model:opus)complexity:trivialORcomplexity:complex— pipeline-decision labelpriority:p<N>— keepsbees readyqueue order
Description sections (markdown H2 or H3):
## CRITICAL— must-not-violate constraints (one bullet per line)## Objective— what success looks like## Context— existing code, prior commits, related PRs## Acceptance criteria— bullet list, testable## Deliverables— concrete artifacts (files, PRs, commits)## Load skills— exact skill names the worker invokes
Single-writer constraint
The SQLite database under .bees/bees.db is single-writer. Concurrent workers MUST NOT run bees create, bees close, bees update, bees label add, or bees dep add directly — concurrent writes raise SQLITE_CONSTRAINT or daemon.lock failures that lose work.
Workers collect proposed writes in their final report (a ## BEES REQUESTS section). The lead applies the queued writes through a single serial writer — the bees-manager agent (see agents/bees-manager.md).
bees ready as canonical queue
bees ready (run from the repo root that owns the .bees/ directory) is the canonical ordering of "what an agent picks up next". Edit the queue order via bees (priority:pN label OR bees dep add), never by mutating storage out-of-band. Downstream systems that synchronize bee state to other trackers read bees ready order; raw-database edits skip the synchronization layer and leave consumers stale.
Troubleshooting
Database Issues
# Check database integrity
sqlite3 .bees/bees.db "PRAGMA integrity_check;"
# Database is locked
# Ensure no other process has an exclusive lock
lsof .bees/bees.db
bees upgrade --help runs the migration
bees upgrade --help does not print help — it executes the real upgrade (refreshes .bees/.gitignore and applies schema migrations to bees.db), verified against bees 0.4.0. Do not probe upgrade with --help on a tracker you are not ready to migrate.
Build Issues (from source)
Troubleshooting for source builds lives with the build instructions: references/installation.md.
JSONL Out of Sync
If issues.jsonl is stale, regenerate:
bees sync
References
references/commands.md: Per-flag syntax for the 13 day-to-day subcommands,--jsonoutput, jq scripting recipes, and the agent task-loop scriptreferences/installation.md: Install matrix (mise, pre-built binaries, source build) and build troubleshootingreferences/teams-integration.md: Protocol for mirroring bees issues into Claude's task list for Agent Teams coordinationreferences/migration-from-beads.md: Guide for migrating from beads to beesreferences/skill-catalog.md: Marketplace-wide skill catalog with keyword triggers for matching tracker issues to skills
Paired agents
agents/bees-manager.md: Serial writer for bees DBs. Use when concurrent workers need to apply queued bees writes through a single SQLite writer to avoidSQLITE_CONSTRAINTanddaemon.lockfailures.agents/bees-worker.md: Processes bees issues by pollingbees ready, executing work, and syncing results. Use for automating issue queues or AI-driven workflows.
Code Review Best Practices
This skill activates when reviewing code for quality, correctness, security, and maintainability.
Anti-fabrication
This skill follows core:anti-fabrication, but has little to verify against an external
source: the checklist and etiquette content is house convention (Google's review guide,
cited in sources.md, for the checklist's shape), and "Language-Specific
Considerations" is broad, stable idiom rather than versioned API claims. Don't assert a
language-specific rule this skill doesn't cover without checking that language's own
style skill first.
Code Review Checklist
1. Correctness and Functionality
Does the code do what it's supposed to do?
- Logic is correct and handles all cases
- Edge cases are considered
- Error handling is appropriate
- No obvious bugs or logical errors
- Assertions and validations are present
- Return values are correct
Questions to ask:
- What happens if this receives null/nil?
- What if the list is empty?
- What if the number is negative/zero?
- Are there off-by-one errors?
- Are comparisons correct (>, >=, <, <=)?
2. Security
Is the code secure?
- No SQL injection vulnerabilities
- No XSS (Cross-Site Scripting) vulnerabilities
- No CSRF vulnerabilities (CSRF protection in place)
- User input is validated and sanitized
- Sensitive data is not logged
- Authentication and authorization are properly implemented
- No hardcoded secrets or credentials
- File uploads are validated (type, size, content)
- External URLs are validated
- Rate limiting is in place for APIs
Worked BAD/GOOD examples (SQL injection, XSS, hardcoded secrets, mass assignment): references/checklist-examples.md.
3. Performance
Is the code efficient?
- No N+1 query problems
- Appropriate data structures chosen
- Algorithms are efficient
- Database indexes are used
- Caching is implemented where appropriate
- Large datasets are paginated or streamed
- Unnecessary computations are avoided
- Resources are cleaned up properly
Worked BAD/GOOD examples (N+1 queries, loading full datasets, list vs set lookups): references/checklist-examples.md.
4. Code Quality and Maintainability
Is the code readable and maintainable?
- Clear, descriptive variable and function names
- Functions are small and focused (single responsibility)
- No code duplication (DRY principle)
- Comments explain "why", not "what" — watch for restated, over-explained, missing-purpose, missing-inputs, or contradicting comments. See
comment-reviewerfor a dedicated pass. - Code follows project conventions and style guide
- Magic numbers are replaced with named constants
- Complexity is minimized
- Code is self-documenting
Worked BAD/GOOD examples (unclear names, multi-responsibility functions, magic numbers): references/checklist-examples.md.
5. Error Handling
Are errors handled properly?
- Errors don't crash the system unexpectedly
- Error messages are helpful
- Errors are logged appropriately
- Happy path and error paths are both tested
- No swallowed errors (empty catch blocks)
- Proper error types are used
Worked BAD/GOOD examples (swallowed errors, generic error messages, bang functions that crash): references/checklist-examples.md.
6. Testing
Is the code properly tested?
- New functionality has tests
- Edge cases are tested
- Error conditions are tested
- Tests are clear and focused
- Tests are deterministic (no flaky tests)
- Test names describe what they test
- Mocks are used appropriately
- Test coverage is adequate
Worked BAD/GOOD examples (unclear test names, over-broad tests, non-deterministic sleeps): references/checklist-examples.md.
7. Documentation
Is the code documented?
- Public APIs have documentation
- Complex logic has explanatory comments
- README is updated if needed
- Changelog is updated for user-facing changes
- API documentation is accurate
- Examples are provided
8. Dependencies
Are dependencies handled properly?
- New dependencies are justified
- Dependencies are up-to-date and maintained
- Licenses are compatible with project
- Security vulnerabilities are checked
- Dependency versions are pinned or bounded
9. Restraint and Scope
Does every new symbol earn its place in the diff?
For each NEW symbol introduced by the diff (function, class, config, dependency), check it against the restraint ladder before approving:
- Does this need to exist at all, or is it speculative scaffolding? (YAGNI)
- Is it a duplicate of an existing helper, stdlib function, or already-installed dependency? (Reuse-First)
- Could it be expressed in a smaller form — fewer lines, no new abstraction?
Flag speculative abstractions (interfaces with one implementation, config for values that never change, factories for one product) and unrequested features as findings, not nits. See /core:restraint.
Review Process
Before Reviewing
-
Understand the context
- Read the PR description
- Understand the problem being solved
- Check related issues
-
Get execution evidence
- An agent reviewer requests execution hands per
/core:agent-loopreferences/reviewer.mdand judges the records; a human reviewer runs checks directly.
- An agent reviewer requests execution hands per
During Review
-
Start with the big picture
- Is the approach sound?
- Does it fit the architecture?
- Is there a better way?
-
Review for correctness
- Does it work as intended?
- Are edge cases handled?
- Is error handling appropriate?
-
Check security and performance
- Are there security vulnerabilities?
- Will it perform well at scale?
-
Review code quality
- Is it readable and maintainable?
- Does it follow conventions?
- Is it well-tested?
Providing Feedback
Agent reviewers report findings per /extras-claude-code:claude-output-styles assets/review-findings-format.md.
Be constructive and specific:
# BAD: Vague criticism
"This function is bad."
# GOOD: Specific, actionable feedback
"This function has three responsibilities: validation, database update, and email sending. Consider splitting it into separate functions for better testability and maintainability:
```elixir
def update_user(user, attrs) do
with {:ok, changeset} <- validate_user_update(user, attrs),
{:ok, user} <- save_user(changeset),
:ok <- send_update_notification(user) do
{:ok, user}
end
end
BAD: Demanding
"You must change this."
GOOD: Collaborative
"What do you think about extracting this into a separate function? It would make the code easier to test."
BAD: Nitpicking without context
"Use single quotes instead of double quotes."
GOOD: Explain reasoning
"Our style guide prefers single quotes for consistency (see CONTRIBUTING.md section 3.2)."
**Use labels to categorize feedback:**
- **[blocking]**: Must be fixed before merging
- **[suggestion]**: Optional improvement
- **[question]**: Asking for clarification
- **[nit]**: Very minor, cosmetic issue
- **[security]**: Security concern
- **[performance]**: Performance concern
**Example** (SQL-injection-shaped BAD/GOOD code for a `[blocking]` label: [references/checklist-examples.md](references/checklist-examples.md)):
```markdown
[blocking] This creates a SQL injection vulnerability. Use parameterized queries.
[suggestion] Consider extracting this logic into a separate function for reusability.
[question] Why are we using a map here instead of a struct?
[nit] Extra blank line here.
After Review
- Respond to author's questions
- Re-review after changes
- Approve when satisfied
- Celebrate good code
Key Principles
- Correctness first: Code must work correctly
- Security matters: Always consider security implications
- Be specific: Provide actionable, concrete feedback
- Be respectful: Kind, constructive communication
- Focus on important issues: Don't bike-shed
- Explain reasoning: Help author learn, don't just dictate
- Approve good code: Don't let perfect be enemy of good
- Collaborate: You're on the same team
- Check restraint: Every new symbol earns its place on the ladder — see
/core:restraint
References
references/no-todos-scan.md— Scan PR diffs for newTODO/FIXME/XXX/HACK/KLUDGE/DEFERREDmarkers; treat as BLOCKER, not nit- references/language-specifics.md — read this when reviewing Elixir, JavaScript/TypeScript, Python, or Rust code for the per-language checklist items on top of the general checklist above
- references/smells-and-antipatterns.md — read this when naming a code smell (complexity, duplication, naming, design) or checking a diff against premature optimization, premature abstraction, or error-swallowing anti-patterns with worked BAD/GOOD examples
- references/review-etiquette.md — read this for how to conduct yourself during a review (DO/DON'T etiquette) or the self-review checklist an author runs before submitting code
Apple Container CLI
This skill activates when working with Apple Container for running Linux containers natively on Apple silicon Macs.
What is Apple Container?
Apple Container is a macOS-native tool for running Linux containers as lightweight virtual machines on Apple silicon:
- Swift-based: Built on Apple's Virtualization.framework
- OCI-compatible: Produces and runs standard OCI container images
- Apple silicon only: Requires Apple silicon Mac (M1 or later)
- Stable 1.0: Currently at version 1.4.1 (released 2026-09-09); 0.x minor releases carried frequent breaking changes — see Version Differences below when upgrading
- Lightweight VMs: Each container runs as a lightweight Linux VM
Prerequisites
- macOS 26 or later (Tahoe)
- Apple silicon Mac (M1, M2, M3, M4 series)
- Install via signed
.pkgfrom GitHub releases
System Management
Manage the container system service (start, stop, status, version, logs, disk usage) and its TOML configuration file. Full command list, flag tables, and the TOML config detail: references/command-reference.md.
⚠ BREAKING — 1.0.0: A TOML configuration file at
~/.config/container/config.tomlreplaces the UserDefaults-backed system properties.container system property get,set, andclearare REMOVED — edit the TOML file, then restart the service (container system stop && container system start).
Container Lifecycle
Run, manage, and export containers (run, list/ls, start, stop, kill, delete/rm, exec, logs, inspect, cp, stats, prune, clean, export, create). Full flag tables and worked examples: references/command-reference.md.
Two corrections worth keeping in view: a custom MAC address is set via --network <name>,mac=XX:XX:XX:XX:XX:XX on container run — there is no separate --mac-address flag. container export produces a filesystem tar only (-o/--output); it does not create or tag an image, and there is no -t/--tag flag. It supported only stopped containers from 0.11.0; 1.2.1 added support for exporting live (running) containers.
container clean (1.4.1+) cleans one or more RUNNING containers identified by explicit container ID, and is unrelated to the stopped-container accumulation problem described in Troubleshooting below — container prune remains the command for that. USAGE shows <container-ids> as optional, so a zero-argument invocation parses; what it then acts on is not established here (requires verification: run container clean with no arguments on a disposable host). Pass explicit IDs.
⚠ Observed —
--rmdoes not reliably remove the container on 1.0.0.container run --rm ...left a stopped container behind on one host running Apple Container 1.0.0, despite--rmbeing set. This is stated as a direct operator observation at 1.0.0, not independently reproduced or verified against the binary here — do not treat it as confirmed on every 1.0.0 install. It is the likely accumulation mechanism behind roughly 300 stopped containers found on a dev host, a large share of them anonymous short-lived scan containers (e.g. from a gitleaks pre-commit hook that also relied on--rm). If a workflow depends on containers being reaped automatically, do not trust--rmalone on 1.0.0 — give the container an explicit unique--nameand follow up with a defensivecontainer rm -f <that-exact-name>scoped to only the container you just created. See Troubleshooting below for why an unscoped cleanup is worse than no cleanup at all. No release from 1.1.0 to 1.4.1 is documented as fixing this behavior. requires verification: re-run the--rmscenario on a 1.4.1 host and observe whether the container is reaped.
Container Machines (1.0.0+)
Machines are long-lived Linux environments with tight host integration — a full Linux system with init support, not an ephemeral application container. Use machines for "edit on the Mac, build inside Linux" workflows, running system services under systemd, and testing across multiple distributions. The subcommand alias is m (container m ls = container machine ls).
container machine create accepts --virtualization (enable nested virtualization; requires Apple Silicon M3+, macOS 15+, and a kernel with CONFIG_KVM=y), --home-mount <ro|rw|none> (host home directory mount mode inside the VM; default rw), --no-boot (create the machine without booting it), and --platform <platform> (target platform for a multi-platform image, taking precedence over --os/--arch). Full flag table: references/command-reference.md.
Isolation caveat: A machine auto-mounts the host home directory at
/Users/<username>inside the VM, unless created with--home-mount none. That tight host integration makes machines a development convenience, NOT an isolation boundary for untrusted workloads — run untrusted agents in regular containers or a dedicated sandboxing substrate instead. Pass--home-mount noneoncontainer machine createto suppress the auto-mount.
# Create a machine from an image
container machine create alpine:latest --name dev
# Run a single command in the machine
container machine run -n dev uname -a
container machine run -n dev -- cat /proc/cpuinfo
# Open an interactive shell
container machine run -n dev
# Set a default machine, then omit -n
container machine set-default dev
container machine run
# List, inspect, stop, delete
container machine ls
container machine inspect dev
container machine stop dev
container machine rm dev
# Resize CPUs/memory (stop, then run to apply)
container machine set -n dev cpus=4 memory=8G
container machine stop dev
container machine run -n dev -- nproc
The machine maps the host user automatically: the host home directory is mounted at /Users/<username> inside the machine and the machine user matches the host UID/GID.
Custom Machine Images
Machine images require /sbin/init (a process supervisor such as systemd). An optional first-boot script at /etc/machine/create-user.sh receives CONTAINER_UID, CONTAINER_GID, CONTAINER_USER, CONTAINER_HOME, and CONTAINER_MACHINE_ID:
# Build a custom machine image, then create a machine from it
container build -t local/ubuntu-machine:latest .
container machine create local/ubuntu-machine:latest --name ubuntu
See templates/1.0.0/commands.md and the upstream machine guide for the full machine reference.
Image Management
Pull, tag, push, save/load, delete, inspect, and prune images (container image ...). Full flag tables: references/command-reference.md.
Architecture aliases (0.8.0+): amd64=x86_64, arm64=aarch64. Set CONTAINER_DEFAULT_PLATFORM (0.11.0+) to avoid specifying --platform on every pull/build.
Build
Build OCI-compatible images from a Dockerfile or Containerfile (container build) and manage the builder process. Full flag tables: references/command-reference.md.
When no Dockerfile is found, the builder falls back to Containerfile (0.6.0+).
Network Management
Create, inspect, and prune container networks (container network ...). Full flag tables: references/command-reference.md. See Common Workflows below for a multi-container networking example.
Full IPv6 support (0.8.0+); host-only/isolated modes (0.9.0+, verify syntax with --help); mtu network attachment (0.11.0+).
To reach host services from a container: the default network's gateway (192.168.64.1, no setup required) only reaches services bound to a non-loopback address. Services bound to 127.0.0.1 (the common local-dev-server case) are NOT reachable via the gateway — use container system dns create <domain> --localhost <ip> instead, which is a reachability feature, not just a naming convenience. See references/command-reference.md "Reaching host services from a container".
Volume Management
Create, inspect, and prune persistent volumes (container volume ...). Full flag tables: references/command-reference.md. Mount with -v name:/path[:ro] on container run; see Common Workflows below for a persistent-data example.
Registry
Authenticate with container registries:
# Log in to a registry
container registry login <registry-url>
# Log out from a registry
container registry logout <registry-url>
# List configured registries (0.10.0+)
container registry list
Note: In 0.5.0, the keychain ID changed from com.apple.container to com.apple.container.registry. Re-login is required after upgrading from 0.4.x.
Kubernetes (k8s) Plugin (1.2.1+, EXPERIMENTAL)
container k8s manages local Kubernetes development clusters. Upstream marks the whole command EXPERIMENTAL and lists it under container --help's PLUGINS: heading, separate from the core subcommands.
container k8s create # create a local cluster
container k8s delete # alias: rm
container k8s list # alias: ls
container k8s load-image # load a local image into the cluster
container k8s start
container k8s write-config
Six subcommands: create, delete/rm, list/ls, load-image, start, write-config. Full reference: references/command-reference.md.
Version Differences (0.5.0 to 1.4.1)
Breaking Changes
| Version | Change | Migration |
|---|---|---|
| 0.6.0 | Image store directory moved from .build to builder | Update paths referencing .build |
| 0.7.0 | --disable-progress-updates removed | Use --progress none|ansi instead |
| 0.8.0 | Client API reorganization | Update API consumers |
| 0.8.0 | Subnet allocation defaults changed | Review network configurations |
| 0.10.0 | ClientContainer reworked as generic client | Update API consumers for generic client interface |
| 0.10.0 | Bundle creation moved to SandboxService | Move bundle creation code from main container ops |
| 0.10.0 | Multiple network plugins support | Review network configuration for multi-plugin model |
| 0.12.0 | Default Linux capability set REDUCED | Delete & recreate all existing containers; use --cap-add to restore needed capabilities |
| 0.12.0 | Builder-shim gRPC protocol changed | Incompatible with pre-0.12.0 clients — update all builder clients |
| 1.0.0 | TOML config file replaces UserDefaults-backed system properties | Move property set values into ~/.config/container/config.toml; property get/set/clear are removed |
| 1.0.0 | Structured (JSON/YAML/TOML) output shape changed for container/image/network/volume ls and inspect | Update scripts that parse structured output |
| 1.0.0 | Application major version 0 XPC API compatibility removed | Update XPC API consumers |
| 1.3.0 | --scheme auto removed for image operations; default now https | Drop --scheme auto; rely on the https default or pass --scheme http explicitly for a plaintext registry |
| 1.4.1 | container system status output shape now reports host, client, paths, and resources | Update anything parsing that output |
⚠ BREAKING — 0.12.0 capability change: The default Linux capability set was reduced. Users MUST delete and recreate existing containers to apply the new defaults. Use
--cap-addto restore capabilities; use--cap-dropto further restrict them. See 0.12.0 template for details.
Required Migrations
- 0.12.0: Delete and recreate all existing containers (reduced default capability set); add
--cap-addfor containers needing elevated capabilities - 0.12.0: Update builder clients (gRPC protocol changed, incompatible with older clients)
- 1.0.0: Move
container system property setvalues into~/.config/container/config.toml, then restart the service - 1.0.0: Update automation that parses
ls/inspectstructured output (shape changed) - 1.3.0: Drop
--scheme autofrom image operations; rely on thehttpsdefault or pass--scheme httpexplicitly for a plaintext registry - 1.4.1: Update automation parsing
container system statusoutput (host/client/paths/resources shape)
The full per-release feature history, the complete 0.5.x-to-1.0.0 migration checklist, and the dependency matrix live in references/version-history.md. The exhaustive per-command flag reference lives in references/command-reference.md.
See templates/<version>/commands.md for version-specific details (0.4.1, 0.5.0, 0.6.0, 0.7.0, 0.8.0, 0.9.0, 0.10.0, 0.11.0, 0.12.0, 0.12.3, 1.0.0, 1.2.1, 1.3.1, 1.4.1).
Scripts
This skill includes focused Nushell scripts for container management:
container-system.nu
System service management with health checks:
# Start system service
nu scripts/container-system.nu start
# Check status
nu scripts/container-system.nu status
# Full health check (status + disk + container count)
nu scripts/container-system.nu health
# View disk usage
nu scripts/container-system.nu df
# Show version
nu scripts/container-system.nu version
container-images.nu
Image lifecycle operations:
# List images
nu scripts/container-images.nu list
# Pull an image
nu scripts/container-images.nu pull ubuntu:latest
# Build from Dockerfile
nu scripts/container-images.nu build -t myimage:latest .
# Prune unused images
nu scripts/container-images.nu prune
container-lifecycle.nu
Container run/stop/exec/logs/export:
# List running containers
nu scripts/container-lifecycle.nu ps
# Run a container
nu scripts/container-lifecycle.nu run ubuntu:latest
# View logs
nu scripts/container-lifecycle.nu logs mycontainer
# Execute command
nu scripts/container-lifecycle.nu exec mycontainer /bin/bash
# Export container to image (0.10.0+)
nu scripts/container-lifecycle.nu export mycontainer -o exported.tar
container-cleanup.nu
Prune and disk usage:
# Prune everything unused
nu scripts/container-cleanup.nu prune-all
# Prune only containers
nu scripts/container-cleanup.nu prune-containers
# Show disk usage
nu scripts/container-cleanup.nu df
Mise Tasks
Copy templates/mise.toml to add container management tasks to any project:
mise container:start # Start system service
mise container:stop # Stop system service
mise container:status # Show formatted status
mise container:run # Run container (accepts image arg)
mise container:ps # List running containers
mise container:images # List images
mise container:build # Build from Dockerfile/Containerfile
mise container:prune # Clean up unused resources
mise container:health # System status + disk + container count
mise container:df # Disk usage
mise container:version # CLI version
Common Workflows
Quick Start
# Start the system
container system start
# Pull and run an image
container run -it --rm ubuntu:latest /bin/bash
# Check what's running
container ls
Build and Run
# Build your image
container build -t myapp:latest .
# Run it
container run -d --name myapp -p 8080:80 myapp:latest
# Check logs
container logs --follow myapp
Multi-Container with Networking
# Create network
container network create mynet
# Start database
container run -d --name postgres --network mynet \
-e POSTGRES_PASSWORD=secret \
-v pgdata:/var/lib/postgresql/data \
postgres:16
# Start application
container run -d --name app --network mynet \
-p 3000:3000 \
-e DATABASE_URL=postgres://postgres:secret@postgres:5432/mydb \
myapp:latest
Persistent Data with Volumes
# Create a volume
container volume create appdata
# Run with volume
container run -d --name db -v appdata:/var/lib/data mydb:latest
# Volume persists after container removal
container rm db
container run -d --name db2 -v appdata:/var/lib/data mydb:latest
Troubleshooting
Accumulated Stopped Containers (--rm unreliable on 1.0.0)
If container ls -a shows a growing pile of stopped containers despite scripts using --rm, see the --rm note under Container Lifecycle above. Clean up deliberately, never with an unfiltered command:
# Inspect the full target list FIRST — always, before any destructive command
container ls -a
# Remove specific, identified containers by name or ID — never a blind splat
container rm -f <name-or-id> [<name-or-id> ...]
Never run container rm -f $(container ls -aq). That command has no filter: on one host it removed every container present, including unrelated k8s control planes that happened to be running alongside the anonymous scan containers it was meant to clean up. Images and named volumes survived that incident; container state did not. Two lessons, both binding for any cleanup script or agent-authored one-liner touching this CLI:
- Inspect the target list before a destructive command.
container ls -afirst, always — confirm what you are about to remove matches what you intend to remove. - Never splat an unfiltered
lsintorm. Scope every cleanup to specific names or IDs you created or explicitly identified, not "everything the list command currently returns."
System Not Started
# Check status
container system status
# Start if not running
container system start
# View logs for errors
container system logs
Image Pull Failures
# Check system is running
container system status
# Try with explicit platform
container image pull --platform linux/arm64 <image>
# Check registry authentication
container registry login <registry>
Volume Permission Issues
# Check volume exists
container volume list
# Inspect volume for mount details
container volume inspect <name>
# Run container with specific user
container run -u 1000:1000 -v myvol:/data myimage:latest
Builder Issues
# Check builder status
container builder status
# Restart builder
container builder stop
container builder start
# Delete and recreate if stuck
container builder delete
container builder start
Key Principles
- Post-1.0 stability, not immutability: 1.0.0 stabilized the CLI surface for the 0.x-to-1.0.0 migration (TOML config, structured-output shape); 1.3.0 then removed
--scheme autoand 1.4.1 changedcontainer system status's output shape — check Version Differences before assuming an old integration still matches current flags or output - Apple silicon only: No Intel Mac support
- macOS 26+ required: Not available on earlier macOS versions
- OCI-compatible: Standard container images work as expected
- Lightweight VMs: Each container is an isolated lightweight VM
- System service: Start the system service before running containers
- Verify, never fabricate: Confirm flags against
container <cmd> --helpbefore scripting them — see /core:anti-fabrication
Technical Documentation Writing
This skill activates when writing or improving technical documentation, including README files, API documentation, user guides, and inline code documentation.
Anti-fabrication
This skill follows core:anti-fabrication. Most of it is house convention — README
structure, ADR templates, changelog format, comment style — not claims that can go stale
against an upstream. The one real claim area is the "Documentation Tools" section's
generator commands (mix docs for ExDoc, cargo doc for rustdoc, Sphinx, MkDocs, JSDoc,
TypeDoc): verify the invocation against the tool's current docs before asserting it,
rather than repeating it from memory — these are stable but not immune to CLI changes.
README Files
Essential README Structure
Every README should cover: overview, features, installation, quick start, usage, configuration, API reference, development setup, contributing, license, acknowledgments, and support. A complete worked template with all these sections: references/templates.md.
README Best Practices
- Start with a clear one-liner: Immediately tell readers what the project does
- Include badges: Build status, coverage, version, license
- Show, don't tell: Use code examples liberally
- Keep it scannable: Use headers, lists, and code blocks
- Make examples runnable: Readers should be able to copy-paste and run
- Include visual aids: Screenshots, diagrams, GIFs when appropriate
- Update regularly: Keep documentation in sync with code
- Think about newcomers: Write for someone seeing the project for the first time
API Documentation
Document functions with language-native doc comments (Elixir @doc/@spec, JSDoc, Python docstrings, Rust doc comments), document modules/classes with their purpose and public API, and document REST endpoints with method, auth, request/response bodies, and error responses. Worked examples for all three: references/api-documentation.md.
User Guides and Tutorials
Tutorial Structure
# Tutorial: Building Your First [Feature]
## What You'll Build
Brief description of the end result.
## Prerequisites
- Knowledge requirement 1
- Installed tool 1
- Account/access requirement
## Step 1: [First Major Step]
Explanation of what we're doing and why.
```language
// Code for this step
What's happening here:
- Explanation of key line 1
- Explanation of key line 2
Step 2: [Next Step]
Continue with incremental steps...
Testing
How to verify it works.
Next Steps
- Related tutorial 1
- Advanced topic 1
- Further reading
### Tutorial Best Practices
- **Show working code first**: Let readers see the goal before diving into details
- **Explain the 'why'**: Don't just show what to do, explain reasoning
- **Incremental steps**: Each step should build on the previous
- **Include checkpoints**: Ways to verify progress
- **Provide complete code**: Include a repository or final code snippet
- **Anticipate problems**: Address common mistakes
- **Link to references**: Point to relevant API docs and resources
## Inline Code Documentation
### When to Write Comments
**DO write comments for:**
- Complex algorithms or business logic
- Non-obvious decisions ("why" not "what")
- Workarounds for bugs or limitations
- Public APIs and exported functions
- Configuration and constants
**DON'T write comments for:**
- Obvious code
- What the code does (prefer clear naming)
- Outdated information
- Commented-out code (use version control)
### Good Comment Examples
```elixir
# Good: Explains WHY
# Use exponential backoff to avoid overwhelming the API after rate limit errors
defp retry_with_backoff(attempt) do
:timer.sleep(:math.pow(2, attempt) * 1000)
end
# Bad: Explains WHAT (obvious from code)
# Multiply 2 to the power of attempt and multiply by 1000
defp retry_with_backoff(attempt) do
:timer.sleep(:math.pow(2, attempt) * 1000)
end
# Good: Documents workaround
# NOTE: Using String.to_existing_atom because the Erlang VM limits atoms to ~1M.
# All valid status atoms are pre-defined in this module.
def parse_status(status_string) do
String.to_existing_atom(status_string)
end
# Good: Explains business rule
# Users must be at least 13 years old per COPPA regulations
@minimum_age 13
Architecture Documentation
Architecture Decision Records (ADR)
Document significant architectural decisions:
# ADR 001: Use PostgreSQL for Primary Database
## Status
Accepted
## Context
We need to choose a database for our application that supports:
- ACID transactions
- Complex queries with joins
- JSON data storage
- Full-text search
- Horizontal scalability (future requirement)
## Decision
We will use PostgreSQL as our primary database.
## Consequences
### Positive
- Mature, stable, well-documented
- Excellent JSON support with JSONB
- Built-in full-text search
- Strong consistency guarantees
- Large ecosystem of tools and extensions
- Can scale with read replicas and partitioning
### Negative
- More complex to operate than simpler databases
- Vertical scaling has limits (though sufficient for our needs)
- Requires more server resources than lighter alternatives
### Neutral
- Team needs to learn PostgreSQL-specific features
- May need to hire PostgreSQL expertise as we scale
## Alternatives Considered
- **MySQL**: Weaker JSON support, less feature-rich
- **MongoDB**: No ACID guarantees, eventual consistency issues
- **SQLite**: Not suitable for multi-user web applications
Changelog Documentation
Follow Keep a Changelog format:
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- New feature in development
## [1.2.0] - 2024-01-15
### Added
- User profile pictures
- Email notification preferences
- Dark mode support
### Changed
- Improved search performance by 40%
- Updated UI to match new brand guidelines
### Fixed
- Login redirect loop on Safari
- Memory leak in background sync process
### Deprecated
- Old `/v1/users` endpoint (use `/v2/users` instead)
## [1.1.0] - 2024-01-01
### Added
- Two-factor authentication
- Export user data to JSON
### Security
- Fixed XSS vulnerability in comment rendering
## [1.0.0] - 2023-12-15
### Added
- Initial release
- User registration and authentication
- Basic user profiles
Documentation Tools
Documentation Generators
- Elixir: ExDoc -
mix docs - JavaScript: JSDoc, TypeDoc
- Python: Sphinx, MkDocs
- Rust: rustdoc -
cargo doc - Static sites: VitePress, Docusaurus, GitBook
Prose Linting
- Vale:
mise run test:prose— checks banned words, clutter, sentence length, and hedged directives. See/vale:valefor the tool and/core:technical-englishfor the register rules it enforces.
Diagram Tools
- Mermaid: Diagrams in Markdown
```mermaid graph TD A[User] -->|Requests| B[Load Balancer] B --> C[Web Server 1] B --> D[Web Server 2] C --> E[Database] D --> E - PlantUML: UML diagrams as code
- Excalidraw: Hand-drawn style diagrams
- Draw.io: Flowcharts and diagrams
Documentation Style Guide
Writing Style
- Use active voice: "The function returns" not "The value is returned"
- Be concise: Remove unnecessary words
- Use present tense: "Returns" not "Will return"
- Be specific: "Timeout in milliseconds" not "Timeout value"
- Avoid jargon: Or explain it when necessary
- Use examples: Show, don't just tell
Formatting Conventions
- Code: Use
backticksfor inline code - Commands: Show with
$prefix or in code blocks - File paths: Use
code formatting - Emphasis: Use bold for important points, italic for slight emphasis
- Lists: Use bullets for unordered, numbers for sequential steps
- Headers: Use sentence case, not title case
Code Examples
- Complete: Include all necessary imports and setup
- Runnable: Readers should be able to copy and run
- Realistic: Use meaningful variable names and realistic data
- Commented: Explain non-obvious parts
- Tested: Ensure examples actually work
- Current: Keep in sync with latest API
Documentation Maintenance
Keeping Docs Updated
- Update documentation in the same PR as code changes
- Review docs during code review
- Set up doc linting (broken links, outdated examples)
- Schedule regular documentation audits
- Use version tags in examples when API changes
- Mark deprecated features clearly
Documentation Testing
# Elixir doctests - examples in docs are actual tests
defmodule Math do
@doc """
Adds two numbers.
## Examples
iex> Math.add(2, 3)
5
"""
def add(a, b), do: a + b
end
/// Adds two numbers.
///
/// # Examples
///
/// ```
/// assert_eq!(add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
Key Principles
- Write for your audience: Tailor complexity to reader's experience level
- Show examples: Code examples are worth a thousand words
- Keep it current: Outdated docs are worse than no docs
- Make it scannable: Use headers, lists, code blocks, and white space
- Explain the 'why': Help readers understand reasoning, not just steps
- Start simple: Begin with quickstart, then go deeper
- Test documentation: Ensure examples run and links work
- Iterate based on feedback: Improve based on user questions and confusion
Git Operations
Activate when creating commits, managing branches, creating pull requests, resolving conflicts, or following Git workflows.
Anti-fabrication
This skill follows core:anti-fabrication. The commit/PR format rules are house
convention, but the "Remote and Authentication Conventions" section makes specific,
checkable claims about Git and the GitHub API — this is the one skill in this set that
does, and its claims are verified in different ways:
- Anonymous access to GitHub Releases on a private repo returns 404, not 403.
Confirmed against GitHub's own documentation, cited in
sources.md: "GitHub uses a 404 Not Found response instead of a 403 Forbidden response to avoid confirming the existence of private repositories." - SSH key auth bypasses the
workflowOAuth scope that HTTPS push enforces. GitHub documents theworkflowscope requirement for OAuth apps/PATs pushing Actions workflow files (cited insources.md), but does not document the SSH-side exemption as a general principle — that half is empirically observed, not centrally documented: pushing a.github/workflows/*.ymlchange over HTTPS with a token lackingworkflowscope is rejected ("Refusing to allow an OAuth App to create or update workflow ... withoutworkflowscope"); the identical push over SSH succeeds. - The Worktrees section's mechanics (index and
HEADper-worktree,refs/stashshared,addrefusing a branch already checked out,-drefusing after a squash merge, the$WORKTREE_ROOTroot formula) are confirmed against git 2.54.0 man pages and reproduced by execution in a throwaway repo, cited insources.md.
Don't assert git/gh/glab CLI or GitHub/GitLab API behavior this skill doesn't
already cover without checking the current docs, or testing it directly when the docs
don't say — CLI flags and API responses do change across versions.
glabcommand/flag names throughout this skill andreferences/gitlab-mr.mdcome from the official docs athttps://docs.gitlab.com/cli/(per-command pages cited insources.md), NOT from local execution —glabwas not installed on the machine where this content was authored, and no command here was tested by running it. Noglabversion is pinned deliberately: pinning a version never actually run against would overstate the evidence. Re-check withglab <cmd> --helpbefore relying on a flag.
Commit Format
Follow the Conventional Commits specification:
type(scope): description
optional body
optional footer
Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
Subject line rules:
- Keep under 50 characters
- Lowercase after type prefix
- No period at the end
- Use imperative mood ("add" not "added" or "adds")
Body (optional): Wrap at 72 characters. Focus on the what and how — never describe the changes themselves, as the git diff handles that.
Footer (optional): Reference issues (Closes #123), note breaking changes (BREAKING CHANGE: ...).
NEVER add agent attribution anywhere in Git or a forge. No robot emoji (🤖), "Generated with Claude Code", AI signatures, Co-Authored-By, Signed-off-by, or similar credit. This covers commits and trailers; branch names and descriptions; tags and annotations; PR/MR titles, bodies and descriptions; issues and their titles/descriptions; comments, reviews, discussions, release notes, and API-posted content. Apply the rule to every creation, edit, reply, and merge message, regardless of tool or agent. Describe the work without crediting the assistant. Ordinary product names and required source/license notices are not assistant signatures.
Check before publishing, not only during review. Inspect the final outgoing title, name, message, description, and any body file before every Git/forge write. Remove attribution inherited from templates, generated text, or commit history. Never append a signature after checking. Core and all-skills register a plugin-level attribution hook for Bash calls; its supported command forms and limits are documented in references/no-attribution.md. Other tools still require the same pre-publication check.
Configure Claude Code's built-in attribution too. When setting up the no-attribution policy, merge "attribution": {"commit": "", "pr": "", "sessionUrl": false} into the chosen settings file, preserving unrelated settings. Use ~/.claude/settings.json for the user's projects on this machine or .claude/settings.json for a shared project policy. Read native configuration and verification for precedence, version compatibility and behavior checks. Keep the hook and pre-publication checks active; this setting controls Claude Code's commit/PR attribution, not all Git/forge output.
Examples:
# Single-line (preferred for most commits)
feat(auth): add JWT authentication
fix(api): handle null values in user response
docs(readme): add installation instructions
chore(deps): bump plugin versions
# With body and footer
feat(api): add user search endpoint
Implement full-text search across user names and emails using
PostgreSQL's full-text search capabilities.
BREAKING CHANGE: API now requires PostgreSQL 12+
Closes #789
PR / MR Format
Title matches commit format. Body is a bullet list of changes only.
gh pr create --title "feat(auth): add JWT authentication" --body "- Add JWT generation and validation
- Implement refresh token rotation
- Add authentication middleware"
glab mr create --title "feat(auth): add JWT authentication" --description "- Add JWT generation and validation
- Implement refresh token rotation
- Add authentication middleware"
Note glab's flag is --description, not --body — the flag name differs from gh's.
Rules:
- No robot emoji, agent credit, "Generated with Claude Code", or similar attribution in any field
- No PR / MR templates or boilerplate sections
- No "Summary", "Test Plan", or other headers
- Just the changes as bullet points
- Keep it minimal and scannable
PR / MR Workflow
Every PR starts in its own worktree off fresh origin/main — see Worktrees below.
- Gate 1 — Local CI:
mise run ci— fix until 0 failures - Commit: Conventional commit, no attribution
- Gitleaks: Scan committed changes for secrets —
$(mise which gitleaks) git . --staged, never a baregitleaks(/core:security). Thecheck-secrets-before-commit.shPreToolUse hook backstops this ongit commit, once/core:securityhas been invoked once this session — it then keeps running on every later turn, not only while that skill's own turn is active (/extras-claude-code:claude-hooks) — and it fails open — allows the commit — when no scanner is available. The gap is a session that never invokes the skill, not one where it is merely "not loaded." Run the scan yourself; don't treat the hook as a substitute for it. - Push:
git push -u origin <branch> - Create PR:
gh pr create(GitHub) orglab mr create(GitLab) with minimal format (title + bullets) - Gate 2 — Watch remote CI:
gh pr checks --watch(GitHub) orglab ci status --live(GitLab) (wait for CI to complete) - After CI passes (if using bees) — run
bees close <task-id>from the primary checkout, then land the.bees/issues.jsonlexport as its ownchore(bees)PR from a worktree; see Worktrees, "Bees runs from the primary." Nevergit add .bees/ && git commitinside this PR's own worktree — the live tracker state lives in the primary, not here. - Notify (Gate 2 satisfied — local + remote green): "CI passed, PR ready for merge review"
- Cleanup (after user merges) — follow the Worktrees "Cleanup, merged-only" sequence
below: confirm
MERGED,git worktree remove,git branch -D. - Continue:
bees readyfor next task
Three-Gate Merge Policy
Three gates protect main. None is optional, and none substitutes for another.
Gate 1 — Local (before every commit). mise run ci runs green — tests, lint, and format, 0 failures — before each git commit. A red local CI means the commit is broken: fix it locally, never push past it. Scan staged changes with gitleaks before push — resolved binary path, never a bare gitleaks: $(mise which gitleaks) git . --staged. The PreToolUse hook backstops this on git commit, once /core:security has been invoked once this session — it then keeps running for the rest of the session, not only while that skill is loaded (/extras-claude-code:claude-hooks) — and fails open when no scanner is available — it is not a substitute for the scan (/core:security).
Gate 2 — Remote (before every squash merge). Squash-merge a PR only when both conditions hold:
- Local
mise run ciis green on the branch HEAD being merged, and gh pr checks(GitHub) orglab ci status(GitLab) reports every remote check passing.
Gate 3 — Adversarial review (before every squash merge). Every PR gets a review from a separate agent on the strongest thinking model the harness offers — the same tier as /core:agent-loop's reviewer default, and overridable by its model-overrides convention. Name a capability, never a model literal. No exemption: not for one-line fixes, not for documentation, not for version bumps.
The reviewer answers two questions in order, and the record carries each under its own heading (## Fit and size, ## Findings). First, fit and size: what problem does this change solve, who is on the other side of it, and what is the smallest change that satisfies the acceptance criteria — name it, even when it is what shipped. Anything in the diff beyond that answer is a finding before any bug is. Second, defeat the change: given the specific failure it is meant to prevent, construct a case that still gets through. Size the hunt to the other side: a first-party agent that forgets is beaten by one obvious check, and a bypass that needs evasion is a disclosure, not a defect; only an untrusted principal justifies chasing evasions (/core:restraint, "Never lazy about"). A reviewer told to "check this over" returns nothing useful; a reviewer told "assume a defect exists and find it" returns the defect.
Three focus areas are standing — every review carries them, whatever else the brief adds:
-
Restraint (
/core:restraint). Does this change need to exist? Is it the minimum that works, or does it add a symbol, an abstraction, or a config knob the task never asked for? Could an existing helper, stdlib call, or platform feature have done it? A reviewer that only hunts bugs approves well-built things that should not have been built. -
Documentation the change obligates. If the change alters behaviour, an interface, or a decision, did it update what depends on that — user docs, READMEs, ADRs, system-design documents, and the skill or reference that describes the thing? A change that silently invalidates a document is a defect with a delayed fuse.
-
Claims in the PR body. Every measurement, count, and "verified" in the description is checkable. Check them. Overstated PR bodies are a common defect this process finds.
Gate 3 requirements:
- A separate agent. The author cannot review its own work — the point is a reader without the author's assumptions.
- Read-only; execution through execution hands. See ADR 0001 decision 4 and
/core:agent-loop'sreferences/reviewer.md. - Findings are addressed or answered, not waved through. Applying a fix, disputing it with evidence, and filing it as a tracked follow-up all count. Silence does not.
- Verify the reviewer's claims independently before acting on them. A review is evidence, not a verdict.
- Recheck attribution before declaring gates green — inspect the branch's commits, PR/MR title and description, and outgoing comments:
git log origin/main..HEAD --format='%B' | grep -niE '🤖|co-authored-by|signed-off-by|assisted-by|generated (with|by)', then apply the same check to the other fields. This supplements the pre-publication check; it does not postpone it. Exclude bare product/vendor names from the pattern and inspect signatures the pattern misses. - The verdict and each finding's disposition land as a durable record on the PR. Under
approval, the record is the PR comment carrying the marker line of "Merge authorization" rule 2. Post it withgh pr comment, never inside a review body, which thecommentsfield excludes. Underoperator, a bees comment the PR links also counts, and it travels in the trackedissues.jsonlexport. - Confirm the record before declaring Gate 3 green. Confirm a PR comment with
gh pr view <n> --comments. Confirm a bees comment withbees comment list <task-id>and the link to it in the PR body or comments. Confirm it opens with the fit-and-size answer; a record that begins with findings has skipped focus area 1.
No gh pr merge --squash while any gate is red. Who may take the merge is set by the deployment's merge policy — see "Merge authorization" below.
Merge authorization
AGENT_LOOP_MERGE_POLICY selects the authorization source. It never carries the authorization itself.
| Value | Source consulted | Effect |
|---|---|---|
operator (default) | none | The agent reports the PR and stops. |
approval | a forge review approval bound to headRefOid by a non-author identity, read at merge time | A leader-tier agent merges once the precondition holds. |
Unset and "" resolve to operator silently. Any other unrecognised value resolves to operator and emits one line: merge-policy: AGENT_LOOP_MERGE_POLICY=<value> not recognized; proceeding as operator.
Under operator no agent merges, so no agent evaluates the precondition. Step 8 of the PR / MR Workflow above is unchanged.
Scope. This policy governs first-party work only. The github plugin's pr-review and dependabot-consolidator skills merge third-party code and stay operator-approved whatever this variable is set to. A PR with isCrossRepository == true is out of scope.
The precondition
The precondition binds a merging agent. It does not bind a human. Read the forge immediately before the merge, except where a rule sets its own read timing. The transcript is not an input. An earlier tool result is not an input.
gh pr view <n> --json headRefOid,baseRefName,isCrossRepository,mergeStateStatus,mergeable,statusCheckRollup,reviews,comments,autoMergeRequest
- Checks.
statusCheckRollupreturns two types with different fields:CheckRuncarriesstatusandconclusion;StatusContextcarriesstateand noconclusion. BLOCK on anyCheckRunconclusion in {FAILURE, CANCELLED, TIMED_OUT, ACTION_REQUIRED, STARTUP_FAILURE, STALE}, or anyStatusContextstate in {ERROR, FAILURE}. WAIT on anyCheckRunstatus other than COMPLETED, or anyStatusContextstate in {PENDING, EXPECTED}. Accept conclusions {SUCCESS, NEUTRAL, SKIPPED} and state SUCCESS. Require at least one SUCCESS — an all-SKIPPED rollup satisfies "a check is present" and proves nothing. - Gate 3 record. A PR comment carries, on its own line,
Gate 3: APPROVE <40-hex-oid>matchingheadRefOidexactly. A free-text sha mention does not satisfy this. Treat an APPROVE comment whoseincludesCreatedEditis true as absent. The comment's author must not be the identity performing the merge. AGate 3: REJECT <40-hex-oid>comment matchingheadRefOidBLOCKS regardless of any APPROVE marker at the same head, and blocks whether or not it was edited. Do not extend theincludesCreatedEditrule to a REJECT: discarding an edited APPROVE fails closed, and discarding an edited REJECT fails open, because anyone with write access can edit another user's comment. Any block signal wins. - Base.
baseRefNameequals the repository default branch. Read the default branch once per session withgh repo view --json defaultBranchRef -q .defaultBranchRef.name;gh pr view --jsoncarries no such field (verified against gh 2.93.0's field list). - Mergeability.
mergeStateStatusis in {CLEAN, HAS_HOOKS}, or UNSTABLE when rule 1 is independently satisfied. BLOCK on DIRTY, BLOCKED, and BEHIND. On UNKNOWN, re-read a bounded number of times — watchingmergeablealongside it — then WAIT. Never merge on UNKNOWN. - Reviews. Compute each author's latest review from
reviews[]bysubmittedAt, restricted to entries whose state is APPROVED or CHANGES_REQUESTED. This restriction drops DISMISSED and COMMENTED entries from consideration (a COMMENTED review never clears a CHANGES_REQUESTED block — GitHub keeps the block until dismissal or a new approving review from the same author). Any author whose latest qualifying review is CHANGES_REQUESTED blocks, whatever commit it targets. Readreviews[], neverlatestReviews[]. - Under
approvalonly. Areviews[]entry hasstate == APPROVEDandcommit.oid == headRefOid, from a login other than the PR author and other than the identity performing the merge, which the merging agent learns viagh api user -q .login. - Under
approvalonly.isCrossRepository == false. - Dismissals — allowlist, not denylist. Evaluate this rule only when rule 5's
reviews[]read contains a DISMISSED entry; the common path with no dismissal skips this read entirely. When triggered, rungh api repos/<owner>/<repo>/issues/<n>/timeline --paginateafter thegh pr viewread. WAIT on a non-zero exit, or when the output is not a JSON array of events. BLOCK unless everyreview_dismissedevent'sdismissed_review.stateis in {approved,commented}. Rule 5 cannot see a dismissal: a dismissed entry readsstate == DISMISSED, which its {APPROVED, CHANGES_REQUESTED} restriction drops, so a dismissed CHANGES_REQUESTED silently restores an earlier approval as that author's latest qualifying review.
Then merge pinned to the sha that was read:
gh pr merge <n> --squash --match-head-commit <headRefOid>
glab mr merge <n> --squash --yes --auto-merge=false --sha <headRefOid>
Forbidden — each one defers the merge, bypasses a requirement, or edits the evidence. gh pr merge --auto queues a merge that fires later. gh pr merge --admin bypasses branch requirements and a merge queue. glab mr merge without --auto-merge=false queues on a flag that defaults to true. On a repo with a merge queue, plain gh pr merge adds the PR to the queue instead of merging it. Detect the queue and wait. autoMergeRequest in the read is the observable for "no auto-merge is already queued". A merging agent never dismisses a review or deletes a Gate 3 comment — both are writes on the evidence this precondition reads. gh has no dismissal verb; dismissal requires gh api --method PUT .../pulls/<n>/reviews/<id>/dismissals -f message=....
Enforcement hook (claude-skills-340)
plugins/core/skills/git/hooks/block-merge-writes.nu, wired in this file's hooks:
frontmatter, backstops the Forbidden list above at the Bash tool boundary. It does not
replace the rule — the same posture as the gitleaks PreToolUse hook in /core:security.
It is a cheap deterministic gate, not a security boundary.
Two named approximations stand in for cases the hook cannot decide from a command
string alone. A gh pr merge lacking --match-head-commit blocks, standing in for the
undecidable merge-queue case — whether plain gh pr merge queues or merges depends on
repo state, not the command. A non-GET gh api call touching /pulls/ or
/issues/comments/ blocks, standing in for review-dismissal and Gate-3-comment-deletion
writes — deletion of a comment names a comment id, not its content, so the hook blocks
the broader shape instead.
Known over-blocks, none of them fixed — a gate that blocks ordinary work gets switched
off, not tightened further: a heredoc line beginning gh pr merge --admin becomes its
own segment after the hook's newline split and blocks (rare, since file writes go
through Write/Edit and never reach this hook); every gh api graphql call carrying
the substring mutation anywhere, including a field literally named mutationCount;
and every non-GET gh api call touching /pulls/, whether or not the call is actually
a merge-path write.
Evasion is out of scope by design, not a gap to close: a command reaching gh through
$( ), a shell alias, bash -c, a variable-held command name, a subshell or brace
group, !/time/then/do prefixes, or an emptied --match-head-commit= value all
defeat the hook. None of those are defects in it — the hook exists to catch the everyday
mistake, the same reason a linter exists, not to stop an agent actively trying to get
around it.
Lifetime limitation: the hook fires only in a session that has loaded this skill (or a plugin whose frontmatter wires the same hook command). It is absent in a session that never invokes this skill — the rule in "Forbidden" above still binds there, unenforced.
A missing signal means WAIT, never denied. Denied is a terminal disposition, and an unattended session may act on it — close the PR, abandon the branch, fail the issue. Wait means this: leave the PR exactly as it is, report what is being waited on, and end the turn. Safe means the PR's forge state is unchanged by the session.
Re-attestation. The Gate 3 record names the sha that merges. When commits land after the record, the reviewer reads git diff <reviewed-sha>..<head> only, confirms the delta addresses its findings and introduces nothing else, then posts the marker line at the new sha. A marker posted without reading the delta is the unverifiable assertion Gate 3 exists to catch.
What approval is entitled to claim
An APPROVED review pinned to head by a login other than the PR author, with author.login as the actor record. That is a distinct forge identity — not a human. Two consequences follow. In a single-identity deployment approval is unsatisfiable, because the author cannot self-approve; it is operator with a longer read. In a bot-identity deployment, one agent holding tokens for two identities satisfies it with zero humans. The deployment obligation therefore lands on the approving identity: it must not be one the agent can authenticate as. An allowed-approver list or an authorAssociation filter is the knob.
Residual risks
approvalguarantees a distinct forge identity, not a human review.- Field consistency inside one
gh pr view --jsonread is treated as a consistent snapshot; GitHub does not document it as one.--match-head-commitbounds the damage to a check status flipping on an unchanged head. - Base moved, not head: the checks ran against the branch, not against a squash onto current main. BEHIND is reported only under a "require branches up to date" rule, so
mergeStateStatusdoes not cover this. Post-merge main verification (/core:tdd,references/ci-discipline.md) is the only backstop. reviews[].commit.oidis the field this precondition reads. A reader who substituteslatestReviews[]may get a value that does not equalheadRefOid— it fails safe, but silently.- GitLab here is docs-only:
--sha,glab mr viewapproval fields, and self-approval project settings are unverified, the same evidence class disclosed in "Anti-fabrication" above. - A merge queue inverts the meaning of plain
gh pr merge— it queues rather than merges. The forbidden-command list and theautoMergeRequestobservable handle it; it is restated because it changes a command this skill otherwise uses. - A repo with no CI, or with fully path-filtered CI, never satisfies the at-least-one-SUCCESS rule and waits permanently under
approval. That is correct behavior, not a defect. mergedByrecords the agent's forge identity, so the audit trail cannot distinguish an agent merge from a human one. Removing the standing axiom grows this risk.- Records are editable and deletable, and rule 2 treats the two markers asymmetrically on purpose. Deleting an APPROVE fails closed, while deleting a REJECT is undetectable — GitHub documents no REST event type for comment deletion. A REJECT at a stale sha does not block, which follows from re-attestation but is asymmetric with rule 5. An implementer who reads records as immutable, or who applies one marker's treatment to the other, reintroduces all of this.
- A force-push orphans a review's commit. The
commit.oid == headRefOidpin handles APPROVED, and the per-author-latest rule keeps a CHANGES_REQUESTED on an unreachable commit blocking. - A repo-local
mise.toml[env]block can setAGENT_LOOP_MERGE_POLICY, so on a deployment that trusts repo config the policy is settable by a PR branch. Set the variable in the launcher environment and do not let repo config override it. - Rule 8 blocks permanently once a disallowed dismissal lands, including an operator's legitimate one, because the timeline event never clears; the remedy is an operator merge, not a re-review. Risk 2's single-snapshot treatment does not cover rule 8's timeline read. An agent that dismisses a review after completing every read can still merge, because no rule pins review state at merge time. Rule 8 detects a dismissal; it does not prevent one. The forge-side control that constrains one is branch protection's restriction on who may dismiss reviews, the counterpart to the allowed-approver knob above; it binds a merging identity only when that identity is neither a repository administrator nor on the allowed-dismisser list. Whether GraphQL
deletePullRequestReviewcan remove a submitted review requires verification; a removed review would silence rule 8's trigger. A sample of 8 public repositories, over each repository's last 100 PRs, found 21 review dismissals with prior stateapprovedand 8 withchanges_requested, and none at all in 3 of them — evidence that a bot self-dismissing its own CHANGES_REQUESTED occurs, not a measured rate forapprovaldeployments generally.
Gate 3 is not the pipeline's review tier
/core:agent-loop's five-tier pipeline has its own reviewers — P5 verifies tests exercise the acceptance criteria, the test-review stage checks for redundancy. Those judge whether the implementation meets the issue's spec.
Gate 3 runs on the PR and judges whether the change is defensible against someone trying to break it. Identify it by its brief, not its timing: no pipeline reviewer counts, even one that read the full PR diff — Forge's Final Reviewer does exactly that and is still not Gate 3. Gate 3 is the review carrying the two-question brief described under "Gate 3 — Adversarial review" above and the three standing focus areas, dispatched after the pipeline reports done.
Why three gates and not two
Gates 1 and 2 prove the suite passes, not that the change is correct. A green build is evidence the tests ran, not evidence the work is right — and the defects worth catching here are the ones a passing suite cannot see: documentation that describes behaviour the code does not have, a check that reports success without checking, a claim in a PR body that nobody verified.
Each gate therefore owes an observable. Gate 1 has mise run ci output and Gate 2 has gh pr checks; Gate 3 has the durable record, without which "review done" is an assertion nobody can check.
Merge Strategy
Squash merge only, and only after all three gates are green:
mise run ci # Gate 1: local, already green before the last commit
gh pr checks <number> # Gate 2: remote (GitHub)
glab ci status --branch <branch> # Gate 2: remote (GitLab)
# Gate 3: adversarial review reported, findings addressed or answered
# Merge authorization: see "Merge authorization" above for the full read set
gh pr view <number> --json headRefOid,baseRefName,isCrossRepository,mergeStateStatus,mergeable,statusCheckRollup,reviews,comments,autoMergeRequest
gh pr merge <number> --squash --match-head-commit <headRefOid> # GitHub
glab mr merge <number> --squash --yes --auto-merge=false --sha <headRefOid> # GitLab
Never use regular merge or rebase merge for PRs or MRs. Squash merge keeps main history clean with one commit per PR.
Deferred-firing and bypass paths. A merge that fires later is a merge nobody authorized at the moment it happened, against forge state nobody read. glab mr merge's --auto-merge defaults to true, so an unset flag queues one — always pass --auto-merge=false. gh pr merge --auto queues the same way. gh pr merge --admin bypasses branch requirements and a merge queue. On a repo with a merge queue, plain gh pr merge adds the PR to the queue rather than merging it (gh pr merge --help, gh 2.93.0). Detect the queue and wait; never queue.
Branch Naming
<type>/<description>
<type>/<issue-number>-<description>
Examples: feature/user-authentication, fix/456-null-pointer-error, chore/update-dependencies
Branch naming is platform-agnostic — identical on GitHub and GitLab. So are the Three-Gate Merge Policy and Key Rules; only the CLI verbs change.
Worktrees
New work happens in its own worktree. The primary checkout stays on main, clean, and
advances only via git pull --ff-only — nobody commits or switches branches there. Clean
means git status --short -- . ':!.bees' is empty; .bees/ churn is tracker bookkeeping
and doesn't count against that clean check.
Bees runs from the primary. bees close, bees update, and other write commands
operate on the primary checkout's live .bees/bees.db — a worktree's own .bees/ lacks
it. The resulting .bees/issues.jsonl export lands as its own chore(bees) PR, opened
from a worktree like any other work; the primary itself never commits it.
Location — $WORKTREE_ROOT/<repo>-<slug>, defaulting to:
$(dirname "$(dirname "$(git rev-parse --path-format=absolute --git-common-dir)")")/worktrees
--git-common-dir resolves identically from the primary checkout and from inside a
worktree; --show-toplevel does not — run inside a worktree, it returns the worktree
itself, yielding a nested worktrees/worktrees. The formula assumes the ordinary layout
— .git is a directory inside the primary checkout; it resolves one directory too high
in a bare repo and relative to the git dir, not the checkout, under --separate-git-dir.
Set $WORKTREE_ROOT explicitly in either of those layouts. Never /tmp,
/private/tmp, or a harness scratchpad (cleared on reboot), and never inside the
project tree (.worktrees/, .claude/worktrees/) — tree-walking build and scan tools
descend into a nested checkout.
Create — fetch first, so the branch point isn't stale:
git fetch origin
git worktree add "$WORKTREE_ROOT/<repo>-<slug>" -b <type>/<slug> origin/main
What is actually shared. The object database and refs are shared across worktrees,
including refs/stash — a stash taken in one worktree is visible and poppable in
every other. The index and HEAD are per-worktree (gitrepository-layout(5)), so git worktree add refuses a branch already checked out elsewhere — a safeguard, not the
index corruption an earlier version of this rule claimed (see sources.md).
Build state never travels — never symlink (it has caused disasters) or copy
_build, deps, .zig-cache, zig-out, node_modules into a worktree. Cold builds
are expensive: one worktree per issue or PR, reused across every review round, never a
throwaway review worktree. Share only toolchain-designed caches: ~/.cache/zig,
~/.hex, ~/.mix.
Cleanup, merged-only — confirm gh pr view <n> --json state reports MERGED. Before
removing, confirm the Gate 3 record quotes the evidence it cites — git worktree remove
deletes the worktree's evidence directory along with the worktree (/core:agent-loop's
references/reviewer.md, "Output") — then run git fetch origin and confirm git cat-file -e $(gh pr view <n> --json mergeCommit -q .mergeCommit.oid) succeeds: the merge
commit's presence holds as a removal precondition whether or not the head branch survives
the merge. Where the forge deletes the head branch on merge (gh repo view --json deleteBranchOnMerge reports true), the branch itself is gone from origin afterward
and is never a usable precondition on its own — check the merge commit's presence
instead. Then git worktree remove <path> (never rm -rf), then git branch -D <branch> (-d refuses
after a squash merge, since the tip is never an ancestor). git worktree remove itself
refuses on modified or untracked files ("use --force to delete it") — an evidence
directory alone does not trigger this. Inspect what's untracked, then --force if it's
expected debris; --force removes the directory and the entry together, while rm -rf
removes only the directory and leaves a registered entry pointing at nothing
(prunable) — that orphan is why rm -rf is banned. git worktree prune stays banned
too — it drops entries for a missing directory that can still belong to another agent's
open PR, and it never helps a directory that still exists. Afterward, confirm git worktree list shows other agents' worktrees intact.
An auto-approval mode flags git worktree remove and git branch -D as irreversible
local destruction. That is expected for a merged-only cleanup that already confirmed
MERGED and the merge commit's presence above — the flag is not a signal to stop or
override.
Recovery — when a reboot cleared a worktree directory whose PR is still open, git worktree add -f <same-path> <branch> re-attaches the registered entry.
Harness worktrees (EnterWorktree, .claude/worktrees/) are excluded for any work
that becomes a commit or PR — harness-specific, inside the repo, and they leave
untracked detached leftovers. isolation: 'worktree' inside a workflow run stays
sanctioned: the harness creates a per-agent worktree and removes it only if the agent
leaves it unchanged (/extras-claude-code:claude-workflows, /extras-claude-code:claude-agents). An
implementer that commits has changed the tree, so that tree persists — the same
untracked-leftover exclusion above then applies to it.
Destructive commands still run in a scratchpad clone, not a worktree — see
/core:agent-loop's references/researcher.md "Execution hands".
Who may run what inside a worktree, and when, is /core:agent-loop's concern — see its
worktree exclusivity section.
Remote and Authentication Conventions
SSH-form remote URLs for operations
Use SSH-form remote URLs (git@github.com:<owner>/<repo>.git, or git@gitlab.com:<group>/<project>.git on GitLab), not HTTPS, for any worker that performs git push, git fetch, or other operations. SSH key-based auth bypasses OAuth scope checks that HTTPS push enforces, so it works reliably across container hosts and CI runners that do not carry GitHub-aware credential helpers.
# Convert an https remote to ssh form
git remote set-url origin git@github.com:<owner>/<repo>.git
git remote set-url origin git@gitlab.com:<group>/<project>.git
GitHub Releases on private repositories require authentication
Anonymous curl against https://github.com/<owner>/<repo>/releases/... for a PRIVATE repository returns HTTP 404, not 401. Always authenticate (gh auth login or Authorization: token <gh-token> header) before fetching release assets from a private repo. Anonymous-first probes silently report "not found" when the real problem is "not authenticated".
Layered GitHub authentication
Prefer the layered auth chain over a single static GITHUB_TOKEN env var:
ghkeychain (primary on operator boxes —gh auth login).- Scoped Personal Access Tokens for unattended hosts (containers, CI runners), with the minimum scopes the workflow needs.
- Per-node OAuth for federated deployments.
A single GITHUB_TOKEN env var blanket-deployed across hosts loses scope granularity and rotation independence. Use gh auth refresh -h github.com -s workflow to add the workflow scope when CI scripts need it.
GitLab's entry point is glab auth login (--hostname for self-managed instances, --stdin for CI token input, --job-token in CI) — the same layering principle applies: keyring first, scoped token for unattended hosts.
Prefer git-backed substrate
Default to git-backed designs (local, private, or GitHub) for any system that needs an audit trail, replicability, or merge semantics. Git provides commit-level history, signature verification, hooks, and a uniform protocol across local files, private servers, and public hosts. Build atop git before introducing a new storage layer.
GitHub PR Commands
gh pr create --title "type(scope): description" --body "- change 1"
gh pr create --draft # Draft PR
gh pr list # List PRs
gh pr view 123 # View PR
gh pr checkout 123 # Checkout PR locally
gh pr merge 123 --squash # Squash merge PR — see "Merge authorization" for the pinned form required at merge time
GitLab MR Commands
Same workflow, different verbs. glab mirrors gh's shape, including the -R, --repo global flag. Flag detail, auth, and the surfaces this skill deliberately does not model are in gitlab-mr.md.
| Action | GitHub | GitLab |
|---|---|---|
| Create | gh pr create --title "..." --body "..." | glab mr create --title "..." --description "..." |
| Draft | gh pr create --draft | glab mr create --draft |
| List | gh pr list | glab mr list |
| View | gh pr view 123 | glab mr view 123 |
| View with comments | gh pr view 123 --comments | glab mr view 123 --comments |
| Checkout | gh pr checkout 123 | glab mr checkout 123 |
| Comment (Gate 3 record) | gh pr comment 123 --body "..." | glab mr note create 123 -m "..." |
| CI status (Gate 2) | gh pr checks 123 | glab ci status --branch <branch> |
| Watch CI | gh pr checks --watch | glab ci status --live |
| Squash-merge | gh pr merge 123 --squash | glab mr merge 123 --squash --yes --auto-merge=false |
| Authenticate | gh auth login | glab auth login |
gh pr checks is scoped to the PR; glab ci status is scoped to a branch (current branch by default). They are not interchangeable at Gate 2 — on GitLab, confirm the branch being checked is the MR's actual source branch before trusting the result.
The squash-merge row above shows the bare command for reference. Never run it unpinned — see "Merge authorization" for the required --match-head-commit / --sha form.
Key Rules
- No attribution anywhere: Check all Git/forge writes before publication, including issues, branches, descriptions, comments, commits, PRs and MRs. No robot emoji or assistant signatures.
- Squash merge PRs: Always use
gh pr merge --squash - Single-line commits preferred: Use body only when explanation is needed
- Merge per policy: Under the default, wait for the user; never queue a deferred merge — see "Merge authorization"
- Clean up after merge: Confirm
MERGEDviagh pr view --json state, thengit worktree remove <path>(neverrm -rf), thengit branch -D <branch>— see Worktrees, "Cleanup, merged-only" - Use gcms: Generate commit messages with
/core:gcmsskill
References
For detailed command references and advanced topics, see:
- commands.md — Branch management, staging, committing, viewing changes, stashing, remote operations, tags, aliases
- gitlab-mr.md — GitLab MR equivalents in full:
glabflag detail for create/view/note/merge,glab ci statusvsgh pr checksscoping,glab auth login, and the GitLab-only surfaces this skill deliberately does not model - advanced.md — Rebasing, merge strategies, conflict resolution, interactive rebase, history management, cherry-picking, bisect, submodules
- troubleshooting.md — Common issues (wrong branch, sensitive data, recover deleted branch, bad merge) and best practices
- shallow-clone-remotes.md — When
originis a file-based local clone: addgithubremote, push there, verify withgh api - build-source-staleness.md — Before submitting a build chain that clones from a local source cache:
git pullnotgit fetch. Verify viagit rev-parse HEAD, notgit rev-parse origin/<branch>
shallow-clone-remotes.md and build-source-staleness.md are one family of bugs — a file-based git remote silently absorbing an operation that should have reached (or read from) GitHub — covering the push side and the read side respectively. Read both when a git chain touches a local source cache or a shallow clone.
mise - Development Environment Management
This skill activates when working with mise for managing tool versions, environment variables, and project tasks.
What is mise?
Current stable: v2026.3.15
mise is a polyglot runtime manager and development environment tool that combines:
- Tool version management - Install and manage multiple versions of dev tools
- Environment configuration - Set environment variables per project
- Task automation - Define and run project tasks
- Cross-platform - Works on macOS, Linux, and Windows
Install with curl https://mise.run | sh (or brew install mise), then activate in the shell: eval "$(mise activate zsh)". Full install matrix, shims, IDE and CI/CD integration: references/setup-and-troubleshooting.md.
Tool Backends
mise uses different backends (package managers) to install tools:
- asdf - Traditional asdf plugins (default for many tools)
- github - GitHub release-asset installer (replaces deprecated ubi backend)
- cargo - Rust packages (requires Rust installed)
- npm - Node.js packages (requires Node installed)
- go - Go packages (requires Go installed)
- aqua - Package manager
- pipx - Python packages (requires Python installed)
- gem - Ruby packages (requires Ruby installed)
- gitlab - Direct from GitLab repositories
- http - Direct HTTP downloads
Prefer registry short names (ripgrep) over backend-prefixed forms (cargo:ripgrep) when the tool is in the mise registry (mise registry | grep <tool-name>). Fall back to an explicit backend prefix when the registry has no entry.
Per-backend detail — github backend options (exe, asset_pattern, extract_all, rename_exe), multi-arch platform keys, cargo prerequisites and git installs, upgrades and aliases: references/backends.md.
Verify Before Pinning — ls-remote
mise ls-remote <backend>:<target> returns all available versions for any backend. Run this BEFORE pinning a version in mise.toml to confirm the backend can actually see the tool:
mise ls-remote node # registry tool
mise ls-remote github:sharkdp/fd # explicit backend
mise registry | grep <tool-name> # search the registry
Failure mode — the tool lives in a different repo than you expect. Sometimes the CLI binary is released from a different repository than the documentation or project homepage:
$ mise ls-remote github:juxt/allium | head -5
(no output) # wrong repo — homepage, no releases
$ mise ls-remote github:juxt/allium-tools | head -5
0.1.0 # correct repo for the CLI releases
If ls-remote returns nothing, check whether the project publishes releases to a separate repository (e.g., a -tools, -cli, or -releases repo). Don't pin a version you haven't verified ls-remote can see. Per-backend ls-remote output examples: references/backends.md.
Installing and Using Tools
Key difference: mise install only installs tools; mise use installs AND adds the tool to your configuration file. mise use is the primary way to add tools to projects.
mise install # install everything in .mise.toml / .tool-versions
mise install node@20.10.0 # install without touching config
mise use node@20 # fuzzy version — saves "20" (default)
mise use --pin node@20.10.0 # exact version — saves "20.10.0"
mise use node@latest # saves "latest"
mise use cargo:ripgrep@latest # explicit backend
mise use --remove node # remove tool from config
mise use --force node@20 # force reinstall
mise use --dry-run node@20 # preview changes
Version pinning: fuzzy (node@20) auto-updates within the major version; --pin locks the exact version; latest always updates. Best Practice: Use fuzzy versions for flexibility, mise.lock for reproducibility.
Configuration file selection
mise use writes to configuration files in this priority order:
--globalflag:~/.config/mise/config.toml--path <file>flag: Specified file path--env <env>flag:.mise.<env>.toml- Default:
mise.tomlin current directory
.mise.toml Schema
[tools]
node = "20.10.0"
python = "3.12"
terraform = "latest"
# Backends - use quotes for namespaced tools
"cargo:ripgrep" = "latest" # Requires rust installed
"github:sharkdp/fd" = "latest" # GitHub releases
"npm:typescript" = "latest" # Requires node installed
"github:nushell/nushell" = "latest" # Nushell (structured shell)
# Version from file
node = { version = "lts", resolve = "latest-lts" }
mise reads configuration from multiple locations (in order):
.mise.toml- Project local config.mise/config.toml- Project local config (alternative)~/.config/mise/config.toml- Global config- Environment variables -
MISE_*
Environment Variables
[env]
DATABASE_URL = "postgresql://localhost/myapp"
NODE_ENV = "development"
# Go templates — {{ config_root }} is the directory containing mise.toml
APP_ROOT = "{{ config_root }}"
PATH = ["{{ config_root }}/bin", "$PATH"]
# File-based env vars
_.file = ".env"
_.path = ["/custom/bin"]
Secrets via mise set:
mise set SECRET_KEY sops://path/to/secret # sops
mise set API_TOKEN age://path/to/secret # age
mise set BUILD_ID "$(git rev-parse HEAD)" # from command
Tasks
[tasks.build]
description = "Build the project"
run = "npm run build"
sources = ["src/**/*.ts"] # Only run if sources changed
outputs = ["dist/**/*"] # Check outputs for changes
dir = "frontend" # Run in specific directory
env = { NODE_ENV = "production" }
[tasks.test]
description = "Run tests"
run = "npm test"
[tasks.lint]
description = "Run linter"
run = "npm run lint"
depends = ["build"] # depends run first, in order
[tasks.ci]
description = "Run CI pipeline"
depends = ["lint", "test"]
[tasks.watch]
run = "npm run watch"
raw = true # Don't wrap in shell
mise run build # run a task
mise build # short form
mise run lint test # run multiple tasks
mise tasks # list available tasks
mise run script -- arg1 # pass arguments
Define a ci task that aggregates the project's format, lint, and test checks — mise run ci is the local quality gate other skills and agents in this workspace invoke before commit. File-based tasks (.mise/tasks/) and complete Node/Python/monorepo/multi-tool project setups: references/tasks-and-workflows.md.
Sandboxing
mise sandboxing restricts filesystem, network, and env access for mise exec / mise run using OS-level primitives (Landlock/seccomp on Linux, Seatbelt on macOS; Windows unsupported). Gotcha: mise settings experimental=true is required first — without it, deny/allow flags are silently no-ops.
mise x --deny-all --allow-read=. --allow-write=./dist --allow-net=registry.npmjs.org -- npm install
Full flag reference, platform support matrix, task-level config, and limitations: references/sandboxing.md. Runnable examples: templates/sandboxing.md.
Lock Files
mise lock # generate .mise.lock
mise install --locked # use locked versions
[settings]
lockfile = true # Auto-generate lock file
Templates
The templates/ directory contains reusable configuration snippets for common mise patterns:
templates/multi-arch.md— platform-specific asset patterns for GitHub-release tools (pattern detail inreferences/backends.md)templates/sandboxing.md— runnable sandbox invocations
Best Practices
- Use .mise.toml for projects: Better than .tool-versions (more features)
- Pin versions in projects: Ensure consistency across team
- Use tasks for common operations: Document and standardize workflows
- Lock files in production: Use
mise lockfor reproducibility - Global tools for dev: Set global defaults, override per project
- Environment per project: Keep secrets and config in .mise.toml
- Commit .mise.toml: Share config with team
- Don't commit .mise.lock: Let mise generate per environment
- Zero setup for team: Clone and
mise installto get started
References
references/backends.md— per-backend ls-remote examples, github backend options, multi-arch asset patterns, cargo backend, upgrades and aliasesreferences/tasks-and-workflows.md— file-based tasks and complete project workflow examples (Node.js, Python, monorepo, multi-tool)references/sandboxing.md— sandbox flag reference, platform support matrix, task-level config, limitationsreferences/setup-and-troubleshooting.md— installation matrix, shims, IDE integration, CI/CD integration (GitHub Actions, GitLab CI), troubleshooting,.tool-versionsmigrationreferences/transitive-runtime-deps.md—mise execdoes NOT auto-install transitive deps (Elixir-needs-Erlang failure mode); prefer portable secret-generation commands (openssl,python3,/dev/urandom)
Nushell - Modern Structured Shell
This skill activates when working with Nushell (Nu), writing Nu scripts, working with structured data pipelines, or configuring the Nu environment.
What is Nushell?
Current stable: 0.113.1 (pre-1.0, breaking changes possible between minor versions)
Nushell is a modern shell that:
- Treats data as structured (not just text streams)
- Works cross-platform (Windows, macOS, Linux)
- Combines shell and programming language features
- Has built-in data format support (JSON, CSV, YAML, TOML, XML, etc.)
When Nushell over bash
- Nushell for scripts: any multi-line script, structured-data pipeline, or cross-platform automation. Bash one-liners with
grep/awk/sedchains lose type information Nu keeps. jqfor JSON one-liner parsing in bash contexts; Nu'sopen/from json/where/getreplacejqinside Nu scripts.- Bash remains for shell-only operations with no Nu alternative, and for embedded commands inside CI runners that only speak POSIX shell.
Installation
# Via mise (recommended for project-level management)
# mise.toml: [tools] → "github:nushell/nushell" = "latest"
mise install github:nushell/nushell
# macOS: brew install nushell | Linux: cargo install nu | Windows: winget install nushell
Core model: everything is structured data
Commands output tables/records, not text. Pipelines transform structured data stage by stage:
# Bash greps text; Nu filters columns
ls | where name =~ ".txt"
ls | where size > 1kb and type == file | sort-by modified | reverse
# Read/write structured formats directly
open data.json | get users | where age > 25 | select name email
open data.csv | to json | save data.json
'{"name": "Alice"}' | from json
Syntax essentials
# Variables: let (immutable), mut (mutable), $env for environment
let threshold = 1mb
mut counter = 0
$counter = $counter + 1
$env.MY_VAR = "value"
# String interpolation: $"..." with parens for expressions
let name = "Alice"
print $"Hello, ($name)! Result: (5 * 2)"
# Collections: lists, records, tables
let users = [{name: "Alice", age: 30} {name: "Bob", age: 25}]
$users | where age > 25 | get name
# Control flow: if/else and match are expressions
let status = if $is_active { "active" } else { "inactive" }
match $age {
0..17 => "minor"
_ => "adult"
}
# Iteration: each (functional), for (imperative)
1..5 | each { |i| $i * 2 }
for file in (ls | where type == file) { print $file.name }
# Custom commands: typed params, flags with defaults
def greet [
name: string
--loud (-l) # Flag
--repeat (-r): int = 1 # Named parameter with default
] {
1..$repeat | each { print $"Hello, ($name)!" }
}
# Error handling
try { open missing.txt } catch { |err| print $"Error: ($err)" }
let value = ($env.MY_VAR? | default "fallback")
# HTTP built in
http get https://api.example.com/users
http post https://api.example.com/users {name: "Alice"}
Scripts and def main
nu script.nu auto-invokes def main when the script defines one. main's parameters become the script's CLI arguments and flags:
#!/usr/bin/env nu
def main [
input: path
--output (-o): path = "output.txt"
--verbose (-v)
] {
if $verbose { print $"Processing ($input)..." }
open $input | save $output
}
Run as nu script.nu data.csv --verbose or chmod +x script.nu && ./script.nu data.csv.
Critical gotchas
These have each caused real script failures. Check every Nu script against them.
No 2>&1 — use out+err>
Bash-style file-descriptor redirection does not exist in Nushell. 2>&1 is not parsed as redirection. Use out+err> file.log (short form o+e>) to capture both streams:
# WRONG — nushell does not speak 2>&1
^some-command > out.log 2>&1
# CORRECT
^some-command out+err> out.log
Audit existing scripts with grep -rn '2>&1' **/*.nu.
Bare main call after def main runs main TWICE
Because nu script.nu auto-invokes def main, a script that defines def main AND has a bare main line at the end runs main twice, silently doubling every side effect (HTTP posts, file writes, subprocess spawns, workflow submissions).
# WRONG — fires main twice
def main [] {
http post $url $body
print "done"
}
main # ← Nushell already invoked this; the explicit call duplicates work
# CORRECT — Nushell handles the invocation
def main [] {
http post $url $body
print "done"
}
# (no bare `main` line — script ends with the def)
Why it matters: silent duplication is hard to debug. The classic symptom is "this single-step workflow somehow fired two HTTP requests." Confirmed via instrumented print counters: the file parses once but the main entry counter increments twice.
Detection: grep -nE '^main(\s|$)' script.nu flags any bare invocations at column 0. Add this as a CI lint rule for repos that contain multiple Nushell scripts — chained workflows multiply the impact (each chain hop doubles the next).
External commands need the ^ prefix
# Wrong - Nu tries to parse as Nu command
ls -la
# Right - Explicitly call external command
^ls -la
# Capture output
let output = (^git status)
Parens in string interpolation parse as expressions
$"hello (world)" tries to evaluate world as an expression. Escape the parens or lift the value into a variable first.
Read-and-rewrite-same-path truncates the file
open --raw returns a stream. If a save back to that same path is still in the same pipeline, save can open the path for writing while the stream is still being read, and the file is truncated. This zeroed .claude-plugin/plugin.json from 142 lines to 0 bytes during a real batch edit.
Whether it truncates depends on whether the pipeline streams or collects — lines | each | str join streams and destroys the file every time; a collecting stage such as str replace happens to survive. Do not rely on that distinction: treat any read-and-save of one path in a single pipeline as unsafe.
# WRONG — save races the still-reading open on the same path
open --raw $f | lines | each {|l| ... } | str join "\n" | save --force --raw $f
# CORRECT — force the read to finish before any save touches the path
let content = (open --raw $f | lines | each {|l| ... })
# append "\n" only if the target had one — see the trailing-newline bullet below
($content | str join "\n") + "\n" | save --force --raw $f
Diagnostic tell: a partial blast radius. In the incident, ten sibling files rewritten with let lines = (open --raw $path | lines) all survived; only the one file piped straight into save on its own path died. Same logic, one casualty — that split is the signature of this bug, not a logic error.
Two more failures ride along with it:
linesdrops the trailing newline andstr joindoes not restore it, so a rewrite silently strips the final byte — check the target's existing convention withxxd <file> | tail -1first (not every file has one) and append+ "\n"only when it matches.- Do not verify a rewrite with
tail -c1. Verified: on a zero-byte file it returns empty, same as a healthy file ending in a newline —tail -c1reported the destroyed file as fine. Verify againstgit show HEAD:<path>or a line count instead.
Detection, with two caveats that matter more than the pattern:
grep -nE 'open .*\$([A-Za-z_][A-Za-z0-9_]*).*save .*\$\1' script.nu # BSD grep
grep -nP 'open .*\$([A-Za-z_][A-Za-z0-9_]*).*save .*\$\1' script.nu # GNU grep, ugrep
The backreference is what narrows this to the same variable being read and written, and it is also why no single invocation is portable. Directly tested: -E with \1 works under BSD /usr/bin/grep, which has no -P option at all; ugrep's -E rejects \1 as an invalid escape but its -P works. GNU grep accepts -P where built with PCRE — documented, not tested here. Check which grep you actually have before trusting a clean run.
Both forms are line-based, so both miss a pipeline split across lines — confirmed against a fixture. There is no reliable one-line detection for that case; read any pipeline containing both open --raw and save by eye when they are more than a line or two apart.
Key principles
- Structured data first: think in tables and records, not text; leverage
where/select/getover regex - Pipeline composition: chain simple stages to build complex workflows
- Type annotations: add types to custom command parameters
- Error handling: use try-catch for operations that can fail
- Modules for reuse: organize shared commands in modules (
export def+use) - Cross-platform: same syntax works in REPL and scripts on all platforms
References
references/language-basics.md— data types, ranges, variables/env, string methods, conditionals, loops, try-catch and null handling, variable-scope and bare-word pitfallsreferences/data-pipelines.md— file/directory operations, filtering/selecting/sorting/transforming/aggregation, JSON/CSV/YAML/TOML round-trips, table queries, worked patterns (batch file processing, data transformation, HTTP, system commands)references/commands-and-modules.md— custom command definitions and parameter forms, pipeline-input commands, modules, script files anddef mainparameters, config.nu/env.nu setupreferences/bash-migration.md— side-by-side bash-to-Nu translations, redirection mappingreferences/shell-interop.md"Runex HTTP API response shape via nushell" —.dataunwrap pattern, INT-to-string coercion for IDs, terminal-status set,$env.HOME, parens-in-interpolation,sort-by -rinstability,out+err>instead of2>&1references/shell-interop.md"Bash logical-operator silent error mask" —cmd1 && cmd2 || cmd3is NOT if/else; useif/elseto propagate exit codes; detection grep for the pattern
Restraint
The best code is the code you never wrote. Write only what the task needs; cut scope, never correctness. Code ends up small because it is necessary, not golfed.
This is a standing principle, like /core:tdd and /core:twelve-factor — it governs every phase of a change, not a command you run.
The ladder
Understand the problem first. Read the task and the code it touches, trace the real flow end to end, then climb. The ladder shortens the solution, never the reading — a small diff you do not understand is a second bug, not a clean fix.
Then, before writing any code — or any documentation: an ADR, a diagram, a README — stop at the first rung that holds:
1. Does this need to exist? → no: skip it, say so in one line. (YAGNI)
2. Already in this codebase? → reuse the helper/util/pattern. (Reuse-First)
3. Stdlib does it? → use it. (Reuse-First)
4. Native platform feature? → use it. (Reuse-First)
5. Installed dependency? → use it; add none for a few lines. (Reuse-First)
6. One line? → make it one line.
7. Only then → write the minimum that works.
- Rung 1 — YAGNI. Speculative need is no need. No interface with one implementation, no factory for one product, no config for a value that never changes, no scaffolding "for later."
- Rungs 2–5 — Reuse-First. Re-implementing what already exists a few files over is the most common agent slop. Grep before you write. Prefer the platform:
<input type="date">over a picker lib, CSS over JS, a DB constraint over app code. Use an installed dependency; add a new one only when a few lines cannot cover it. - Rungs 6–7 — Minimum. One line if one line works. The minimum that works is the last rung, not the first move.
Two rungs both work → take the higher one and move on. Two stdlib options the same size → take the one that is correct on edge cases. Restraint means less code, never the flimsier algorithm.
The ladder governs documentation the same way: does this ADR or diagram need to exist, or does an existing one already cover it? Amend the existing doc instead of adding a parallel one; write the minimum that conveys the decision. An unread page or a duplicate diagram is over-production like any other. Document only what is built, not what is planned — an ADR or diagram describing unbuilt or changed behavior is the prose form of dead code.
Scope — commodity code, not strategic surface
The ladder governs incidental, commodity code: plumbing a task needs in passing — parsing, HTTP, retries, glue. It does NOT relitigate product surface a project has deliberately chosen to own. Building a first-party tool, framework, runtime, or library is a strategic decision; "an off-the-shelf X already does this" is not a rung-1 or rung-5 objection to that surface. Reuse-First applies within what you own — don't reinvent your own helpers — never against the decision to own it.
Never lazy about
These sit outside the ladder. Never simplify them away:
- Input validation at trust boundaries, error handling that prevents data loss, security, accessibility. See
/core:security. - Honest claims about what the code does — tool-verified, never asserted for brevity. See
/core:anti-fabrication. - Understanding the problem (above).
- Calibration that real hardware needs — a clock drifts, a sensor reads off. Leave the knob, not just less code.
- Anything explicitly requested. The user insists on the full version → build it, no re-arguing.
Restraint without its check is unfinished. Non-trivial logic (a branch, loop, parser, money/security path) leaves ONE runnable check behind — the smallest thing that fails if the logic breaks. Drive that through /core:tdd. YAGNI applies to tests; non-trivial logic still leaves one runnable check. — this sentence is shared verbatim with /core:tdd as the reconciliation between tdd's thoroughness and restraint's minimalism.
The restraint: comment
Mark a deliberate simplification with a restraint: comment so a reader sees intent, not ignorance. A shortcut with a known ceiling names the ceiling and the upgrade path:
# restraint: global lock — switch to per-account locks if throughput matters
These inline markers are a grep, not a stored ledger — find outstanding shortcuts on demand. Real, prioritized technical debt still belongs in the issue tracker; a restraint: marker is a breadcrumb, not a backlog item.
Bug fix = root cause, not symptom
A report names a symptom. Before editing, grep every caller of the function you touch and fix the shared function once. One guard there is a smaller diff than one per caller — and patching only the path the ticket names leaves a sibling caller still broken. The lazy fix IS the root-cause fix.
Anti-prose
If the explanation is longer than the code, delete the explanation. Every paragraph defending a simplification is complexity smuggled back in as prose. Boring over clever — clever is what someone decodes at 3am. See /extras-claude-code:claude-output-styles's assets/worker-report-format.md for a reusable contract that enforces terseness in agent output.
In the agent loop
This principle binds at every tier — if restraint is not in the plan, the work has already failed. See references/agent-loop-phases.md for what each phase owes the ladder: planning, test planning, test authoring, implementation, review.
References
references/agent-loop-phases.md— what each agent-loop phase owes the ladderreferences/attribution.md— source and licensescripts/restraint-audit.nu— grepsrestraint:markers repo-wide; paired with the/core:restraint-auditcommand
Security: Secret Detection
This skill activates when performing secret detection, credential scanning, or implementing security checks for leaked sensitive data in code repositories.
Pre-Commit Hook (Automatic)
When this skill is loaded, a pre-commit hook automatically scans staged files for secrets before every git commit command, providing defense-in-depth by catching secrets before they enter git history. Only staged files are scanned (not the entire working tree); .gitleaks-baseline.json and .gitleaks.toml, when present, are honored for known false positives and custom rules.
If the hook detects secrets, the commit is blocked (exit code 2) with guidance to remove the secret, switch to an environment variable, or add it to the baseline if it's a false positive.
The hook requires a container runtime (Apple Container, Docker, or Colima via mise) to run gitleaks. If no runtime is available, the hook logs a warning and allows the commit — it fails open, not closed.
See references/gitleaks-usage.md for the hook's exact flow diagram and block-message text.
Agent Secret Safety
When agents interact with secrets (1Password, environment variables, keychains):
- Never print secret values in output, logs, or reports
- Confirm existence only:
test -n "$VAR" && echo "set" || echo "empty" - Never use
--revealin agent scripts — use it only in launcher scripts that don't capture output - If a secret value is accidentally exposed in conversation context, the user must rotate it immediately
This applies to all agent tiers. A leaked secret in agent output forces credential rotation.
Commands that leak environments
"Never print secret values" is not enough on its own — some commands leak the full environment as a side effect of an unrelated-looking diagnostic. The command reads as "get a bit more context on this process," not "dump every credential this process can see," so the guidance above does not visibly apply and the leak happens anyway.
Incident (2026-08-04): an agent confirming one environment variable on a running process followed up with ps -E -p <pid> as a diagnostic. On macOS, -E appends the process's entire environment after the command line, undifferentiated from the command-line arguments — four live credentials landed in the transcript in plaintext, requiring rotation of all four. A prior incident (2026-07-30) came from printenv | grep -i database on a pod — same shape, different command. A third incident, the same day as the first, happened while drafting the guidance below: an agent ran the exact command this section warns about, to confirm it leaks, against a session holding live credentials — and leaked them.
Do not run these commands to check whether they leak. This is the operative instruction, ahead of the table below. ps -E/-e-shaped flags, COMMAND_MODE=legacy ps -e, /proc/<pid>/environ, and unfiltered printenv/env all read and emit the target's real environment the instant they execute — there is no dry-run, no filtered form, no "just to see." Verifying the hazard reproduces the hazard. An agent session routinely holds live service-account tokens and API keys in its own environment, so "let me confirm this actually leaks" against a real process is itself the leak, not a safe way to check one. Take the mechanism below as established fact — do not re-derive it by running anything:
- Observed on macOS 26.6, against a mise-installed (non-platform) binary:
ps -Eoutput grew from an 11-word baseline (command line only) to 105 words once the process's environment was appended, with a marker variable present only in the appended portion. - Observed on macOS 26.6:
COMMAND_MODE=legacy ps -etargeted at one process returned 2 lines — a header and that process with its environment appended. The same flag withCOMMAND_MODEunset returned 961 lines, one per running process on the system, confirming the default (unix2003) reading of-eis "select all processes" (matching Linux), not "append environment."man psLEGACY DESCRIPTION documents the flip: "-eDisplay the environment as well. Same as-E." - Apple's own platform binaries (
/bin/sleep,/bin/cat, and similar) ship codesigned with the hardened runtime and are shielded from the environment-append behavior — a check against one of those looks clean and is not evidence the flag is safe. That shielding does not extend to anything an agent actually spawns: mise-installed binaries, language runtimes (nu,node,python,elixir), and project-local tooling all leak reliably. This is background for why the hazard is broader than "system processes," not an invitation to compare the two yourself.
Banned outright — never run any of these, on any platform, filtered or not:
| Command | Platform | Why it leaks |
|---|---|---|
ps -E | macOS/BSD | Documented flag: "Display the environment as well" (man ps). Appends the target process's full environment to its command-line output. |
ps eww (or any BSD keyletter set with e appended, e.g. auxe) | macOS/BSD | The no-dash keyletter form of the same append-environment behavior as -E. |
ps e (bare e appended to a keyletter set, e.g. psaux → auxe, or lwwe) | Linux (GNU ps / procps) | Documented: "Show the environment after the command." GNU ps has no -E flag — -e there means "select all processes" (same as -A), not environment; do not confuse the two. |
COMMAND_MODE=legacy ps -e | macOS/BSD | man ps LEGACY DESCRIPTION: "-e Display the environment as well. Same as -E." Under the default unix2003 COMMAND_MODE (or with the variable unset), macOS -e means "select all processes," matching Linux — no environment appended. Setting COMMAND_MODE=legacy flips -e to behave exactly like -E. |
cat /proc/<pid>/environ or any read of it | Linux | "This file contains the initial environment that was set when the currently executing program was started" (proc_pid_environ(5)), NUL-separated. Readable for any process you can ptrace — typically your own processes or, as root, any process. |
Unfiltered printenv / env (no args) | All | Prints the calling shell's entire environment, not one variable. |
No safe invocation. These commands are banned outright above — presenting a "correct" piped form here would imply a sanctioned way to run a banned command, and there isn't one. Each command reads the complete environment into its own process memory the instant it runs, independent of any pipe; that much is unavoidable, but it is not itself a transcript exposure — in ps … | grep, the full output goes into a pipe that grep consumes, and only what grep matches reaches stdout and the transcript. What makes a piped form dangerous instead of protective is that the protection is entirely conditional on the filter being exactly right: one mistyped variable name, one over-broad pattern, a stray -v, a missing anchor, and the full dump reaches the transcript with no way to take it back — a single-mistake failure mode on a command that cannot be run twice safely to check. The incident history backs this up rather than undercuts it: the 2026-07-30 incident ran a filtered form — printenv | grep -i database — and still leaked, because a case-insensitive substring match is exactly the over-broad pattern described above. A bare, unfiltered command is still the natural first move when you don't yet know the variable name you're hunting for, and that instinct is real — but the record includes both shapes, filtered and unfiltered, which is itself the point: neither shape is safe. Do not run ps eww -p <pid> | tr ' ' '\n' | grep '^VARNAME=' or any variant expecting the pipe to make it safe.
If you need to know something about your OWN process's environment, use test -n "$VAR" (Agent Secret Safety, above) — that reads your own shell state directly, with no diagnostic exec'd against a target process. If you need a variable belonging to a DIFFERENT process, there is no safe way to read it via ps, /proc, or printenv: use that process's own introspection surface (a documented health/info/config endpoint) or ask the operator, rather than enumerating its environment.
Inspection discipline.
- Never inspect an environment "for context" or "to see what's there." Name the specific variable you need before running anything.
- Never place a secret on a command line (
env VAR=value cmd,curl -H "Authorization: Bearer $TOKEN"with$TOKENinterpolated visibly) — command lines land in shell history and process listings same as the commands above. - Treat
-e/-E-shaped flags on any unfamiliar tool as suspect until you've checked what they do; the macOS/Linux split above (-Evs bareevs-e-means-"all") is exactly the kind of one-letter, cross-platform inconsistency that causes an agent to reach for the wrong flag under the impression it is the safe one.
Recovery. If an environment dump reaches the transcript despite the above, self-report the exposure immediately and ask the operator to rotate every credential that appeared — do not wait to be asked, and do not attempt to redact it after the fact (the value is already in context/logs).
When to Use security-review Instead
Use the security-review skill for:
- STRIDE threat modeling
- Security architecture reviews
- Vulnerability assessments
- Security documentation and reports
- Risk prioritization
- Attack surface analysis
| Task | Use security | Use security-review |
|---|---|---|
| Scan for secrets in code | ✓ | |
| Detect leaked API keys | ✓ | |
| Pre-commit secret scanning | ✓ | |
| STRIDE threat modeling | ✓ | |
| Security architecture review | ✓ | |
| Vulnerability assessment | ✓ | |
| Security report documentation | ✓ | |
| Risk prioritization | ✓ |
Key Principles
- Defense in depth: Run checks at multiple stages (local, CI, scheduled)
- Fail fast: Block PRs with detected secrets
- Zero tolerance: Treat all secret exposures as security incidents
- Continuous monitoring: Schedule regular scans of entire history
- Clear ownership: Define who handles secret remediation
- No restraint trade-offs: restraint never trades security or validation for brevity (
/core:restraint"Never lazy about") - Evidence-based claims: every behavior claim in the references below (scan scope, hook bypasses, runtime detection) is tagged with how it was checked — re-verify against the current gitleaks/hook version before trusting an old claim; see
core:anti-fabrication
References
- references/gitleaks-usage.md — read this when invoking gitleaks directly: manual scan commands,
.gitleaks.tomlconfig, exit codes, the bundledgitleaks.nu/gitleaks.shscripts, the shell-function shadowing trap, baseline management, and the full "committed history only" scan-scope caveat with known hook bypasses - references/container-runtimes.md — read this when no native gitleaks binary is available and you need the Apple Container/Docker/Colima fallback, or when copying the Mise Tasks Template into a new project
- references/ci-and-prevention.md — read this when wiring gitleaks into
pre-commitor a CI/CD pipeline (GitHub Actions, GitLab CI) outside this skill's own PreToolUse hook, or reviewing the shift-left prevention checklist
Test-Driven Development
A discipline for growing software guided by tests, one small step at a time.
The TDD Cycle
Five Steps
- Write a test list — brainstorm the tests you think you'll need
- Write one failing test — pick the next test from the list
- Make it pass — write the simplest code that makes the test green
- Refactor — remove duplication and improve design, keeping tests green
- Repeat — pick the next test, update the list as you learn
Red-Green-Refactor
The micro-cycle is a three-state machine:
┌──────────────────────────────────────┐
│ │
▼ │
[RED] ──── write minimal code ────► [GREEN] ──── refactor ────► [GREEN]
▲ │
│ │
└──────────── write next failing test ◄──────────────────────────┘
RED: Write a test that fails. Confirm it fails for the right reason — the missing behavior, not a syntax error or wrong import.
GREEN: Make the test pass with the simplest change possible. "Sinful" code is fine — hardcoded values, copy-paste, whatever gets green fastest.
REFACTOR: Clean up while all tests stay green. Remove duplication between test and production code. Improve names. Extract methods. This is where design emerges.
Rules:
- Never write production code without a failing test
- Never write more test code than needed to fail
- Never write more production code than needed to pass
The Three Laws
Uncle Bob's formalization of Beck's constraints:
- You shall not write production code unless you have a failing test
- You shall not write more of a test than is sufficient to fail (including compile failures)
- You shall not write more production code than is sufficient to pass the currently failing test
These laws enforce the micro-cycle. They keep steps small and feedback immediate.
Test List
A test list is a brainstorm of all the tests you think you'll need, written before you start coding. It is your roadmap.
How to Create One
- Think about the behavior you need to implement
- List the specific cases: happy path, edge cases, error cases
- Order them from simplest to most complex
- Start with a degenerate case if possible
Example: Stack
Test List:
- [ ] new stack is empty
- [ ] push one item, stack is not empty
- [ ] push one item then pop, returns that item
- [ ] push two items then pop, returns second item
- [ ] pop empty stack raises error
- [ ] push and pop multiple items (LIFO order)
- [ ] peek returns top without removing
When to Update
The test list is alive. As you work:
- Cross off completed tests
- Add new tests you discover along the way
- Remove tests that turn out to be redundant
- Reorder if a different sequence makes more sense
A test list can seed beads tasks — create one task per test with skill:tdd labels for tracking.
Strategies for Getting to Green
Three strategies for making a failing test pass, in order of safety:
Fake It
Return a hardcoded value that makes the test pass. Then write the next test to force generalization.
# Test: add(1, 2) returns 3
# Fake It:
def add(a, b):
return 3
# Next test forces real implementation:
# Test: add(3, 4) returns 7
When to use: When you're unsure how to implement the real thing. When the step to real code feels too big. When you want maximum safety.
Obvious Implementation
Type the real implementation directly, because it's clear what the code should be.
# Test: add(1, 2) returns 3
# Obvious Implementation:
def add(a, b):
return a + b
When to use: When the implementation is trivially obvious. When you're confident. If you get an unexpected failure, fall back to Fake It.
Triangulation
Use two or more test cases to force removal of hardcoded values and drive toward the general solution.
# Test 1: add(1, 2) returns 3
def add(a, b):
return 3 # fake it
# Test 2: add(3, 4) returns 7
def add(a, b):
return a + b # now forced to generalize
When to use: When you're uncertain about the abstraction. When two examples make the pattern clearer than one. When you need confidence before generalizing.
Test Sequencing
"As tests get more specific, code gets more generic." — Robert C. Martin
Start with degenerate cases and progress toward forcing generalization:
- Degenerate/boundary cases — null, empty, zero, one element
- Simple happy path — the most basic successful case
- Variations — different inputs that exercise the same path
- Edge cases — boundaries, maximums, special values
- Error cases — invalid input, missing data, failure conditions
Each new test should require a small, incremental change to the production code. If a test requires a large change, you skipped a step — find a simpler test to write first.
Sequencing Example: FizzBuzz
Test List (ordered):
1. returns "1" for 1 → hardcode "1"
2. returns "2" for 2 → return string of number
3. returns "Fizz" for 3 → add modulo-3 check
4. returns "Fizz" for 6 → confirms generalization
5. returns "Buzz" for 5 → add modulo-5 check
6. returns "Buzz" for 10 → confirms generalization
7. returns "FizzBuzz" for 15 → add modulo-15 check
8. returns "FizzBuzz" for 30 → confirms generalization
Double-Loop TDD
Freeman & Pryce's model from Growing Object-Oriented Software, Guided by Tests:
Outer Loop (Acceptance Test)
┌──────────────────────────────────────────────────┐
│ │
│ Write failing Acceptance test passes │
│ acceptance test ──────────────────► Done │
│ │ ▲ │
│ ▼ │ │
│ Inner Loop (Unit Tests) │ │
│ ┌────────────────────┐ │ │
│ │ RED → GREEN → │ │ │
│ │ REFACTOR → repeat │─────┘ │
│ └────────────────────┘ │
│ │
└──────────────────────────────────────────────────┘
Outer loop: Write a failing end-to-end acceptance test that describes the feature from the user's perspective. This test stays red while you build the internals.
Inner loop: Use the standard Red-Green-Refactor cycle to implement the components needed to make the acceptance test pass.
Walking Skeleton
Start with the thinnest possible slice that exercises the full architecture:
- Write a failing acceptance test for the simplest end-to-end scenario
- Build just enough of each layer to make it pass — UI, service, persistence
- Deploy the skeleton to a production-like environment
- Every subsequent feature builds on this proven foundation
The walking skeleton proves your architecture works before you invest in features. It's the first acceptance test in the outer loop.
Outside-In Development
Start at the system boundary and work inward, discovering collaborators through tests.
The Process
- Start at the boundary — write a test for the entry point (HTTP handler, CLI command, message consumer)
- Discover collaborators — when the boundary object needs help, define an interface for the collaborator
- Test the collaborator — drop down one level and TDD the collaborator
- Repeat inward — each layer discovers the next through its tests
- Integrate — wire real implementations together; the acceptance test goes green
Tell, Don't Ask
Prefer commands over queries. Tell objects what to do rather than asking for data and acting on it:
# Ask (fragile — coupled to internal structure):
if order.status == "paid" and order.items_in_stock():
warehouse.ship(order.items)
# Tell (robust — delegates to the object that knows):
order.fulfill(warehouse)
Ports and Adapters
Separate domain logic from infrastructure for testability:
┌─────────────────────────┐
HTTP ───►│ Adapter │
│ └► Port (interface) │
│ └► Domain Logic │
│ ┌► Port (interface) │
│ Adapter │◄─── Database
└─────────────────────────┘
- Ports: Interfaces defined by the domain (what it needs)
- Adapters: Implementations that connect to infrastructure (how it's provided)
- Tests can substitute adapters with test doubles, keeping tests fast and isolated
Listen to the Tests
When tests are hard to write, they're telling you something about your design. Difficulty in testing is a symptom of a design problem.
| Difficulty Signal | Probable Design Issue | Suggested Refactoring |
|---|---|---|
| Test needs many objects to set up | Class has too many dependencies | Extract class, introduce facade |
| Test setup is deeply nested | Object graph is too complex | Flatten hierarchy, use composition |
| Hard to name the test | Method does too many things | Extract method, single responsibility |
| Test needs to access private state | Public interface is insufficient | Improve public API, add query method |
| Many tests break for one change | High coupling between classes | Introduce interface, dependency inversion |
| Slow tests (not integration) | Hidden I/O or expensive operations | Extract port/adapter, inject dependency |
| Test requires complex mocking | Violation of Law of Demeter | Wrap and delegate, tell don't ask |
| Test duplicates production logic | Missing abstraction | Extract shared concept |
| Can't test in isolation | Static calls, global state, new | Inject dependencies, use factory |
Craftsmanship Principles
From the Software Craftsmanship Manifesto, applied to TDD:
- Well-crafted software — TDD produces code that works, is clean, and communicates intent
- Steadily adding value — each green test is a verified increment of working software
- A community of professionals — TDD is a shared discipline, not a personal preference
- Productive partnerships — tests document behavior for the team; they're a communication tool
TDD is a professional practice. Not every line of code requires it, but when you practice it, practice it with discipline. Half-hearted TDD (writing tests but skipping refactoring, or testing after the fact) delivers little of the benefit.
Language Testing Skills
TDD teaches when and why to write tests. Language-specific skills teach how to use the testing framework. Load both when practicing TDD in a specific language.
| TDD Concept | Elixir (testing) | Rust (rust) | Zig (zig) |
|---|---|---|---|
| Write a failing test | test "name" do ... end | #[test] fn name() | test "name" = || { ... } |
| Assertions | assert, assert_receive | assert!, assert_eq! | try expect(...) |
| Test isolation | async: true, sandbox | Module-level isolation | Test allocator |
| Test doubles | Mox for behaviours | Trait-based injection | Comptime interfaces |
| Property tests | StreamData | proptest, quickcheck | N/A |
| Test organization | describe blocks, tags | Module hierarchy, #[cfg(test)] | Nested test blocks |
Anti-Patterns
Test-After Development
Writing code first, tests second. You lose the design feedback loop — tests conform to the code rather than driving it. Tests become verification scripts, not design tools.
Writing Too Many Tests Before Going Green
Writing five tests at once, then trying to make them all pass. You lose the tight feedback cycle and can't triangulate. Write one test, make it pass, then write the next.
Skipping the Refactor Step
Going from green straight to the next test. Duplication accumulates. Design degrades. The codebase becomes harder to change, and TDD feels slower than it should. Refactoring is where TDD pays for itself.
Testing Implementation Details
Testing how code works rather than what it does. Brittle tests that break when you refactor internals. Test behavior through the public interface.
Gold-Plating (YAGNI)
Adding behavior not driven by a test. Adding tests for scenarios nobody asked for. If it's not on the test list and not an edge case you discovered, you ain't gonna need it.
YAGNI applies to tests; non-trivial logic still leaves one runnable check. — this sentence is shared verbatim with /core:restraint as the reconciliation between tdd's thoroughness and restraint's minimalism.
Ice Cream Cone
Many end-to-end tests, few unit tests. Invert the pyramid — most tests should be fast unit tests. End-to-end tests verify integration, not logic.
References
For deeper theory and worked examples:
references/beck-tdd.md— Kent Beck's canonical TDD: Fake It, Triangulation, test isolationreferences/goos-outside-in.md— Freeman & Pryce's GOOS: double-loop TDD, walking skeleton, outside-in designreferences/ci-discipline.md—mise run cibefore every commit; CI green = local AND remote; verbatim output as evidence; no pre-existing carve-outs; post-merge main verification; docs-first TDD; no fabricated time estimatesreferences/os-subprocess-boundary.md— OS subprocess calls are external boundaries; introduce a behaviour/interface, real adapter for dev/prod, mock for tests; do NOT gate tests onfind_executable
Key Principles
- Write the test first — always
- Keep steps small — if it feels like a leap, find a smaller step
- Red-Green-Refactor is a discipline, not a suggestion — never skip refactor
- The test list is your roadmap — update it as you learn
- Listen to the tests — difficulty testing signals design problems
- Fake It when unsure, Obvious Implementation when confident
- As tests get more specific, code gets more generic
- Walking skeleton first — prove the architecture before building features
- Outside-in discovers interfaces — let tests drive the design inward
- TDD is about design, not just verification
Technical English
Technical English is a controlled-language discipline for procedural and explanatory writing. It sets one strict register for instructions and a second, looser register for context and rationale.
Two registers
Pick the register from the artifact, not from taste.
| Artifact | Register | Why |
|---|---|---|
| Skill descriptions | Strict | Claude parses these at load; ambiguity misfires activation |
| Procedure steps | Strict | A step is an instruction, not a discussion |
| Agent definitions | Strict | Dispatch logic runs unattended; one meaning per term |
| Slash commands | Strict | Arguments and flags need exact, repeatable wording |
| Output contracts | Strict | A caller parses a worker's report by its shape |
| Error and CI-failure text | Strict | A reader hits this under time pressure |
| Bees titles and acceptance criteria | Strict | Criteria must be checkable, not interpreted |
| Commit subjects | Strict | One line, one fact, searchable history |
| ADR Decision lines | Strict | The decision is the artifact; hedging voids it |
| SKILL.md explanatory sections | Flavored | Context needs nuance and connecting prose |
references/*.md | Flavored | Depth material rewards variety and color |
| READMEs | Flavored | A README sells the project before it instructs |
| ADR Context and Consequences | Flavored | Trade-offs need qualification, not a checklist |
| PR bodies | Flavored | A reviewer wants the story, not a manual |
The strict rule set
- Give every term exactly one meaning and one part of speech, and hold that meaning across the whole document set.
- Write every instruction and every procedure step in active voice.
- Reserve passive voice for description, and only when no one knows the actor.
- Use five tenses only: imperative, simple present, simple past, simple future, infinitive.
- Put one instruction in each sentence.
- Cap procedure sentences at 20 words and description sentences at 25.
- Cap each paragraph at 6 sentences and one topic.
- Never drop an article, a subject, or a verb.
- State a warning, a caution, or a precondition before the step it governs.
- Choose the short word, the concrete noun, and the verb over its noun form.
- Cut a qualifier or an adverb that only restates its verb.
- Reread the draft once, and cut what the first pass missed.
Worked before/after pairs for eleven of the twelve, several pulled from this repo's own text: references/strict-mode-rules.md.
Word choice
Pick the plainest available word, and use it the same way every time. The pairs below recur in this repo; the plain form wins in strict-mode text.
Substitute only where the plain word carries the same meaning. A term of art stays: implement names a tier and a Behaviour relationship here, and ensure states a guarantee that confirm (a verification) does not.
| Wordy | Plain |
|---|---|
| leverage | use |
| perform | do |
| additional | more |
| functionality | feature |
| modify | change |
| currently | now |
Hedges vs directives
A directive states what to do. A hedge states an unconfirmed claim. Mixing the two inside a procedure buries the actual instruction under a guess.
- A step is a directive:
Run mise run ci.NeverYou might want to run mise run ci. - Keep a hedge only where the evidence is thin, and name the gap: "requires verification" carries more information than "may work."
/core:anti-fabricationsets the canonical rule for uncertainty markers, banned superlatives, and evidence-based claims. Follow that skill directly; this section is a pointer, not a restatement.
Warnings precede the step
State a warning, a caution, or a precondition before the step it governs, never after. A reader who executes line by line has already acted by the time a trailing warning arrives. plugins/core/skills/security/SKILL.md:45 states its warning immediately before the command table it governs — copy that placement.
Where this binds
| Context | Binds to |
|---|---|
| Main-loop conversation | The active output style — core ships Plain Technical, opt-in |
| Subagent prompts and reports | This skill plus the response contract |
| Authored artifacts (skills, ADRs, READMEs) | This skill plus review |
| CI | Vale, via mise run test:prose |
Select the shipped style with /config → Output style → Plain Technical, or set "outputStyle": "Plain Technical" in .claude/settings.local.json. It takes effect after /clear or in a new session. It is never forced on you: it does not override a style you already chose. The style ships with the core plugin and with all-skills; a plugin that vendors this skill alone does not carry it.
What CI checks and what it cannot
Vale runs as mise run test:prose, inside mise run test. It checks banned superlatives, clutter phrases, weak qualifiers, hedged directives, sentence length, and nominalizations. Rule files live in styles/Strict/ and styles/Flavored/; .vale.ini picks the register by path. See /vale:vale for the tool itself — extension points, scopes, alert levels, and how to author a rule.
A rule reports at warning while its findings burn down, then moves to error once it reaches zero. Clutter gates today; the rest report. Burn-down is claude-skills-307.
Sentence length skips code. Headings, table rows, and list items all count, because a reader parses each of them the same way.
Two things stay a review-time judgment call whatever the tooling does. Vale cannot tell whether a sentence carries exactly one instruction. It cannot tell whether a paragraph needed to exist. Both belong to review.
Anti-fabrication
This skill inherits /core:anti-fabrication in full. Every claim about a tool's behavior, a file's content, or a test's result needs tool verification before it reaches a document. Mark an unverified claim as unverified; never round a guess up to a fact. See /core:anti-fabrication for the complete rule set and its worked examples.
References
- references/strict-mode-rules.md — each of the 12 rules with a before/after pair, several drawn from real lines in this repo.
- references/flavored-prose.md — Zinsser's four principles restated for this repo, the clutter/qualifier guidance, the rewriting loop, and why strict mode gives up Humanity.
- references/repo-glossary.md — the one-term-one-meaning list for this repo's own vocabulary.
- references/attribution.md — sourcing and copyright for the material this skill draws on.
12-Factor App Methodology
Guide for building scalable, maintainable, and portable cloud-native applications following the 12-Factor App principles and modern extensions.
Anti-fabrication
This skill follows core:anti-fabrication. The 12 factors themselves are the
methodology cited in sources.md (12factor.net) — a stable, versionless reference, so
naming a factor correctly is low-risk. The risk sits in the worked examples: the
Kubernetes manifests, runtime.exs snippets, and Docker Compose configs in
references/kubernetes.md and references/factor-examples.md assert real API fields
(e.g. livenessProbe, ConfigMap keys) that do change across Kubernetes versions —
verify a manifest field against current API docs before asserting it applies, rather
than assuming an older example still matches the current API.
The 12 Factors
I. Codebase
One codebase tracked in revision control, many deploys
- Single Git repository for the application; every environment deploys from it
- Environment-specific config lives outside the code
- Use GitOps (ArgoCD, Flux) for deployment automation
Violations: multiple repositories for one application, per-environment codebases, copying code between repositories. Fix: consolidate to one repository and move the differences into environment config.
II. Dependencies
Explicitly declare and isolate dependencies
- Declare every dependency in the package manager manifest; never rely on system-wide packages
- Commit lock files for reproducible builds (
package-lock.json,mix.lock,Cargo.lock,go.sum) - Multi-stage container builds isolate build-time dependencies from the runtime image
Worked Dockerfile and per-language manifest list: references/factor-examples.md.
III. Config
Store config in the environment
All configuration comes from environment variables — anything that varies between deploys: credentials, hostnames, ports, pool sizes, backing service URLs, model names.
# Elixir - config/runtime.exs
config :my_app, MyApp.Repo,
hostname: System.get_env("DATABASE_HOST") || "localhost",
password: System.fetch_env!("DATABASE_PASSWORD"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
What makes a violation, and the smallest correct fix:
- Hardcoded value that differs (or could differ) between deploys → read it from an environment variable, with a default only when a safe dev default exists
- Hardcoded model name, API endpoint, or service hostname → environment variable; model names are config, not code
- Config file with real values committed to version control → environment variables plus a committed
.exampletemplate - Environment-specific code path (
if env == "production") → one code path driven by a config value
Litmus test from 12factor.net: the codebase could be made open source at any moment without compromising any credentials.
Kubernetes ConfigMap/Secret wiring: references/kubernetes.md.
IV. Backing Services
Treat backing services as attached resources
- Databases, queues, caches, and third-party APIs all attach via URLs in environment variables
- No distinction between local and third-party services
- Swapping a backing service is a configuration change only — never a code change
V. Build, Release, Run
Strictly separate build and run stages
- Build: convert code to executable bundle
- Release: combine build with config
- Run: execute in target environment
- Releases are immutable and uniquely identified (git SHA, semver)
- Roll back by redeploying a previous release, never by modifying one
- Build artifacts stay separate from runtime config
CI/CD pipeline example: references/factor-examples.md.
VI. Processes
Execute the app as one or more stateless processes
- Processes are stateless and share-nothing; persistent state lives in backing services
- No sticky sessions, no local filesystem for persistent data
- Violation: in-memory session or state store → move it to Redis or the database
Session-store example: references/factor-examples.md. Deployment manifest: references/kubernetes.md.
VII. Port Binding
Export services via port binding
- Bind to
0.0.0.0, neverlocalhost; take the port number from the environment - HTTP server library embedded in the app — no reliance on runtime injection (Apache, Nginx)
VIII. Concurrency
Scale out via the process model
- Scale horizontally by adding processes, not vertically by enlarging them
- Distinct process types (web, worker, scheduler) scale independently
- The OS or platform process manager owns processes — never daemonize or write PID files
IX. Disposability
Maximize robustness with fast startup and graceful shutdown
- Minimize startup time (under 10 seconds ideal) — fast startup enables rapid scaling
- Handle SIGTERM: finish in-flight requests, close connections, then exit
- Stay robust against sudden death
Graceful-shutdown example: references/factor-examples.md.
X. Dev/Prod Parity
Keep development, staging, and production as similar as possible
- Same backing service types in dev and prod (not SQLite in dev, Postgres in prod)
- Containers ensure environment consistency; infrastructure as code for reproducibility
- Same deployment process for all environments; minimize the time gap between dev and production
Docker Compose dev-environment example: references/factor-examples.md.
XI. Logs
Treat logs as event streams
- Write unbuffered to stdout/stderr; never manage or rotate log files in the app
- Use structured logging (JSON) with correlation IDs for tracing
- The platform routes logs (Fluentd, Logstash) — never send directly to an aggregation service from app code
XII. Admin Processes
Run admin/management tasks as one-off processes
- Migrations, consoles, and one-time scripts use the same codebase, config, and environment as regular processes
- Run against a release, not development code
- Use the platform scheduler for recurring tasks; ship admin code with application code
Kubernetes Job/CronJob examples: references/kubernetes.md.
Modern Extensions (Beyond 12)
Three extensions round out contemporary cloud-native practice — full detail and examples in references/modern-extensions.md:
- XIII. API First — design and document APIs (OpenAPI) before implementation; contract-first development
- XIV. Telemetry —
/metricsendpoint, distributed tracing (OpenTelemetry), health check endpoints - XV. Security — OAuth 2.0/OIDC, RBAC, secrets in environment never in code, TLS everywhere, security scanning in CI/CD
Common Patterns
Configuration Validation
Validate required configuration at startup — fail fast, naming the missing variables:
function validateConfig() {
const required = ['DATABASE_URL', 'JWT_SECRET', 'REDIS_URL'];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
// Call before starting server
validateConfig();
Health checks, graceful degradation, and the troubleshooting guide: references/operations.md.
Anti-Patterns to Avoid
❌ Environment-Specific Code Paths
// DON'T: branch on environment
if (process.env.NODE_ENV === 'production') { /* different behavior */ }
// DO: one code path, configured value
const timeout = parseInt(process.env.TIMEOUT || '5000');
❌ Local File Storage
// DON'T: write persistent data to local filesystem
fs.writeFile('/tmp/uploads/' + filename, data);
// DO: use object storage
await s3.putObject({ Bucket: process.env.S3_BUCKET, Key: filename, Body: data });
❌ In-Memory State
// DON'T: store state in memory
const sessions = new Map();
// DO: use external store
const session = await redis.get(`session:${sessionId}`);
❌ Hardcoded Dependencies
// DON'T: hardcode service locations
const db = connect('localhost:5432');
// DO: use environment variables
const db = connect(process.env.DATABASE_URL);
Best Practices Summary
- Environment variables for all configuration
- Stateless processes that can scale horizontally
- Structured logging to stdout
- Containers for development parity
- Automated CI/CD pipelines
- Health checks for orchestration
- Graceful shutdown handling
- Fast startup times (< 10s)
- Immutable releases with unique IDs
- Monitoring and telemetry via metrics and tracing
Resources
- 12factor.net: Original methodology
- Kubernetes Documentation: https://kubernetes.io/docs/
- Docker Best Practices: https://docs.docker.com/develop/dev-best-practices/
- OpenTelemetry: https://opentelemetry.io/
- Prometheus: https://prometheus.io/
Key Insights
"The twelve-factor methodology can be applied to apps written in any programming language, and which use any combination of backing services (database, queue, memory cache, etc)."
"The twelve-factor app never assumes that anything cached in memory or on disk will be available on a future request or job – with many processes of each type running, chances are high that a future request will be served by a different process." — Factor VI, Processes
Design applications from day one to be cloud-native, scalable, and maintainable.
References
references/factor-examples.md— per-factor worked code examples (Dockerfile, runtime config, session storage, graceful shutdown, Docker Compose, structured logging, CI/CD pipeline)references/kubernetes.md— Kubernetes manifests per factor (ConfigMaps, Secrets, Deployments, HPA, Jobs, probes) and Kubernetes-specific best practicesreferences/modern-extensions.md— API First, Telemetry, and Security extensions with examplesreferences/operations.md— health check endpoints, graceful degradation, troubleshooting guidereferences/infrastructure-conventions.md— NGINX upstream over community ingress; Kustomize + Helm layout; single universal secret store; IaC over manual UI; bind all interfaces in prod
Web Accessibility
Apply W3C Web Accessibility Initiative (WAI) principles when working on web interfaces to ensure usability for people with disabilities.
Anti-fabrication
This skill follows core:anti-fabrication. The claim area is the WCAG version cited and
the ARIA Authoring Practices Guide (APG) pattern attributions. Verified against W3C's
live WCAG22 quickref and the APG patterns index (claude-skills-223): the WCAG citation
was bumped from 2.1 to 2.2 (2.2 became a Recommendation 2023-10-05, and per its own text
"content that conforms to WCAG 2.2 also conforms to WCAG 2.0 and WCAG 2.1" — compatibility
runs 2.2-to-2.1, not the reverse this skill previously implied); and "skip links" was
corrected from an APG pattern to what it actually is, a WCAG bypass-blocks technique — the
APG index lists 30 named patterns and skip links is not one of them. Re-verify against
w3.org/TR/WCAG22/ before citing a WCAG version or success-criterion number this skill
doesn't cover.
Core Principles (POUR)
Web accessibility is organized around four foundational principles:
1. Perceivable
Information must be presentable to users in ways they can perceive.
Key requirements:
- Provide text alternatives for non-text content (images, icons, charts)
- Provide captions and transcripts for multimedia
- Create content that can be presented in different ways (responsive, reflow)
- Make content distinguishable (color contrast, text sizing, audio control)
Quick example:
<img src="chart.png" alt="Sales increased 40% in Q4 2024">
<button aria-label="Close dialog">
<span class="icon-close" aria-hidden="true"></span>
</button>
2. Operable
User interface components must be operable by all users.
Key requirements:
- Make all functionality keyboard accessible
- Provide sufficient time for users to complete tasks
- Avoid content that causes seizures (no rapid flashing)
- Help users navigate and find content
- Support various input modalities (touch, voice, keyboard)
Quick example:
<button>Click me</button> <!-- Already keyboard accessible -->
<!-- Custom interactive element needs keyboard support -->
<div role="button" tabindex="0"
onclick="handleClick()"
onkeydown="handleKeyDown(event)">
Custom Button
</div>
3. Understandable
Information and UI operation must be understandable.
Key requirements:
- Make text readable and understandable
- Make web pages appear and operate predictably
- Help users avoid and correct mistakes
- Provide clear labels and instructions
Quick example:
<html lang="en">
<label for="email">Email address</label>
<input type="email" id="email"
aria-describedby="email-help"
required>
<div id="email-help">We'll never share your email</div>
4. Robust
Content must work reliably across user agents and assistive technologies.
Key requirements:
- Use valid, well-formed markup
- Ensure compatibility with assistive technologies
- Use ARIA correctly for custom components
- Follow semantic HTML practices
Quick example:
<!-- Use semantic HTML first -->
<nav aria-label="Main navigation">
<ul>
<li><a href="/">Home</a></li>
</ul>
</nav>
<!-- ARIA for custom components when needed -->
<div role="dialog" aria-labelledby="title" aria-modal="true">
<h2 id="title">Dialog Title</h2>
</div>
Common Tasks
Making Forms Accessible
- Associate every label with its input (
for/idor wrapping<label>) - Identify errors in text and link the message to the failing control
- Indicate required fields in the label, not by color alone
- Pair validation with specific correction guidance
Implementing ARIA
- Use semantic HTML first; add ARIA only when no native element fits
- Keep ARIA states (
aria-expanded,aria-selected) in sync with component state - Announce dynamic content with live regions (
aria-live,role="status") - Follow the ARIA Authoring Practices patterns (linked under Resources) for tabs, accordions, modals, and dropdown menus. Skip links are a WCAG technique (a "skip to main content" link as the first focusable element), not an ARIA APG design pattern — the APG's pattern index has no skip-link entry
Testing for Accessibility
- Navigate the full interface with keyboard only (Tab, Shift+Tab, Enter, Space, arrows)
- Test with a screen reader (VoiceOver, NVDA, or JAWS)
- Run automated checkers (axe, Lighthouse, WAVE) as a first pass, not a substitute for manual testing
- Check color contrast against the 4.5:1 text and 3:1 UI-component minimums
Quick Reference Checklist
Every page should have:
- Valid HTML structure
- Unique, descriptive page title
- Proper heading hierarchy (h1, h2, h3...)
- Language attribute on
<html> - Sufficient color contrast (4.5:1 minimum)
- Keyboard accessibility for all interactive elements
- Visible focus indicators
- Text alternatives for images
- Form labels associated with inputs
- Semantic landmark regions
For interactive components:
- Keyboard accessible (Tab, Enter, Space, Arrow keys)
- Proper ARIA roles, states, and properties
- Focus management (modals, dynamic content)
- Descriptive labels and instructions
- Error messages linked to form controls
Key Principles
- Semantic HTML first: Use native HTML elements before adding ARIA
- Keyboard accessibility is fundamental: If it works with mouse, it must work with keyboard
- Test with actual users: Include people with disabilities in testing
- Color is not enough: Never use color alone to convey information
- Provide alternatives: Text for images, captions for video, transcripts for audio
- Make it predictable: Consistent navigation and behavior across pages
- Help users recover: Clear error messages with suggestions for correction
Resources
- WCAG 2.2 Guidelines: https://www.w3.org/WAI/WCAG22/quickref/ (current W3C Recommendation since 2023-10-05; backward-compatible — content conforming to 2.2 also conforms to 2.1 and 2.0)
- ARIA Authoring Practices: https://www.w3.org/WAI/ARIA/apg/
- WebAIM: https://webaim.org/
- MDN Accessibility: https://developer.mozilla.org/en-US/docs/Web/Accessibility
Material Design 3 (Material You)
Apply Google's Material Design 3 principles when designing and developing user interfaces with emphasis on personalization, accessibility, and cross-platform consistency.
Anti-fabrication
This skill follows core:anti-fabrication. The claim area is the tonal-palette, type-
scale, and layout-breakpoint numbers, which come from a living spec rather than a
versioned release. Verified against m3.material.io plus the first-party
material-color-utilities source (claude-skills-223), three corrections: tonal palettes
have 13 tones (0,10,20...90,95,99,100 per commonTones), not "50-99 tones per color";
the type scale is 5 categories x 3 sizes = 15 styles total, not "5 display sizes and 9
text sizes" (the sp values 57/32/16/11 were already correct); and MD3 now defines 5
window-size classes, not 3 — Expanded is capped at 1199dp, with Large and Extra-large
added above it. Re-verify against m3.material.io before asserting a token count or
breakpoint this skill doesn't cover — Google updates this spec continuously, with no
versioned release to pin against.
What is Material Design 3?
Material Design 3 (Material You) represents Google's latest design system with:
- Personalization: Dynamic color extraction from user preferences
- Expressiveness: Softer, rounded components with visual hierarchy
- Adaptability: Responsive across devices and platforms
- Accessibility: Built-in inclusive design features
Key Differences from Material Design 2
| Aspect | MD2 | MD3 |
|---|---|---|
| Colors | Fixed brand palettes | Dynamic, user-generated schemes |
| Customization | Limited theming | Highly personalized |
| Components | Flat, rigid shapes | Rounded, expressive |
| Accessibility | Basic support | Priority built-in |
Core Foundations
1. Dynamic Color System
Material Design 3 uses HCT (Hue, Chroma, Tone) color space for perceptually accurate color generation.
Key concepts:
- Color roles (primary, secondary, tertiary, error, neutral)
- Tonal palettes (13 tones per color: 0, 10, 20...90, 95, 99, 100 — per material-color-utilities'
commonTones) - Automatic light/dark theme generation
- User-driven personalization from wallpaper/system
2. Typography
Type scale with 5 categories (display, headline, title, body, label), each with 3 sizes (large, medium, small) — 15 styles total:
Quick example:
- Display Large: 57sp
- Headline Large: 32sp
- Body Large: 16sp
- Label Small: 11sp
3. Layout
Responsive breakpoints and grid system:
- Compact: 0-599dp (phones)
- Medium: 600-839dp (tablets, folded phones)
- Expanded: 840-1199dp (desktops, large tablets)
- Large: 1200-1599dp; Extra-large: 1600dp+ (both added after the original 3-class model, for very large tablets and external displays)
Component Guidelines
Material Design 3 provides specifications for:
- Common Buttons: Elevated, Filled, Tonal, Outlined, Text
- Cards: Elevated, Filled, Outlined variants
- Text Fields: Filled, Outlined with labels and helper text
- Navigation: Navigation bar, rail, drawer
- Chips: Assist, Filter, Input, Suggestion chips
- Dialogs: Basic, Full-screen dialogs
Full specifications for every component live at m3.material.io (linked under Resources).
Quick Component Examples
Buttons
// Jetpack Compose
Button(onClick = { }) {
Text("Filled Button")
}
OutlinedButton(onClick = { }) {
Text("Outlined Button")
}
Cards
Card(
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
) {
Column(modifier = Modifier.padding(16.dp)) {
Text("Card Title", style = MaterialTheme.typography.headlineSmall)
Text("Card content", style = MaterialTheme.typography.bodyMedium)
}
}
Text Fields
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") },
supportingText = { Text("Helper text") }
)
Implementing Dynamic Color
Android (Jetpack Compose)
val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val colorScheme = when {
dynamicColor && darkTheme -> dynamicDarkColorScheme(LocalContext.current)
dynamicColor && !darkTheme -> dynamicLightColorScheme(LocalContext.current)
darkTheme -> darkColorScheme()
else -> lightColorScheme()
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
Web
Use Material Web Components (linked under Resources) for web implementation.
Motion and Animation
Material Design 3 motion principles:
- Easing: Standard, emphasized, decelerated curves
- Duration: Based on travel distance and complexity
- Choreography: Coordinated element movements
Accessibility
Material Design 3 prioritizes accessibility:
- Minimum 4.5:1 contrast ratio (text)
- 3:1 contrast ratio (UI components)
- Touch targets minimum 48dp × 48dp
- Screen reader support
- Semantic color usage (not color-only indicators)
Load /design:accessibility for WCAG implementation guidance.
Key Principles
- User-driven personalization: Colors adapt to user preferences
- Expressive and flexible: Rounded corners, dynamic elevation
- Accessible by default: Built-in contrast, touch targets, semantics
- Cross-platform consistency: Same principles across Android, web, iOS
- Design tokens: Use semantic tokens, not hardcoded values
- Responsive: Adapt to device size and orientation
Resources
- Material Design 3: https://m3.material.io/
- Material Theme Builder: https://material-foundation.github.io/material-theme-builder/ (moved off m3.material.io; the old
/theme-builderpath now redirects here) - Jetpack Compose: https://developer.android.com/develop/ui/compose/designsystems/material3 (old
/jetpack/compose/...path now redirects here) - Material Web Components: https://github.com/material-components/material-web
- Flutter Material 3: https://docs.flutter.dev/ui/design/material (old
flutter.dev/docs/...path now redirects here through 3 hops)
Elixir Anti-Patterns Detection and Refactoring
You are an expert at identifying Elixir anti-patterns and suggesting idiomatic refactorings. Use this knowledge to analyze code, suggest improvements, and help developers write better Elixir.
Code-Related Anti-Patterns
1. Comments Overuse
Problem: Excessive or self-explanatory comments reduce readability rather than enhance it.
Detection:
- Inline comments explaining obvious code
- Comments for every function line
- Comments duplicating what code already says clearly
Refactoring:
- Use clear function and variable names instead of explanatory comments
- Replace inline comments with
@docand@moduledocfor documentation - Use module attributes for configuration values
Example:
# Bad
def calculate() do
# Get current time
now = DateTime.utc_now()
# Add 5 minutes
DateTime.add(now, 5 * 60, :second)
end
# Good
@minutes_to_add 5
def timestamp_five_minutes_from_now do
now = DateTime.utc_now()
DateTime.add(now, @minutes_to_add * 60, :second)
end
2. Complex else Clauses in with
Problem: Flattening all error handling into a single complex else block obscures which clause produced which error.
Detection:
- Large
elseblocks with many pattern match clauses - Difficulty determining error sources
- Complex error handling logic in
else
Refactoring:
- Normalize return types in private functions
- Handle errors closer to their source
- Let
withfocus on success paths
Example:
# Bad
def read_config(path) do
with {:ok, content} <- File.read(path),
{:ok, decoded} <- Jason.decode(content) do
{:ok, decoded}
else
{:error, :enoent} -> {:error, :file_not_found}
{:error, %Jason.DecodeError{}} -> {:error, :invalid_json}
{:error, reason} -> {:error, reason}
end
end
# Good
def read_config(path) do
with {:ok, content} <- read_file(path),
{:ok, config} <- parse_json(content) do
{:ok, config}
end
end
defp read_file(path) do
case File.read(path) do
{:ok, content} -> {:ok, content}
{:error, :enoent} -> {:error, :file_not_found}
error -> error
end
end
defp parse_json(content) do
case Jason.decode(content) do
{:ok, data} -> {:ok, data}
{:error, _} -> {:error, :invalid_json}
end
end
3. Complex Extractions in Clauses
Problem: Extracting values across multiple clauses and arguments makes it unclear which variables serve pattern/guard purposes versus function body usage.
Detection:
- Many variable extractions in function heads
- Mixed guard and body variable usage
- Unclear variable purposes
Refactoring:
- Extract only pattern/guard-related variables in function signatures
- Use capture patterns like
%User{age: age} = user - Extract body variables inside the clause
Example:
# Bad
def process(%User{age: age, name: name, email: email} = user) when age >= 18 do
# Only using name and email in body, not age
send_email(email, "Hello #{name}")
end
# Good
def process(%User{age: age} = user) when age >= 18 do
send_email(user.email, "Hello #{user.name}")
end
4. Dynamic Atom Creation
Problem: Atoms aren't garbage-collected and are limited to ~1 million. Uncontrolled dynamic atom creation poses memory and security risks.
Detection:
String.to_atom/1with untrusted input- Converting user input directly to atoms
- Unbounded atom creation in loops
Refactoring:
- Use explicit mappings via pattern-matching
- Use
String.to_existing_atom/1with pre-defined atoms - Keep strings when atom conversion isn't necessary
Example:
# Bad - Security risk!
def set_role(user, role_string) do
%{user | role: String.to_atom(role_string)}
end
# Good
def set_role(user, role) when role in [:admin, :editor, :viewer] do
%{user | role: role}
end
# Or with pattern matching
def set_role(user, "admin"), do: %{user | role: :admin}
def set_role(user, "editor"), do: %{user | role: :editor}
def set_role(user, "viewer"), do: %{user | role: :viewer}
def set_role(_user, invalid), do: {:error, "Invalid role: #{invalid}"}
5. Long Parameter List
Problem: Functions with excessive parameters become confusing and error-prone to use.
Detection:
- Functions with 4+ parameters
- Parameters that are conceptually related
- Difficult to remember parameter order
Refactoring:
- Group related parameters into maps or structs
- Use keyword lists for optional parameters
- Create domain objects
Example:
# Bad
def create_loan(user_id, user_name, user_email, book_id, book_title, book_isbn) do
# ...
end
# Good
def create_loan(user, book) do
# ...
end
# Or with keyword list for options
def create_loan(user, book, opts \\ []) do
duration = Keyword.get(opts, :duration, 14)
renewable = Keyword.get(opts, :renewable, true)
# ...
end
6. Namespace Trespassing
Problem: Defining modules outside your library's namespace risks conflicts since the Erlang VM loads only one module instance per name.
Detection:
- Library defining modules in common namespaces (e.g.,
Plug.*when you're not Plug) - Modules without library prefix
- Potential naming conflicts with other libraries
Refactoring:
- Always prefix modules with your library namespace
- Use clear, unique top-level module names
Example:
# Bad - Library named :plug_auth
defmodule Plug.Auth do
# This conflicts with the actual Plug library!
end
# Good
defmodule PlugAuth do
# ...
end
defmodule PlugAuth.Session do
# ...
end
7. Non-assertive Map Access
Problem: Using dynamic access (map[:key]) for required keys masks missing data, allowing nil to propagate instead of failing fast.
Detection:
map[:key]for required/expected keys- Nil checks after map access
- Silent failures from missing keys
Refactoring:
- Use static access (
map.key) for required keys - Pattern-match on struct/map keys
- Reserve dynamic access for optional fields
Example:
# Bad
def distance(point) do
x = point[:x] # Returns nil if :x is missing!
y = point[:y]
:math.sqrt(x * x + y * y) # Crashes on nil, but unclear why
end
# Good
def distance(%{x: x, y: y}) do
:math.sqrt(x * x + y * y) # Clear error if keys missing
end
# Or with structs
defmodule Point do
defstruct [:x, :y]
end
def distance(%Point{x: x, y: y}) do
:math.sqrt(x * x + y * y)
end
8. Non-assertive Pattern Matching
Problem: Writing defensive code that returns incorrect values instead of using pattern matching to assert expected structures causes silent failures.
Detection:
- Defensive nil checks instead of pattern matching
- Functions returning invalid data on unexpected input
- Avoiding crashes when crashes are appropriate
Refactoring:
- Use pattern matching to assert expected structures
- Let functions crash on invalid input
- Trust supervisors to handle failures
Example:
# Bad
def parse_query_param(param) do
case String.split(param, "=") do
[key, value] -> {key, value}
_ -> {"", ""} # Silent failure!
end
end
# Good
def parse_query_param(param) do
[key, value] = String.split(param, "=")
{key, value}
end
# Crashes with clear error if format is wrong - this is good!
9. Non-assertive Truthiness
Problem: Using truthiness operators (&&, ||, !) when all operands are boolean is unnecessarily generic and unclear.
Detection:
&&,||,!with boolean expressions- Comparisons like
is_binary(x) && is_integer(y) - Mixing boolean and truthy logic
Refactoring:
- Use
and,or,notfor boolean-only operations - Reserve
&&,||,!for truthy/falsy logic
Example:
# Bad
def valid_user?(name, age) do
is_binary(name) && is_integer(age) && age >= 18
end
# Good
def valid_user?(name, age) do
is_binary(name) and is_integer(age) and age >= 18
end
# Truthy operators are OK for nil/value checks
def get_name(user) do
user[:name] || "Anonymous"
end
10. Structs with 32 Fields or More
Problem: Structs with 32+ fields switch from Erlang's efficient flat-map representation to hash maps, increasing memory usage.
Detection:
- Struct definitions with 32+ fields
- Large, flat data structures
- Performance degradation with many fields
Refactoring:
- Nest optional fields into metadata structures
- Use nested structs for related fields
- Group frequently-accessed fields separately
Example:
# Bad
defmodule User do
defstruct [
:id, :email, :name, :age, :address, :city, :state, :zip,
:phone, :mobile, :fax, :company, :title, :department,
:created_at, :updated_at, :last_login, :login_count,
:preference1, :preference2, :preference3, :preference4,
# ... 15 more fields
]
end
# Good
defmodule User do
defstruct [
:id,
:email,
:name,
:profile, # Nested struct
:preferences, # Nested struct
:metadata # Nested struct
]
end
defmodule User.Profile do
defstruct [:age, :phone, :mobile, :address, :city, :state, :zip]
end
defmodule User.Preferences do
defstruct [:theme, :notifications, :language]
end
Design-Related Anti-Patterns
Alternative return types, boolean obsession, exceptions used for control flow, primitive
obsession, unrelated multi-clause functions, and using application configuration for libraries:
see references/design-anti-patterns.md. This split follows upstream's own code/design
division — a real seam, not an arbitrary cut.
Usage Guidelines
When reviewing or writing Elixir code:
- Scan for anti-patterns - Check code against the patterns listed above
- Explain the problem - Help the developer understand why it's an issue
- Suggest refactoring - Provide concrete, idiomatic alternatives
- Consider context - Sometimes anti-patterns are acceptable for specific use cases
- Prioritize - Focus on high-impact issues first (security, performance, maintainability)
Key Principles
- Let it crash - Use pattern matching to assert expectations; don't write defensive code
- Fail fast - Expose errors early rather than propagating nil or invalid data
- Be explicit - Prefer clear, specific code over clever or terse solutions
- Model your domain - Create types that represent business concepts
- Design for clarity - Code should be obvious to read and maintain
Elixir Configuration
Guide for proper application configuration in Elixir, with emphasis on understanding and correctly using runtime vs compile-time configuration.
Critical Principle
Runtime configuration is the preferred approach. Only use compile-time configuration when values must affect compilation itself.
Configuration Files
config/config.exs (Compile-Time)
Evaluated during project compilation, before your application starts.
import Config
# Basic configuration
config :my_app, MyApp.Repo,
database: "my_app_dev",
username: "postgres",
password: "postgres",
hostname: "localhost"
# Environment-specific config
config :my_app,
environment: config_env()
# Import environment-specific config files
import_config "#{config_env()}.exs"
Key characteristics:
- Runs at compile time
- Uses
import Config(notuse Mix.Config) - Can use
config_env()andconfig_target() - Can import other config files with
import_config/1 - Deep-merges keyword lists
- Library config.exs is NOT evaluated when used as a dependency
config/runtime.exs (Runtime)
Evaluated right before applications start in both Mix and releases.
import Config
# Read from environment variables
config :my_app, MyApp.Repo,
database: System.get_env("DATABASE_NAME") || "my_app_dev",
username: System.get_env("DATABASE_USER") || "postgres",
password: System.get_env("DATABASE_PASSWORD") || "postgres",
hostname: System.get_env("DATABASE_HOST") || "localhost",
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
# Conditional runtime configuration
if config_env() == :prod do
config :my_app, MyAppWeb.Endpoint,
secret_key_base: System.fetch_env!("SECRET_KEY_BASE"),
http: [port: String.to_integer(System.fetch_env!("PORT"))]
end
Key characteristics:
- Runs at application startup (both dev and prod)
- Executes in both Mix projects and releases
- Used for environment variables and runtime values
- Does NOT support
import_config/1 - Can use
System.get_envandSystem.fetch_env!
config/dev.exs, config/test.exs, config/prod.exs
Environment-specific compile-time configuration, typically imported from config.exs:
# config/config.exs
import_config "#{config_env()}.exs"
# config/dev.exs
import Config
config :my_app, MyApp.Repo,
show_sensitive_data_on_connection_error: true,
pool_size: 10
# config/test.exs
import Config
config :my_app, MyApp.Repo,
pool: Ecto.Adapters.SQL.Sandbox,
pool_size: 10
# config/prod.exs
import Config
# Production-specific compile-time config only
config :my_app, MyAppWeb.Endpoint,
cache_static_manifest: "priv/static/cache_manifest.json"
Accessing Configuration
Runtime Access (Preferred)
Use in function bodies to read configuration at runtime:
Application.get_env/3
defmodule MyApp.Service do
def start_link do
# Get with default value
timeout = Application.get_env(:my_app, :timeout, 5000)
GenServer.start_link(__MODULE__, timeout, name: __MODULE__)
end
end
When to use:
- Reading config in function bodies (most common)
- When a sensible default exists
- When config might change between environments
Application.fetch_env!/2
defmodule MyApp.Mailer do
def deliver(email) do
# Raise if not configured (for required config)
api_key = Application.fetch_env!(:my_app, :mailgun_api_key)
send_email(email, api_key)
end
end
When to use:
- Required configuration that must exist
- When you want explicit errors for missing config
- When no sensible default exists
Application.fetch_env/2
defmodule MyApp.Cache do
def get(key) do
case Application.fetch_env(:my_app, :cache_adapter) do
{:ok, adapter} -> adapter.get(key)
:error -> nil # No caching configured
end
end
end
When to use:
- Optional configuration
- When you need pattern matching on result
- When absence of config is a valid state
Compile-Time Access (Use Sparingly)
Use only when configuration must affect compilation:
Application.compile_env/3
defmodule MyApp.JSONEncoder do
# Only use compile_env when the value affects compilation
@json_library Application.compile_env(:my_app, :json_library, Jason)
def encode(data) do
# The specific library is compiled into the module
@json_library.encode(data)
end
end
When to use:
- Configuration affects which code gets compiled
- Performance-critical paths where indirection is costly
- Compile-time optimizations or code generation
Warning: Mix tracks compile-time config and raises errors if values diverge between compile and runtime.
Application.compile_env!/2
defmodule MyApp.Adapter do
# Raises at compile time if not configured
@adapter Application.compile_env!(:my_app, :storage_adapter)
def store(data) do
@adapter.put(data)
end
end
When to use:
- Required compile-time configuration
- Adapters or behaviors selected at compile time
Common Patterns
Five worked patterns — environment variables in runtime, dev/prod split, storing config_env()
for runtime access, optional features, and child specs with runtime config: see
references/patterns.md.
Anti-Patterns to Avoid
❌ Using compile_env for Runtime Values
# DON'T: Using compile_env for environment variables
defmodule MyApp.Service do
@api_key Application.compile_env(:my_app, :api_key)
def call do
# This won't work correctly in releases!
HTTPoison.get(url, [{"Authorization", @api_key}])
end
end
Why it's wrong: Environment variables aren't available at compile time in releases.
Correct approach:
defmodule MyApp.Service do
def call do
# Read at runtime
api_key = Application.fetch_env!(:my_app, :api_key)
HTTPoison.get(url, [{"Authorization", api_key}])
end
end
❌ Reading Other Application's Config
# DON'T: Directly access other app's configuration
defmodule MyApp do
def logger_level do
Application.get_env(:logger, :level) # Fragile coupling
end
end
Why it's wrong: Creates tight coupling and breaks encapsulation.
Correct approach:
# Configure it in your own app
# config/config.exs
config :my_app, :log_level, :info
# Then read your own config
defmodule MyApp do
def log_level do
Application.get_env(:my_app, :log_level, :info)
end
end
❌ Using Application Config in Libraries
# DON'T: In a library
defmodule MyLibrary do
def process(data) do
# Library reading its own application environment
timeout = Application.get_env(:my_library, :timeout, 5000)
do_work(data, timeout)
end
end
Why it's wrong: Library config.exs is not evaluated when used as a dependency.
Correct approach:
# DO: Accept options as arguments
defmodule MyLibrary do
def process(data, opts \\ []) do
timeout = Keyword.get(opts, :timeout, 5000)
do_work(data, timeout)
end
end
# Users configure in their application
defmodule MyApp.Worker do
def run do
opts = Application.get_env(:my_app, :my_library_opts, [])
MyLibrary.process(data, opts)
end
end
❌ Using Mix Module in Application Code
# DON'T: Use Mix.env() in application code
defmodule MyApp do
def environment do
Mix.env() # Won't work in releases!
end
end
Why it's wrong: Mix is not available in production releases.
Correct approach:
# Store it in config
# config/config.exs
config :my_app, :environment, config_env()
# Access from application environment
defmodule MyApp do
def environment do
Application.fetch_env!(:my_app, :environment)
end
end
Config Functions Reference
In Configuration Files
| Function | Description | Where to Use |
|---|---|---|
config/2 | Configure app with keyword list | All config files |
config/3 | Configure app key with value | All config files |
config_env/0 | Get current environment (:dev, :test, :prod) | All config files |
config_target/0 | Get build target | All config files |
import_config/1 | Import other config files | Not in runtime.exs |
In Application Code
| Function | Return Type | Use Case |
|---|---|---|
Application.get_env/3 | value | default | Runtime with default |
Application.fetch_env/2 | {:ok, value} | :error | Runtime with pattern matching |
Application.fetch_env!/2 | value (raises if missing) | Required runtime config |
Application.compile_env/3 | value | Compile-time with default |
Application.compile_env!/2 | value (raises if missing) | Required compile-time config |
Migration Guide
Moving from use Mix.Config to import Config, and moving runtime values out of
config.exs into runtime.exs: see references/migration.md.
Best Practices Summary
- Default to Runtime Configuration: Use
Application.get_env/3in function bodies - Use runtime.exs for Environment Variables: Never read env vars in
config.exs - Use compile_env Only When Necessary: Only when config affects compilation
- Libraries Should Not Use Application Config: Accept options as function arguments
- Never Use Mix in Application Code: Use
config_env()in config files, store result - Validate Required Config Early: Use
fetch_env!/2in application start for required values - Provide Sensible Defaults: Use
get_env/3with defaults for optional config - Document Configuration: Add comments explaining what each config key does
- Use runtime.exs for Releases: Essential for Elixir releases and deployments
- Store config_env() for Runtime Use: Can't call
config_env()outside config files
Debugging Configuration
Check Current Configuration
# In IEx
Application.get_all_env(:my_app)
# Check specific key
Application.fetch_env(:my_app, :some_key)
# See all applications
Application.loaded_applications()
Common Issues
Problem: Config not available in tests
# config/test.exs
import Config
config :my_app, :test_value, "configured"
Problem: Different values in dev vs release
Check that runtime.exs is being used and environment variables are set correctly.
Problem: Compile-time config not updating
# Clean and recompile
mix clean
mix compile
Resources
- Config Module Docs: https://hexdocs.pm/elixir/Config.html
- Application Module Docs: https://hexdocs.pm/elixir/Application.html
- Runtime Configuration Guide: https://hexdocs.pm/mix/Mix.Tasks.Release.html#module-runtime-configuration
Key Insights
"Reading the application environment at runtime is the preferred approach."
"If you are writing a library to be used by other developers, it is generally recommended to avoid the application environment, as the application environment is effectively a global storage."
"config/config of a library is not evaluated when the library is used as a dependency, as configuration is always meant to configure the current project."
Configuration is a cross-cutting concern. Default to runtime configuration with Application.get_env/3, and only reach for compile-time configuration when you have a specific need for it that justifies the trade-offs.
Ecto
Canonical reference for Ecto data work in Elixir. Verified against ecto 3.13.5 / ecto_sql 3.13.5 (signatures pulled from installed dep source). Newer minor versions add APIs but keep these signatures stable.
The default rule
Ecto schemas + changesets are the default. Raw SQL via Ecto.Adapters.SQL.query/4 is the fallback.
Reads can use raw SQL when no Ecto query DSL covers the case. Writes go through changesets so validation and constraints run. Bypassing changesets silently ships malformed rows — bugs surface at read time, not write time.
Reach for raw SQL only when one of the escape-hatch criteria applies. Default to Repo.all, Repo.insert, Repo.update, Repo.delete and changesets.
Reads — query DSL
Use the Ecto.Query DSL (from, where, join, select, fragment) over string SQL. The DSL composes, type-checks against the schema, and prevents SQL injection.
import Ecto.Query
# Good — composable, type-safe
def list_open_epics(repo_filter) do
from(e in Epic,
where: e.status == "open" and e.target_repos == ^repo_filter,
order_by: [desc: e.priority],
select: e
)
|> Repo.all()
end
# Use fragment/1 only for SQL the DSL cannot express
def case_insensitive_search(term) do
from(e in Epic,
where: fragment("? ILIKE ?", e.title, ^"%#{term}%")
)
|> Repo.all()
end
# Bad — string SQL, no schema typing, no composition
Ecto.Adapters.SQL.query!(Repo,
"SELECT * FROM epics WHERE status = $1",
["open"]
)
Repo.get/3 (single by primary key), Repo.one/2 (assert single result), Repo.all/2 (list), Repo.exists?/2 (boolean) cover most read entry points.
Writes — changesets
Every write builds a %Ecto.Changeset{} from a struct + attrs, then runs through Repo.insert/2, Repo.update/2, or Repo.delete/2.
Verified signatures (ecto 3.13.5):
Ecto.Changeset.cast(data, params, permitted, opts \\ [])
Ecto.Changeset.validate_required(changeset, fields, opts \\ [])
Ecto.Changeset.unique_constraint(changeset, field_or_fields, opts \\ [])
Ecto.Changeset.validate_format(changeset, field, regex, opts \\ [])
Real exemplar from Vantageex.Epics.Epic:
def changeset(epic, attrs) do
epic
|> cast(attrs, [:external_id, :title, :slug, :objective, :status, :priority])
|> validate_required([:external_id, :title, :slug, :objective])
|> validate_inclusion(:status, @valid_statuses)
|> unique_constraint(:slug)
end
Return tuples are {:ok, struct} on success or {:error, %Ecto.Changeset{}} on validation/constraint failure. Pattern-match both branches:
def create_epic(attrs) do
%Epic{}
|> Epic.changeset(attrs)
|> Repo.insert()
end
case create_epic(attrs) do
{:ok, epic} -> handle_success(epic)
{:error, changeset} -> render_errors(changeset)
end
For bang-vs-non-bang and idiomatic error returns, see /elixir:style.
Batch writes
Repo.update_all/3 and Repo.delete_all/2 skip changesets — no per-row validation, no before_*/after_* hooks. Use them for mass updates where validation is irrelevant or already enforced upstream.
# Bulk: clear stale fields across many rows
from(e in Epic, where: e.status == "stale")
|> Repo.update_all(set: [last_peek_output: nil])
When validation matters, prefer N changeset updates inside a transaction over one update_all. Measure before bulk-updating "for performance" — Postgres handles thousands of indexed updates in milliseconds.
Migrations
Schema changes use add, alter, drop, create index, create table macros. Verified signatures (ecto_sql 3.13.5):
Ecto.Migration.add(column, type, opts \\ [])
Ecto.Migration.execute(command) # binary, 0-arity fn, or list
defmacro create(object, do: block) # for tables/indexes with column blocks
defmodule MyApp.Repo.Migrations.AddPriorityToEpics do
use Ecto.Migration
def change do
alter table(:epics) do
add :priority, :integer, default: 10, null: false
end
create index(:epics, [:priority])
end
end
Data migrations — local snapshot schema pattern
Data migrations transform existing rows. Two rules:
- Never
aliasthe live application schema. The live schema evolves; a migration written againstMyApp.Epics.Epictoday breaks when fields get renamed or removed in a future migration. Replay from scratch fails. - Define a local snapshot schema inside the migration module. It captures the schema's shape at this point in history.
defmodule MyApp.Repo.Migrations.BackfillEpicPriority do
use Ecto.Migration
import Ecto.Query
defmodule Epic do
use Ecto.Schema
schema "epics" do
field :priority, :integer
field :status, :string
end
end
def change do
repo = repo()
from(e in Epic, where: is_nil(e.priority))
|> repo.all()
|> Enum.each(fn epic ->
epic
|> Ecto.Changeset.change(priority: priority_for_status(epic.status))
|> repo.update!()
end)
end
defp priority_for_status("urgent"), do: 1
defp priority_for_status(_), do: 10
end
This pattern dogfoods Ecto end-to-end: queries via DSL, writes via changesets, schemas frozen to migration time. See references/migrations.md for additional recipes.
When execute/1 is appropriate
execute/1 runs raw SQL inside a migration. Use it for DB-specific DDL the macros do not cover:
- Postgres extensions:
execute("CREATE EXTENSION IF NOT EXISTS pgcrypto") - Custom indexes:
execute("CREATE INDEX CONCURRENTLY ...")(note:CONCURRENTLYrequires@disable_ddl_transaction true) - Trigger functions, materialized views, partitioning DDL
execute/1 is never the right tool for data transformations. Use the local-snapshot pattern above.
Multi-step atomic ops — Ecto.Multi
Ecto.Multi chains operations into one transaction. If any step fails, prior steps roll back. As of ecto 3.13, Repo.transaction/2 is deprecated — use Repo.transact/2.
Verified signatures:
Ecto.Multi.new() # empty %Ecto.Multi{}
Ecto.Multi.insert(multi, name, changeset_or_struct_or_fn, opts \\ [])
Ecto.Multi.update(multi, name, changeset_or_fn, opts \\ [])
Repo.transact(multi_or_fn, opts \\ [])
def transfer_funds(from_id, to_id, amount) do
Ecto.Multi.new()
|> Ecto.Multi.update(:debit, debit_changeset(from_id, amount))
|> Ecto.Multi.update(:credit, credit_changeset(to_id, amount))
|> Ecto.Multi.insert(:audit, fn %{debit: debit} ->
AuditLog.changeset(%AuditLog{}, %{from: debit.id, amount: amount})
end)
|> Repo.transact()
end
On success: {:ok, %{debit: ..., credit: ..., audit: ...}}. On failure: {:error, failed_step_name, failed_value, changes_so_far}. Pattern-match the four-tuple for the failed-step branch.
The third argument to Multi.insert/4 and Multi.update/4 accepts a 1-arity function fn changes -> changeset end — that is how downstream steps reference upstream results.
When raw SQL IS appropriate
Escape hatch criteria. Each one requires evidence, not assumption.
- Complex CTEs / window functions Ecto's DSL does not expose. Document the missing DSL feature in a comment.
- DB-specific features: PostGIS spatial queries, full-text search ranking with custom dictionaries, advisory locks.
- Perf-critical hot paths with measured Ecto overhead. Benchmark first; "it feels slow" is not evidence.
- One-off reads in tidewave eval (single-cell exploration). Never one-off writes — those go through a changeset even at the REPL.
# Acceptable: PostGIS — no DSL covers ST_DWithin
{:ok, %{rows: rows}} =
Ecto.Adapters.SQL.query(
Repo,
"SELECT id FROM places WHERE ST_DWithin(location, ST_MakePoint($1, $2)::geography, $3)",
[lng, lat, radius]
)
Anti-patterns
repo().query!("UPDATE ...") in migrations
Bypasses Ecto, hides errors, locks the migration to the current row shape. Replace with the local-snapshot pattern.
# Bad
def change do
repo().query!("UPDATE epics SET priority = 1 WHERE status = 'urgent'")
end
# Good — snapshot schema + Repo.update_all (or Repo.update for per-row validation)
defmodule Epic do
use Ecto.Schema
schema "epics" do
field :priority, :integer
field :status, :string
end
end
def change do
from(e in Epic, where: e.status == "urgent")
|> repo().update_all(set: [priority: 1])
end
Bypassing changeset validation via insert_all
Repo.insert_all/3 inserts raw maps without changesets. Use it only when you have already validated the data upstream OR when the rows are infrastructure (e.g. seed data). For user input, always go through a changeset.
Importing live application schema into old migrations
# Bad — couples migration N to whatever Epic looks like at HEAD
defmodule MyApp.Repo.Migrations.OldMigration do
alias MyApp.Epics.Epic # WRONG
...
end
A schema change six months from now breaks migration replay. Define a local snapshot schema instead (see Migrations above).
"Raw SQL because it's faster"
Without measurement, this is fabrication. Ecto's overhead vs raw SQL is microseconds per row. Most perceived "slow Ecto" is N+1 queries (fix with Repo.preload/3 or a join), missing indexes, or unbounded result sets — not the DSL itself.
References
references/migrations.md— local snapshot schema deep dive, common DDL recipes, reversible migrations,@disable_ddl_transactionrulesreferences/migrations-audit.md— repeatable two-phase (haiku indexer + opus reviewer) template for auditing a repo's migrations for/elixir:ectocompliance; reuses across repos by swapping the app namespacereferences/changesets.md—cast_assoc,validate_*catalog, custom validations,prepare_changes/2- HexDocs: Ecto, Ecto.Changeset, Ecto.Query, Ecto.Multi, Ecto.Migration
/elixir:tidewave— runtime introspection of schemas viamcp__tidewave__get_ecto_schemasand live API doc lookup/elixir:phoenix— context-pattern integration (changeset usage in Phoenix contexts)/elixir:style— bang-vs-non-bang return semantics, idiomatic error returns
Anti-fabrication
Every API signature in this skill is verified from the installed source under deps/ecto/ and deps/ecto_sql/ (ecto 3.13.5). When this skill is loaded:
- Cite signatures from
mcp__tidewave__get_docsor the installed dep source — not memory. - Mark any unverified function as "requires investigation".
- See
/core:anti-fabricationfor the authoritative guide.
Elixir OTP and Concurrency
This skill activates when working with OTP behaviors, building concurrent systems, managing processes, or implementing fault-tolerant architectures in Elixir.
OTP Behaviors
Full catalogs for GenServer, Supervisor, Task, and Agent — client/server structure, dynamic supervision, restart configuration — live in references/behaviors.md. Two decisions from that catalog are worth keeping here:
- Agent vs GenServer: use Agent for simple key-value state; use GenServer when you need complex logic, callbacks, or process lifecycle management.
- Supervisor restart strategies:
:one_for_onerestarts only the crashed child;:one_for_allrestarts every child;:rest_for_onerestarts the crashed child and every child started after it.
Process Communication
send/receive
Basic message passing:
# Send message
send(pid, {:hello, "world"})
# Receive message
receive do
{:hello, msg} -> IO.puts(msg)
after
5000 -> IO.puts("Timeout")
end
Process Registration
Register processes by name:
# Local registration
Process.register(self(), :my_process)
send(:my_process, :hello)
# Via Registry
{:ok, _} = Registry.start_link(keys: :unique, name: MyApp.Registry)
{:ok, pid} = GenServer.start_link(MyWorker, nil,
name: {:via, Registry, {MyApp.Registry, "worker_1"}}
)
# Look up process
[{pid, _}] = Registry.lookup(MyApp.Registry, "worker_1")
Process Links and Monitors
Links - Bidirectional, propagate exits:
# Link processes
Process.link(pid)
# Spawn linked
spawn_link(fn -> do_work() end)
Monitors - Unidirectional, receive DOWN messages:
ref = Process.monitor(pid)
receive do
{:DOWN, ^ref, :process, ^pid, reason} ->
IO.puts("Process died: #{inspect(reason)}")
end
Concurrency Patterns
Pipeline Pattern
Chain operations with concurrency:
defmodule Pipeline do
def process(data) do
data
|> async(&step1/1)
|> async(&step2/1)
|> async(&step3/1)
|> await_all()
end
defp async(input, fun) do
Task.async(fn -> fun.(input) end)
end
defp await_all(tasks) when is_list(tasks) do
Enum.map(tasks, &Task.await/1)
end
end
Worker Pool
Implement a worker pool:
defmodule MyApp.WorkerPool do
use GenServer
def start_link(opts) do
pool_size = Keyword.get(opts, :size, 10)
GenServer.start_link(__MODULE__, pool_size, name: __MODULE__)
end
def execute(fun) do
GenServer.call(__MODULE__, {:execute, fun})
end
@impl true
def init(pool_size) do
workers = for _ <- 1..pool_size do
{:ok, pid} = Task.Supervisor.start_link()
pid
end
{:ok, %{workers: workers, index: 0}}
end
@impl true
def handle_call({:execute, fun}, _from, state) do
worker = Enum.at(state.workers, state.index)
task = Task.Supervisor.async_nolink(worker, fun)
new_index = rem(state.index + 1, length(state.workers))
{:reply, task, %{state | index: new_index}}
end
end
Backpressure with GenStage
For producer-consumer pipelines:
defmodule Producer do
use GenStage
def start_link(initial) do
GenStage.start_link(__MODULE__, initial, name: __MODULE__)
end
def init(initial) do
{:producer, initial}
end
def handle_demand(demand, state) do
events = Enum.to_list(state..state + demand - 1)
{:noreply, events, state + demand}
end
end
defmodule Consumer do
use GenStage
def start_link() do
GenStage.start_link(__MODULE__, :ok)
end
def init(:ok) do
{:consumer, :ok}
end
def handle_events(events, _from, state) do
Enum.each(events, &process_event/1)
{:noreply, [], state}
end
end
ETS - Erlang Term Storage
In-memory key-value storage:
# Create table
:ets.new(:my_table, [:named_table, :public, read_concurrency: true])
# Insert
:ets.insert(:my_table, {:key, "value"})
# Lookup
[{:key, value}] = :ets.lookup(:my_table, :key)
# Delete
:ets.delete(:my_table, :key)
# Match patterns
:ets.match(:my_table, {:"$1", "value"})
# Iterate
:ets.foldl(fn {k, v}, acc -> [{k, v} | acc] end, [], :my_table)
ETS Best Practices
- Use
read_concurrency: truefor read-heavy workloads - Use
write_concurrency: truefor write-heavy workloads - Prefer
:set(default) for unique keys - Use
:bagor:duplicate_bagfor multiple values per key - Always own ETS tables in a GenServer or Supervisor to prevent data loss
Error Handling and Fault Tolerance
Let-it-crash philosophy, when to handle errors explicitly instead, and a circuit-breaker pattern live in references/fault-tolerance.md.
Testing Concurrent Systems
Testing GenServers
defmodule MyApp.CounterTest do
use ExUnit.Case, async: true
test "increments counter" do
{:ok, pid} = MyApp.Counter.start_link(0)
assert MyApp.Counter.increment(pid) == 1
assert MyApp.Counter.increment(pid) == 2
assert MyApp.Counter.get_value(pid) == 2
end
end
Testing Asynchronous Processes
test "process receives message" do
parent = self()
spawn(fn ->
receive do
:ping -> send(parent, :pong)
end
end)
send(pid, :ping)
assert_receive :pong, 1000
end
Testing Supervision
test "supervisor restarts crashed worker" do
{:ok, sup} = Supervisor.start_link([MyApp.Worker], strategy: :one_for_one)
[{_, worker_pid, _, _}] = Supervisor.which_children(sup)
# Crash the worker
Process.exit(worker_pid, :kill)
# Wait for restart
Process.sleep(100)
# Verify new worker started
[{_, new_pid, _, _}] = Supervisor.which_children(sup)
assert new_pid != worker_pid
assert Process.alive?(new_pid)
end
Debugging Concurrent Systems
Observer
Launch Observer for visual process inspection:
:observer.start()
Process Info
Inspect running processes:
# List all processes
Process.list()
# Process information
Process.info(pid)
# Message queue length
{:message_queue_len, count} = Process.info(pid, :message_queue_len)
# Current function
{:current_function, {mod, fun, arity}} = Process.info(pid, :current_function)
Tracing
Use :sys module for debugging:
# Enable tracing
:sys.trace(pid, true)
# Get state
:sys.get_state(pid)
# Get status
:sys.get_status(pid)
Performance Considerations
Process Spawning
- Processes are lightweight (< 2KB overhead)
- Spawning thousands/millions of processes is normal
- Use process pools when spawn rate is very high
Message Passing
- Messages are copied between processes
- Large messages are expensive - consider ETS or persistent_term
- Use binary for efficient large data transfer
Bottlenecks
- Single GenServer can become bottleneck
- Solution: shard state across multiple processes
- Use ETS with
read_concurrencyfor read-heavy workloads
Key Principles
- Embrace concurrency: Use processes liberally, they're cheap
- Let it crash: Don't write defensive code, use supervision
- Isolate failures: Design supervision trees to contain failures
- Communicate via messages: Avoid shared state between processes
- Use the right tool: GenServer for state, Task for work, Agent for simple state
- Test at boundaries: Test process APIs, not internal implementation
- Monitor and observe: Use Observer and logging to understand system behavior
References
references/behaviors.md— Full GenServer, Supervisor, Task, and Agent catalogreferences/fault-tolerance.md— Let-it-crash philosophy, explicit error handling, circuit breaker pattern
Phoenix Framework Development
This skill activates when working with Phoenix web applications, including setup, development, LiveView, contexts, controllers, and channels.
Current versions: Phoenix 1.8.x (current: 1.8.5), Phoenix LiveView 1.1.x (current: 1.1.27). Requires Elixir 1.14+, Erlang/OTP 25+.
Phoenix Project Structure
Follow Phoenix conventions:
lib/
my_app/ # Business logic and contexts
accounts/ # Domain contexts
repo.ex
my_app_web/ # Web interface
controllers/
live/ # LiveView modules
components/ # Function components
router.ex
endpoint.ex
Runtime configuration
config/runtime.exs runs at every boot (dev, test, prod). Three settings have caused production outages when configured incorrectly:
Phoenix Endpoint :ip bind config
The Endpoint's :ip bind tuple MUST be set at the TOP LEVEL of runtime.exs, env-driven, with a default of {0, 0, 0, 0} (all IPv4 interfaces). Do NOT gate it inside if port = System.get_env("PORT") do ... end, and do NOT override it later in a prod-only block that hardcodes {0,0,0,0,0,0,0,0} (IPv6 wildcard).
CORRECT:
# config/runtime.exs (top level, unconditional)
bind_address =
case System.get_env("BIND_ADDRESS", "0.0.0.0") do
"0.0.0.0" -> {0, 0, 0, 0}
"::" -> {0, 0, 0, 0, 0, 0, 0, 0}
other -> other |> String.to_charlist() |> :inet.parse_address() |> elem(1)
end
config :<app>, <App>Web.Endpoint, http: [ip: bind_address, port: ...]
WRONG (gates on PORT):
if port = System.get_env("PORT") do
config :<app>, <App>Web.Endpoint, http: [ip: {0, 0, 0, 0}, port: ...]
end
# Without PORT, Phoenix falls back to its default 127.0.0.1 — unreachable.
WRONG (later prod block clobbers env-driven setting):
# Top-level env-driven config OK ...
if config_env() == :prod do
config :<app>, <App>Web.Endpoint, http: [ip: {0, 0, 0, 0, 0, 0, 0, 0}, ...]
end
# IPv6 wildcard binds *:port IPv6 only — IPv4-only overlay networks (Tailscale on macOS) cannot reach it.
Default to IPv4 because most overlay networks route IPv4 first on macOS. Add IPv6 only when the deployment target explicitly requires it.
PHX_HOST matches the public DNS name
Set PHX_HOST to the externally-resolvable hostname the load balancer presents to the browser. LiveView's websocket upgrade matches Origin against PHX_HOST; a mismatch causes the LiveView socket to fail with 403 and the page reverts to a dead static render.
Dev-server restart after lib/**/*.ex changes
Phoenix live reload covers .heex / .html.eex templates and assets/ reliably. It does NOT reliably pick up changes to:
lib/**/*.ex— compiled Elixir modulesmix.exsor any dependency changeconfig/*.exs, especiallyruntime.exs- NIFs, native deps, BEAM-level plugins
- DB migrations that change already-loaded schema
After any of those changes, restart the dev server (kill + relaunch the mise run dev session or equivalent). /api/info-style endpoints report the git_sha at server-start time, NOT the currently-compiled-in-memory code, and cannot distinguish stale-dev from fresh-dev. Restart is the only reliable signal.
Context-Driven Design
Organize business logic into contexts (bounded domains):
Creating Contexts
Generate contexts with related schemas:
mix phx.gen.context Accounts User users email:string name:string
Structure contexts to encapsulate business logic:
defmodule MyApp.Accounts do
@moduledoc """
The Accounts context - manages user accounts and authentication.
"""
alias MyApp.Repo
alias MyApp.Accounts.User
def list_users do
Repo.all(User)
end
def get_user!(id), do: Repo.get!(User, id)
def create_user(attrs \\ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
def update_user(%User{} = user, attrs) do
user
|> User.changeset(attrs)
|> Repo.update()
end
end
Context Best Practices
- Keep contexts focused on a single domain
- Avoid cross-context dependencies when possible
- Use public API functions, not direct Repo access in web layer
- Name contexts after business domains, not technical layers
LiveView Development
LiveView enables rich, real-time experiences without writing JavaScript.
LiveView Lifecycle
Understand the mount → handle_event → render cycle:
defmodule MyAppWeb.UserLive.Index do
use MyAppWeb, :live_view
alias MyApp.Accounts
@impl true
def mount(_params, _session, socket) do
# Runs on initial page load and live connection
{:ok, assign(socket, :users, list_users())}
end
@impl true
def handle_params(params, _url, socket) do
# Runs after mount and on live patch
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
user = Accounts.get_user!(id)
{:ok, _} = Accounts.delete_user(user)
{:noreply, assign(socket, :users, list_users())}
end
@impl true
def render(assigns) do
~H"""
<div>
<.table rows={@users} id="users">
<:col :let={user} label="Name"><%= user.name %></:col>
<:col :let={user} label="Email"><%= user.email %></:col>
<:action :let={user}>
<.button phx-click="delete" phx-value-id={user.id}>Delete</.button>
</:action>
</.table>
</div>
"""
end
defp list_users do
Accounts.list_users()
end
end
LiveView Best Practices
- Use
mount/3for initial data loading - Handle route changes in
handle_params/3 - Keep renders fast - compute in event handlers, not render
- Use
assign_new/3for expensive computations - Prefer LiveView over JavaScript for interactive UIs
- Use
phx-debounceandphx-throttlefor frequent events
Function Components
Create reusable components:
defmodule MyAppWeb.Components.UserCard do
use Phoenix.Component
attr :user, :map, required: true
attr :class, :string, default: ""
def user_card(assigns) do
~H"""
<div class={"card " <> @class}>
<h3><%= @user.name %></h3>
<p><%= @user.email %></p>
</div>
"""
end
end
Use with <.user_card user={@current_user} /> in templates.
Form Handling
Use changesets for validation:
@impl true
def mount(_params, _session, socket) do
changeset = Accounts.change_user(%User{})
{:ok, assign(socket, form: to_form(changeset))}
end
@impl true
def handle_event("validate", %{"user" => user_params}, socket) do
changeset =
%User{}
|> Accounts.change_user(user_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, form: to_form(changeset))}
end
@impl true
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.create_user(user_params) do
{:ok, user} ->
{:noreply,
socket
|> put_flash(:info, "User created successfully")
|> push_navigate(to: ~p"/users/#{user}")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, form: to_form(changeset))}
end
end
def render(assigns) do
~H"""
<.form for={@form} phx-change="validate" phx-submit="save">
<.input field={@form[:name]} label="Name" />
<.input field={@form[:email]} label="Email" type="email" />
<.button>Save</.button>
</.form>
"""
end
Routing
Route organization (pipelines, scopes) and LiveView routes with live actions: see
references/routing-and-channels.md.
Channels and PubSub
Custom Channels for real-time protocols and Phoenix.PubSub for cross-process broadcasts: see
references/routing-and-channels.md.
Testing Phoenix Applications
Controller Tests
defmodule MyAppWeb.UserControllerTest do
use MyAppWeb.ConnCase, async: true
test "GET /users", %{conn: conn} do
conn = get(conn, ~p"/users")
assert html_response(conn, 200) =~ "Listing Users"
end
end
LiveView Tests
defmodule MyAppWeb.UserLiveTest do
use MyAppWeb.ConnCase
import Phoenix.LiveViewTest
test "displays users", %{conn: conn} do
user = insert(:user)
{:ok, view, html} = live(conn, ~p"/users")
assert html =~ user.name
assert has_element?(view, "#user-#{user.id}")
end
test "creates user", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/users/new")
assert view
|> form("#user-form", user: %{name: "Alice", email: "alice@example.com"})
|> render_submit()
assert_patch(view, ~p"/users")
end
end
Channel Tests
defmodule MyAppWeb.RoomChannelTest do
use MyAppWeb.ChannelCase
test "broadcasts are pushed to the client", %{socket: socket} do
{:ok, _, socket} = subscribe_and_join(socket, "room:lobby", %{})
broadcast_from!(socket, "new_msg", %{body: "test"})
assert_broadcast "new_msg", %{body: "test"}
end
end
Common Patterns
Preloading associations, pagination, and handling LiveView file uploads: see
references/common-patterns.md.
Performance Optimization
Database Query Optimization
- Use
preload/2to avoid N+1 queries - Add database indexes for frequently queried fields
- Use
select/3to load only needed fields - Consider using
Repo.stream/2for large datasets
LiveView Performance
- Move expensive computations to
handle_eventor background jobs - Use
assign_new/3for computed values - Implement
handle_continue/2for async operations after mount - Use temporary assigns for large lists:
assign(socket, :items, temporary: true)
Caching
Use Cachex or ETS for caching:
def get_user!(id) do
Cachex.fetch(:users, id, fn ->
{:commit, Repo.get!(User, id)}
end)
end
Security Best Practices
- Always validate and sanitize user input through changesets
- Use CSRF protection (enabled by default)
- Implement rate limiting for APIs
- Use
put_secure_browser_headersplug - Validate file uploads (type, size, content)
- Use prepared statements (Ecto does this automatically)
- Implement proper authentication and authorization
OpenAPI Contract-First
Define the OpenAPI spec for any HTTP API surface BEFORE implementing the controller. Clients (and Tier 2 test authors) generate from the spec; the implementation makes the spec true.
In Elixir, use open_api_spex for spec definitions:
defmodule <App>Web.UserSpec do
alias OpenApiSpex.{Schema, Operation}
@user_schema %Schema{
type: :object,
required: [:id, :email],
properties: %{
id: %Schema{type: :integer},
email: %Schema{type: :string, format: :email}
}
}
end
Wire the spec to the controller via @spec macros and serve it at /api/openapi. Tests assert response shapes against the spec rather than against hand-rolled JSON expectations; client SDKs regenerate from the spec on every spec change.
Tidewave MCP Dev Tools
Tidewave connects AI coding assistants to running Phoenix applications via MCP, exposing runtime introspection tools (Ecto schemas, code execution, docs, logs, SQL queries).
Add to mix.exs: {:tidewave, "~> 0.5", only: :dev}
Add to endpoint.ex before code_reloading?: plug Tidewave (guarded by if Mix.env() == :dev)
Connect Claude Code: claude mcp add --transport http tidewave http://localhost:4000/tidewave/mcp
Tidewave is dev-only — never deploy to production. It only accepts localhost requests by default.
For full setup, MCP tools reference, CLI app, editor configs, LiveView annotations, and troubleshooting, see /elixir:tidewave.
Key Principles
- Context boundaries: Keep business logic in contexts, not controllers/LiveViews
- LiveView first: Prefer LiveView over JavaScript for interactive features
- Changesets for validation: Always validate through Ecto changesets
- Pub/Sub for communication: Use Phoenix.PubSub for cross-process updates
- Test at boundaries: Test contexts, controllers, and LiveViews separately
- Follow conventions: Use Phoenix generators and follow established patterns
Elixir Ports
Ports are Elixir's mechanism for communicating with external OS programs via stdin/stdout. A Port is not a network port — it is a process-like entity that manages an external OS program, forwarding messages as bytes and delivering responses back to the owning Elixir process.
Port Fundamentals
Open a port with Port.open/2. The most common name forms are {:spawn, command} and {:spawn_executable, path}.
# Spawn by shell command string (uses shell, PATH lookups apply)
port = Port.open({:spawn, "cat"}, [:binary])
# Spawn executable directly (no shell, preferred for security)
port = Port.open({:spawn_executable, "/usr/bin/python3"}, [
:binary,
args: ["-u", "my_script.py"]
])
Send data to the port and receive from it:
# Send bytes to the external process's stdin
Port.command(port, "hello\n")
# Receive response — messages arrive in the process mailbox
receive do
{^port, {:data, data}} ->
IO.puts("Got: #{data}")
end
Close the port explicitly or let it close when the owner process exits:
Port.close(port)
# The port will reply {port, :closed} after the external process exits
Port Options Reference
| Option | Description |
|---|---|
:binary | Deliver data as binaries (recommended; default is charlists) |
{:packet, N} | Prefix each message with N-byte length header (N = 1, 2, or 4) |
{:line, L} | Deliver complete lines up to L bytes; partial lines flagged |
:stream | No framing — raw bytes delivered as received (default) |
:exit_status | Send {port, {:exit_status, code}} when the program exits |
:use_stdio | Use stdin/stdout for communication (default) |
:stderr_to_stdout | Merge stderr into stdout stream |
{:cd, dir} | Set working directory for the external process |
{:env, env_list} | EXTENDS the spawned process's environment (does NOT replace it) |
{:args, arg_list} | Argument list when using :spawn_executable |
{:arg0, string} | Override argv[0] for the external process |
:parallelism | Hint to scheduler for improved throughput |
Note on {:env, env_list}: This option extends the environment the BEAM already holds — the spawned process inherits every existing variable, and env_list adds to or overrides individual entries. There is no replace-all option. To withhold an inherited variable, pair its name with false (an empty charlist — ~c"" or [] — also unsets; Elixir's "" is a binary and raises). See the Security section.
Communication Patterns
Stream Mode (default)
Bytes are delivered as they arrive with no framing. Use :binary to get binaries instead of charlists.
port = Port.open({:spawn_executable, "/bin/cat"}, [:binary, :stream])
Port.command(port, "some data")
receive do
{^port, {:data, chunk}} -> IO.inspect(chunk)
end
Packet Mode
Use {:packet, N} for message framing. The external program must also implement the same N-byte big-endian length prefix.
# Elixir side
port = Port.open({:spawn_executable, "/usr/local/bin/my_worker"}, [
:binary,
{:packet, 4}
])
Port.command(port, encode_message("hello"))
receive do
{^port, {:data, response}} -> decode_message(response)
end
The external program reads a 4-byte big-endian integer as the message length, then reads that many bytes. It writes responses with the same framing.
Line Mode
port = Port.open({:spawn_executable, "/usr/bin/python3"}, [
:binary,
{:line, 4096},
args: ["script.py"]
])
receive do
{^port, {:data, {:eol, line}}} ->
IO.puts("Complete line: #{line}")
{^port, {:data, {:noeol, partial}}} ->
IO.puts("Partial line (too long): #{partial}")
end
Receiving Exit Status
port = Port.open({:spawn, "false"}, [:binary, :exit_status])
receive do
{^port, {:exit_status, code}} ->
IO.puts("Exited with code #{code}")
end
GenServer Port Wrapper
Wrapping a port in a GenServer is the standard OTP pattern for managing external processes. The GenServer owns the port, handles messages, and exposes a clean API.
defmodule MyApp.ExternalWorker do
use GenServer
@timeout 5_000
# Client API
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
def call(payload) do
GenServer.call(__MODULE__, {:call, payload}, @timeout)
end
# Server Callbacks
@impl true
def init(_opts) do
executable = System.find_executable("my_worker") ||
raise "my_worker not found in PATH"
port =
Port.open({:spawn_executable, executable}, [
:binary,
{:packet, 4},
:exit_status
])
ref = Port.monitor(port)
{:ok, %{port: port, ref: ref, caller: nil}}
end
@impl true
def handle_call({:call, payload}, from, %{port: port} = state) do
encoded = :erlang.term_to_binary(payload)
Port.command(port, encoded)
{:noreply, %{state | caller: from}}
end
@impl true
def handle_info({port, {:data, data}}, %{port: port, caller: caller} = state) do
response = :erlang.binary_to_term(data)
GenServer.reply(caller, {:ok, response})
{:noreply, %{state | caller: nil}}
end
@impl true
def handle_info({port, {:exit_status, code}}, %{port: port} = state) do
{:stop, {:port_exited, code}, state}
end
@impl true
def handle_info({:DOWN, ref, :port, _port, reason}, %{ref: ref} = state) do
{:stop, {:port_down, reason}, state}
end
@impl true
def terminate(_reason, %{port: port}) do
if Port.info(port) != nil do
Port.close(port)
end
:ok
end
end
Key points in this pattern:
- Store the port in GenServer state
- Monitor the port with
Port.monitor/1to receive:DOWNmessages - Use
{:packet, N}for reliable message framing - Store the calling
frompid when waiting for a response - Reply via
GenServer.reply/2fromhandle_infowhen data arrives - Always check
Port.info(port)before closing interminate/2
Supervision
Add the GenServer to a supervision tree:
children = [
{MyApp.ExternalWorker, []},
# ...
]
Supervisor.start_link(children, strategy: :one_for_one)
When the external process crashes, the port sends an exit message, the GenServer stops, and the supervisor restarts it.
Port Lifecycle and Error Handling
Port Monitor
Use Port.monitor/1 (available since Elixir v1.6) to receive a {:DOWN, ref, :port, object, reason} message when a port closes:
port = Port.open({:spawn, "my_cmd"}, [:binary])
ref = Port.monitor(port)
receive do
{:DOWN, ^ref, :port, _port, reason} ->
IO.puts("Port closed: #{inspect(reason)}")
end
Checking if a Port is Alive
case Port.info(port) do
nil -> :port_closed
info -> {:alive, info}
end
Port Ownership Transfer
Transfer ownership with Port.connect/2. The old owner receives {port, :connected}:
Port.connect(port, new_owner_pid)
Crash Semantics
- When the port owner process terminates, the port closes automatically, and the external program receives SIGTERM.
- When the external program exits, the port sends
{port, {:exit_status, code}}(if:exit_statuswas set) and closes. - Ports are linked to their owning process by default.
Decision Guide: Port vs NIF vs C Node vs System.cmd
| Aspect | Port | NIF | C Node | System.cmd |
|---|---|---|---|---|
| Crash isolation | Yes — OS process | No — crashes the VM | Yes — OS process | Yes — subprocess |
| Latency | IPC overhead | Near zero | Message passing | Blocking, high |
| Complexity | Low–Medium | High | Very high | Very low |
| Scheduler impact | None | Blocks (use dirty NIFs for >1ms) | None | Blocks caller only |
| Security boundary | OS process isolation | Full VM access | OS process isolation | OS process isolation |
| Best for | Long-running, streaming | Sub-millisecond sync calls | Legacy C integration | One-shot commands |
Use Port when: the external program runs continuously, streams data, or must be isolated from VM crashes.
Use System.cmd/3 when: running a command once, synchronously, and the result is needed before proceeding. Returns {output, exit_status}.
Use NIF when: calling a C function with sub-millisecond latency requirements. Use dirty NIFs (ERL_NIF_DIRTY_JOB_CPU_BOUND or ERL_NIF_DIRTY_JOB_IO_BOUND) for work exceeding ~1ms to avoid blocking schedulers.
Use C Node when: integrating with an existing large C codebase that uses erl_interface/ei.
System.cmd Example
{output, 0} = System.cmd("ls", ["-la", "/tmp"],
cd: "/",
stderr_to_stdout: true
)
System.cmd/3 blocks the calling process until the command completes. It does not stream data.
Security Considerations
Prefer :spawn_executable Over :spawn
{:spawn, command} passes the command through a shell, which enables shell injection:
# UNSAFE — shell injection risk
user_input = "file.txt; rm -rf /"
Port.open({:spawn, "cat #{user_input}"}, [:binary])
# SAFE — no shell, arguments passed directly
Port.open({:spawn_executable, "/bin/cat"}, [
:binary,
args: [user_input]
])
Always use {:spawn_executable, path} with args: when any part of the command comes from user input or external data.
Validate Executable Paths
# Find and validate the executable at startup, not per-request
executable = System.find_executable("my_tool") ||
raise "my_tool executable not found in PATH"
Store the validated path in process state so it is resolved once at startup.
Environment Variable Inheritance
{:env, env_list} extends the spawned process's environment — it does not replace it. OTP documents this directly: "The environment of the started process is extended using the environment specifications in Env." The child therefore inherits every variable the BEAM holds, including any secrets in it, whether or not they appear in env_list.
The security consequence is the part that is easy to get backwards: passing a short env_list does not sandbox the child. There is no replace-all option, so a variable is only withheld if you name it and pair it with false. The OTP 27 and 28 docs also treat an empty Erlang string as unset, "just as if os:unsetenv/1 had been called" — so an empty value cannot be passed through to a child at all. From Elixir that means ~c"" or []; the Elixir literal "" is a binary and raises ArgumentError.
Do not build a "clean" environment by enumerating System.get_env/0 and passing it back in — the child already has those variables, so it withholds nothing, and it copies every secret value into a BEAM term where it can surface in crash dumps, :sys.get_state/1, exception messages, and any stray IO.inspect/1.
See references/erlang-ports.md for a deny example and a minimal allowlist helper.
Note: Name and Val must be Erlang strings (charlists). Binaries raise ArgumentError — unlike :cd, :args, and :arg0, whose typespecs explicitly allow binary(), the :env typespec does not. Convert with String.to_charlist/1. System.cmd/3 differs: it accepts binaries and takes nil (not false) as its unset marker, converting both before reaching the port.
Windows Batch File Injection
On Windows, spawning .bat or .cmd files via :spawn passes through cmd.exe, which has its own injection vectors. Use explicit executable paths and validate all arguments.
Testing Port-Based Code
Mock the Port Interaction
Test the GenServer wrapper by sending fake port messages directly:
defmodule MyApp.ExternalWorkerTest do
use ExUnit.Case, async: true
test "call sends to port and returns response" do
{:ok, pid} = MyApp.ExternalWorker.start_link([])
# Retrieve the port from state for inspection
%{port: port} = :sys.get_state(pid)
# Simulate the port sending a response
fake_response = :erlang.term_to_binary({:ok, "result"})
send(pid, {port, {:data, fake_response}})
# Verify state updated (caller cleared)
%{caller: nil} = :sys.get_state(pid)
end
test "handles port exit" do
{:ok, pid} = MyApp.ExternalWorker.start_link([])
ref = Process.monitor(pid)
%{port: port} = :sys.get_state(pid)
send(pid, {port, {:exit_status, 1}})
assert_receive {:DOWN, ^ref, :process, ^pid, {:port_exited, 1}}
end
end
Integration Test with a Real Port
For integration tests, use a real external program:
test "communicates with cat process" do
port = Port.open({:spawn_executable, "/bin/cat"}, [:binary, :stream])
Port.command(port, "hello")
assert_receive {^port, {:data, "hello"}}, 1_000
Port.close(port)
end
Use assert_receive with a timeout rather than bare receive in tests to avoid hanging on failure.
Common Pitfalls
Orphan processes on VM crash: If the BEAM VM is killed with SIGKILL (not SIGTERM), external port processes may not receive SIGTERM and can persist. Design external programs to detect closed stdin and exit.
Charlists vs binaries: Without :binary, data arrives as charlists (lists of integers). Always use :binary unless working with legacy code that expects charlists.
Assuming {:env, list} sandboxes the child: it extends the environment rather than replacing it, so the spawned process inherits everything the BEAM holds no matter how short the list is. Withholding a variable requires naming it explicitly with false. See the Security section.
Blocking the GenServer: A GenServer that sends a command and awaits a reply synchronously in handle_call will block the entire GenServer during the wait. The pattern above avoids this by storing the from and replying in handle_info.
Not monitoring the port: Without Port.monitor/1 or :exit_status, a silently exiting external process leaves the GenServer in a state where it will never receive a reply.
Packet mode mismatch: If the Elixir side uses {:packet, 4} but the external program uses a different framing, all messages will be corrupted or silently dropped. Verify the framing protocol matches on both sides.
References
See references/erlang-ports.md for:
- Complete
open_port/2Erlang option reference - Binary protocol wire format and byte calculations
erl_interface/eiC library overview- Port driver architecture (linked-in drivers)
- ERTS scheduling and backpressure options
Anti-Fabrication
Verify all port behavior claims through tool execution. Use Port.info/1 to confirm port state before asserting properties. Run actual port commands and check exit statuses rather than assuming behavior. Reference core:anti-fabrication for the complete validation methodology.
Key Principles
- Use
:spawn_executable: Avoid shell injection by passing arguments directly - Wrap ports in GenServer: Follow OTP patterns for lifecycle management and supervision
- Monitor the port: Use
Port.monitor/1to detect unexpected port closure - Use
{:packet, N}for framing: Stream mode requires external framing logic - Design for orphan processes: External programs should detect stdin closure and exit
- Test with
assert_receive: Avoid barereceivein tests to prevent hangs - Prefer Port over NIF for isolation: NIF crashes bring down the entire VM
Elixir Style and Conventions
This skill complements elixir:anti-patterns — that skill covers what to avoid; this one covers what to do instead.
Tagged Tuples and Return Conventions
Elixir functions signal success or failure through return values, not exceptions.
Standard return shapes:
# Two-element ok/error tuples (most common)
{:ok, result}
{:error, reason}
# Bare atoms for side-effect operations
:ok
:error
# Richer error tuples for typed failures
{:error, :not_found}
{:error, :unauthorized}
{:error, %Ecto.Changeset{}}
Why this convention matters:
Pattern matching on tagged tuples is the foundation of Elixir error handling. When every function in a call chain returns {:ok, _} or {:error, _}, with expressions can thread success values through and exit early on the first failure — without nested if or try/rescue.
# Callers can match exhaustively
case fetch_user(id) do
{:ok, user} -> render_profile(user)
{:error, :not_found} -> send_resp(conn, 404, "Not found")
{:error, reason} -> send_resp(conn, 500, inspect(reason))
end
Logger over IO.puts
All application output goes through Logger. Do NOT use IO.puts/1, IO.write/1, or :io.format/2 from application code. Logger respects log levels, supports metadata, and routes through the configured backends (console, file, structured log shippers). IO.puts writes directly to stdout regardless of log level and bypasses backend configuration.
# WRONG — IO.puts("worker started")
# CORRECT
Logger.info("worker started")
Logger.info("worker started", worker_id: id, module: __MODULE__)
Flush concerns at shutdown go through Logger configuration (Logger.flush/0 in an at_exit, or the :logger_std_h flush settings), not by bypassing Logger to write directly. The only legitimate use of IO in app code is reading from / writing to a specific IO device the user requested (e.g., a CLI tool's stdout output, where the OUTPUT IS the contract).
Bang Functions: When to Avoid
The Convention
Every standard library function with a ! variant follows this contract:
| Non-bang | Bang |
|---|---|
File.read/1 → {:ok, content} or {:error, reason} | File.read!/1 → content or raises |
Map.fetch/2 → {:ok, value} or :error | Map.fetch!/2 → value or raises KeyError |
Repo.insert/1 → {:ok, struct} or {:error, changeset} | Repo.insert!/1 → struct or raises |
Repo.get/2 → struct or nil | Repo.get!/2 → struct or raises Ecto.NoResultsError |
When Bangs Are Appropriate
Use bang functions when failure represents a programming error or an invalid system state that should crash loudly:
# Application startup — missing config is a bug, not a user error
def start(_type, _args) do
api_key = Application.fetch_env!(:my_app, :stripe_api_key)
# ...
end
# Seeds and migrations — invalid data is a developer error
Repo.insert!(%User{email: "admin@example.com", role: :admin})
# Pipelines operating on already-validated, known-good data
"hello world"
|> String.split()
|> Enum.map(&String.capitalize/1)
|> Enum.join(" ")
# Tests asserting expected state
user = Repo.get!(User, user_id)
When to Avoid Bangs
Avoid bang functions wherever failure is a normal, expected outcome:
# BAD: user input can always fail validation
def create_user(conn, %{"user" => params}) do
user = Repo.insert!(%User{email: params["email"]}) # raises on validation failure
json(conn, %{id: user.id})
end
# GOOD: handle the error path explicitly
def create_user(conn, %{"user" => params}) do
case %User{} |> User.changeset(params) |> Repo.insert() do
{:ok, user} -> json(conn, %{id: user.id})
{:error, changeset} -> conn |> put_status(422) |> json(changeset_errors(changeset))
end
end
# BAD: external APIs can return 404, 500, network errors
def fetch_payment(payment_id) do
Stripe.PaymentIntent.retrieve!(payment_id) # raises on API error
end
# GOOD: return a tagged tuple, let the caller decide
def fetch_payment(payment_id) do
case Stripe.PaymentIntent.retrieve(payment_id) do
{:ok, payment} -> {:ok, payment}
{:error, %{code: "resource_missing"}} -> {:error, :not_found}
{:error, reason} -> {:error, reason}
end
end
Rule of thumb: if a user action, external service, or DB constraint could cause the failure, use the non-bang variant and handle it.
Pattern Matching for Error Handling
with for Chaining Dependent Operations
Use with when multiple steps must all succeed, and any failure should short-circuit to an error response:
def register_user(params) do
with {:ok, validated} <- validate_registration_params(params),
{:ok, user} <- create_user(validated),
{:ok, _profile} <- create_default_profile(user),
{:ok, _email} <- send_welcome_email(user) do
{:ok, user}
else
{:error, %Ecto.Changeset{} = cs} -> {:error, {:validation_failed, cs}}
{:error, :email_unavailable} -> {:error, :email_taken}
{:error, reason} -> {:error, reason}
end
end
The else block is optional. Without it, unmatched patterns in with clauses propagate the first failing value as the return value of the entire expression.
Keep with flat. Nesting with inside with is a sign the function is doing too much:
# BAD: nested with — hard to follow
with {:ok, user} <- fetch_user(id) do
with {:ok, order} <- fetch_order(user, order_id) do
{:ok, {user, order}}
end
end
# GOOD: flat with
with {:ok, user} <- fetch_user(id),
{:ok, order} <- fetch_order(user, order_id) do
{:ok, {user, order}}
end
case for Single-Expression Branching
Use case when branching on one expression with multiple outcomes:
def handle_webhook(event_type, payload) do
case event_type do
"payment.succeeded" -> handle_payment_succeeded(payload)
"payment.failed" -> handle_payment_failed(payload)
"customer.created" -> handle_customer_created(payload)
unknown -> Logger.warning("Unhandled webhook: #{unknown}")
end
end
Multi-Clause Function Heads
Use multi-clause functions for structural dispatch — matching on the shape or value of arguments:
defmodule MyApp.Notifier do
def notify(%User{email: nil} = user, _message) do
Logger.warning("No email for user #{user.id}, skipping notification")
{:error, :no_email}
end
def notify(%User{} = user, message) do
Mailer.deliver(to: user.email, body: message)
end
def notify({:admin, email}, message) do
Mailer.deliver(to: email, subject: "[ADMIN] " <> message.subject, body: message)
end
end
Avoid try/rescue for Expected Errors
try/rescue is reserved for exceptions from code outside your control (third-party libraries that raise instead of returning error tuples). It is not idiomatic for expected application errors:
# BAD: using rescue for control flow
def parse_integer(str) do
try do
{:ok, String.to_integer(str)}
rescue
ArgumentError -> {:error, :invalid_integer}
end
end
# GOOD: use functions that return ok/error tuples
def parse_integer(str) do
case Integer.parse(str) do
{value, ""} -> {:ok, value}
_ -> {:error, :invalid_integer}
end
end
Ecto as Data Shape Gatekeeper
Validate data once, at the changeset layer — schema defines shape, changeset validates, the
context/controller route on {:ok, _} / {:error, changeset}, and the form template renders
changeset errors directly. Includes the duplicated-validation anti-pattern and cast vs
change. This is the duplicated surface the dedicated /elixir:ecto skill already owns in
depth; see references/ecto-data-shapes.md.
Embedded Schemas for Non-DB Data
Non-DB data (search forms, filter panels, API query params) still gets full changeset
validation via embedded_schema or a schemaless changeset — a continuation of the gatekeeper
principle above: see references/ecto-data-shapes.md.
Pipe Operator Conventions
When to Pipe
Pipe when chaining data transformations where each step passes its result to the next:
# Good use of pipe: transforming a value through a sequence of steps
def normalize_email(email) do
email
|> String.trim()
|> String.downcase()
|> String.replace(~r/\+.*@/, "@")
end
When Not to Pipe
Avoid piping a single function call — it adds visual noise without clarity benefit:
# BAD: unnecessary pipe
result = value |> some_function()
# GOOD: direct call
result = some_function(value)
Avoid piping side effects that don't transform data:
# BAD: pipe into a side effect
user |> send_welcome_email()
# GOOD: explicit call
send_welcome_email(user)
Map and Struct Access
Elixir provides two access patterns with different semantics:
# Dot access — raises KeyError if key missing
# Use for required fields on known structs
user.email # raises if :email key not present
config.timeout # use when the field must exist
# Bracket access — returns nil if key missing
# Use for optional fields on dynamic maps
params[:email] # returns nil if missing, no crash
opts[:timeout] # safe for optional config keys
Struct fields always use dot access — structs enforce their shape at compile time, so a missing key is a programming error:
# Always use dot access for structs
%User{} = user
user.email # correct
user[:email] # valid but unusual — prefer dot for structs
Dynamic maps from external sources use bracket access for optional fields:
def build_query(filters) do
base_query = from(u in User)
base_query
|> maybe_filter_role(filters[:role])
|> maybe_filter_after(filters[:created_after])
end
Anti-Fabrication
Apply core:anti-fabrication when generating code examples or making claims about library behavior. Verify function signatures and return types against actual documentation. Do not fabricate error codes, changeset validator names, or Ecto API details.
Key Principles
- Return
{:ok, result}/{:error, reason}tuples to enable exhaustive pattern matching - Use bang functions only when failure indicates a programming error or invalid system state
- Use
withfor multi-step operations where each step depends on the previous - Let the Ecto changeset own all data validation — do not duplicate it in controllers or LiveView
- Use
embedded_schemaor schemaless changesets for non-DB data that still needs validation - Pipe for transformation chains; call directly for single operations and side effects
- Reserve
try/rescuefor third-party code that raises; use tagged tuples for your own error paths
Elixir Testing with ExUnit
This skill activates when writing, organizing, or improving tests for Elixir applications using ExUnit and related testing tools.
ExUnit Basics
Test Module Structure
defmodule MyApp.MathTest do
use ExUnit.Case, async: true
describe "add/2" do
test "adds two positive numbers" do
assert Math.add(2, 3) == 5
end
test "adds negative numbers" do
assert Math.add(-1, -1) == -2
end
test "adds zero" do
assert Math.add(5, 0) == 5
end
end
describe "divide/2" do
test "divides two numbers" do
assert Math.divide(10, 2) == 5.0
end
test "returns error for division by zero" do
assert Math.divide(10, 0) == {:error, :division_by_zero}
end
end
end
Assertion patterns and the full setup/setup_all/conditional-setup catalog live in references/exunit-reference.md.
Test Organization
Using describe blocks
Group related tests:
defmodule MyApp.UserTest do
use ExUnit.Case
describe "create_user/1" do
test "creates user with valid attributes" do
# ...
end
test "returns error with invalid email" do
# ...
end
end
describe "update_user/2" do
test "updates user attributes" do
# ...
end
end
end
Test tags
Categorize and filter tests:
@moduletag :integration
@tag :slow
test "expensive operation" do
# ...
end
@tag :external
test "calls external API" do
# ...
end
# Run only tagged tests
# mix test --only slow
# mix test --exclude external
Setup and teardown forms (setup, setup_all, describe-scoped setup, conditional setup) live in references/exunit-reference.md. Every setup that starts an owned resource or mutates shared state pairs it with on_exit(fn -> ... end) to restore it — the mechanism behind this workspace's binding test-isolation rules (restore Application.put_env, clean up Process.put keys, remove temp dirs).
Database Testing
Sandbox Mode
Configure for concurrent tests:
# config/test.exs
config :my_app, MyApp.Repo,
pool: Ecto.Adapters.SQL.Sandbox
# test/test_helper.exs
Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, :manual)
# test/support/data_case.ex
defmodule MyApp.DataCase do
use ExUnit.CaseTemplate
using do
quote do
alias MyApp.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import MyApp.DataCase
end
end
setup tags do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(MyApp.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
:ok
end
end
Test factories (ExMachina) and changeset test patterns live in references/database-testing.md.
Phoenix Testing
Controller, LiveView, and Channel test examples live in references/phoenix-testing.md.
Mocking and Stubbing
Using Mox
Define behaviors and mocks:
# Define behaviour
defmodule MyApp.HTTPClient do
@callback get(String.t()) :: {:ok, map()} | {:error, term()}
end
# In config/test.exs
config :my_app, :http_client, MyApp.HTTPClientMock
# In test/test_helper.exs
Mox.defmock(MyApp.HTTPClientMock, for: MyApp.HTTPClient)
# In application code
defmodule MyApp.UserFetcher do
@http_client Application.compile_env(:my_app, :http_client)
def fetch_user(id) do
@http_client.get("/users/#{id}")
end
end
# In tests
defmodule MyApp.UserFetcherTest do
use ExUnit.Case, async: true
import Mox
setup :verify_on_exit!
test "fetches user successfully" do
expect(MyApp.HTTPClientMock, :get, fn "/users/1" ->
{:ok, %{"name" => "Alice"}}
end)
assert {:ok, %{"name" => "Alice"}} = MyApp.UserFetcher.fetch_user(1)
end
test "handles error" do
expect(MyApp.HTTPClientMock, :get, fn _ ->
{:error, :network_error}
end)
assert {:error, :network_error} = MyApp.UserFetcher.fetch_user(1)
end
end
Stubbing Multiple Calls
test "calls API multiple times" do
MyApp.HTTPClientMock
|> expect(:get, 3, fn url ->
{:ok, %{"url" => url}}
end)
MyApp.batch_fetch([1, 2, 3])
end
Global Stubs
setup do
stub(MyApp.HTTPClientMock, :get, fn _ -> {:ok, %{}} end)
:ok
end
test "can override stub" do
expect(MyApp.HTTPClientMock, :get, fn _ ->
{:error, :timeout}
end)
# ...
end
Property-Based Testing
Property-based tests with StreamData, including custom generators, live in references/property-based-testing.md.
Testing Async and Concurrent Code
Testing Processes
test "GenServer handles messages" do
{:ok, pid} = MyApp.Worker.start_link()
MyApp.Worker.process(pid, :work)
assert_receive {:done, :work}, 1000
end
Testing Tasks
test "async task completes" do
parent = self()
Task.start(fn ->
result = expensive_computation()
send(parent, {:result, result})
end)
assert_receive {:result, value}, 5000
assert value == expected
end
Testing Race Conditions
test "concurrent updates are handled correctly" do
{:ok, counter} = Counter.start_link(0)
tasks = for _ <- 1..100 do
Task.async(fn -> Counter.increment(counter) end)
end
Task.await_many(tasks)
assert Counter.get(counter) == 100
end
Test Coverage
Generating coverage reports and configuring thresholds lives in references/exunit-reference.md.
Best Practices
Test Organization
- One test file per module:
lib/my_app/user.ex→test/my_app/user_test.exs - Use
describeblocks to group related tests - Use
test/supportfor shared test helpers - Keep tests focused on one behavior per test
Naming
- Use descriptive test names that explain what is being tested
- Start with the action being tested
- Include the expected outcome
# Good
test "create_user/1 returns error with invalid email"
test "add/2 returns sum of two positive integers"
# Avoid
test "it works"
test "test1"
Setup
- Use
setupfor common test data - Keep setup focused - don't create unnecessary data
- Use context to pass data between setup and tests
- Use factories for complex data structures
Assertions
- Prefer pattern matching over multiple assertions
- Use specific assertions (
assert_receivevsassert Process.info(...)) - Test one logical assertion per test when possible
Async Tests
# Mark tests as async when they don't share state
use ExUnit.Case, async: true
# A test that touches shared state (global config, a shared key, the
# filesystem) is not automatically an async: false candidate — isolate
# the state first (see Test Isolation below); reach for async: false
# only when isolation genuinely is not possible, e.g. real unsandboxed
# database access.
Test Data
- Use factories (ExMachina) for consistent test data
- Avoid hardcoded IDs - use factories and references
- Keep test data minimal - only what's needed for the test
- Use descriptive data that makes tests readable
External Dependencies
- Mock external APIs and services
- Use Mox for behavior-based mocking
- Stub at the boundary - don't mock internal modules
- Tag tests that require external services
Test Isolation
Non-deterministic test failures (SQLite "database busy", env-dependent, fails-locally-passes-in-CI) are broken test isolation, not runtime flakiness. Default diagnosis: shared mutable state leaking across tests, not the runtime being unreliable.
- Every test that mutates
Application.put_env/3saves and restores it insetup+on_exit. - Every test that uses
Process.put/2on a shared key cleans up inon_exit. - Every test that writes files uses a unique temp dir (
System.unique_integer([:positive])) and removes it viaon_exit. async: falseis a LAST RESORT, with a comment naming the shared state that forces it.- The determinism check varies the CONCURRENCY SHAPE, not the repetition count: run the suite normally, then again at a 2-vCPU CI runner's shape via
mix test --max-cases 4. Repeating identical runs samples the same shape N times and proves nothing. - Never rerun CI to turn a failure green. A remote-only failure is a reproduction recipe: reproduce locally at the runner's concurrency shape, fix the isolation bug, push the fix.
Debugging Tests
Running Specific Tests
# Run single test file
mix test test/my_app/user_test.exs
# Run specific line
mix test test/my_app/user_test.exs:42
# Run tests matching pattern
mix test --only integration
# Run tests excluding pattern
mix test --exclude slow
Test Output
# Add IEx.pry breakpoint
import IEx
test "debugging" do
user = build(:user)
IEx.pry() # Stops here
# ...
end
# Print during tests
IO.inspect(value, label: "DEBUG")
Failed Test Debugging
# Re-run only failed tests
mix test --failed
# Show detailed error traces
mix test --trace
# Run tests one at a time
mix test --max-cases 1
Key Principles
- Test behavior, not implementation: Test what the code does, not how it does it
- Keep tests fast: Use async tests, avoid unnecessary setup, mock slow dependencies
- Make tests readable: Use descriptive names, clear assertions, minimal setup
- Test at the right level: Unit tests for logic, integration tests for interactions
- Use factories: Consistent, reusable test data with ExMachina
- Mock at boundaries: Mock external services, not internal modules
- Property-based testing: Use StreamData for algorithmic code
- Embrace the database: Use Ecto sandbox for fast, isolated database tests
References
references/exunit-reference.md— Assertion patterns, setup/teardown forms, and coverage toolingreferences/database-testing.md— Test factories (ExMachina) and changeset test patternsreferences/phoenix-testing.md— Controller, LiveView, and Channel test examplesreferences/property-based-testing.md— StreamData property tests and custom generatorsreferences/os-subprocess-adapter.md— Elixir @callback + Mox shape for wrappingSystem.cmd/Port.opencalls behind a mockable seam; config wiring per environmentreferences/elixir-tdd-discipline.md— Elixir-specific TDD defaults:@cmd_modcompile-time seam,async: trueeverywhere, mock external boundaries (HTTP / OS / time / third-party APIs), no:integrationtags, no log noise, no error-swallowingelse _ -> :ok
Tidewave MCP Dev Tools
Tidewave is a dev tool by Dashbit that connects AI coding assistants to running Phoenix applications via the Model Context Protocol (MCP). It exposes runtime introspection tools: Ecto schemas, code execution, documentation lookup, log inspection, and SQL queries.
Current version: ~> 0.5 (v0.5.6 released 2026-03-13 — adds :extra_apps plug option)
When connected, prefer MCP tools over web fetches
When Tidewave MCP is connected to an Elixir/Phoenix project, route documentation, source, and runtime queries through the MCP tools — not WebFetch or hexdocs.pm.
get_docsinstead of WebFetch onhexdocs.pm/<package>/<Module>.htmlsearch_package_docsinstead of broader hex-doc searchesget_source_locationinstead of readingdeps/<package>/lib/...with Readexecute_sql_queryinstead of shelling intopsqlproject_evalinstead of runningiex -S mixsnippets
Why: MCP tool calls return results pinned to the exact versions in the project's mix.lock, complete in a single round-trip, and skip HTML→markdown conversion and page chrome — significantly fewer tokens per lookup than WebFetch, and the answer is guaranteed to match the running app rather than whatever version is on hexdocs.pm today.
Using tidewave in tier prompts
When a worker in a staged pipeline interacts with unfamiliar dependencies, the lead's prompt to that worker MUST explicitly direct the worker to verify dep APIs via tidewave MCP tools before stubbing or implementing.
Add this block to Tier 2 (test author) and Tier 3 (implementer) prompts when the work touches a dep not already exercised in the codebase:
## Module docs via tidewave (PREFERRED over WebFetch or guessing)
For unfamiliar deps, verify the actual API surface via tidewave MCP before stubbing or implementing:
- `mcp__tidewave-<app>__search_package_docs` (q: "<ModuleName>") — keyword search across installed package docs
- `mcp__tidewave-<app>__get_docs` (module: "<Module>", function: "<func>") — full docstrings for a specific function
Particularly important for: <list the specific deps this tier touches>.
Tidewave hits the running BEAM's loaded modules — it returns what is ACTUALLY in the dep, not what the model remembers from training data. Guessing produces code that does not compile or behaves wrong; tidewave produces code matching the real API surface.
The lead lists the SPECIFIC dep names in the prompt — abstract "use tidewave" instructions are ignored. Naming the dep (Cloak, Slipstream, Phoenix.Token, Mox, etc.) and the exact MCP tool names triggers the worker to call them.
This applies whenever a tier worker touches a dependency that:
- Is new to the codebase (not already imported / used in
lib/). - Has changed API across a recent major version.
- The worker would otherwise stub from training-data memory.
Installation
New Projects (via Igniter)
mix archive.install hex igniter_new
mix igniter.install tidewave
Existing Projects (Manual)
- Add to
mix.exs:
defp deps do
[
{:tidewave, "~> 0.5", only: :dev}
]
end
- Add plug to
lib/my_app_web/endpoint.exbefore thecode_reloading?block:
if Mix.env() == :dev do
plug Tidewave
end
if code_reloading? do
# ...existing code reload plugs...
end
- Fetch dependencies:
mix deps.get
Umbrella Projects
Apply the manual steps to the application defining the Phoenix endpoint (typically apps/your_app_web).
MCP Server Configuration
Tidewave exposes an MCP server at /tidewave/mcp on the Phoenix app's port. The transport type is HTTP (streamable) — SSE was removed in v0.4.0. Tidewave is unauthenticated; decline any "Authenticate" prompt the editor offers.
Default URL: http://localhost:4000/tidewave/mcp
See references/mcp-setup.md for verbatim setup commands and JSON config for Claude Code, Codex CLI, Gemini CLI, and opencode, an unverified Cursor/VS Code/Zed config table, plus a curl ping for raw verification and a troubleshooting table.
MCP Tools Reference
| Tool | Description |
|---|---|
project_eval | Execute Elixir code within the running application runtime |
execute_sql_query | Run SQL queries against the application database |
get_ecto_schemas | List all Ecto schema modules with their fields and associations |
get_ash_resources | List all Ash resources (when using the Ash framework) |
get_docs | Retrieve documentation for modules/functions using exact project versions |
search_package_docs | Query hexdocs.pm filtered to project dependencies (availability varies by framework) |
get_source_location | Find module/function source code file paths and line numbers |
get_models | List all application modules with their file locations |
get_logs | Access server logs; supports log level filtering (added v0.5.5) |
Note: search_package_docs may not be available in all frameworks. Verify availability for your setup.
Usage Patterns
See "When connected, prefer MCP tools over web fetches" at the top of this skill for the routing rule.
Introspect schemas before writing queries:
get_ecto_schemas → discover schema structure → execute_sql_query
Look up documentation for project dependencies:
get_docs for specific modules, search_package_docs for broader hex dependency searches
Execute and test code in the running app:
project_eval → run Elixir expressions against live application state
Plug Configuration Options
if Mix.env() == :dev do
plug Tidewave,
allow_remote_access: false,
inspect_opts: [pretty: true, limit: 50]
end
| Option | Default | Description |
|---|---|---|
allow_remote_access | false | Allow connections from non-localhost |
inspect_opts | [] | Options passed to Kernel.inspect/2 for output formatting |
team | nil | Team configuration (e.g., [id: "my-company"]) |
extra_apps | [] | Additional OTP apps to include in source/module discovery (v0.5.6+) |
CLI App (Standalone MCP Server)
The Tidewave desktop/CLI app (tidewave_app) runs a standalone MCP server without requiring a Phoenix application. Useful for containers, remote dev environments, or non-Phoenix Elixir projects.
- Default server:
http://localhost:9832 - Only allows access from the same machine by default
Installation
- Desktop app (macOS, Windows, Linux): https://tidewave.ai/install
- Development CLI:
cargo run -p tidewave-cli [-- --help]
When to Use CLI vs Phoenix Plug
| Scenario | Use |
|---|---|
| Phoenix application | plug Tidewave in endpoint.ex |
| Container/remote dev | CLI app or plug with allow_remote_access: true |
| Non-Phoenix Elixir | CLI app |
| Standalone MCP server | CLI app on port 9832 |
LiveView Debug Annotations
Enable in config/dev.exs to help Tidewave map rendered HTML back to source HEEx templates:
config :phoenix_live_view,
debug_heex_annotations: true
config :phoenix,
debug_attributes: true
Requires Phoenix LiveView v1.1+.
Security
- Dev-only: Always guard with
Mix.env() == :devoronly: :devin deps - Localhost-only: Tidewave only accepts localhost requests by default
- No production use: Tidewave exposes code execution and database access — never deploy to production
- Docker/remote dev: Set
allow_remote_access: trueonly on trusted networks - CSP: Tidewave injects
unsafe-evalinscript-srcdirectives and disablesframe-ancestorsrestrictions
Troubleshooting
MCP connection fails
- Verify Phoenix server is running:
mix phx.server - Check the port matches your configuration (default 4000)
- Try
http://127.0.0.1:4000/tidewave/mcpif IPv6 causes issues
Tools not appearing
- Confirm
plug Tidewaveis placed beforeif code_reloading?inendpoint.ex - Restart the Phoenix server after adding the plug
- Verify the dependency is installed:
mix deps.get
Claude Code authentication error
- Run
claudein your terminal and confirm authentication - Verify CLI availability:
which claude
Umbrella project issues
- Add the plug only in the endpoint of the web application
- Ensure
:tidewaveis added to the correctmix.exsin the umbrella
Rust Anti-Patterns
Catalog of Rust anti-patterns and clippy anti-idioms for reviewers and implementers actively hunting code to fix or remove. Complements /rust:troubleshooting (which teaches the idiomatic GOOD patterns) by naming the BAD patterns explicitly, with detection hints.
Sources
Rust Design Patterns book (anti-patterns, idioms) and the Clippy lint index — full attribution per entry in references/anti-patterns.md, dated URLs in sources.md.
Example
// BAD: clippy::ptr_arg — forces callers to hold an owned Vec
fn process(data: &Vec<i32>) { /* ... */ }
// GOOD: accepts a Vec, an array, or a slice via deref coercion
fn process(data: &[i32]) { /* ... */ }
The full catalog (9 entries) is in references/anti-patterns.md.
Usage Guidelines
- Scan for the pattern — check the diff or module against
references/anti-patterns.md - Confirm it's not deliberate — a
restraint:comment or documented tradeoff can justify what looks like an anti-pattern; anti-patterns are defaults to avoid, not absolute bans - Fix at the root — apply the GOOD replacement, don't just silence the lint
- Cite the source — when flagging in review, reference the anti-pattern name so the author can look it up
Anti-Fabrication
Every entry in references/anti-patterns.md cites its source URL. Do not assert a clippy lint name, its default-enabled status, or a "this catches N% of cases" claim without verifying against the linked clippy documentation — see /core:anti-fabrication.
Rust Async and Concurrency
Async functions, tokio runtime, streams, threads, channels, and shared state.
For async patterns, concurrency primitives, and shared state examples, see references/async.md.
Anti-fabrication
This skill follows core:anti-fabrication. Every claim about async/await behavior, the
tokio runtime, and std concurrency primitives is verified against the Async Book and tokio
documentation cited in sources.md — not inferred from generic familiarity with the
ecosystem. Before asserting a tokio API or concurrency behavior this skill and its
references do not cover, check the installed crate version's docs.rs page rather than
guessing.
Rust CLI Applications
Argument parsing, user-facing output, exit codes, signal handling, and subprocess testing for command-line tools.
For argument parsing, error context, output, signals, exit codes, and testing patterns, see references/cli.md.
Example
use clap::Parser;
#[derive(Parser)]
struct Cli {
pattern: String,
path: std::path::PathBuf,
}
fn main() {
let cli = Cli::parse(); // derives parsing, validation, and --help
}
The full argument-parsing, error-context, output, signals, exit-code, and testing patterns are in references/cli.md.
This skill covers CLI-specific ecosystem crates. For custom error enum design (thiserror) shared with non-CLI code, see rust:error-handling. For unit and integration test structure not specific to CLI binaries, see rust:testing.
See /core:anti-fabrication — crate versions and behavior claims in this skill are verified against crates.io and the upstream Rust CLI Book, not assumed.
Rust Error Handling
Result, Option, error propagation, and custom error types.
For Result, Option, ? operator, custom error type patterns, and the thiserror/anyhow ecosystem crates, see references/error-handling.md.
Anti-fabrication
This skill follows core:anti-fabrication. Every claim about Result/Option behavior,
the ? operator, and the thiserror/anyhow crate APIs is verified against the official
documentation and crates.io versions cited in sources.md — not inferred from generic
familiarity with the ecosystem. Before asserting an error-handling pattern or crate API this
skill and its references do not cover, check the installed crate version's docs.rs page
rather than guessing.
Rust Ownership and Borrowing
Ownership rules, borrowing, slices, and lifetimes.
For ownership rules, borrowing patterns, slices, and lifetime annotations, see references/ownership.md.
Anti-fabrication
This skill follows core:anti-fabrication. Every claim about ownership, borrowing, and
lifetime rules is verified against the official Rust Book chapters cited in sources.md —
not inferred from generic familiarity with the language. Before asserting borrow-checker
behavior this skill and its references do not cover, check the installed Rust toolchain's
documentation rather than guessing.
Rust Programming Language
Entry point for Rust development. Provides an overview and routes to focused skills.
Available Skills
This plugin provides focused skills for specific Rust topics:
- rust:ownership - Ownership rules, borrowing, slices, lifetimes
- rust:error-handling - Result, Option, ? operator, custom error types
- rust:anti-patterns - Anti-patterns and clippy anti-idioms to hunt and fix
- rust:async - Async functions, tokio, streams, threads, channels, shared state
- rust:testing - Unit tests, integration tests, cargo test, Cargo.toml, commands
- rust:troubleshooting - Best practices, common patterns, idiomatic Rust
- rust:cli - Argument parsing with clap, CLI output and progress, exit codes, testing CLI binaries
For core language features (traits, generics, collections, pattern matching), see references/language.md.
Quick Start
# Install via mise
mise use rust@latest
# Create a new project
cargo new myproject
cd myproject
# Build and run
cargo run
See templates/mise.toml for project task definitions.
Key Principles
- Ownership ensures memory safety: no garbage collector needed
- Borrow checker prevents data races: compile-time safety
- Zero-cost abstractions: high-level code compiles to efficient machine code
- Explicit over implicit: be clear about ownership, mutability, errors
- Prefer immutability: use
mutonly when needed - Use the type system: let the compiler catch errors
- Test thoroughly: tests are first-class in Rust
- Use clippy: catch common mistakes and non-idiomatic code
Anti-fabrication
This skill follows core:anti-fabrication. Every claim about Rust language behavior, the
standard library, and tooling commands is verified against the official documentation cited
in sources.md — not inferred from generic familiarity with the language. Before asserting a
language feature, API signature, or command behavior this skill and its references do not
cover, check the installed Rust toolchain's documentation (rustup doc) or crates.io rather
than guessing.
Rust Testing and Cargo
Unit tests, integration tests, Cargo.toml configuration, and common commands.
For test patterns, Cargo.toml configuration, and command reference, see references/testing.md.
Anti-fabrication
This skill follows core:anti-fabrication. Every claim about cargo test/cargo command
behavior and Cargo.toml configuration is verified against the Cargo Book cited in
sources.md — not inferred from generic familiarity with the tool. Before asserting a
Cargo command or flag this skill and its references do not cover, check cargo help or the
installed Cargo version's documentation rather than guessing.
Rust Troubleshooting
Best practices, common patterns, and idiomatic Rust.
For best practices, common patterns, and idiomatic guidelines, see references/troubleshooting.md.
Anti-fabrication
This skill follows core:anti-fabrication. Every claim about idiomatic patterns and API
guidelines is verified against the Rust API Guidelines and clippy documentation cited in
sources.md — not inferred from generic familiarity with the ecosystem. Before asserting a
clippy lint name or its default-enabled status this skill and its references do not cover,
check the clippy lint index rather than guessing.
TypeScript Language
Core TypeScript: strict mode, the type system, utility types, declaration files, and discriminated unions.
Strict Mode
strict: true in tsconfig.json is the floor for new TypeScript code in this workspace, not an opt-in extra. It is a single flag that enables a family of component flags — turn it on first, then reach for a component flag only when you need something strict doesn't cover.
{
"compilerOptions": {
"strict": true
}
}
strict enables, among others:
| Flag | What it catches |
|---|---|
noImplicitAny | A variable or parameter would be inferred as any because no annotation is present |
strictNullChecks | null/undefined stop being implicitly assignable to every type |
strictFunctionTypes | Function parameter types are checked contravariantly instead of bivariantly |
strictBindCallApply | .call/.bind/.apply are checked against the underlying function's signature |
strictPropertyInitialization | A class field must be assigned in the constructor or have a definite-assignment marker |
noImplicitThis | this inside a function with unclear context is flagged instead of defaulting to any |
alwaysStrict | Every emitted file is parsed as, and emits, ECMAScript strict mode |
useUnknownInCatchVariables | catch (e) types e as unknown, not any — forces a type check before use |
Two flags strict does not enable — they are separate opt-ins the strict family does not imply, though a current tsc --init now writes both into a fresh project's generated tsconfig.json alongside strict: true (listed under its own "Stricter Typechecking Options" heading, not inside the strict block itself):
exactOptionalPropertyTypes— an optional property (foo?: string) rejects an explicitundefinedassignment unless the type saysfoo?: string | undefined. Catches call sites that "clear" a field by writingundefinedwhen the schema meant "omit it."noUncheckedIndexedAccess— indexing into aRecord<string, T>or array by a computed key returnsT | undefinedinstead ofT, since JavaScript doesn't guarantee the key exists.
Both close real holes; both also touch a large fraction of existing index/optional-property call sites when retrofitted onto an established codebase. For a new project, accept them as part of the scaffolded default rather than deleting them — that's what tsc --init on a current release now hands you. For an existing codebase without them, treat enabling them as its own reviewed migration, not a drive-by addition alongside an unrelated change.
The Type System
Generics
A generic function or class defers a type decision to its caller instead of committing to one type or widening to any:
function firstOf<T>(items: T[]): T | undefined {
return items[0];
}
const n = firstOf([1, 2, 3]); // T inferred as number
const s = firstOf<string>(["a"]); // T explicit
Constrain a type parameter with extends when the function body needs to rely on a property existing:
interface HasLength {
length: number;
}
function longest<T extends HasLength>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
keyof combined with a second type parameter constrained to it is the standard shape for a type-safe property getter:
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Generic classes are generic only over their instance side — a static member cannot reference the class's own type parameter.
Conditional types and infer
A conditional type picks between two branches based on an extends check evaluated at the type level:
type IsString<T> = T extends string ? true : false;
infer introduces a type variable inside the extends clause and captures whatever the checked type matched there — this is how library-authored utility types extract a piece of a larger type:
type Flatten<T> = T extends Array<infer Item> ? Item : T;
type ElementOf<T extends readonly unknown[]> = T extends readonly (infer E)[] ? E : never;
Conditional types distribute over a union type parameter by default — Cond<A | B> evaluates as Cond<A> | Cond<B>. Wrap both sides in a tuple ([T] extends [U] ? ... : ...) to compare the union as one type instead of distributing across it. Distribution is usually what you want for a "filter this union" utility; non-distribution is what you want when the conditional is deciding between two shapes of the same aggregate type.
Mapped types and key remapping
A mapped type transforms every property of an existing type using the same rule:
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Partial<T> = { [K in keyof T]?: T[K] };
The as clause in a mapped type (TypeScript 4.1+) remaps the resulting key, not just its value — the standard shape for deriving a getter/setter interface or an event-name map from a data shape:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface Person { name: string; age: number; }
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }
Template literal types
Template literal types build string-literal unions the same way template literal values build strings, but at the type level — combined with as remapping above, or standalone for validating a string shape like a route pattern or a CSS unit.
type Vertical = "top" | "bottom";
type Horizontal = "left" | "right";
type Corner = `${Vertical}-${Horizontal}`;
// "top-left" | "top-right" | "bottom-left" | "bottom-right"
Utility Types
Built-in generic types the compiler ships — reach for one of these before writing a custom mapped type; most "helper type" needs are already covered.
| Utility | Does |
|---|---|
Partial<T> | Every property optional |
Required<T> | Every property required (drops ?) |
Readonly<T> | Every property readonly |
Record<K, V> | Object type with keys K, all values V |
Pick<T, K> | Subset of T limited to keys K |
Omit<T, K> | T minus keys K |
Exclude<U, M> | Union U minus members assignable to M |
Extract<U, M> | Union U narrowed to members assignable to M |
NonNullable<T> | T minus null and undefined |
Parameters<F> | Tuple of a function type's parameter types |
ReturnType<F> | A function type's return type |
InstanceType<C> | The instance type of a constructor type |
Awaited<P> | Recursively unwraps a Promise type, mirroring await |
Pick/Omit are the two to reach for first when a type needs to be "the same shape as X, minus/plus a couple of fields" — writing that mapped type by hand is the YAGNI case the ladder in /core:restraint calls out directly.
Full signatures, the string-manipulation utility types (Uppercase, Capitalize, ...), and ThisType/ThisParameterType are in references/type-system-deep-dive.md.
Declaration Files and Type-Only Imports
A .d.ts file describes the shape of JavaScript without an implementation — the mechanism that lets an untyped JS library, or a project's own public API surface, carry types without shipping .ts source:
// maths.d.ts
export function absolute(num: number): number;
export const pi: number;
import type and inline type imports mark an import as type-only, so the compiler strips it entirely at emit — no runtime module load for something only used in annotations. Prefer the inline form when a module mixes value and type exports:
import type { Cat } from "./animal.js"; // whole import is types-only
import { createCatName, type Cat, type Dog } from "./animal.js"; // mixed
export type { Cat } does the same at the export boundary. Both forms exist specifically to avoid pulling in a module at runtime just because one of its exports is used as a type — relevant to bundler tree-shaking and to breaking import cycles that only exist because of type references.
Enums, Unions, and Exhaustiveness
Prefer a union of string literals over enum for new code. A literal union has no runtime footprint, structurally matches plain strings from JSON/HTTP without a cast, and doesn't carry enum's reverse-mapping surprises for numeric variants:
type Status = "pending" | "active" | "archived"; // prefer this
enum StatusEnum { Pending, Active, Archived } // over this, for new code
A discriminated union is a union whose members share a literal-typed tag property — the tag lets the compiler narrow the whole object from one if/switch check:
interface Circle { kind: "circle"; radius: number }
interface Square { kind: "square"; side: number }
type Shape = Circle | Square;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
}
}
Add an exhaustiveness check so a new union member fails to compile instead of falling through silently at runtime:
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
default: {
const _exhaustive: never = shape;
return _exhaustive;
}
}
}
Adding a Triangle variant to Shape without a matching case now fails at compile time — shape in the default branch is no longer assignable to never.
tsconfig.json Practices
- Start from
tsc --initon a current TypeScript release rather than an old copied config — recenttsc --initoutput defaults to"strict": true,"module": "nodenext", and"moduleDetection": "force", which match modern Node/bundler resolution instead of the legacycommonjsdefault. - Set
"module"and"moduleResolution"to match the runtime, not to whatever a tutorial used —"nodenext"for a Node ESM/CJS-dual package,"bundler"when a bundler (Vite, esbuild, webpack) does resolution and TypeScript only type-checks. - Keep
include/excludenarrow —dist,node_modules, and generated output excluded explicitly rather than relying on defaults, since a stray.tsfile underdistbeing re-type-checked is a common source of duplicate-identifier errors. - One
tsconfig.jsonper emit target in a monorepo (tsconfig.build.jsonfor the compiled output, a basetsconfig.jsonfor editor/type-check-only use) via"extends", rather than one config trying to serve both.
Anti-fabrication
This skill follows /core:anti-fabrication. Every flag, utility type signature, and version number here was verified against the TypeScript Handbook (typescriptlang.org/docs/handbook) and the npm registry — see sources.md for the exact pages and access dates. Where a TypeScript release changes a flag's default or a utility type's signature, treat this skill as stale until re-verified against the current Handbook rather than assumed still accurate.
References
references/type-system-deep-dive.md— full utility type signatures, string-manipulation utility types,ThisType/ThisParameterType, and theNoInferutility type
TypeScript Linting and Formatting
ESLint + typescript-eslint for type-aware linting, Biome as a fast all-in-one alternative, Prettier for formatting, and CI wiring.
ESLint with typescript-eslint
Setup
npm install -D eslint @eslint/js typescript typescript-eslint
ESLint 9+ uses flat config (eslint.config.js / .mjs) — a plain array of config objects, not the older .eslintrc cascading-file format. npm init @eslint/config@latest scaffolds one interactively; the shape by hand:
// eslint.config.mjs
import js from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
js.configs.recommended,
...tseslint.configs.strict,
...tseslint.configs.stylistic,
{
rules: {
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
},
},
);
@eslint/js exports { meta, configs } — js.configs.recommended, not js.recommended or js.default. Running js.recommended directly fails at config-load time (Unexpected undefined config) since it resolves to undefined.
Preset selection
typescript-eslint ships three stacked preset tiers — pick a floor, don't cherry-pick individual rules out of a higher tier without understanding what the lower tier already covers:
| Preset | What it adds |
|---|---|
recommended | Rules that catch common bugs and mistakes with minimal false positives — the floor for any TypeScript project |
strict | A superset of recommended with more opinionated rules that catch bugs recommended deliberately leaves out to avoid false positives |
stylistic | Consistency rules with no bug-catching intent — naming conventions, member ordering; layered on top of either of the above, never a substitute |
Default to recommended + stylistic for most projects; reach for strict when the codebase can absorb its stricter defaults (banning // @ts-ignore without a description, disallowing certain type assertions) without a large one-off migration. This mirrors the workspace's general strictness posture (/core:security, /core:tdd CI-strictness discipline) — start strict on new code, treat loosening as the exception that needs a reason.
Type-aware rules
Some typescript-eslint rules (no-floating-promises, no-unsafe-assignment, await-thenable) require the TypeScript type checker, not just the parser — they need parserOptions.project (or projectService: true in newer configs) pointed at a tsconfig.json:
export default tseslint.config(
...tseslint.configs.strictTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
);
Type-aware linting is slower than syntax-only linting — it invokes the compiler. Scope it to source files (exclude generated output and config files) rather than running it over the whole repo, and expect it to dominate lint wall-clock time on a large codebase.
Biome
Biome is a single Rust-implemented binary that combines a linter, a formatter, and import organization — the case for reaching for it instead of ESLint+Prettier is speed and zero-config startup, at the cost of a smaller (though fast-growing) rule set and plugin ecosystem compared to ESLint's.
Setup
npm install -D -E @biomejs/biome
npx @biomejs/biome init
The -E flag pins the exact installed version — Biome's formatting output can shift between versions, so an unpinned range risks a CI failure from a formatter update alone, not a real style violation.
Commands
npx biome format --write . # formatting only
npx biome lint --write . # linting, with safe autofixes
npx biome check --write . # format + lint + import organization together
npx biome ci . # non-mutating check, exit-code gate for CI
Choosing Biome over ESLint+Prettier
Reach for Biome when starting a new project and the team values one fast tool over ESLint's larger rule/plugin ecosystem. Don't migrate an existing ESLint config with custom plugins or shareable configs to Biome as a drive-by — Biome's rule set doesn't map 1:1 to typescript-eslint's, and a migration is its own reviewed change with a real rule-parity check, not a mechanical swap.
Prettier Integration
If linting with ESLint (not Biome), keep Prettier as the formatter and ESLint focused on code-quality rules — don't run Prettier as an ESLint rule via eslint-plugin-prettier. Running formatting through the lint pipeline is slower than running Prettier directly and produces editor squiggles for pure formatting differences that autofix on save anyway.
Use eslint-config-prettier instead, which disables the ESLint stylistic rules that would otherwise conflict with Prettier's own formatting decisions:
import prettierConfig from "eslint-config-prettier";
export default tseslint.config(
// ...other configs
prettierConfig, // last — turns off conflicting stylistic rules
);
Run prettier --check . as its own CI step, separate from eslint.
Pre-Commit Hooks
npm install -D husky lint-staged
npx husky init
// package.json
{
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"]
}
}
# .husky/pre-commit
npx lint-staged
lint-staged runs the configured commands only against staged files, not the whole repo — keeps the pre-commit hook fast enough that it doesn't become the thing developers reach for --no-verify to skip. Per /core:git, skipping hooks is not something an agent does without explicit instruction; that applies to lint-staged-backed pre-commit hooks the same as any other.
CI Wiring
# mise.toml
[tasks.lint]
description = "Lint and type-check"
run = [
"npx eslint .",
"npx tsc --noEmit",
]
[tasks.format]
description = "Check formatting"
run = "npx prettier --check ."
[tasks.ci]
description = "Full CI gate"
depends = ["lint", "format", "test"]
tsc --noEmit belongs in the lint task, not the test task — a type error is a lint-time signal (it should fail fast, before tests even run) not a test-time one, and running it separately from eslint means a type error and a lint error are distinguishable in CI output.
Anti-fabrication
This skill follows /core:anti-fabrication. Commands, config shapes, and preset names were verified against each tool's own documentation (eslint.org, typescript-eslint.io, biomejs.dev, prettier.io) — see sources.md for exact pages and access dates. Rule-level behavior for any specific typescript-eslint or Biome rule not named here should be checked against that tool's rule reference before being asserted, since individual rule defaults change across releases more often than the preset structure does.
References
references/rule-catalog.md— specific typescript-eslint rules worth enabling deliberately (no-floating-promises,no-explicit-any,consistent-type-imports) with the bug each one catches
Node.js Runtime
Async patterns, streams, module systems, package managers, and mise/CI integration for Node.js TypeScript projects.
Async Patterns
async/await over raw Promise chains
async function fetchUserAndPosts(userId: string) {
const user = await fetchUser(userId);
const posts = await fetchPosts(user.id);
return { user, posts };
}
Prefer await in sequence over .then() chains for anything with more than one step — the stack trace on a rejected await points at the actual failing line, where a long .then() chain's error frequently doesn't.
Concurrency with Promise.all / Promise.allSettled
Sequential await calls that don't depend on each other's results waste wall-clock time — run independent async work concurrently:
// Sequential — unnecessarily slow if these don't depend on each other
const user = await fetchUser(id);
const settings = await fetchSettings(id);
// Concurrent — same total work, shorter wall time
const [user, settings] = await Promise.all([fetchUser(id), fetchSettings(id)]);
Promise.all rejects as soon as any one input rejects, discarding the other results. Promise.allSettled never rejects — it resolves with a { status: "fulfilled" | "rejected", ... } record per input, appropriate when partial failure is an expected, handled case (e.g. "notify five webhooks, report which ones failed") rather than a hard error.
EventEmitter
Node's EventEmitter is the base of most non-stream async Node APIs (process, net.Server, child_process) — extend it for a custom object that fires multiple named events over its lifetime, as opposed to a Promise's single resolve/reject:
import { EventEmitter } from "node:events";
class JobQueue extends EventEmitter {
enqueue(job: Job) {
// ...
this.emit("enqueued", job);
}
}
const queue = new JobQueue();
queue.on("enqueued", (job: Job) => console.log(`queued ${job.id}`));
Reach for EventEmitter for "zero or more things will happen over time, listeners subscribe/unsubscribe" — reach for a Promise for "exactly one thing happens once." Mixing the two (a Promise that also emits progress events) is a common source of Node API confusion; if progress reporting is needed, an EventEmitter combined with a distinct completion Promise (or an async generator) is clearer than overloading one Promise for both jobs.
Streams
Four stream types, all EventEmitter subclasses under the hood:
| Type | Direction | Example |
|---|---|---|
Readable | Data flows out | fs.createReadStream(), an HTTP response body |
Writable | Data flows in | fs.createWriteStream(), process.stdout |
Duplex | Both, independently | net.Socket |
Transform | Both, output derived from input | zlib.createGzip() |
Piping
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";
createReadStream("input.txt")
.pipe(createGzip())
.pipe(createWriteStream("input.txt.gz"));
.pipe() is the default choice over manual data/end event listeners — it handles backpressure automatically, which manual event handling does not.
Backpressure
A Writable.write() call returns false when its internal buffer is full — code writing directly (not through .pipe()) must pause until the stream's 'drain' event fires, or memory grows unbounded on a fast producer / slow consumer:
function writeAll(stream: NodeJS.WritableStream, data: string, done: () => void) {
if (!stream.write(data)) {
stream.once("drain", done);
} else {
process.nextTick(done);
}
}
stream.pipeline() (from node:stream/promises) is the preferred modern API over chained .pipe() calls for anything that needs error propagation across the whole chain — a .pipe() chain does not automatically forward an error from an earlier stream to destroy later ones, pipeline() does.
ESM vs CommonJS
"type" field
{ "type": "module" }
"module"—.jsfiles are ES modules (import/export)"commonjs"or omitted —.jsfiles are CommonJS (require/module.exports).mjsis always ESM and.cjsis always CommonJS, regardless of"type"— use the explicit extension when a package needs to ship both formats in adjacent files.
Default new projects to "type": "module" — ESM is where the Node and browser ecosystems converge, and tsc --init on a current TypeScript release defaults "module" to "nodenext", which follows this field.
exports field
exports is both an encapsulation boundary (only listed paths are importable from outside the package — deep imports into unlisted internal files fail) and the mechanism for dual ESM/CJS publishing via conditional exports:
{
"name": "my-package",
"type": "module",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./utils": {
"import": "./dist/utils.mjs",
"require": "./dist/utils.cjs"
}
}
}
Node evaluates conditions in the order they're written in the object — first matching key wins, not some engine-enforced specificity ranking. Author them most-specific-first (node-addons, then node, then import/require, then default last) as a matter of convention, because listing a broader condition earlier would shadow every narrower one written after it and it would never be reached. "default" always goes last for the same reason: it matches everything, so anything after it is dead. Keep a top-level "main" pointing at the CJS build alongside "exports" only for consumers on Node versions old enough not to read exports — new projects that don't need that floor can rely on exports alone.
Package Managers
| Tool | Reach for it when |
|---|---|
| npm | The default — ships with Node, needs no extra install, fine for most single-package projects |
| pnpm | A monorepo, or disk/install-speed matters — content-addressable store avoids per-project dependency duplication, and its non-flat node_modules (symlinks, not hoisting) catches undeclared-dependency bugs npm's flat hoisting hides |
| Bun | The whole toolchain (runtime + package manager + test runner + bundler) is being adopted, not just the installer — Bun's bun install is fast, but picking Bun-the-package-manager while running Node-the-runtime forfeits most of its advantage |
Bun ships as a single dependency-free binary combining a JavaScriptCore-based runtime (a drop-in Node replacement, still working toward full Node API parity), bun install, bun test (Jest-compatible), and bun build. It executes .ts/.tsx directly without a separate compile step. Node compatibility is an ongoing effort, not a guarantee — verify a specific Node API/package works under Bun before committing a production service to it, rather than assuming parity.
Restraint applies to this choice directly: don't add pnpm to a single-package project that npm already handles, and don't adopt Bun for one fast test runner when the rest of the deployment target is Node.
mise Integration
# mise.toml
[tools]
node = "24" # fuzzy — tracks the latest 24.x patch/minor
# node = "24.1.2" # --pin exact, for reproducible CI
[tasks.dev]
run = "node --watch src/index.ts"
[tasks.build]
run = "tsc -p tsconfig.build.json"
Pin the Node major to whichever release is Active LTS at the time (see sources.md for the version verified for this skill) — new projects should not start on a Current (non-LTS) release line, since Current releases have a shorter support window and are more likely to carry breaking changes between minors. mise install inside a freshly cloned repo installs the pinned version with no separate nvm/fnm step, consistent with /core:mise's "mise, not brew" convention for this workspace's tool management.
CI/CD Patterns
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: jdx/mise-action@v3
- run: mise run ci
Delegate to mise run ci from the CI workflow rather than duplicating individual npm run lint / npm test steps in YAML — the local and remote invocations then run the exact same command, so "passes locally, fails in CI" collapses to an environment difference (Node version, missing env var) instead of a command drift, per this workspace's /core:git Gate 2 discipline (local mise run ci green is a precondition for remote CI being meaningful, not a redundant check).
Anti-fabrication
This skill follows /core:anti-fabrication. Stream types, backpressure behavior, and exports/type field semantics were verified against the Node.js API docs (nodejs.org/api) and the current Active LTS/Current release lines from nodejs.org/en/about/previous-releases; package manager claims were verified against each tool's own docs (pnpm.io, bun.sh/docs). See sources.md for exact pages and access dates. Bun's Node-compatibility status changes release to release — treat any specific "Bun supports X Node API" claim as needing a fresh check against bun.sh/docs/runtime/nodejs-compat, not this skill.
References
references/module-resolution.md—moduleResolutionstrategies (node16/nodenext/bundler), the dual-package hazard, and subpath import patterns (#internal/*)
TypeScript Testing
Vitest and Jest for unit/integration tests, Playwright for end-to-end, type-level testing, coverage, and CI wiring.
Choosing Vitest vs Jest
Both are viable; the deciding factor is the rest of the toolchain, not raw feature count.
- Vitest reads the project's existing Vite config and reuses its transform pipeline, so a Vite-based app (React/Vue/Svelte via Vite, or a Vite-built library) gets test config for near-free. Vitest requires Vite ≥6 and Node ≥20. Its API is Jest-compatible (
describe/test/expect/vi.fn()), so migrating an existing Jest suite is mostly a find-and-replace of the mock namespace. - Jest is the default for a project with no Vite in its pipeline — plain Node libraries, Next.js (which documents first-class Jest support), or a codebase already standardized on Jest tooling (snapshot serializers, custom matchers written against Jest's APIs). TypeScript support comes via
ts-jest(type-checks as part of the test run) or Babel (transpile-only, faster, no type errors caught).
Restraint applies here directly: don't add Vitest to a project that already has a working Jest suite just because Vitest is newer, and don't bolt Jest onto a Vite app that would get Vitest for free.
Vitest
Setup
npm install -D vitest
No separate config file is required — Vitest reads vite.config.ts by default. Add a dedicated vitest.config.ts only when test-specific settings (environment, coverage thresholds, setup files) would otherwise clutter the Vite config:
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node", // or "jsdom" / "happy-dom" for DOM tests
globals: false, // false = import describe/test/expect explicitly (recommended)
coverage: {
provider: "v8",
thresholds: { lines: 80, functions: 80, branches: 75, statements: 80 },
},
},
});
Leaving globals: false and importing describe/test/expect/vi explicitly from "vitest" keeps test files free of ambient globals — the same reasoning as avoiding any: an explicit import is a grep target and a type-checked one.
Assertions and structure
import { describe, test, expect } from "vitest";
import { add } from "./math.js";
describe("add", () => {
test("adds two positive numbers", () => {
expect(add(2, 3)).toBe(5);
});
test("adds negative numbers", () => {
expect(add(-1, -1)).toBe(-2);
});
});
Mocking
import { vi, expect, test } from "vitest";
import { fetchUser } from "./api.js";
vi.mock("./api.js", () => ({
fetchUser: vi.fn().mockResolvedValue({ id: 1, name: "Ada" }),
}));
test("uses the mocked fetch", async () => {
const user = await fetchUser(1);
expect(user.name).toBe("Ada");
});
vi.fn() creates a spy/mock function; vi.mock(path, factory) replaces a module's exports for the whole file. vi.useFakeTimers() / vi.advanceTimersByTime(ms) control time for code under test that uses setTimeout/setInterval — mock the boundary (the module doing I/O or the clock), never the function under test itself, matching the /core:agent-loop mock-external-boundaries convention this workspace uses across languages.
Jest
Setup
npm install -D jest ts-jest @types/jest
npx ts-jest config:init
ts-jest type-checks test files as part of the run — a type error in a test fails the test run, not just tsc. The Babel path (babel-jest + @babel/preset-typescript) is faster because it strips types without checking them; pick it only when a separate tsc --noEmit step in CI already covers type-checking, so Babel isn't silently letting a type error through untested.
Basic test
// math.test.ts
import { add } from "./math";
test("adds 1 + 2 to equal 3", () => {
expect(add(1, 2)).toBe(3);
});
Mocking modules
import { fetchUser } from "./api";
jest.mock("./api");
const mockFetchUser = fetchUser as jest.MockedFunction<typeof fetchUser>;
test("uses the mocked fetch", async () => {
mockFetchUser.mockResolvedValue({ id: 1, name: "Ada" });
const user = await fetchUser(1);
expect(user.name).toBe("Ada");
});
The as jest.MockedFunction<typeof fetchUser> cast is the standard Jest+TypeScript pattern for getting mock-specific methods (mockResolvedValue, mockReturnValueOnce) on a function whose static type is the real implementation's signature.
Type-Level Testing
A test suite that only exercises runtime behavior can still ship a type regression — a generic that silently widens to any, an overload that resolves to the wrong branch. Two focused tools assert on the type, not the value:
-
expect-type— runtime-free type assertions inside a normal test file, checked bytsc, not executed:import { expectTypeOf } from "expect-type"; expectTypeOf(add(1, 2)).toEqualTypeOf<number>(); expectTypeOf<Partial<{ a: number }>>().toEqualTypeOf<{ a?: number }>();These assertions run as part of a normal
vitest/tscpass — no separate command. Vitest also ships anexpectTypeOfre-export built on the same library. -
tsd— a standalone CLI that type-checks.test-d.tsfiles against.d.tsoutput, aimed at library authors verifying their published declaration file, not internal application types:// index.test-d.ts import { expectType } from "tsd"; import { add } from "./index.js"; expectType<number>(add(1, 2));Run via
npx tsd. Reach fortsdspecifically when the thing under test is a package's public.d.ts, not its implementation —expect-typeinside the normal suite covers everything else.
Playwright (End-to-End)
Setup
npm init playwright@latest
Interactive: choose TypeScript, the test directory (default tests/ or e2e/), whether to add a GitHub Actions workflow, and which browsers to install. Produces playwright.config.ts.
Running tests
npx playwright test # headless, parallel across configured browsers
npx playwright test --headed # watch the browser
npx playwright test --project=chromium
npx playwright test --ui # interactive UI mode with time-travel debugging
npx playwright show-report # HTML report from the last run
Example test
import { test, expect } from "@playwright/test";
test("home page has expected heading", async ({ page }) => {
await page.goto("/");
await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
});
Playwright tests run against a real browser engine (Chromium/Firefox/WebKit) — treat them as the outermost layer of the test pyramid (/core:tdd "Ice Cream Cone" anti-pattern applies directly): cover behavior with fast Vitest/Jest unit tests first, and reserve Playwright for flows that only a real browser can verify (navigation, layout, cross-tab behavior).
Coverage and CI Integration
// package.json
{
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:e2e": "playwright test"
}
}
# mise.toml
[tasks.test]
description = "Run unit tests"
run = "npm run test"
[tasks."test:coverage"]
description = "Run unit tests with coverage"
run = "npm run test:coverage"
[tasks.ci]
description = "Full CI gate"
depends = ["lint", "test", "test:coverage"]
Fail CI on a coverage threshold drop, not just on a red test — set coverage.thresholds in vitest.config.ts (see the Vitest section above) so a PR that adds code without tests fails the same gate a red test would, consistent with /core:tdd "code without tests is not complete."
Anti-fabrication
This skill follows /core:anti-fabrication. Package names, CLI commands, and config shapes were verified against each tool's own documentation (vitest.dev, jestjs.io, playwright.dev) and the npm registry for version numbers — see sources.md for exact pages and access dates. expect-type and tsd API surfaces shown here are the documented public entry points (expectTypeOf, expectType); verify against the installed package version before relying on a less common assertion method not shown here.
References
references/mocking-patterns.md— timer mocking, partial module mocks, and spying on object methods in both Vitest and Jest
Zig Allocators
Memory management patterns, allocator types, and allocation lifecycle.
For allocator types, patterns, and examples, see references/allocators.md.
Anti-fabrication
This skill follows core:anti-fabrication. Verified against zig 0.16.0 (locally
installed, claude-skills-204): references/allocators.md's DebugAllocator snippets
compile and pass as zig test — this file already had the correct init form
(pub const init: Self = .{};, a value, not a function call); a contradicting
function-call form was found and fixed in the troubleshooting skill instead, not here.
Re-verify against a locally installed zig test before asserting an allocator API this
skill doesn't cover — std.heap's allocator-init pattern changed between 0.15 and 0.16.
Zig Build System
Build configuration, cross-compilation, dependency management, and CI patterns.
For detailed build.zig patterns, API methods, and examples, see references/build.md.
Anti-fabrication
This skill follows core:anti-fabrication. Verified against zig 0.16.0 (locally
installed, claude-skills-204): references/build.md's build.zig + build.zig.zon
sample builds, tests, and runs end to end, and the documented flags (--watch,
-fincremental, --time-report, -Doptimize, -Dtarget) are all present in
zig build --help — no corrections needed. Re-verify against a locally installed
zig build --help and a real build before asserting a flag or API this skill doesn't
cover — Zig is pre-1.0 and the build system has broken across minor releases before
(0.15's Writergate, 0.16's root_source_file/.fingerprint changes this file already
documents).
Zig C Interop
Importing C libraries, exporting Zig to C, type mappings, and translate-c.
For type mappings, linking patterns, and string interop examples, see references/c-interop.md.
Anti-fabrication
This skill follows core:anti-fabrication. Verified against zig 0.16.0 (locally
installed, claude-skills-204): references/c-interop.md's type mappings and linking
snippets compile as documented — no corrections needed here. A related claim, that
@cImport emits a deprecation warning, was found wrong and corrected, but that
claim lived in the troubleshooting skill's compiler-error catalog, not in this file.
Re-verify against a locally installed zig build-exe with a real C header before
asserting a type mapping this skill doesn't cover — Zig is pre-1.0 and translate-c
behavior has changed across minor releases.
Commands 15
Hooks 2
Sponsors
Details
- Marketplace
- vinnie357/claude-skills
- Category
- Meta
- License
- MIT
- Keywords
- skills, development, elixir, rust, wasm, zig, complete, all, bundle
More from vinnie357/claude-skills
All 33- alliumv0.1.3
- altanav0.1.3
- ansiblev0.1.7
- awmanv0.2.8
- beadsv0.1.10
- claude-codev0.1.11
- claudiov1.0.0
- corev0.2.93
- daguv0.1.10
- designv0.1.5
- elixirv0.1.25
- extras-claude-codev0.3.1
- githubv0.3.17
- graphifyv0.1.4
- linearv0.1.10
- playwrightv0.1.3
- pmv0.1.6
- proxmoxv0.1.1
- qav0.1.7
- rigv0.1.2
- runexv0.1.11
- rustv0.1.13
- sbxv0.1.3
- slidevv0.2.11