Agent loop

From vinnie357/claude-skills · View interactive version

Agent loop is an AI agent skill from the GitHub repository vinnie357/claude-skills. Generic epic-to-PR agent workflow (codename Forge) with 4-phase execution, a 6-tier hierarchy, and paired-team fan-out. Use when coordinating any feature delivery, working an issue or epic ("work epic <id>", "work issue <id>", "use Forge on the next bees ready item", "forge <id>"), picking up an epi

How to use this skill

Skill file

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 <id>", 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:

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:

  1. bees: bees list --epic <slug> — does the epic already have issues?
  2. DECOMPOSITION_PATH env 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:

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

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:

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:

Glob patterns like /core:* do not expand in Agent prompts. List skill names explicitly.

Key Conventions

Agent Worker Execution Order

Every agent worker (Tier 3) follows these steps:

  1. Create feature branch
  2. Write tests first (TDD)
  3. Implement
  4. Gate 1 — Run local CI (mise run ci) — fix until 0 failures
  5. Commit without attribution
  6. Run gitleaks scan on committed changes — fix if secrets detected
  7. Push, create PR
  8. Gate 2 — Watch remote CI (gh pr checks --watch) — fix and push until local + remote are green
  9. 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 calling SendMessage reports 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

The Layered Model

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:

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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.