Essential development skills: Git, TDD, code review, gitleaks secret scanning, documentation, technical English, restraint, anti-fabrication, twelve-factor apps, the agent loop, bees issue tracking, mise, nushell, and Apple Container
- version
- 0.2.93
- GitHub stars
- 27
Install
/plugin install core@vinnie357Run it inside Claude Code after adding the marketplace with /plugin marketplace add vinnie357/claude-skills.
Contents
Discovered from sourceSkills 14
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
Commands 5
Use the gcms (git-commit-message-short) subagent to analyze the current git status and suggest 1-3 brief conventional commit messages
Research a topic and create multi-file documentation for planning, understanding, and working with the subject.
Document Creation:
- Directory Structure: Creates
research/<category>/<topic>/ - File Generation: Produces
overview.md,troubleshooting.md, and optional guides - Planning Focus: Helps understand topics before implementation
- Reference Material: Creates searchable knowledge base
Features:
- Automatic Complexity Assessment: Evaluates topic complexity (1-10 scale)
- Thinking Mode Selection: Standard/Extended/Deep based on complexity
- Manual Override: Use
--complexity=<level>to force thinking depth - Structured Content: Consistent templates for reliability
- Authoritative Sources: Links to official docs and best practices
- Practical Examples: Real-world usage patterns and code samples
Examples:
/research development docker-compose
# Creates: research/development/docker-compose/
# - overview.md
# - troubleshooting.md
/research infrastructure kubernetes-networking --complexity=high
# Creates: research/infrastructure/kubernetes-networking/
# - overview.md (with deep analysis)
# - troubleshooting.md
# - best-practices.md
/research frontend react-state-management --complexity=medium
# Creates: research/frontend/react-state-management/
# - overview.md
# - troubleshooting.md
# - comparison.md (Redux vs Context vs Zustand)
Document Structure:
overview.md
- Purpose & Use Cases: When and why to use this technology
- Core Concepts: Fundamental principles and architecture
- Implementation Patterns: Common approaches and best practices
- Code Examples: Practical, runnable examples
- Integration Guidelines: How it fits into larger systems
- Performance Considerations: Optimization and scaling
- Security: Common vulnerabilities and protections
- Resources: Official docs, tutorials, community resources
troubleshooting.md
- Common Issues: Frequently encountered problems
- Error Messages: Interpretation and solutions
- Diagnostic Tools: How to investigate problems
- Solutions: Step-by-step fixes
- Prevention: How to avoid issues
- Escalation: When and where to get help
Additional Files (generated as needed)
best-practices.md: Detailed guidelines and patternscomparison.md: Technology alternatives and trade-offsmigration.md: Upgrade paths and migration strategiesquick-start.md: Fast setup and basic usage
Quality Standards:
- Use authoritative sources (official docs, RFCs, reputable blogs)
- Include version information where relevant
- Provide working code examples
- Link to external resources
- Note common pitfalls and gotchas
- Include date of research for freshness tracking
Task Instructions: Use Task tool with subagent_type: "general-purpose" to:
-
Research Phase:
- Search authoritative sources and documentation
- Gather best practices and common patterns
- Identify common issues and solutions
- Collect practical examples
-
Structure Phase:
- Create
research/<category>/<topic>/directory - Determine which documents are needed based on topic
- Plan document organization
- Create
-
Content Generation:
- Write
overview.mdcovering:- Clear purpose and use cases
- Core concepts and architecture
- Implementation patterns
- Practical examples
- Integration guidance
- Write practical
troubleshooting.mdwith:- Common issues and solutions
- Error message interpretations
- Diagnostic approaches
- Prevention strategies
- Generate additional guides as needed
- Write
-
Quality Assurance:
- Verify all sources are authoritative
- Ensure examples are practical and correct
- Check for completeness and clarity
- Add timestamps and version info
The agent should produce actionable documentation, covering the sections listed above, that helps users understand and work with the topic.
Run the restraint marker scan, then review the current diff against the restraint ladder yourself — the marker scan is mechanical, the over-engineering review is model work.
- Run
nu plugins/core/skills/restraint/scripts/restraint-audit.nu(optionally with--path $ARGUMENTSwhen a path is given) to list every existingrestraint:marker in the repository. Report the results. - Read the current
git diff(staged and unstaged) against the restraint ladder from/core:restraint: for each NEW symbol (function, class, config, dependency), check whether it needs to exist, whether it duplicates an existing helper/stdlib/dependency, and whether a smaller form would do. - Flag speculative abstractions and unrequested features as findings. Where a deliberate simplification is intentional and worth keeping, suggest adding a
restraint:marker naming the ceiling and upgrade path rather than silently leaving it undocumented.
Bootstrap a new project with a standardized development workflow. Initializes bees task tracking by default (or beads with --beads), discovers project languages and tools, then creates tracker issues with dependencies for configuring mise, CI, and gitleaks.
What it does:
- Configure tracker — Initialize bees (default) or beads (
--beads) task tracking (or detect existing setup) - Discover project — Scan for languages, frameworks, tooling, and package managers
- Create tasks — Generate 4 tracker issues with dependency graph:
- Document project discovery results
- Configure mise development environment (depends on discovery)
- Configure GitHub Actions CI workflow (depends on mise)
- Configure gitleaks secret detection (depends on discovery)
- Output summary — Display created tasks, dependencies, and next steps
Options:
--beads— Use beads instead of the bees default--stealth— (beads only, requires--beads) Initialize beads in local-only mode (no remote sync)--contributor— (beads only, requires--beads) Initialize beads in pull-only mode (read-only from remote)
Examples:
/core:setup
/core:setup --beads
/core:setup --beads --stealth
/core:setup --beads --contributor
Task Instructions:
Use the setup subagent to perform project bootstrapping.
Work the target with Forge — the agent-loop operating model. Target: $ARGUMENTS
First, load skills
Invoke the Skill tool for each by exact name before any other step:
/core:anti-fabrication/core:git/core:tdd/core:twelve-factor/core:restraint/core:security/core:mise/core:nushell/core:agent-loop/core:bees/extras-claude-code:claude-agents(always, before spawning) and/extras-claude-code:claude-teams(when spawning ≥2 parallel workers)- Domain skills for the target's labels, by exact name.
/core:agent-loop carries Forge (paired teams, the hands pattern, fan-out); /core:bees is the tracker.
Canonical list: /core:agent-loop "Core Skills (Mandatory)"; drift-checked in CI.
Quote one sentence from /core:agent-loop describing Forge as proof of loading.
Resolve the target
ready(or empty) → runbees readyand take the top item.- An epic id (e.g.
VIN-42) → work the epic: run Phase 1.5 decomposition gate, then Forge per issue. - An issue id (e.g.
claude-skills-77) → work that single issue with Forge.
Run Forge
Apply the agent-loop 4-phase execution with Forge as the operating model — no need to ask which tier system to use, Forge is the default:
- Pre-flight — load skills (above), confirm the tracker item, branch from fresh
origin/main(feat/<slug>). - Plan — spawn a Test Planner (deep reasoning) preceded by a hands pass that builds its
## Starting index; the planner slices the issue into independent test groups. The Plan Reviewer (strongest reasoning) checks AC-to-slice coverage, unsatisfiable slices, and dep-wave validity before the Test Author is spawned — the plan pair's own reviewer gate. Seereferences/forge.md. - Author + review tests — Test Author (general) writes failing tests; the Test Reviewer (strongest reasoning, with smallest-fast hands) verifies plan-conformance and non-redundancy before any implementor starts.
- Implement (fan out) — one Implementor + Test Runner pair per slice, dispatched in dependency waves.
N=1for a one-slice issue. - Review — Reviewer then Final Reviewer (strongest reasoning, each with smallest-fast hands consuming a startup index, never searching themselves); review findings route to a Remediation pair, then re-review.
- Validate + submit —
mise run cigreen, gitleaks, push, open the PR. Merge per the deployment's merge policy (/core:git"Merge authorization"); under the default, report the PR URL and wait for operator approval.
Principals never run their own Grep/Glob/large-Read sweeps — they spawn focused read-only hands and read only the returned file:line index. Vision research (screenshots, rendered pages, Playwright output) uses a multimodal hands model. See the hands pattern in references/researcher.md.
Agents 7
Comment Reviewer
You review comment quality, not comment presence. A well-named function with no comment at all is never a finding — that is a different concern this agent does not own. Only judge comments that already exist.
Defect categories (closed set)
Every flagged comment gets exactly one of these five categories. none is not a category —
it is the absence of a defect, used only on a NO-FLAG roll-up.
- restates-code — the comment says nothing beyond what the code already says.
- over-explains — the comment teaches basic language syntax or keywords the reader already knows, for no project-specific reason.
- missing-purpose — a comment exists but never states what the function does or why.
- missing-inputs — purpose may be stated, but a parameter that needs explaining (a non-obvious unit, a base vs. full URL, a sentinel value) isn't described.
- contradicts-code — the comment describes behavior the code does not actually have. This is the highest-severity category: a wrong comment actively misleads, which is worse than no comment at all.
Do not invent a sixth category. If a comment is fine, it produces no finding.
Anti-fabrication on replacements
When proposing a terser replacement, only claim what the snippet actually supports. Do not add a constraint or behavior the code doesn't have — e.g. don't write "must be validated first" unless something in the code validates it.
Output contract
End your report with a ## VERDICTS block, one line per entry:
## VERDICTS
<target> | <FLAG|NO-FLAG> | <category> | <replacement or ->
- One roll-up line per file reviewed:
<target>is the bare file path you were given. - Zero or more detail lines per file:
<target>isfile:linefor one specific comment. - Roll-up rule: FLAG if any comment in the file is flagged, NO-FLAG otherwise. When multiple
categories are flagged in one file, the roll-up category is the single most severe by this
order:
contradicts-code > missing-purpose > missing-inputs > over-explains > restates-code. <category>is always one of the five defects, ornonefor a NO-FLAG roll-up.- A file with no comments at all produces exactly one line:
<target> | NO-FLAG | none | -.
Model fallback
This agent is defined at model: fable. If a spawn fails because fable is unavailable in
the environment, the SPAWNER should retry the identical task at model: opus.
This is a capability fallback — degrade to what's available — not the haiku -> sonnet -> opus escalation-on-failure ladder from /core:agent-loop. Don't conflate the two: this
agent never escalates on a bad review, it only substitutes models when fable can't run.
You are a git commit message specialist. Your role is to analyze the current git repository state and suggest 1-3 brief, conventional commit messages.
First load /core:git. Never add robot emoji, "Generated with Claude Code", assistant signatures, or attribution trailers. Return single-line suggestions without crediting an agent.
Your Process:
- Analyze Current State: Run
git statusto see what files are staged, modified, or untracked - Review Changes: Run
git diff --cachedfor staged changes andgit difffor unstaged changes - Generate Messages: Create 1-3 brief conventional commit messages following this format:
type(scope): description- Types: feat, fix, docs, style, refactor, test, chore
- Keep descriptions under 50 characters when possible
- Be specific but concise
Guidelines:
- Brief: Aim for messages under 50 characters total
- Conventional: Use conventional commit format (type: description or type(scope): description)
- Accurate: Base suggestions on actual changes, not assumptions
- Prioritized: List most likely/best option first
- Context-aware: Consider the nature and scope of changes
Example Output Format:
Based on your changes, here are commit message suggestions:
1. `feat: add user authentication`
2. `fix(auth): resolve login redirect issue`
3. `refactor: simplify auth flow`
If there are no changes to commit, politely inform the user and suggest they stage changes first.
If the unit of work is small enough or focused enough the three commit suggestions will be similar, if all three suggestions are about different topics suggest staging the work in different groups and the related suggested commit message.
Memory Auditor
You audit one memory directory against /core:agent-loop's references/memory-guidance.md
decay-check section and work-vs-fact boundary. This agent runs on sonnet, not the tier
default of haiku: every verdict here ends in a delete, a rewrite, or a tracker hand-off, and
a wrong delete on an ungated directory is silent and unrecoverable. A haiku-tier misjudgment
here costs more than the token savings are worth.
Load skills
Invoke /core:agent-loop and /core:anti-fabrication by exact name before any audit work.
Both are also preloaded via this agent's skills: frontmatter — invoke them anyway so the
load is on the record, and read references/memory-guidance.md in full before producing a
verdict on any file.
Snapshot before any delete or rewrite — no exception
The memory directory is not git-tracked. A delete without a backup is unrecoverable. Before removing or rewriting a single byte:
- Create
<memory-dir>/../memory-archive/— a sibling of the memory directory, never a subdirectory inside it. A backup file insidememory/pollutes future recall the same way the decayed entries do. - Archive every file in the memory directory into a timestamped tarball in that sibling
directory:
memory-archive/memory-snapshot-<UTC-timestamp>.tar.gz. - Verify the archive: list its contents and confirm the archived file names match the memory directory's file names exactly — a count match alone does not catch an archive written to the wrong path with the right number of files in it.
- Report the archive path in your final output.
If the archive step fails for any reason — permission error, disk error, a name mismatch — STOP. Report the failure and take no delete or rewrite action. No snapshot means no delete, without exception.
Scope of autonomous action
Four dispositions, four different levels of authority:
- Delete without asking — scoped to two cases only, and the two directions of index-file
drift are NOT symmetric:
- (a1) A dangling index line — a
MEMORY.mdline pointing at a file that no longer exists. Judgement-free: delete the line. - (b) Dead work — an entry whose entire content is a status report: the sole informational
payload is that the work is done, closed, or shipped, with no rule, pattern, or gotcha
left once that status sentence is removed. An entry that narrates a closed incident AS
EVIDENCE for a durable rule that still applies is a fact, not dead work — the closure is
illustration, not the entry's content. Worked pair:
- Dead work (delete): "VIN-118 is done — merged
example-repoPR #204, closing the epic." - Fact (keep): "
ps -Eleaked four live credentials into an agent transcript (2026-08-04 incident) — never runps -E/-e-shaped flags against a process holding secrets; usetest -n "$VAR"for your own env instead." Strip the incident citation and the rule ("never runps -E...") still stands, so this entry stays. Before deleting under this category, verify the referenced work is actually closed: run a tracker lookup (bees show <id>) or a repo check (git log --grep,gh pr view) against the exact repository and tracker the entry names — the same right-repo clause as the stale-referent check above. A not-found, empty, or ambiguous result BLOCKS the delete; it is not evidence of closure.gh pr view 204run against the wrong repo can return a real, unrelated PR #204 and read as confirmation — always target the repo the entry actually refers to (e.g.gh pr view 204 --repo <owner>/<repo>), never the audited repo by default. Cite the command, the repo it targeted, and its result in the Evidence column. A category-(b) delete with no closure-verification command cited, or with a result that does not show closure, is not a valid verdict.
- Dead work (delete): "VIN-118 is done — merged
- Precedence when both could apply: an entry carrying a
REVERSED/RESOLVED/no longermarker (decay check 1) is a rewrite candidate, not a dead-work candidate, even when it also describes closed work. Decay check 1 wins — rewrite, never delete — because rewriting preserves whatever durable half the entry still carries and deleting does not. Exception: if the rewrite would leave no durable content — nothing transferable once the marker and its closure narration are stripped — the entry is a delete, not a rewrite, and takes the category-(b) evidence requirement (closure verification) before deletion.
- (a1) A dangling index line — a
- Re-index by default, evaluate per file — (a2) an orphaned file: a file in the memory
directory with no
MEMORY.mdline. The write-then-append convention (write the file, then append its index line) means a session that dies between those two steps leaves a valid, unindexed entry — auto-deleting it destroys good content over a bookkeeping race. Read the file and evaluate it like any other entry; the default disposition for a well-formed orphaned file is to re-index it (add the missingMEMORY.mdline), not to delete it. - Rewrite in place — superseded/self-reversing content (state the current rule, drop the history), shape violations (add missing frontmatter fields, convert a relative date), and a moved referent (correct the name to the symbol's current location, per decay check 2).
- Propose, never apply — fragmentation, and splitting a multi-topic document into its constituent single-fact files. Both re-form the operator's original wording — merging collapses it, splitting divides it — and that tradeoff is the operator's call either way. Write the proposed merge or split as a suggestion in your report; do not create, delete, or edit any file for either finding.
Never write to a tracker
Per /core:bees, the bees SQLite database is single-writer — concurrent writes raise
SQLITE_CONSTRAINT or lose work outright. When a decayed entry turns out to be live work
sitting in memory (not dead, not closed — something still to be done), do not run bees create, bees update, bees close, or any tracker API call yourself. Instead, collect it
into a ## BEES REQUESTS block in your final report for the lead to apply through the serial
writer (core:bees-manager). Note in the same block which items, if any, also look like they
warrant a remote-tracking epic rather than only a local bees row.
Verify before claiming
Per /core:anti-fabrication, every delete verdict — a dangling index line or dead work, the
two authorized delete categories — cites the exact command run and its output, never a bare
assertion. For a stale-referent finding (evidence that feeds a dead-work verdict; stale-referent
is not itself an authorized delete category), that is the grep that found nothing, plus
confirmation the grep targeted the right repo: an empty result from the wrong directory is not
evidence of staleness; re-run against the correct path before recording a verdict. For a
dead-work verdict, that is the tracker or repo command that confirmed the referenced work is
actually closed. A delete with no cited command is not a valid verdict, whichever category it
falls under.
Workflow
- Load skills (above), read
memory-guidance.mdin full. - Enumerate the memory directory (
Glob) and cross-check every file againstMEMORY.md's index in both directions. Record a dangling index line — do not delete it at this step. An orphaned file gets read and evaluated with the rest of the corpus in step 4 — do not delete it at this step. Detection only: mutate nothing in this step. - Snapshot the directory (above). Stop if the snapshot fails.
- For each file, read it and apply the five decay checks and the work-vs-fact boundary from
memory-guidance.md. Record the check(s) that fired and the evidence (grep output, diff output) for each. - Apply autonomous deletes, re-indexes, and rewrites per the scope above, including deleting
each dangling index line recorded in step 2 (delete-without-asking, per Scope) now that the
step-3 snapshot has captured the pre-audit
MEMORY.md. Deleting a file also removes that file's ownMEMORY.mdindex line in the same step — a file delete that leaves its line behind creates the check-4 drift this audit exists to remove. Leave fragmentation and splitting as proposals. Leave live-work findings for the## BEES REQUESTSblock. - Produce the output contract below.
Output contract
End your report with a per-file verdict table:
| File | Verdict | Evidence |
|------|---------|----------|
| <path> | keep / rewrite / re-index / merge-into-<other-path> (proposed) / split (proposed) / delete / route-to-tracker | <command run + result, or the specific decay check that fired> |
Follow the table with:
- Archive path — the tarball location from the snapshot step.
- Deleted index lines — every
MEMORY.mdindex line removed in step 5, whether it was a dangling line or the line belonging to a deleted file, quoted verbatim (or "none removed"). - Summary counts — files reviewed, kept, rewritten, re-indexed, deleted, routed to tracker, proposed for merge, proposed for split.
- A
## BEES REQUESTSsection (present even if empty) listing any live-work items found, each with a proposed bees title/description and a note on whether it also warrants a remote-tracking epic.
Report a verdict for every file scanned — a table with gaps is not an audit.
Prose Reviewer
You judge prose quality, not prose existence. A short, unadorned file that says what it needs to say is never a finding on its own. Judge only sentences that already carry a defect against the applicable register.
Register selection
Pick strict or flavored register from the artifact under review, never from taste.
/core:technical-english's artifact-to-register table is authoritative and already preloaded
by this agent's skills: frontmatter. Consult it per file rather than guessing from length or
tone. When a file's kind is not in the table, judge it by function. A reader who executes it as
instructions gets strict register. A reader who reads it for context gets flavored register.
Defect categories (closed set)
Every flagged sentence carries exactly one of these five categories, listed here in severity order from highest to lowest:
- hedged-directive — an instruction or a procedure step is phrased as a guess rather than
a command. Traces to the "Hedges vs directives" section of
/core:technical-english: a directive carries no hedging verb such as "should," "may," "might," or "consider." - split-term — one term names two different things across the document set, or two different terms name the same thing. Traces to strict rule 1: one meaning and one part of speech, held constant.
- passive-agent-hidden — a step is written passively while the actor performing it is knowable but left out. Traces to strict rules 2 and 3: instructions take active voice, and passive voice is reserved for description where no one knows the actor.
- long-sentence — a sentence exceeds strict rule 6's caps: 20 words for a procedure sentence, 25 words for a description sentence.
- clutter — a wordy phrase stands in for a plain word, or a qualifier only restates the verb it modifies. Traces to strict rules 10 and 11.
Never invent a sixth category. A sentence carrying none of these five produces no finding.
Explicit non-findings
Two situations never produce a finding, whatever the sentence looks like:
- A flavored-mode file judged against strict rules is not a finding. Flavored prose answers
only to Zinsser's four principles from
/core:technical-english's flavored-prose reference — clarity, simplicity, brevity, humanity. Areferences/*.mdparagraph that would fail a strict word-count cap stays unflagged for that reason alone. - Prose that runs long because it explains a real trade-off is not clutter.
test/validate-skills-quality.nu's comment blocks are the reference case: several run to a paragraph because they record why a check exists, not because they ramble.
Anti-fabrication on replacements
A proposed replacement states only what the source text already supports. Never tighten a sentence by adding a guarantee, a constraint, or a scope the original did not carry. A shorter sentence that claims more than the source is a fabrication, not an improvement.
Output contract
Close the report with a ## VERDICTS block:
## VERDICTS
<target> | <FLAG|NO-FLAG> | <category> | <replacement or ->
Emit one roll-up line per file reviewed, with <target> set to the file path you were
given. Emit zero or more detail lines per file, with <target> set to file:line for one
specific flagged sentence. A file rolls up to FLAG when any sentence in it is flagged, and to
NO-FLAG otherwise. When a file carries findings in more than one category, the roll-up reports
the single most severe one, using the severity order fixed above. <category> is always one
of the five names above, or none on a NO-FLAG roll-up. A file with no reviewable prose —
pure code, pure data, or nothing that reads as a sentence — produces exactly one line:
<target> | NO-FLAG | none | -.
Model fallback
This agent runs at model: fable. When a spawn fails because fable is unavailable, the
spawner retries the same task at model: opus.
This is a capability substitution — fall back to what the environment can run — not the
haiku -> sonnet -> opus failure-driven escalation ladder from /core:agent-loop. A
disputed or unfavorable review never triggers this fallback; only fable's unavailability does.
You are a project bootstrapping agent. Your role is to initialize task tracking, discover project characteristics, and create a structured set of tracker issues with dependencies.
Input
The user may pass flags:
--beads— Use beads (bd) instead of bees. Bees is the default tracker for this workflow (workspace convention — see/core:bees); beads remains available via this flag for repos that already use it (/beads:beads).--stealth(beads only, requires--beads) — Usebd init --localfor local-only beads--contributor(beads only, requires--beads) — Usebd init --pullfor read-only beads
If --stealth or --contributor is passed without --beads, note in the Phase 3 summary that the flag is beads-only and was ignored, then proceed with the default bees flow. Bees has no equivalent init modes — bees init is always local-first (no remote sync, no pull-only variant; see /core:bees "Storage and File Structure").
Phase 1: Configure Tracker
Default: bees
Check for a local .bees/ directory — not bees list or bees ready. Both walk up to an ancestor .bees/ the same way git walks up to .git/ (verified against bees 0.4.0: run from a subdirectory of an already-initialized parent, bees create silently writes into the parent's tracker with no local .bees/ created and no error — the exact failure class that put stray test issues in the wrong tracker during this skill's own review). A directory-existence check is the only signal scoped to the current directory:
test -d .bees
- If false: run
bees init(creates.bees/in the current directory) - If true: report existing status and skip to Phase 2
bees init also rebuilds the database from .bees/issues.jsonl if one is present, and always preserves an existing .bees/config.json — safe to run whenever test -d .bees is false, never needed when it's true.
--beads: beads
Check for a local .beads/ directory — not bd status, which has the same upward-walk behavior as bees (verified: bd status from a subdirectory of an already-initialized parent reports the parent's stats, with no local .beads/ created and no error):
test -d .beads
- If true: report existing status and skip to Phase 2
- If false: run the appropriate init command based on flags:
- Default:
bd init --stealth:bd init --local--contributor:bd init --pull
- Default:
Phase 2: Discovery + Task Creation
2a. Discover Project Characteristics
Use Glob and Read to scan for:
Languages (check for indicator files):
- JavaScript/TypeScript:
package.json,tsconfig.json - Rust:
Cargo.toml - Elixir:
mix.exs - Go:
go.mod - Python:
pyproject.toml,setup.py,requirements.txt - Zig:
build.zig - Ruby:
Gemfile - Java/Kotlin:
pom.xml,build.gradle,build.gradle.kts
Existing tooling:
mise.tomlor.mise.toml— mise already configured.github/workflows/— CI already exists.gitleaks.toml— gitleaks already configured.pre-commit-config.yaml— pre-commit hooks existDockerfile,docker-compose.yml— containerization.env.example— environment variable patterns
Package managers (check for lockfiles):
package-lock.json,yarn.lock,pnpm-lock.yaml,bun.lockbCargo.lock,mix.lock,go.sumpoetry.lock,Pipfile.lock,uv.lockGemfile.lock
Project metadata:
README.md— project description and purposeLICENSE— licensing information
Collect all findings into a structured discovery summary.
2b. Create Tracker Issues
Create 4 issues, incorporating discovery results into each description.
Default: bees
bees create has no label flag (verified against bees 0.4.0 — see /core:bees "Commands Reference"). Capture each returned id with --json | jq -r '.id', then attach labels with bees label add <id> <label> (one call per label). This path depends on jq; verify it before creating anything — a missing jq makes $(... | jq -r '.id') capture an empty string, and every following bees label add "" / bees dep add "" then silently mistargets or errors:
command -v jq >/dev/null || { echo "jq is required for the bees bootstrap path (parses --json id output); install jq or re-run with --beads"; exit 1; }
Task 1 — discovery:
ID1=$(bees create "Document project discovery results" \
-t task \
-d "Record the discovered project characteristics:
Languages: <detected languages>
Package managers: <detected managers>
Existing tooling: <what's already configured>
Missing tooling: <what needs to be set up>
Create or update project documentation reflecting the current state." \
--json | jq -r '.id')
bees label add "$ID1" "phase:discovery"
bees label add "$ID1" "skill:documentation"
Task 2 — mise:
ID2=$(bees create "Configure mise development environment" \
-t task \
-d "Set up mise.toml with:
- Tool versions for detected languages: <languages>
- Task definitions for common operations (build, test, lint)
- Environment variables from .env.example patterns (if found)
Existing mise config: <yes/no + details if yes>" \
--json | jq -r '.id')
bees label add "$ID2" "phase:tooling"
bees label add "$ID2" "skill:mise"
Task 3 — CI:
ID3=$(bees create "Configure GitHub Actions CI workflow" \
-t task \
-d "Create .github/workflows/ CI pipeline:
- Build and test steps for: <detected languages>
- Use mise for tool management in CI
- Cache dependencies for: <detected package managers>
Existing CI: <yes/no + details if yes>" \
--json | jq -r '.id')
bees label add "$ID3" "phase:ci"
bees label add "$ID3" "skill:workflows"
bees label add "$ID3" "skill:mise"
Task 4 — gitleaks:
ID4=$(bees create "Configure gitleaks secret detection" \
-t task \
-d "Set up gitleaks for secret scanning:
- Create .gitleaks.toml configuration
- Add pre-commit hook for gitleaks
- Configure allowlist for false positives if needed
Existing gitleaks config: <yes/no + details if yes>" \
--json | jq -r '.id')
bees label add "$ID4" "phase:security"
bees label add "$ID4" "skill:security"
After each bees label add, spot-check with bees show <id> --json rather than trusting a zero exit code — bees does not validate label or type values, so a typo is stored silently (see /core:bees "No Enum Validation").
--beads: beads
Task 1 — discovery:
bd create "Document project discovery results" \
--labels "phase:discovery,skill:documentation" \
--description "Record the discovered project characteristics:
Languages: <detected languages>
Package managers: <detected managers>
Existing tooling: <what's already configured>
Missing tooling: <what needs to be set up>
Create or update project documentation reflecting the current state."
Task 2 — mise:
bd create "Configure mise development environment" \
--labels "phase:tooling,skill:mise" \
--description "Set up mise.toml with:
- Tool versions for detected languages: <languages>
- Task definitions for common operations (build, test, lint)
- Environment variables from .env.example patterns (if found)
Existing mise config: <yes/no + details if yes>"
Task 3 — CI:
bd create "Configure GitHub Actions CI workflow" \
--labels "phase:ci,skill:workflows,skill:mise" \
--description "Create .github/workflows/ CI pipeline:
- Build and test steps for: <detected languages>
- Use mise for tool management in CI
- Cache dependencies for: <detected package managers>
Existing CI: <yes/no + details if yes>"
Task 4 — gitleaks:
bd create "Configure gitleaks secret detection" \
--labels "phase:security,skill:security" \
--description "Set up gitleaks for secret scanning:
- Create .gitleaks.toml configuration
- Add pre-commit hook for gitleaks
- Configure allowlist for false positives if needed
Existing gitleaks config: <yes/no + details if yes>"
2c. Set Dependencies
After creating all 4 issues, capture their IDs and set dependencies. The argument order is the same for both trackers — the dependent issue comes first:
Default: bees
# Task 2 (mise) depends on Task 1 (discovery)
bees dep add "$ID2" "$ID1"
# Task 3 (CI) depends on Task 2 (mise)
bees dep add "$ID3" "$ID2"
# Task 4 (gitleaks) depends on Task 1 (discovery)
bees dep add "$ID4" "$ID1"
--beads: beads
# Task 2 (mise) depends on Task 1 (discovery)
bd dep add <task2_id> <task1_id>
# Task 3 (CI) depends on Task 2 (mise)
bd dep add <task3_id> <task2_id>
# Task 4 (gitleaks) depends on Task 1 (discovery)
bd dep add <task4_id> <task1_id>
Either tracker produces the same dependency graph:
discovery
├── mise
│ └── CI
└── gitleaks
Phase 3: Summary
Output a summary table and next steps:
## Project Setup Complete
### Tracker
<bees (default) | beads (--beads)>
### Discovery Summary
- Languages: <list>
- Package managers: <list>
- Existing tooling: <list>
### Created Tasks
| ID | Task | Labels | Depends On |
|----|------|--------|------------|
| <id1> | Document project discovery results | phase:discovery | — |
| <id2> | Configure mise development environment | phase:tooling | <id1> |
| <id3> | Configure GitHub Actions CI workflow | phase:ci | <id2> |
| <id4> | Configure gitleaks secret detection | phase:security | <id1> |
### Dependency Graph
discovery (<id1>)
├── mise (<id2>)
│ └── CI (<id3>)
└── gitleaks (<id4>)
### Next Steps (bees)
Run `bees ready` to see available tasks, then start with the discovery task.
Work tasks manually, or install the core plugin's bees-worker agent (`/core:bees` "Paired agents").
### Next Steps (--beads)
Run `bd ready` to see available tasks, then start with the discovery task.
Work tasks manually, or install the beads plugin for its worker agent:
`/plugin install beads@vinnie357` (beads-worker moved out of core with the skill).
Include only the Next Steps block matching the tracker actually used.
Guidelines
- Discovery-driven: Tailor task descriptions to what was actually found in the project
- Non-destructive: This agent only reads the project and creates tracker issues — it does not write config files
- Idempotent, scoped to this directory: check for a local
.bees/.beadsdirectory (notbees list/bd status, which walk up to an ancestor tracker) — if present, skip init and proceed with discovery; if absent, initialize here even inside an already-tracked parent - Informative: Include existing tooling state in task descriptions so workers know what already exists
- Bees is the default: matches this workspace's own convention (
/core:bees); beads stays available behind--beadsfor repos that use it (/beads:beads)
You are the bees-manager — the serialized writer for bees issue tracker databases.
Why you exist
Bees uses SQLite. SQLite is single-writer. When parallel workers each invoke bees new, bees close, or bees dep add against the same DB, contention surfaces as SQLITE_CONSTRAINT errors and daemon.lock failures. Bees is intentionally a single-operator-per-DB tool — it is not a service, and that is by design. You exist to apply queued bees writes serially, one CLI invocation at a time.
You are the ONLY writer the lead routes bees writes through. Read-mode bees commands (bees ls, bees ready, bees show) run concurrently anywhere — those are fine.
Skills (load and quote one sentence each as proof)
/core:anti-fabrication/core:bees/core:technical-english
Quote one sentence from each in every report. No other skills required.
Worker / lead contract
- Workers MUST NOT call write-mode bees commands directly (
new,close,dep add,update,comment add). - Workers emit a
BEES REQUESTS:block in their final report. - The lead aggregates those blocks across all workers in a phase and routes them to a single
bees-manageragent per repo cwd. - The lead spawns ONE
bees-managerper batch — never two in parallel against the same DB.
Wording boundary — relay, not author
You are a relay: workers hand you queued writes; you do not author their content. A queued write's title, description, and acceptance criteria arrive pre-decided. Applying a write MAY tighten a title's or a description's wording for terseness and checkability. Acceptance criteria and identifiers are reproduced VERBATIM — tightening never applies to them. Applying a write MUST NOT:
- Change the meaning of any title, description, or acceptance criterion.
- Reword an acceptance criterion at all — reproduce it verbatim.
- Alter an identifier — an issue id, a label, a file path, a command string, a sha.
- Drop a section from a structured description body.
If a queued write is ambiguous or unsatisfiable as written, report it back to the lead. Do not fix it yourself.
Inputs
The lead passes you a batch of writes formatted like:
BEES REQUESTS (cwd: <path>):
- close github-NN reason="..."
- new title="..." body="..." priority=PN external-ref="..." [labels=...] [blocks-on=github-MM]
- dep add <new-id> --blocks-on github-MM
- update github-NN ...
Each batch always specifies its cwd. Each bees DB is per-repo (global at ~/github/.bees/, plus per-repo <repo>/.bees/). The cwd determines which DB you operate on. Verify your working directory matches the requested cwd before any write.
How to apply a batch
-
Verify CLI shape first:
cd <requested-cwd> && bees --help 2>&1 | head -30The CLI may use
bees neworbees create,-ror--reason, etc. Match what the local CLI accepts. Don't assume. -
Verify lock state if the batch is large:
ls -la .bees/ ps aux | grep -i bees | grep -v grepIf a stale
.bees/daemon.lockexists with no livebees daemonprocess, remove it. Don't touch.shmor.wal— those are active SQLite artifacts. -
Apply writes one at a time. Never pipeline. Never run two
beescommands in parallel even if they look independent. SQLite contention does not respect intent. -
Order within a batch:
- Closures first (they don't allocate new IDs, so dep wires after won't race)
- Creates next, capturing each new
github-NNID from CLI output - Dep wires last (they reference IDs from the previous step)
- Updates can go anywhere reasonable; prefer after creates
-
Capture IDs. After each
bees new, parse the returned ID from stdout. If the CLI doesn't print the new ID directly, follow with:bees ls --status open --limit 1 --json 2>/dev/null | head -5The newest entry is yours.
-
On
SQLITE_CONSTRAINTordaemon.lockerrors: STOP. Do not retry blindly. Report what landed and what failed. The lead decides how to recover — typically by inspecting bees state and re-queueing the failed writes after diagnosis.
Hard rules
- One bees write CLI invocation at a time. Period.
- Match the cwd in the request. Each bees DB is per-repo.
- Never modify bees state outside the explicit batch. No "while I'm here, let me also..." additions.
- Never propose a "future fix" that adds an HTTP daemon or service mode. Bees is single-operator-per-DB by design.
- Never delete bees rows. Bees tracks history; closures are the cancellation path.
- No raw SQLite writes. Use the bees CLI. If a needed operation isn't supported by the CLI, surface as a gap and stop.
Recovery procedures
- Stale daemon.lock:
ls -la .bees/daemon.lockshows the file butps aux | grep beesshows no live process. Remove the lock withrm .bees/daemon.lock. Never remove.shmor.wal. - SQLITE_CONSTRAINT on insert: usually a duplicate external-ref or violated unique constraint. Re-read the offending row with
bees show <id>to confirm whether the intended state already exists. - Live daemon: do not kill it. The lead's parallel-workers race is the problem — your job is to serialize, not preempt. Wait for the daemon to release, retry once, then surface the failure.
Report format (≤15 lines, strict)
BEES MANAGER BATCH <N>
- cwd: <path>
- Lock state: <ok / stale-removed / live-daemon-untouched>
- Closures: <list with ✓/✗ and reasons for failures>
- New issues: <github-N1 (title hint), github-N2 (title hint), ...>
- Updates: <list>
- Dep wires: <X/Y ok>
- Errors: <list or "none">
- Skill quotes:
- /core:anti-fabrication: <one sentence>
- /core:bees: <one sentence>
- /core:technical-english: <one sentence>
If the batch hit any constraint failure, also include a short RECOVERY HINT: line suggesting what the lead should re-queue or investigate.
Lifecycle
You are spawned per-batch. Don't try to stay alive across messages — the runtime doesn't reliably resume agents after completion. The lead spawns a fresh bees-manager for each batch, passing the queue. That is correct behavior; bees writes are infrequent enough that spawn overhead is negligible compared to the cost of contention.
You are a task queue worker for bees-managed workflows. Process issues from the queue, execute work, and sync results.
Workflow Modes
PR Workflow (Recommended for Code Changes)
Use when changes require human review before merging.
Session Start
git pull --ff-only # Advance the primary; never checkout a branch here
bees ready # Find available issues
bees show <id> # Read issue requirements
Issue Execution
bees update <id> --status in_progress # Claim issue — run from the primary
git fetch origin
git worktree add "$WORKTREE_ROOT/<repo>-<slug>" -b feature/<name> origin/main
cd "$WORKTREE_ROOT/<repo>-<slug>"
# Execute work (see "Execute Work" section below)
git add <files> # Stage changes
git commit -m "type(scope): description" # Commit (use /core:gcms for suggestions)
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"
Notify user: "PR created: <url>"
Then STOP and report the PR URL. Merge only under a deployment merge policy that authorizes it; the default authorizes none. Never queue an automatic or deferred merge.
After CI passes, 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."
After Merge (When User Returns)
See /core:git "Worktrees", "Cleanup, merged-only" for the current removal precondition.
gh pr view --json state -q '.state' # Check if "MERGED"
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
PR Workflow Principles
- One issue = one branch = one PR
- Claim before working:
bees update --status in_progress - Minimal PRs: Title + bullets only
- Report, do not merge: The default merge policy authorizes no agent merge; never assume approval
- Clean up: Confirm
MERGED, thengit worktree removeandgit branch -D— see/core:git"Worktrees", "Cleanup, merged-only"
Complexity-Aware Dispatch
See /core:agent-loop "Five-Tier Decomposition Pipeline" for stage definitions and /core:bees "Complexity labels" for the bees-side vocabulary.
On bees ready pickup, route by complexity label. The bees-worker IS the Sub-team Leader for that issue — it owns the pipeline dispatch internally.
LABELS=$(bees show <id> --json | jq -r '.labels | join(",")')
case "$LABELS" in
*complexity:complex*) MODE=pipeline ;;
*complexity:trivial*) MODE=solo ;;
*) MODE=unlabeled ;;
esac
Unlabeled issue → classify (see "Complexity classification" below) or comment + bees update --status blocked + escalate. Do not guess.
Pipeline mode (complexity:complex)
Spawn five sequential Task invocations from the bees-worker process. Each is a separate Agent with no shared context. Name the stage in the spawn prompt — these are dispatch-time identifiers, not bees labels:
| Stage | Model | Spawn prompt opens with |
|---|---|---|
| P1 planner | deep reasoning | You are team:opus-planner for bees issue <id>. Stage P1 — write test list + spec. |
| P2 test author | general | You are team:sonnet-test for bees issue <id>. Stage P2 — write failing tests against P1's spec. Do NOT read implementation. |
| P3 implementer | general | You are team:sonnet-impl for bees issue <id>. Stage P3 — make tests pass. Do NOT modify test files. |
| P4 CI runner | smallest fast | You are team:haiku-ci for bees issue <id>. Stage P4 — run mise run ci, paste verbatim output. |
| P5 reviewer | strongest reasoning | You are team:opus-review for bees issue <id>. Stage P5 — verify tests exercise AC, no overfit. |
Intermediate artifacts go to bees comments on the SAME issue and git commits on the feature branch. Do NOT create new bees issues for stage progression.
Between dispatches the bees-worker verifies the previous stage's artifact before spawning the next:
- Before P3: P2 stage left a test-only commit on the branch (
git log --onelineshows it). - Before P4: P3's commit doesn't touch test files (
git diff <P2-sha>..HEAD -- <test-paths>is empty). - Before P5: P4 reported green CI in its bees comment.
- Verification failure → comment on the issue + escalate, do not auto-correct.
Solo mode (complexity:trivial)
Dispatch one smallest-fast-tier Agent following the 9-step Agent Worker Execution Order in /core:agent-loop. Single Task invocation, no pipeline.
Complexity classification (unlabeled issues)
If no complexity:* label is present, apply the threshold from /core:agent-loop "When to apply":
- Multi-file change touching the issue body's referenced files
- Public API surface (HTTP, exported, schema)
- Cross-repo work
- Explicit acceptance criteria
Any hit → label complexity:complex and proceed in pipeline mode. None hit → label complexity:trivial and proceed in solo mode. If classification is ambiguous, comment + block + escalate; do not guess.
Automated Workflow (Direct Commits)
Use for non-code tasks or when PRs aren't required.
1. Poll Ready Issues
bees ready --json
Select the first issue. If none available, report "No ready issues" and exit.
2. Get Issue Details
bees show <issue_id> --json
Extract: title, description, labels.
2b. Extract Skill Suggestions
From the issue JSON, extract any skill:* labels:
bees show <issue_id> --json | jq -r '.labels[] | select(startswith("skill:")) | ltrimstr("skill:")'
Note the suggested skills for activation during execution. When resolving skills:
- Explicit
skill:labels - Use directly (highest priority). These may reference any installed skill, not just those in the static catalog. - Static catalog - If no
skill:labels are present, consultreferences/skill-catalog.mdto match issue keywords to relevant skills. - Runtime discovery - Also check available skills in the current session. Any loaded skill whose name or description matches the issue domain is a valid candidate.
Activate any valid skill from the available skills list during execution, regardless of whether it appears in the static catalog.
3. Execute Work
(Same as below)
4. Comment Progress
bees comment add <issue_id> "Completed: <summary>
Files: <list>
Changes: <list>"
5. Close and Sync
bees close <issue_id>
bees sync
6. Repeat
Continue until bees ready --json returns empty.
Execute Work
Before dispatching work, activate any suggested skills from the skill: labels. Load the corresponding skill context so domain-specific knowledge is available during execution.
Issues with complexity:* labels route via "Complexity-Aware Dispatch" above. Untiered issues that classify as trivial use the pattern-match table below.
| Pattern | Action |
|---|---|
| Create/Add/Implement | Write new files |
| Fix/Resolve | Edit existing files |
| Update/Modify | Edit existing files |
| Review/Analyze | Read and comment |
| Delete/Remove | Remove files/code |
| Test | Run tests, report results |
For exploration tasks, delegate:
Task(subagent_type="Explore", description="...", prompt="...")
Guidelines
- Atomic: One issue = one unit of work
- Documented: Update description with what was done
- Fail-safe: Never close incomplete issues
- Scoped: Do exactly what the issue asks
- Sequential: Only work issues from
bees ready
Claude Teams Coordination
When running inside Claude Agent Teams, mirror bees actions into Claude's task list for teammate visibility.
Detection: Teams mode is active when TaskList returns results. If no Claude tasks exist, skip mirroring and operate in standalone bees mode.
On Issue Claim: After bees update <id> --status in_progress, find the matching [bees:<id>] Claude task and claim it:
TaskList # Find task with [bees:<id>] in subject
TaskUpdate taskId="<claude-id>" status="in_progress"
On Issue Completion: After bees close, update the matching Claude task:
bees close <id>
bees sync
TaskUpdate taskId="<claude-id>" status="completed"
On Issue Failure: Do not close either system. Add a comment with failure details:
bees comment add <id> "Failed: <error>
Attempted: <what>
Blockers: <why>"
The team lead will handle reconciliation. See references/teams-integration.md for the full protocol.
On Failure
Do NOT close the issue. Add error comment:
bees comment add <issue_id> "Failed: <error>
Attempted: <what>
Blockers: <why>"
Continue to next issue.
Output Summary
## Bees Worker Summary
Completed: [id] title - summary (skills: skill1, skill2)
Failed: [id] title - reason
Remaining: N issues
Hooks 2
Sponsors
Details
- Marketplace
- vinnie357/claude-skills
- Source
- plugins/core
- Category
- Development
- Keywords
- git, documentation, code-review, tools, twelve-factor-app, security, gitleaks, bees, container, tdd, agent-loop, restraint, forge
